• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 14448891397

14 Apr 2025 02:58PM UTC coverage: 69.141% (+0.05%) from 69.091%
14448891397

Pull #9714

github

web-flow
Merge 7020edb60 into 6d648ad90
Pull Request #9714: invoices: reduce log spam when migrating invoices to SQL

21 of 22 new or added lines in 1 file covered. (95.45%)

75 existing lines in 12 files now uncovered.

133671 of 193330 relevant lines covered (69.14%)

22138.08 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.49
/invoices/sql_migration.go
1
package invoices
2

3
import (
4
        "bytes"
5
        "context"
6
        "encoding/binary"
7
        "errors"
8
        "fmt"
9
        "reflect"
10
        "strconv"
11
        "time"
12

13
        "github.com/davecgh/go-spew/spew"
14
        "github.com/lightningnetwork/lnd/graph/db/models"
15
        "github.com/lightningnetwork/lnd/kvdb"
16
        "github.com/lightningnetwork/lnd/lntypes"
17
        "github.com/lightningnetwork/lnd/sqldb"
18
        "github.com/lightningnetwork/lnd/sqldb/sqlc"
19
        "github.com/pmezard/go-difflib/difflib"
20
        "golang.org/x/time/rate"
21
)
22

23
var (
24
        // invoiceBucket is the name of the bucket within the database that
25
        // stores all data related to invoices no matter their final state.
26
        // Within the invoice bucket, each invoice is keyed by its invoice ID
27
        // which is a monotonically increasing uint32.
28
        invoiceBucket = []byte("invoices")
29

30
        // invoiceIndexBucket  is the name of the sub-bucket within the
31
        // invoiceBucket which indexes all invoices by their payment hash. The
32
        // payment hash is the sha256 of the invoice's payment preimage. This
33
        // index is used to detect duplicates, and also to provide a fast path
34
        // for looking up incoming HTLCs to determine if we're able to settle
35
        // them fully.
36
        //
37
        // maps: payHash => invoiceKey
38
        invoiceIndexBucket = []byte("paymenthashes")
39

40
        // numInvoicesKey is the name of key which houses the auto-incrementing
41
        // invoice ID which is essentially used as a primary key. With each
42
        // invoice inserted, the primary key is incremented by one. This key is
43
        // stored within the invoiceIndexBucket. Within the invoiceBucket
44
        // invoices are uniquely identified by the invoice ID.
45
        numInvoicesKey = []byte("nik")
46

47
        // addIndexBucket is an index bucket that we'll use to create a
48
        // monotonically increasing set of add indexes. Each time we add a new
49
        // invoice, this sequence number will be incremented and then populated
50
        // within the new invoice.
51
        //
52
        // In addition to this sequence number, we map:
53
        //
54
        //   addIndexNo => invoiceKey
55
        addIndexBucket = []byte("invoice-add-index")
56

57
        // ErrMigrationMismatch is returned when the migrated invoice does not
58
        // match the original invoice.
59
        ErrMigrationMismatch = fmt.Errorf("migrated invoice does not match " +
60
                "original invoice")
61
)
62

