|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "go-backfill/config" |
| 8 | + "log" |
| 9 | + |
| 10 | + _ "github.com/lib/pq" // PostgreSQL driver |
| 11 | +) |
| 12 | + |
| 13 | +const ( |
| 14 | + creationTimeBatchSizeEvents = 500 |
| 15 | + startTransactionIdEvents = 1 |
| 16 | + endTransactionIdEvents = 1000 |
| 17 | +) |
| 18 | + |
| 19 | +// This script was created to duplicate the creation time of transaction to the events table. |
| 20 | +// The main motivation was to improve the performance of the events query. |
| 21 | + |
| 22 | +func updateCreationTimesForEvents() error { |
| 23 | + envFile := flag.String("env", ".env", "Path to the .env file") |
| 24 | + flag.Parse() |
| 25 | + config.InitEnv(*envFile) |
| 26 | + env := config.GetConfig() |
| 27 | + connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", |
| 28 | + env.DbHost, env.DbPort, env.DbUser, env.DbPassword, env.DbName) |
| 29 | + |
| 30 | + db, err := sql.Open("postgres", connStr) |
| 31 | + if err != nil { |
| 32 | + return fmt.Errorf("failed to connect to database: %v", err) |
| 33 | + } |
| 34 | + defer db.Close() |
| 35 | + |
| 36 | + log.Println("Connected to database") |
| 37 | + |
| 38 | + // Test database connection |
| 39 | + if err := db.Ping(); err != nil { |
| 40 | + return fmt.Errorf("failed to ping database: %v", err) |
| 41 | + } |
| 42 | + |
| 43 | + // Process transactions in batches |
| 44 | + if err := processTransactionsBatchForEvents(db); err != nil { |
| 45 | + return fmt.Errorf("failed to process transactions: %v", err) |
| 46 | + } |
| 47 | + |
| 48 | + log.Println("Successfully updated all events creation times") |
| 49 | + return nil |
| 50 | +} |
| 51 | + |
| 52 | +func processTransactionsBatchForEvents(db *sql.DB) error { |
| 53 | + currentId := startTransactionIdEvents |
| 54 | + totalProcessed := 0 |
| 55 | + totalTransactions := endTransactionIdEvents - startTransactionIdEvents + 1 |
| 56 | + lastProgressPrinted := -1.0 |
| 57 | + |
| 58 | + log.Printf("Starting to process transactions from ID %d to %d", |
| 59 | + startTransactionIdEvents, endTransactionIdEvents) |
| 60 | + log.Printf("Total transactions to process: %d", totalTransactions) |
| 61 | + |
| 62 | + for currentId <= endTransactionIdEvents { |
| 63 | + // Calculate batch end |
| 64 | + batchEnd := currentId + creationTimeBatchSizeEvents - 1 |
| 65 | + if batchEnd > endTransactionIdEvents { |
| 66 | + batchEnd = endTransactionIdEvents |
| 67 | + } |
| 68 | + |
| 69 | + // Process this batch |
| 70 | + processed, err := processBatchForEvents(db, currentId, batchEnd) |
| 71 | + if err != nil { |
| 72 | + return fmt.Errorf("failed to process batch %d-%d: %v", currentId, batchEnd, err) |
| 73 | + } |
| 74 | + |
| 75 | + totalProcessed += processed |
| 76 | + |
| 77 | + // Calculate progress percentage |
| 78 | + transactionsProcessed := batchEnd - startTransactionIdEvents + 1 |
| 79 | + progressPercent := (float64(transactionsProcessed) / float64(totalTransactions)) * 100.0 |
| 80 | + |
| 81 | + // Only print progress if it has increased by at least 0.1% |
| 82 | + if progressPercent-lastProgressPrinted >= 0.1 { |
| 83 | + log.Printf("Progress: %.1f%%", progressPercent) |
| 84 | + lastProgressPrinted = progressPercent |
| 85 | + } |
| 86 | + |
| 87 | + // Move to next batch |
| 88 | + currentId = batchEnd + 1 |
| 89 | + } |
| 90 | + |
| 91 | + log.Printf("Completed processing. Total events updated: %d (100.0%%)", totalProcessed) |
| 92 | + return nil |
| 93 | +} |
| 94 | + |
| 95 | +func processBatchForEvents(db *sql.DB, startId, endId int) (int, error) { |
| 96 | + // Begin transaction for atomic operation |
| 97 | + tx, err := db.Begin() |
| 98 | + if err != nil { |
| 99 | + return 0, fmt.Errorf("failed to begin transaction: %v", err) |
| 100 | + } |
| 101 | + defer tx.Rollback() // Will be ignored if tx.Commit() succeeds |
| 102 | + |
| 103 | + // Update events with creation time from transactions in a single query |
| 104 | + updateQuery := ` |
| 105 | + UPDATE "Events" |
| 106 | + SET creationtime = t.creationtime, "updatedAt" = CURRENT_TIMESTAMP |
| 107 | + FROM "Transactions" t |
| 108 | + WHERE "Events"."transactionId" = t.id |
| 109 | + AND t.id >= $1 AND t.id <= $2 |
| 110 | + ` |
| 111 | + |
| 112 | + result, err := tx.Exec(updateQuery, startId, endId) |
| 113 | + if err != nil { |
| 114 | + return 0, fmt.Errorf("failed to update events: %v", err) |
| 115 | + } |
| 116 | + |
| 117 | + rowsAffected, err := result.RowsAffected() |
| 118 | + if err != nil { |
| 119 | + return 0, fmt.Errorf("failed to get rows affected: %v", err) |
| 120 | + } |
| 121 | + |
| 122 | + // Commit the transaction |
| 123 | + if err := tx.Commit(); err != nil { |
| 124 | + return 0, fmt.Errorf("failed to commit transaction: %v", err) |
| 125 | + } |
| 126 | + |
| 127 | + return int(rowsAffected), nil |
| 128 | +} |
| 129 | + |
| 130 | +func creationTimesEvents() { |
| 131 | + if err := updateCreationTimesForEvents(); err != nil { |
| 132 | + log.Fatalf("Error: %v", err) |
| 133 | + } |
| 134 | +} |
0 commit comments