multi: add a re-usable TxOptions type

Add a re-usable implementation of the sqldb.TxOptions interface and make
use of this in the various spots (invoices, batch and graph/db) where we
had previously defined individual implementations that were all doing
the same thing.
This commit is contained in:
Elle Mouton committed 2025-05-28 10:18:10 +02:00
1 parent 8e96bd0308
commit c4e6f23c5b
9 files changed
+79 -134

No files matched your search

+29
View File
@@ -39,6 +39,35 @@ type TxOptions interface {
ReadOnly() bool
}
// txOptions is a concrete implementation of the TxOptions interface.
type txOptions struct {
// readOnly indicates if the transaction should be read-only.
readOnly bool
}
// ReadOnly returns true if the transaction should be read only.
//
// NOTE: This is part of the TxOptions interface.
func (t *txOptions) ReadOnly() bool {
return t.readOnly
}
// WriteTxOpt returns a TxOptions that indicates that the transaction
// should be a write transaction.
func WriteTxOpt() TxOptions {
return &txOptions{
readOnly: false,
}
}
// ReadTxOpt returns a TxOptions that indicates that the transaction
// should be a read-only transaction.
func ReadTxOpt() TxOptions {
return &txOptions{
readOnly: true,
}
}
// BatchedTx is a generic interface that represents the ability to execute
// several operations to a given storage interface in a single atomic
// transaction. Typically, Q here will be some subset of the main sqlc.Querier
+2 -13
View File
@@ -330,17 +330,6 @@ func (t *replacerFile) Close() error {
return nil
}
// MigrationTxOptions is the implementation of the TxOptions interface for
// migration transactions.
type MigrationTxOptions struct {
}
// ReadOnly returns false to indicate that migration transactions are not read
// only.
func (m *MigrationTxOptions) ReadOnly() bool {
return false
}
// ApplyMigrations applies the provided migrations to the database in sequence.
// It ensures migrations are executed in the correct order, applying both custom
// migration functions and SQL migrations as needed.
@@ -433,12 +422,12 @@ func ApplyMigrations(ctx context.Context, db *BaseDB,
migration.SchemaVersion, err)
}
var opts MigrationTxOptions
opts := WriteTxOpt()
// Run the custom migration as a transaction to ensure
// atomicity. If successful, mark the migration as complete in
// the migration tracker table.
err = executor.ExecTx(ctx, &opts, func(tx *sqlc.Queries) error {
err = executor.ExecTx(ctx, opts, func(tx *sqlc.Queries) error {
// Apply the migration function if one is provided.
if migration.MigrationFn != nil {
log.Infof("Applying custom migration '%v' "+