63
// createInvoiceHashIndex generates a hash index that contains payment hashes
64
// for each invoice in the database. Retrieving the payment hash for certain
65
// invoices, such as those created for spontaneous AMP payments, can be
66
// challenging because the hash is not directly derivable from the invoice's
67
// parameters and is stored separately in the `paymenthashes` bucket. This
68
// bucket maps payment hashes to invoice keys, but for migration purposes, we
69
// need the ability to query in the reverse direction. This function establishes
70
// a new index in the SQL database that maps each invoice key to its
71
// corresponding payment hash.
72
func createInvoiceHashIndex(ctx context.Context, db kvdb.Backend,
73
        tx *sqlc.Queries) error {
4✔
74

4✔
75
        return db.View(func(kvTx kvdb.RTx) error {
8✔
76
                invoices := kvTx.ReadBucket(invoiceBucket)
4✔
77
                if invoices == nil {
4✔
78
                        return ErrNoInvoicesCreated
×
79
                }
×
80

81
                invoiceIndex := invoices.NestedReadBucket(
4✔
82
                        invoiceIndexBucket,
4✔
83
                )
4✔
84
                if invoiceIndex == nil {
6✔
85
                        return ErrNoInvoicesCreated
2✔
86
                }
2✔
87

88
                addIndex := invoices.NestedReadBucket(addIndexBucket)
2✔
89
                if addIndex == nil {
2✔
90
                        return ErrNoInvoicesCreated
×
91
                }
×
92

93
                // First, iterate over all elements in the add index bucket and
94
                // insert the add index value for the corresponding invoice key
95
                // in the payment_hashes table.
96
                err := addIndex.ForEach(func(k, v []byte) error {
6✔
97
                        // The key is the add index, and the value is
4✔
98
                        // the invoice key.
4✔
99
                        addIndexNo := binary.BigEndian.Uint64(k)
4✔
100
                        invoiceKey := binary.BigEndian.Uint32(v)
4✔
101

4✔
102
                        return tx.InsertKVInvoiceKeyAndAddIndex(ctx,
4✔
103
                                sqlc.InsertKVInvoiceKeyAndAddIndexParams{
4✔
104
                                        ID:       int64(invoiceKey),
4✔
105
                                        AddIndex: int64(addIndexNo),
4✔
106
                                },
4✔
107
                        )
4✔
108
                })
4✔
109
                if err != nil {
2✔
110
                        return err
×
111
                }
×
112

113
                // Next, iterate over all hashes in the invoice index bucket and
114
                // set the hash to the corresponding the invoice key in the
115
                // payment_hashes table.
116
                return invoiceIndex.ForEach(func(k, v []byte) error {
8✔
117
                        // Skip the special numInvoicesKey as that does
6✔
118
                        // not point to a valid invoice.
6✔
119
                        if bytes.Equal(k, numInvoicesKey) {
8✔
120
                                return nil
2✔
121
                        }
2✔
122

123
                        // The key is the payment hash, and the value
124
                        // is the invoice key.
125
                        if len(k) != lntypes.HashSize {
4✔
126
                                return fmt.Errorf("invalid payment "+
×
127
                                        "hash length: expected %v, "+
×
128
                                        "got %v", lntypes.HashSize,
×
129
                                        len(k))
×
130
                        }
×
131

132
                        invoiceKey := binary.BigEndian.Uint32(v)
4✔
133

4✔
134
                        return tx.SetKVInvoicePaymentHash(ctx,
4✔
135
                                sqlc.SetKVInvoicePaymentHashParams{
4✔
136
                                        ID:   int64(invoiceKey),
4✔
137
                                        Hash: k,
4✔
138
                                },
4✔
139
                        )
4✔
140
                })
141
        }, func() {})
4✔
142
}
143

144
// toInsertMigratedInvoiceParams creates the parameters for inserting a migrated
145
// invoice into the SQL database. The parameters are derived from the original
146
// invoice insert parameters.
147
func toInsertMigratedInvoiceParams(
148
        params sqlc.InsertInvoiceParams) sqlc.InsertMigratedInvoiceParams {
20,004✔
149

20,004✔
150
        return sqlc.InsertMigratedInvoiceParams{
20,004✔
151
                Hash:               params.Hash,
20,004✔
152
                Preimage:           params.Preimage,
20,004✔
153
                Memo:               params.Memo,
20,004✔
154
                AmountMsat:         params.AmountMsat,
20,004✔
155
                CltvDelta:          params.CltvDelta,
20,004✔
156
                Expiry:             params.Expiry,
20,004✔
157
                PaymentAddr:        params.PaymentAddr,
20,004✔
158
                PaymentRequest:     params.PaymentRequest,
20,004✔
159
                PaymentRequestHash: params.PaymentRequestHash,
20,004✔
160
                State:              params.State,
20,004✔
161
                AmountPaidMsat:     params.AmountPaidMsat,
20,004✔
162
                IsAmp:              params.IsAmp,
20,004✔
163
                IsHodl:             params.IsHodl,
20,004✔
164
                IsKeysend:          params.IsKeysend,
20,004✔
165
                CreatedAt:          params.CreatedAt,
20,004✔
166
        }
20,004✔
167
}
20,004✔
168

