|
| 1 | +package deposit |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/lightninglabs/loop/loopdb" |
| 9 | +) |
| 10 | + |
| 11 | +const ( |
| 12 | + // depositStaticAddressIDMigrationID is the identifier for the migration |
| 13 | + // that backfills the static_address_id column on existing deposits. |
| 14 | + depositStaticAddressIDMigrationID = "deposit_static_address_id" |
| 15 | +) |
| 16 | + |
| 17 | +// MigrateDepositStaticAddressID populates the static_address_id field for all |
| 18 | +// existing deposits by assigning the id of the single static address known to |
| 19 | +// the client. If no static address exists, the migration is a no-op. If more |
| 20 | +// than one static address exists, the migration will fail to avoid ambiguous |
| 21 | +// assignment. |
| 22 | +func MigrateDepositStaticAddressID(ctx context.Context, db loopdb.SwapStore, |
| 23 | + store *SqlStore) error { |
| 24 | + |
| 25 | + migrationDone, err := db.HasMigration( |
| 26 | + ctx, depositStaticAddressIDMigrationID, |
| 27 | + ) |
| 28 | + if err != nil { |
| 29 | + return fmt.Errorf("unable to check migration status: %w", err) |
| 30 | + } |
| 31 | + if migrationDone { |
| 32 | + log.Infof("Deposit static address id migration already done, " + |
| 33 | + "skipping") |
| 34 | + |
| 35 | + return nil |
| 36 | + } |
| 37 | + |
| 38 | + log.Infof("Starting deposit static address id migration") |
| 39 | + startTs := time.Now() |
| 40 | + defer func() { |
| 41 | + log.Infof("Finished deposit static address id migration in %v", |
| 42 | + time.Since(startTs)) |
| 43 | + }() |
| 44 | + |
| 45 | + // Read all static addresses. The address manager logic only allows a |
| 46 | + // single static address to exist for the client. |
| 47 | + addresses, err := store.baseDB.Queries.AllStaticAddresses(ctx) |
| 48 | + if err != nil { |
| 49 | + return fmt.Errorf("unable to fetch static addresses: %w", err) |
| 50 | + } |
| 51 | + |
| 52 | + switch len(addresses) { |
| 53 | + case 0: |
| 54 | + // Nothing to backfill. Mark as done to avoid re-running. |
| 55 | + log.Infof("No static addresses found, nothing to backfill") |
| 56 | + |
| 57 | + return db.SetMigration(ctx, depositStaticAddressIDMigrationID) |
| 58 | + |
| 59 | + case 1: |
| 60 | + // OK. |
| 61 | + |
| 62 | + default: |
| 63 | + return fmt.Errorf("found %d static addresses, expected 1", |
| 64 | + len(addresses)) |
| 65 | + } |
| 66 | + |
| 67 | + // Backfill all deposits that don't yet have a static address id using |
| 68 | + // the store method. |
| 69 | + err = store.BatchSetStaticAddressID(ctx, addresses[0].ID) |
| 70 | + if err != nil { |
| 71 | + return fmt.Errorf("backfill deposits static_address_id: %w", |
| 72 | + err) |
| 73 | + } |
| 74 | + |
| 75 | + // Finally, mark the migration as done. |
| 76 | + return db.SetMigration(ctx, depositStaticAddressIDMigrationID) |
| 77 | +} |
0 commit comments