lnd/graph/db/migration1/test_sql.go
ziggie 932fbc33f0
graph/db/migration1: fix defer commit/rollback in test tx executor
The defer closure checked a local err variable for commit/rollback
decisions, but err remained nil after a successful BeginTx. When
txBody failed, the error was returned directly without assigning to
err, so the defer always committed instead of rolling back.

Additionally, since err was not a named return value, the defer's
Commit error assignment was silently swallowed.

Replace the error-prone defer pattern with explicit rollback on
txBody failure and a direct Commit return.
2026-02-25 18:52:34 +01:00

45 lines
872 B
Go

//go:build test_db_postgres || test_db_sqlite
package migration1
import (
"context"
"database/sql"
"github.com/lightningnetwork/lnd/graph/db/migration1/sqlc"
"github.com/lightningnetwork/lnd/sqldb"
)
// testBatchedSQLQueries is a simple implementation of BatchedSQLQueries for
// testing.
type testBatchedSQLQueries struct {
db *sql.DB
*sqlc.Queries
}
// ExecTx implements the transaction execution logic.
func (t *testBatchedSQLQueries) ExecTx(ctx context.Context,
txOpts sqldb.TxOptions, txBody func(SQLQueries) error,
reset func()) error {
sqlOptions := sql.TxOptions{
Isolation: sql.LevelSerializable,
ReadOnly: txOpts.ReadOnly(),
}
tx, err := t.db.BeginTx(ctx, &sqlOptions)
if err != nil {
return err
}
reset()
queries := sqlc.New(tx)
if err := txBody(queries); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}