169
// MigrateSingleInvoice migrates a single invoice to the new SQL schema. Note
170
// that perfect equality between the old and new schemas is not achievable, as
171
// the invoice's add index cannot be mapped directly to its ID due to SQL’s
172
// auto-incrementing primary key. The ID returned from the insert will instead
173
// serve as the add index in the new schema.
174
func MigrateSingleInvoice(ctx context.Context, tx SQLInvoiceQueries,
175
        invoice *Invoice, paymentHash lntypes.Hash) error {
20,004✔
176

20,004✔
177
        insertInvoiceParams, err := makeInsertInvoiceParams(
20,004✔
178
                invoice, paymentHash,
20,004✔
179
        )
20,004✔
180
        if err != nil {
20,004✔
181
                return err
×
182
        }
×
183

184
        // Convert the insert invoice parameters to the migrated invoice insert
185
        // parameters.
186
        insertMigratedInvoiceParams := toInsertMigratedInvoiceParams(
20,004✔
187
                insertInvoiceParams,
20,004✔
188
        )
20,004✔
189

20,004✔
190
        // If the invoice is settled, we'll also set the timestamp and the index
20,004✔
191
        // at which it was settled.
20,004✔
192
        if invoice.State == ContractSettled {
25,522✔
193
                if invoice.SettleIndex == 0 {
5,518✔
194
                        return fmt.Errorf("settled invoice %s missing settle "+
×
195
                                "index", paymentHash)
×
196
                }
×
197

198
                if invoice.SettleDate.IsZero() {
5,518✔
199
                        return fmt.Errorf("settled invoice %s missing settle "+
×
200
                                "date", paymentHash)
×
201
                }
×
202

203
                insertMigratedInvoiceParams.SettleIndex = sqldb.SQLInt64(
5,518✔
204
                        invoice.SettleIndex,
5,518✔
205
                )
5,518✔
206
                insertMigratedInvoiceParams.SettledAt = sqldb.SQLTime(
5,518✔
207
                        invoice.SettleDate.UTC(),
5,518✔
208
                )
5,518✔
209
        }
210

211
        // First we need to insert the invoice itself so we can use the "add
212
        // index" which in this case is the auto incrementing primary key that
213
        // is returned from the insert.
214
        invoiceID, err := tx.InsertMigratedInvoice(
20,004✔
215
                ctx, insertMigratedInvoiceParams,
20,004✔
216
        )
20,004✔
217
        if err != nil {
20,004✔
218
                return fmt.Errorf("unable to insert invoice: %w", err)
×
219
        }
×
220

221
        // Insert the invoice's features.
222
        for feature := range invoice.Terms.Features.Features() {
34,416✔
223
                params := sqlc.InsertInvoiceFeatureParams{
14,412✔
224
                        InvoiceID: invoiceID,
14,412✔
225
                        Feature:   int32(feature),
14,412✔
226
                }
14,412✔
227

14,412✔
228
                err := tx.InsertInvoiceFeature(ctx, params)
14,412✔
229
                if err != nil {
14,412✔
230
                        return fmt.Errorf("unable to insert invoice "+
×
231
                                "feature(%v): %w", feature, err)
×
232
                }
×
233
        }
234

235
        sqlHtlcIDs := make(map[models.CircuitKey]int64)
20,004✔
236

20,004✔
237
        // Now insert the HTLCs of the invoice. We'll also keep track of the SQL
20,004✔
238
        // ID of each HTLC so we can use it when inserting the AMP sub invoices.
20,004✔
239
        for circuitKey, htlc := range invoice.Htlcs {
115,657✔
240
                htlcParams := sqlc.InsertInvoiceHTLCParams{
95,653✔
241
                        HtlcID: int64(circuitKey.HtlcID),
95,653✔
242
                        ChanID: strconv.FormatUint(
95,653✔
243
                                circuitKey.ChanID.ToUint64(), 10,
95,653✔
244
                        ),
95,653✔
245
                        AmountMsat:   int64(htlc.Amt),
95,653✔
246
                        AcceptHeight: int32(htlc.AcceptHeight),
95,653✔
247
                        AcceptTime:   htlc.AcceptTime.UTC(),
95,653✔
248
                        ExpiryHeight: int32(htlc.Expiry),
95,653✔
249
                        State:        int16(htlc.State),
95,653✔
250
                        InvoiceID:    invoiceID,
95,653✔
251
                }
95,653✔
252

95,653✔
253
                // Leave the MPP amount as NULL if the MPP total amount is zero.
95,653✔
254
                if htlc.MppTotalAmt != 0 {
114,043✔
255
                        htlcParams.TotalMppMsat = sqldb.SQLInt64(
18,390✔
256
                                int64(htlc.MppTotalAmt),
18,390✔
257
                        )
18,390✔
258
                }
18,390✔
259

260
                // Leave the resolve time as NULL if the HTLC is not resolved.
261
                if !htlc.ResolveTime.IsZero() {
147,035✔
262
                        htlcParams.ResolveTime = sqldb.SQLTime(
51,382✔
263
                                htlc.ResolveTime.UTC(),
51,382✔
264
                        )
51,382✔
265
                }
51,382✔
266

267
                sqlID, err := tx.InsertInvoiceHTLC(ctx, htlcParams)
95,653✔
268
                if err != nil {
95,653✔
269
                        return fmt.Errorf("unable to insert invoice htlc: %w",
×
270
                                err)
×
271
                }
×
272

273
                sqlHtlcIDs[circuitKey] = sqlID
95,653✔
274

95,653✔
275
                // Store custom records.
95,653✔
276
                for key, value := range htlc.CustomRecords {
304,229✔
277
                        err = tx.InsertInvoiceHTLCCustomRecord(
208,576✔
278
                                ctx, sqlc.InsertInvoiceHTLCCustomRecordParams{
208,576✔
279
                                        Key:    int64(key),
208,576✔
280
                                        Value:  value,
208,576✔
281
                                        HtlcID: sqlID,
208,576✔
282
                                },
208,576✔
283
                        )
208,576✔
284
                        if err != nil {
208,576✔
285
                                return err
×
286
                        }
×
287
                }
288
        }
289

290
        if !invoice.IsAMP() {
30,804✔
291
                return nil
10,800✔
292
        }
10,800✔
293

294
        for setID, ampState := range invoice.AMPState {
35,033✔
295
                // Find the earliest HTLC of the AMP invoice, which will
25,829✔
296
                // be used as the creation date of this sub invoice.
25,829✔
297
                var createdAt time.Time
25,829✔
298
                for circuitKey := range ampState.InvoiceKeys {
98,985✔
299
                        htlc := invoice.Htlcs[circuitKey]
73,156✔
300
                        if createdAt.IsZero() {
98,985✔
301
                                createdAt = htlc.AcceptTime.UTC()
25,829✔
302
                                continue
25,829✔
303
                        }
304

305
                        if createdAt.After(htlc.AcceptTime) {
64,894✔
306
                                createdAt = htlc.AcceptTime.UTC()
17,567✔
307
                        }
17,567✔
308
                }
309

310
                params := sqlc.InsertAMPSubInvoiceParams{
25,829✔
311
                        SetID:     setID[:],
25,829✔
312
                        State:     int16(ampState.State),
25,829✔
313
                        CreatedAt: createdAt,
25,829✔
314
                        InvoiceID: invoiceID,
25,829✔
315
                }
25,829✔
316

25,829✔
317
                if ampState.SettleIndex != 0 {
33,054✔
318
                        if ampState.SettleDate.IsZero() {
7,225✔
319
                                return fmt.Errorf("settled AMP sub invoice %x "+
×
320
                                        "missing settle date", setID)
×
321
                        }
×
322

323
                        params.SettledAt = sqldb.SQLTime(
7,225✔
324
                                ampState.SettleDate.UTC(),
7,225✔
325
                        )
7,225✔
326

7,225✔
327
                        params.SettleIndex = sqldb.SQLInt64(
7,225✔
328
                                ampState.SettleIndex,
7,225✔
329
                        )
7,225✔
330
                }
331

332
                err := tx.InsertAMPSubInvoice(ctx, params)
25,829✔
333
                if err != nil {
25,829✔
334
                        return fmt.Errorf("unable to insert AMP sub invoice: "+
×
335
                                "%w", err)
×
336
                }
×
337

338
                // Now we can add the AMP HTLCs to the database.
339
                for circuitKey := range ampState.InvoiceKeys {
98,985✔
340
                        htlc := invoice.Htlcs[circuitKey]
73,156✔
341
                        rootShare := htlc.AMP.Record.RootShare()
73,156✔
342

73,156✔
343
                        sqlHtlcID, ok := sqlHtlcIDs[circuitKey]
73,156✔
344
                        if !ok {
73,156✔
345
                                return fmt.Errorf("missing htlc for AMP htlc: "+
×
346
                                        "%v", circuitKey)
×
347
                        }
×
348

349
                        params := sqlc.InsertAMPSubInvoiceHTLCParams{
73,156✔
350
                                InvoiceID:  invoiceID,
73,156✔
351
                                SetID:      setID[:],
73,156✔
352
                                HtlcID:     sqlHtlcID,
73,156✔
353
                                RootShare:  rootShare[:],
73,156✔
354
                                ChildIndex: int64(htlc.AMP.Record.ChildIndex()),
73,156✔
355
                                Hash:       htlc.AMP.Hash[:],
73,156✔
356
                        }
73,156✔
357

73,156✔
358
                        if htlc.AMP.Preimage != nil {
146,312✔
359
                                params.Preimage = htlc.AMP.Preimage[:]
73,156✔
360
                        }
73,156✔
361

362
                        err = tx.InsertAMPSubInvoiceHTLC(ctx, params)
73,156✔
363
                        if err != nil {
73,156✔
364
                                return fmt.Errorf("unable to insert AMP sub "+
×
365
                                        "invoice: %w", err)
×
366
                        }
×
367
                }
368
        }
369

370
        return nil
9,204✔
371
}
372

