|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "go-backfill/config" |
| 8 | + "log" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/jackc/pgx/v5" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + batchSize = 10000 // Reduced batch size for better performance |
| 16 | +) |
| 17 | + |
| 18 | +type Event struct { |
| 19 | + ID int64 |
| 20 | + OrderIndex int64 |
| 21 | +} |
| 22 | + |
| 23 | +func fixBatchOrderIndex(conn *pgx.Conn, lastTransactionId int64) (bool, int64, error) { |
| 24 | + startTime := time.Now() |
| 25 | + |
| 26 | + // Start transaction for writes |
| 27 | + tx, err := conn.Begin(context.Background()) |
| 28 | + if err != nil { |
| 29 | + return false, lastTransactionId, fmt.Errorf("failed to begin transaction: %v", err) |
| 30 | + } |
| 31 | + defer tx.Rollback(context.Background()) |
| 32 | + |
| 33 | + // Get transactions in batch |
| 34 | + query := ` |
| 35 | + SELECT DISTINCT t.id |
| 36 | + FROM "Transactions" t |
| 37 | + JOIN "Events" e ON e."transactionId" = t.id |
| 38 | + WHERE t.id > $1 |
| 39 | + ORDER BY t.id ASC |
| 40 | + LIMIT $2 |
| 41 | + ` |
| 42 | + |
| 43 | + rows, err := tx.Query(context.Background(), query, lastTransactionId, batchSize) |
| 44 | + if err != nil { |
| 45 | + return false, lastTransactionId, fmt.Errorf("failed to query transactions: %v", err) |
| 46 | + } |
| 47 | + defer rows.Close() |
| 48 | + |
| 49 | + var transactionIds []int64 |
| 50 | + for rows.Next() { |
| 51 | + var id int64 |
| 52 | + if err := rows.Scan(&id); err != nil { |
| 53 | + return false, lastTransactionId, fmt.Errorf("failed to scan transaction id: %v", err) |
| 54 | + } |
| 55 | + transactionIds = append(transactionIds, id) |
| 56 | + } |
| 57 | + |
| 58 | + if len(transactionIds) == 0 { |
| 59 | + return false, lastTransactionId, nil |
| 60 | + } |
| 61 | + |
| 62 | + // Update all events in a single query using window functions |
| 63 | + updateQuery := ` |
| 64 | + WITH OrderedEvents AS ( |
| 65 | + SELECT |
| 66 | + e.id, |
| 67 | + ROW_NUMBER() OVER (PARTITION BY e."transactionId" ORDER BY e.id) - 1 as new_order_index |
| 68 | + FROM "Events" e |
| 69 | + WHERE e."transactionId" = ANY($1::bigint[]) |
| 70 | + ) |
| 71 | + UPDATE "Events" e |
| 72 | + SET "orderIndex" = oe.new_order_index |
| 73 | + FROM OrderedEvents oe |
| 74 | + WHERE e.id = oe.id |
| 75 | + AND (e."orderIndex" IS NULL OR e."orderIndex" != oe.new_order_index) |
| 76 | + RETURNING e.id |
| 77 | + ` |
| 78 | + |
| 79 | + rows, err = tx.Query(context.Background(), updateQuery, transactionIds) |
| 80 | + if err != nil { |
| 81 | + return false, lastTransactionId, fmt.Errorf("failed to execute update: %v", err) |
| 82 | + } |
| 83 | + defer rows.Close() |
| 84 | + |
| 85 | + var updatedCount int |
| 86 | + for rows.Next() { |
| 87 | + updatedCount++ |
| 88 | + } |
| 89 | + |
| 90 | + if err := tx.Commit(context.Background()); err != nil { |
| 91 | + return false, lastTransactionId, fmt.Errorf("failed to commit transaction: %v", err) |
| 92 | + } |
| 93 | + |
| 94 | + elapsed := time.Since(startTime) |
| 95 | + log.Printf("Fixed order_index for %d events in %d transactions. Batch time: %.2fs", updatedCount, len(transactionIds), elapsed.Seconds()) |
| 96 | + |
| 97 | + lastProcessedId := transactionIds[len(transactionIds)-1] |
| 98 | + return len(transactionIds) == batchSize, lastProcessedId, nil |
| 99 | +} |
| 100 | + |
| 101 | +func main() { |
| 102 | + envFile := flag.String("env", ".env", "Path to the .env file") |
| 103 | + flag.Parse() |
| 104 | + |
| 105 | + config.InitEnv(*envFile) |
| 106 | + env := config.GetConfig() |
| 107 | + |
| 108 | + // Database connection |
| 109 | + connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", |
| 110 | + env.DbHost, env.DbPort, env.DbUser, env.DbPassword, env.DbName) |
| 111 | + |
| 112 | + conn, err := pgx.Connect(context.Background(), connStr) |
| 113 | + if err != nil { |
| 114 | + log.Fatalf("Failed to connect to database: %v", err) |
| 115 | + } |
| 116 | + defer conn.Close(context.Background()) |
| 117 | + |
| 118 | + log.Println("Connected to database") |
| 119 | + |
| 120 | + lastId := int64(0) |
| 121 | + hasMore := true |
| 122 | + processedTransactions := int64(0) |
| 123 | + |
| 124 | + for hasMore { |
| 125 | + var err error |
| 126 | + hasMore, lastId, err = fixBatchOrderIndex(conn, lastId) |
| 127 | + if err != nil { |
| 128 | + log.Fatalf("Error during batch processing: %v", err) |
| 129 | + } |
| 130 | + processedTransactions += batchSize |
| 131 | + |
| 132 | + if hasMore { |
| 133 | + log.Printf("Progress: Processed up to transaction ID %d", lastId) |
| 134 | + } else { |
| 135 | + log.Printf("Progress: Completed all transactions") |
| 136 | + } |
| 137 | + |
| 138 | + time.Sleep(100 * time.Millisecond) |
| 139 | + } |
| 140 | + |
| 141 | + log.Println("Order index fix completed successfully") |
| 142 | +} |
0 commit comments