373
// OverrideInvoiceTimeZone overrides the time zone of the invoice to the local
374
// time zone and chops off the nanosecond part for comparison. This is needed
375
// because KV database stores times as-is which as an unwanted side effect would
376
// fail migration due to time comparison expecting both the original and
377
// migrated invoices to be in the same local time zone and in microsecond
378
// precision. Note that PostgreSQL stores times in microsecond precision while
379
// SQLite can store times in nanosecond precision if using TEXT storage class.
380
func OverrideInvoiceTimeZone(invoice *Invoice) {
40,016✔
381
        fixTime := func(t time.Time) time.Time {
399,616✔
382
                return t.In(time.Local).Truncate(time.Microsecond)
359,600✔
383
        }
359,600✔
384

385
        invoice.CreationDate = fixTime(invoice.CreationDate)
40,016✔
386

40,016✔
387
        if !invoice.SettleDate.IsZero() {
51,052✔
388
                invoice.SettleDate = fixTime(invoice.SettleDate)
11,036✔
389
        }
11,036✔
390

391
        if invoice.IsAMP() {
58,432✔
392
                for setID, ampState := range invoice.AMPState {
70,078✔
393
                        if ampState.SettleDate.IsZero() {
88,870✔
394
                                continue
37,208✔
395
                        }
396

397
                        ampState.SettleDate = fixTime(ampState.SettleDate)
14,454✔
398
                        invoice.AMPState[setID] = ampState
14,454✔
399
                }
400
        }
401

402
        for _, htlc := range invoice.Htlcs {
231,334✔
403
                if !htlc.AcceptTime.IsZero() {
382,636✔
404
                        htlc.AcceptTime = fixTime(htlc.AcceptTime)
191,318✔
405
                }
191,318✔
406

407
                if !htlc.ResolveTime.IsZero() {
294,094✔
408
                        htlc.ResolveTime = fixTime(htlc.ResolveTime)
102,776✔
409
                }
102,776✔
410
        }
411
}
412

413
// MigrateInvoicesToSQL runs the migration of all invoices from the KV database
414
// to the SQL database. The migration is done in a single transaction to ensure
415
// that all invoices are migrated or none at all. This function can be run
416
// multiple times without causing any issues as it will check if the migration
417
// has already been performed.
418
func MigrateInvoicesToSQL(ctx context.Context, db kvdb.Backend,
419
        kvStore InvoiceDB, tx *sqlc.Queries, batchSize int) error {
4✔
420

4✔
421
        log.Infof("Starting migration of invoices from KV to SQL")
4✔
422

4✔
423
        offset := uint64(0)
4✔
424
        t0 := time.Now()
4✔
425

4✔
426
        // Create the hash index which we will use to look up invoice
4✔
427
        // payment hashes by their add index during migration.
4✔
428
        err := createInvoiceHashIndex(ctx, db, tx)
4✔
429
        if err != nil && !errors.Is(err, ErrNoInvoicesCreated) {
4✔
430
                log.Errorf("Unable to create invoice hash index: %v",
×
431
                        err)
×
432

×
433
                return err
×
434
        }
×
435
        log.Debugf("Created SQL invoice hash index in %v", time.Since(t0))
4✔
436

4✔
437
        s := rate.Sometimes{
4✔
438
                Interval: 30 * time.Second,
4✔
439
        }
4✔
440

4✔
441
        t0 = time.Now()
4✔
442
        chunk := 0
4✔
443
        total := 0
4✔
444

4✔
445
        // Now we can start migrating the invoices. We'll do this in
4✔
446
        // batches to reduce memory usage.
4✔
447
        for {
10✔
448
                query := InvoiceQuery{
6✔
449
                        IndexOffset:    offset,
6✔
450
                        NumMaxInvoices: uint64(batchSize),
6✔
451
                }
6✔
452

6✔
453
                queryResult, err := kvStore.QueryInvoices(ctx, query)
6✔
454
                if err != nil && !errors.Is(err, ErrNoInvoicesCreated) {
6✔
NEW
455
                        return fmt.Errorf("unable to query invoices: %w", err)
×
456
                }
×
457

458
                if len(queryResult.Invoices) == 0 {
10✔
459
                        log.Infof("All invoices migrated. Total: %d", total)
4✔
460
                        break
4✔
461
                }
462

463
                err = migrateInvoices(ctx, tx, queryResult.Invoices)
2✔
464
                if err != nil {
2✔
465
                        return err
×
466
                }
×
467

468
                offset = queryResult.LastIndexOffset
2✔
469
                resultCnt := len(queryResult.Invoices)
2✔
470
                total += resultCnt
2✔
471
                chunk += resultCnt
2✔
472

2✔
473
                s.Do(func() {
4✔
474
                        elapsed := time.Since(t0).Seconds()
2✔
475
                        ratePerSec := float64(chunk) / elapsed
2✔
476
                        log.Debugf("Migrated %d invoices (%.2f invoices/sec)",
2✔
477
                                total, ratePerSec)
2✔
478

2✔
479
                        t0 = time.Now()
2✔
480
                        chunk = 0
2✔
481
                })
2✔
482
        }
483

484
        // Clean up the hash index as it's no longer needed.
485
        err = tx.ClearKVInvoiceHashIndex(ctx)
4✔
486
        if err != nil {
4✔
487
                return fmt.Errorf("unable to clear invoice hash "+
×
488
                        "index: %w", err)
×
489
        }
×
490

491
        log.Infof("Migration of %d invoices from KV to SQL completed", total)
4✔
492

4✔
493
        return nil
4✔
494
}
495

496
func migrateInvoices(ctx context.Context, tx *sqlc.Queries,
497
        invoices []Invoice) error {
2✔
498

2✔
499
        for i, invoice := range invoices {
6✔
500
                var paymentHash lntypes.Hash
4✔
501
                if invoice.Terms.PaymentPreimage != nil {
4✔
502
                        paymentHash = invoice.Terms.PaymentPreimage.Hash()
×
503
                } else {
4✔
504
                        paymentHashBytes, err :=
4✔
505
                                tx.GetKVInvoicePaymentHashByAddIndex(
4✔
506
                                        ctx, int64(invoice.AddIndex),
4✔
507
                                )
4✔
508
                        if err != nil {
4✔
509
                                // This would be an unexpected inconsistency
×
510
                                // in the kv database. We can't do much here
×
511
                                // so we'll notify the user and continue.
×
512
                                log.Warnf("Cannot migrate invoice, unable to "+
×
513
                                        "fetch payment hash (add_index=%v): %v",
×
514
                                        invoice.AddIndex, err)
×
515

×
516
                                continue
×
517
                        }
518

519
                        copy(paymentHash[:], paymentHashBytes)
4✔
520
                }
521

522
                err := MigrateSingleInvoice(ctx, tx, &invoices[i], paymentHash)
4✔
523
                if err != nil {
4✔
524
                        return fmt.Errorf("unable to migrate invoice(%v): %w",
×
525
                                paymentHash, err)
×
526
                }
×
527

528
                migratedInvoice, err := fetchInvoice(
4✔
529
                        ctx, tx, InvoiceRefByHash(paymentHash),
4✔
530
                )
4✔
531
                if err != nil {
4✔
532
                        return fmt.Errorf("unable to fetch migrated "+
×
533
                                "invoice(%v): %w", paymentHash, err)
×
534
                }
×
535

536
                // Override the time zone for comparison. Note that we need to
537
                // override both invoices as the original invoice is coming from
538
                // KV database, it was stored as a binary serialized Go
539
                // time.Time value which has nanosecond precision but might have
540
                // been created in a different time zone. The migrated invoice
541
                // is stored in SQL in UTC and selected in the local time zone,
542
                // however in PostgreSQL it has microsecond precision while in
543
                // SQLite it has nanosecond precision if using TEXT storage
544
                // class.
545
                OverrideInvoiceTimeZone(&invoice)
4✔
546
                OverrideInvoiceTimeZone(migratedInvoice)
4✔
547

4✔
548
                // Override the add index before checking for equality.
4✔
549
                migratedInvoice.AddIndex = invoice.AddIndex
4✔
550

4✔
551
                if !reflect.DeepEqual(invoice, *migratedInvoice) {
4✔
552
                        diff := difflib.UnifiedDiff{
×
553
                                A: difflib.SplitLines(
×
554
                                        spew.Sdump(invoice),
×
555
                                ),
×
556
                                B: difflib.SplitLines(
×
557
                                        spew.Sdump(migratedInvoice),
×
558
                                ),
×
559
                                FromFile: "Expected",
×
560
                                FromDate: "",
×
561
                                ToFile:   "Actual",
×
562
                                ToDate:   "",
×
563
                                Context:  3,
×
564
                        }
×
565
                        diffText, _ := difflib.GetUnifiedDiffString(diff)
×
566

×
567
                        return fmt.Errorf("%w: %v.\n%v", ErrMigrationMismatch,
×
568
                                paymentHash, diffText)
×
569
                }
×
570
        }
571

572
        return nil
2✔
573
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc