Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyMigrations(ctx context.Context, db *BaseDB, migrator MigrationExecutor, ...) error
- func CompareRecords(original, migrated any, identifier string) error
- func DisableLog()
- func ExecuteBatchQuery[I any, T any, R any](ctx context.Context, cfg *QueryConfig, inputItems []I, ...) error
- func ExecuteCollectAndBatchWithSharedDataQuery[C any, T any, I any, D any](ctx context.Context, cfg *QueryConfig, initialCursor C, ...) error
- func ExecutePaginatedQuery[C any, T any](ctx context.Context, cfg *QueryConfig, initialCursor C, ...) error
- func ExecuteSQLTransactionWithRetry(ctx context.Context, makeTx MakeTx, rollbackTx RollbackTx, txBody TxBody, ...) error
- func ExtractSqlInt16[T constraints.Integer](num sql.NullInt16) T
- func IsSerializationError(err error) bool
- func MapSQLError(err error) error
- func SQLBool(b bool) sql.NullBool
- func SQLInt16[T constraints.Integer](num T) sql.NullInt16
- func SQLInt32[T constraints.Integer](num T) sql.NullInt32
- func SQLInt64[T constraints.Integer](num T) sql.NullInt64
- func SQLStr(s string) sql.NullString
- func SQLStrValid(s string) sql.NullString
- func SQLTime(t time.Time) sql.NullTime
- func UseLogger(logger btclog.Logger)
- type BaseDB
- type BatchQueryFunc
- type BatchedQuerier
- type BatchedTx
- type CollectAndBatchDataQueryFunc
- type CollectFunc
- type ConvertFunc
- type CursorExtractFunc
- type DB
- type ErrSQLUniqueConstraintViolation
- type ErrSerializationError
- type ItemCallbackFunc
- type ItemProcessFunc
- type ItemWithBatchDataProcessFunc
- type MakeTx
- type MigrationConfig
- type MigrationExecutor
- type MigrationTarget
- type OnBackoff
- type PagedQueryFunc
- type PostgresConfig
- type PostgresStore
- func (s *PostgresStore) ApplyAllMigrations(ctx context.Context, migrations []MigrationConfig) error
- func (s *PostgresStore) ExecuteMigrations(target MigrationTarget) error
- func (s *PostgresStore) GetBaseDB() *BaseDB
- func (s *PostgresStore) GetSchemaVersion() (int, bool, error)
- func (s *PostgresStore) SetSchemaVersion(version int, dirty bool) error
- type QueryConfig
- type QueryCreator
- type RollbackTx
- type SqliteConfig
- type SqliteStore
- func (s *SqliteStore) ApplyAllMigrations(ctx context.Context, migrations []MigrationConfig) error
- func (s *SqliteStore) ExecuteMigrations(target MigrationTarget) error
- func (s *SqliteStore) GetBaseDB() *BaseDB
- func (s *SqliteStore) GetSchemaVersion() (int, bool, error)
- func (s *SqliteStore) SetSchemaVersion(version int, dirty bool) error
- type TestPgFixture
- type TransactionExecutor
- type Tx
- type TxBody
- type TxExecutorOption
- type TxOptions
Constants ¶
const ( // DefaultNumTxRetries is the default number of times we'll retry a // transaction if it fails with an error that permits transaction // repetition. DefaultNumTxRetries = 20 // DefaultRetryDelay is the default delay between retries. This will be // used to generate a random delay between 0 and this value. DefaultRetryDelay = time.Millisecond * 50 // DefaultMaxRetryDelay is the default maximum delay between retries. DefaultMaxRetryDelay = time.Second )
const (
PostgresTag = "11"
)
const Subsystem = "SQLD"
Subsystem defines the logging code for this subsystem.
Variables ¶
var ( // TargetLatest is a MigrationTarget that migrates to the latest // version available. TargetLatest = func(mig *migrate.Migrate) error { return mig.Up() } // TargetVersion is a MigrationTarget that migrates to the given // version. TargetVersion = func(version uint) MigrationTarget { return func(mig *migrate.Migrate) error { return mig.Migrate(version) } } )
var ( // DefaultPostgresFixtureLifetime is the default maximum time a Postgres // test fixture is being kept alive. After that time the docker // container will be terminated forcefully, even if the tests aren't // fully executed yet. So this time needs to be chosen correctly to be // longer than the longest expected individual test run time. DefaultPostgresFixtureLifetime = 10 * time.Minute )
var ( // DefaultStoreTimeout is the default timeout used for any interaction // with the storage/database. DefaultStoreTimeout = time.Second * 10 )
var ( // ErrMigrationMismatch is returned when a migrated record does not // match the original record. ErrMigrationMismatch = fmt.Errorf("migrated record does not match " + "original record") )
var ( // ErrRetriesExceeded is returned when a transaction is retried more // than the max allowed valued without a success. ErrRetriesExceeded = errors.New("db tx retries exceeded") )
var NoOpReset = func() {}
NoOpReset is a no-op function that can be used as a default reset function ExecTx calls.
Functions ¶
func ApplyMigrations ¶ added in v1.0.7
func ApplyMigrations(ctx context.Context, db *BaseDB, migrator MigrationExecutor, migrations []MigrationConfig) error
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.
func CompareRecords ¶ added in v1.0.11
CompareRecords checks if the original and migrated objects are equal. If they are not, it returns an error with a unified diff of the two objects.
func DisableLog ¶
func DisableLog()
DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.
func ExecuteBatchQuery ¶ added in v1.0.11
func ExecuteBatchQuery[I any, T any, R any](ctx context.Context, cfg *QueryConfig, inputItems []I, convertFunc ConvertFunc[I, T], queryFunc BatchQueryFunc[T, R], callback ItemCallbackFunc[R]) error
ExecuteBatchQuery executes a query in batches over a slice of input items. It converts the input items to a query type using the provided convertFunc, executes the query in batches using the provided queryFunc, and applies the callback to each result. This is useful for queries using the "WHERE x IN []slice" pattern. It takes that slice, splits it into batches of size MaxBatchSize, and executes the query for each batch.
NOTE: it is the caller's responsibility to ensure that the expected return results are unique across all pages. Meaning that if the input items are split up, a result that is returned in one page should not be expected to be returned in another page.
func ExecuteCollectAndBatchWithSharedDataQuery ¶ added in v1.0.11
func ExecuteCollectAndBatchWithSharedDataQuery[C any, T any, I any, D any]( ctx context.Context, cfg *QueryConfig, initialCursor C, pageQueryFunc PagedQueryFunc[C, T], extractPageCursor CursorExtractFunc[T, C], collectFunc CollectFunc[T, I], batchDataFunc CollectAndBatchDataQueryFunc[I, D], processItem ItemWithBatchDataProcessFunc[T, D]) error
ExecuteCollectAndBatchWithSharedDataQuery implements a page-by-page processing pattern where each page is immediately processed with batch-loaded data before moving to the next page.
It: 1. Fetches a page of items using cursor-based pagination 2. Collects identifiers from that page and batch loads shared data 3. Processes each item in the page with the shared batch data 4. Moves to the next page and repeats
Parameters: - initialCursor: starting cursor for pagination - pageQueryFunc: fetches a page of items - extractPageCursor: extracts cursor from paginated item for next page - collectFunc: extracts identifier from paginated item - batchDataFunc: batch loads shared data from collected IDs for one page - processItem: processes each item with the shared batch data
func ExecutePaginatedQuery ¶ added in v1.0.11
func ExecutePaginatedQuery[C any, T any](ctx context.Context, cfg *QueryConfig, initialCursor C, queryFunc PagedQueryFunc[C, T], extractCursor CursorExtractFunc[T, C], processItem ItemProcessFunc[T]) error
ExecutePaginatedQuery executes a cursor-based paginated query. It continues fetching pages until no more results are returned, processing each item with the provided callback.
Parameters: - initialCursor: the starting cursor value (e.g., 0, -1, "", etc.). - queryFunc: function that fetches a page given cursor and limit. - extractCursor: function that extracts cursor from an item for next page. - processItem: function that processes each individual item.
NOTE: it is the caller's responsibility to "undo" any processing done on items if the query fails on a later page.
func ExecuteSQLTransactionWithRetry ¶ added in v1.0.1
func ExecuteSQLTransactionWithRetry(ctx context.Context, makeTx MakeTx, rollbackTx RollbackTx, txBody TxBody, onBackoff OnBackoff, numRetries int) error
ExecuteSQLTransactionWithRetry is a helper function that executes a transaction with retry logic. It will retry the transaction if it fails with a serialization error. The function will return an error if the transaction fails with a non-retryable error, the context is cancelled or the number of retries is exceeded.
func ExtractSqlInt16 ¶ added in v1.0.11
func ExtractSqlInt16[T constraints.Integer](num sql.NullInt16) T
ExtractSqlInt16 turns a NullInt16 into a numerical type. This can be useful when reading directly from the database, as this function handles extracting the inner value from the "option"-like struct.
func IsSerializationError ¶
IsSerializationError returns true if the given error is a serialization error.
func MapSQLError ¶
MapSQLError attempts to interpret a given error as a database agnostic SQL error.
func SQLBool ¶ added in v1.0.11
SQLBool turns a boolean into the NullBool that sql/sqlc uses when a boolean can be permitted to be NULL.
func SQLInt16 ¶ added in v1.0.11
func SQLInt16[T constraints.Integer](num T) sql.NullInt16
SQLInt16 turns a numerical integer type into the NullInt16 that sql/sqlc uses when an integer field can be permitted to be NULL.
We use this constraints.Integer constraint here which maps to all signed and unsigned integer types.
func SQLInt32 ¶
func SQLInt32[T constraints.Integer](num T) sql.NullInt32
SQLInt32 turns a numerical integer type into the NullInt32 that sql/sqlc uses when an integer field can be permitted to be NULL.
We use this constraints.Integer constraint here which maps to all signed and unsigned integer types.
func SQLInt64 ¶
func SQLInt64[T constraints.Integer](num T) sql.NullInt64
SQLInt64 turns a numerical integer type into the NullInt64 that sql/sqlc uses when an integer field can be permitted to be NULL.
We use this constraints.Integer constraint here which maps to all signed and unsigned integer types.
func SQLStr ¶
func SQLStr(s string) sql.NullString
SQLStr turns a string into the NullString that sql/sqlc uses when a string can be permitted to be NULL.
NOTE: If the input string is empty, it returns a NullString with Valid set to false. If this is not the desired behavior, consider using SQLStrValid instead.
func SQLStrValid ¶ added in v1.0.11
func SQLStrValid(s string) sql.NullString
SQLStrValid turns a string into the NullString that sql/sqlc uses when a string can be permitted to be NULL.
NOTE: Valid is always set to true, even if the input string is empty.
Types ¶
type BaseDB ¶
BaseDB is the base database struct that each implementation can embed to gain some common functionality.
type BatchQueryFunc ¶ added in v1.0.11
BatchQueryFunc represents a function that takes a batch of converted items and returns results.
type BatchedQuerier ¶
type BatchedQuerier interface { // Querier is the underlying query source, this is in place so we can // pass a BatchedQuerier implementation directly into objects that // create a batched version of the normal methods they need. sqlc.Querier // BeginTx creates a new database transaction given the set of // transaction options. BeginTx(ctx context.Context, options TxOptions) (*sql.Tx, error) }
BatchedQuerier is a generic interface that allows callers to create a new database transaction based on an abstract type that implements the TxOptions interface.
type BatchedTx ¶
type BatchedTx[Q any] interface { // ExecTx will execute the passed txBody, operating upon generic // parameter Q (usually a storage interface) in a single transaction. // // The set of TxOptions are passed in order to allow the caller to // specify if a transaction should be read-only and optionally what // type of concurrency control should be used. ExecTx(ctx context.Context, txOptions TxOptions, txBody func(Q) error, reset func()) error }
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 interface allowing it to only depend on the routines it needs to implement any additional business logic.
type CollectAndBatchDataQueryFunc ¶ added in v1.0.11
type CollectAndBatchDataQueryFunc[ID any, BatchData any] func(context.Context, []ID) (BatchData, error)
CollectAndBatchDataQueryFunc represents a function that batch loads additional data for collected identifiers, returning the batch data that applies to all items.
type CollectFunc ¶ added in v1.0.11
CollectFunc represents a function that extracts an identifier from a paginated item.
type ConvertFunc ¶ added in v1.0.11
ConvertFunc represents a function that converts from input type to query type for the batch query.
type CursorExtractFunc ¶ added in v1.0.11
CursorExtractFunc represents a function that extracts the cursor value from an item. This cursor will be used for the next page fetch.
type DB ¶ added in v1.0.7
type DB interface { // GetBaseDB returns the underlying BaseDB instance. GetBaseDB() *BaseDB // ApplyAllMigrations applies all migrations to the database including // both sqlc and custom in-code migrations. ApplyAllMigrations(ctx context.Context, customMigrations []MigrationConfig) error }
DB is an interface that represents a generic SQL database. It provides methods to apply migrations and access the underlying database connection.
type ErrSQLUniqueConstraintViolation ¶
type ErrSQLUniqueConstraintViolation struct {
DBError error
}
ErrSQLUniqueConstraintViolation is an error type which represents a database agnostic SQL unique constraint violation.
func (ErrSQLUniqueConstraintViolation) Error ¶
func (e ErrSQLUniqueConstraintViolation) Error() string
type ErrSerializationError ¶
type ErrSerializationError struct {
DBError error
}
ErrSerializationError is an error type which represents a database agnostic error that a transaction couldn't be serialized with other concurrent db transactions.
func (ErrSerializationError) Error ¶
func (e ErrSerializationError) Error() string
Error returns the error message.
func (ErrSerializationError) Unwrap ¶
func (e ErrSerializationError) Unwrap() error
Unwrap returns the wrapped error.
type ItemCallbackFunc ¶ added in v1.0.11
ItemCallbackFunc represents a function that processes individual results.
type ItemProcessFunc ¶ added in v1.0.11
ItemProcessFunc represents a function that processes individual items.
type ItemWithBatchDataProcessFunc ¶ added in v1.0.11
ItemWithBatchDataProcessFunc represents a function that processes individual items along with shared batch data.
type MakeTx ¶ added in v1.0.1
MakeTx is a function that creates a new transaction. It returns a Tx and an error if the transaction cannot be created. This is used to abstract the creation of a transaction from the actual transaction logic in order to be able to reuse the transaction retry logic in other packages.
type MigrationConfig ¶ added in v1.0.7
type MigrationConfig struct { // Name is the name of the migration. Name string // Version represents the "global" database version for this migration. // Unlike the schema version tracked by golang-migrate, it encompasses // all migrations, including those managed by golang-migrate as well // as custom in-code migrations. Version int // SchemaVersion represents the schema version tracked by golang-migrate // at which the migration is applied. SchemaVersion int // MigrationFn is the function executed for custom migrations at the // specified version. It is used to handle migrations that cannot be // performed through SQL alone. If set to nil, no custom migration is // applied. MigrationFn func(tx *sqlc.Queries) error }
MigrationConfig is a configuration struct that describes SQL migrations. Each migration is associated with a specific schema version and a global database version. Migrations are applied in the order of their global database version. If a migration includes a non-nil MigrationFn, it is executed after the SQL schema has been migrated to the corresponding schema version.
func GetMigrations ¶ added in v1.0.7
func GetMigrations() []MigrationConfig
GetMigrations returns a copy of the migration configuration.
type MigrationExecutor ¶ added in v1.0.7
type MigrationExecutor interface { // ExecuteMigrations runs database migrations up to the specified target // version or all migrations if no target is specified. A migration may // include a schema change, a custom migration function, or both. // Developers must ensure that migrations are defined in the correct // order. Migration details are stored in the global variable // migrationConfig. ExecuteMigrations(target MigrationTarget) error // GetSchemaVersion returns the current schema version of the database. GetSchemaVersion() (int, bool, error) // SetSchemaVersion sets the schema version of the database. // // NOTE: This alters the internal database schema tracker. USE WITH // CAUTION!!! SetSchemaVersion(version int, dirty bool) error }
MigrationExecutor is an interface that abstracts the migration functionality.
type MigrationTarget ¶ added in v1.0.3
type MigrationTarget func(mig *migrate.Migrate) error
MigrationTarget is a functional option that can be passed to applyMigrations to specify a target version to migrate to.
type OnBackoff ¶ added in v1.0.1
OnBackoff is a function that is called when a transaction is retried due to a serialization error. The function is called with the retry attempt number and the delay before the next retry.
type PagedQueryFunc ¶ added in v1.0.11
PagedQueryFunc represents a function that fetches a page of results using a cursor. It returns the fetched items and should return an empty slice when no more results.
type PostgresConfig ¶
type PostgresConfig struct { Dsn string `long:"dsn" description:"Database connection string."` Timeout time.Duration `long:"timeout" description:"Database connection timeout. Set to zero to disable."` MaxConnections int `long:"maxconnections" description:"The maximum number of open connections to the database. Set to zero for unlimited."` SkipMigrations bool `long:"skipmigrations" description:"Skip applying migrations on startup."` QueryConfig `group:"query" namespace:"query"` }
PostgresConfig holds the postgres database configuration.
func (*PostgresConfig) Validate ¶
func (p *PostgresConfig) Validate() error
Validate checks that the PostgresConfig values are valid.
type PostgresStore ¶
type PostgresStore struct { *BaseDB // contains filtered or unexported fields }
PostgresStore is a database store implementation that uses a Postgres backend.
func NewPostgresStore ¶
func NewPostgresStore(cfg *PostgresConfig) (*PostgresStore, error)
NewPostgresStore creates a new store that is backed by a Postgres database backend.
func NewTestPostgresDB ¶
func NewTestPostgresDB(t testing.TB, fixture *TestPgFixture) *PostgresStore
NewTestPostgresDB is a helper function that creates a Postgres database for testing using the given fixture.
func NewTestPostgresDBWithVersion ¶ added in v1.0.3
func NewTestPostgresDBWithVersion(t *testing.T, fixture *TestPgFixture, version uint) *PostgresStore
NewTestPostgresDBWithVersion is a helper function that creates a Postgres database for testing and migrates it to the given version.
func (*PostgresStore) ApplyAllMigrations ¶ added in v1.0.7
func (s *PostgresStore) ApplyAllMigrations(ctx context.Context, migrations []MigrationConfig) error
ApplyAllMigrations applies both the SQLC and custom in-code migrations to the Postgres database.
func (*PostgresStore) ExecuteMigrations ¶ added in v1.0.3
func (s *PostgresStore) ExecuteMigrations(target MigrationTarget) error
ExecuteMigrations runs migrations for the Postgres database, depending on the target given, either all migrations or up to a given version.
func (*PostgresStore) GetBaseDB ¶ added in v1.0.7
func (s *PostgresStore) GetBaseDB() *BaseDB
GetBaseDB returns the underlying BaseDB instance for the Postgres store. It is a trivial helper method to comply with the sqldb.DB interface.
func (*PostgresStore) GetSchemaVersion ¶ added in v1.0.8
func (s *PostgresStore) GetSchemaVersion() (int, bool, error)
GetSchemaVersion returns the current schema version of the Postgres database.
func (*PostgresStore) SetSchemaVersion ¶ added in v1.0.8
func (s *PostgresStore) SetSchemaVersion(version int, dirty bool) error
SetSchemaVersion sets the schema version of the Postgres database.
NOTE: This alters the internal database schema tracker. USE WITH CAUTION!!!
type QueryConfig ¶ added in v1.0.11
type QueryConfig struct { // MaxBatchSize is the maximum number of items included in a batch // query IN clauses list. MaxBatchSize uint32 `` /* 178-byte string literal not displayed */ // MaxPageSize is the maximum number of items returned in a single page // of results. This is used for paginated queries. MaxPageSize uint32 `` /* 137-byte string literal not displayed */ }
QueryConfig holds configuration values for SQL queries.
func DefaultPostgresConfig ¶ added in v1.0.11
func DefaultPostgresConfig() *QueryConfig
DefaultPostgresConfig returns a default configuration for SQL queries to a Postgres backend.
func DefaultSQLiteConfig ¶ added in v1.0.11
func DefaultSQLiteConfig() *QueryConfig
DefaultSQLiteConfig returns a default configuration for SQL queries to a SQLite backend.
func (*QueryConfig) Validate ¶ added in v1.0.11
func (c *QueryConfig) Validate(sqlite bool) error
Validate checks that the QueryConfig values are valid.
type QueryCreator ¶
QueryCreator is a generic function that's used to create a Querier, which is a type of interface that implements storage related methods from a database transaction. This will be used to instantiate an object callers can use to apply multiple modifications to an object interface in a single atomic transaction.
type RollbackTx ¶ added in v1.0.1
RollbackTx is a function that is called when a transaction needs to be rolled back due to a serialization error. By using this intermediate function, we can avoid having to return rollback errors that are not actionable by the caller.
type SqliteConfig ¶
type SqliteConfig struct { Timeout time.Duration `long:"timeout" description:"The time after which a database query should be timed out."` BusyTimeout time.Duration `` /* 126-byte string literal not displayed */ MaxConnections int `long:"maxconnections" description:"The maximum number of open connections to the database. Set to zero for unlimited."` PragmaOptions []string `` /* 219-byte string literal not displayed */ SkipMigrations bool `long:"skipmigrations" description:"Skip applying migrations on startup."` QueryConfig `group:"query" namespace:"query"` }
SqliteConfig holds all the config arguments needed to interact with our sqlite DB.
func (*SqliteConfig) Validate ¶ added in v1.0.11
func (p *SqliteConfig) Validate() error
Validate checks that the SqliteConfig values are valid.
type SqliteStore ¶
type SqliteStore struct { *BaseDB // contains filtered or unexported fields }
SqliteStore is a database store implementation that uses a sqlite backend.
func NewSqliteStore ¶
func NewSqliteStore(cfg *SqliteConfig, dbPath string) (*SqliteStore, error)
NewSqliteStore attempts to open a new sqlite database based on the passed config.
func NewTestSqliteDB ¶
func NewTestSqliteDB(t testing.TB) *SqliteStore
NewTestSqliteDB is a helper function that creates an SQLite database for testing.
func NewTestSqliteDBWithVersion ¶ added in v1.0.3
func NewTestSqliteDBWithVersion(t *testing.T, version uint) *SqliteStore
NewTestSqliteDBWithVersion is a helper function that creates an SQLite database for testing and migrates it to the given version.
func (*SqliteStore) ApplyAllMigrations ¶ added in v1.0.7
func (s *SqliteStore) ApplyAllMigrations(ctx context.Context, migrations []MigrationConfig) error
ApplyAllMigrations applies both the SQLC and custom in-code migrations to the SQLite database.
func (*SqliteStore) ExecuteMigrations ¶ added in v1.0.3
func (s *SqliteStore) ExecuteMigrations(target MigrationTarget) error
ExecuteMigrations runs migrations for the sqlite database, depending on the target given, either all migrations or up to a given version.
func (*SqliteStore) GetBaseDB ¶ added in v1.0.7
func (s *SqliteStore) GetBaseDB() *BaseDB
GetBaseDB returns the underlying BaseDB instance for the SQLite store. It is a trivial helper method to comply with the sqldb.DB interface.
func (*SqliteStore) GetSchemaVersion ¶ added in v1.0.8
func (s *SqliteStore) GetSchemaVersion() (int, bool, error)
GetSchemaVersion returns the current schema version of the SQLite database.
func (*SqliteStore) SetSchemaVersion ¶ added in v1.0.8
func (s *SqliteStore) SetSchemaVersion(version int, dirty bool) error
SetSchemaVersion sets the schema version of the SQLite database.
NOTE: This alters the internal database schema tracker. USE WITH CAUTION!!!
type TestPgFixture ¶
type TestPgFixture struct {
// contains filtered or unexported fields
}
TestPgFixture is a test fixture that starts a Postgres 11 instance in a docker container.
func NewTestPgFixture ¶
func NewTestPgFixture(t testing.TB, expiry time.Duration) *TestPgFixture
NewTestPgFixture constructs a new TestPgFixture starting up a docker container running Postgres 11. The started container will expire in after the passed duration.
func (*TestPgFixture) GetConfig ¶
func (f *TestPgFixture) GetConfig(dbName string) *PostgresConfig
GetConfig returns the full config of the Postgres node.
func (*TestPgFixture) TearDown ¶
func (f *TestPgFixture) TearDown(t testing.TB)
TearDown stops the underlying docker container.
type TransactionExecutor ¶
type TransactionExecutor[Query any] struct { BatchedQuerier // contains filtered or unexported fields }
TransactionExecutor is a generic struct that abstracts away from the type of query a type needs to run under a database transaction, and also the set of options for that transaction. The QueryCreator is used to create a query given a database transaction created by the BatchedQuerier.
func NewTransactionExecutor ¶
func NewTransactionExecutor[Querier any](db BatchedQuerier, createQuery QueryCreator[Querier], opts ...TxExecutorOption) *TransactionExecutor[Querier]
NewTransactionExecutor creates a new instance of a TransactionExecutor given a Querier query object and a concrete type for the type of transactions the Querier understands.
func (*TransactionExecutor[Q]) ExecTx ¶
func (t *TransactionExecutor[Q]) ExecTx(ctx context.Context, txOptions TxOptions, txBody func(Q) error, reset func()) error
ExecTx is a wrapper for txBody to abstract the creation and commit of a db transaction. The db transaction is embedded in a `*Queries` that txBody needs to use when executing each one of the queries that need to be applied atomically. This can be used by other storage interfaces to parameterize the type of query and options run, in order to have access to batched operations related to a storage object.
type Tx ¶
type Tx interface { // Commit commits the database transaction, an error should be returned // if the commit isn't possible. Commit() error // Rollback rolls back an incomplete database transaction. // Transactions that were able to be committed can still call this as a // noop. Rollback() error }
Tx represents a database transaction that can be committed or rolled back.
type TxBody ¶ added in v1.0.1
TxBody represents the function type for transactions. It returns an error to indicate success or failure.
type TxExecutorOption ¶
type TxExecutorOption func(*txExecutorOptions)
TxExecutorOption is a functional option that allows us to pass in optional argument when creating the executor.
func WithTxRetries ¶
func WithTxRetries(numRetries int) TxExecutorOption
WithTxRetries is a functional option that allows us to specify the number of times a transaction should be retried if it fails with a repeatable error.
func WithTxRetryDelay ¶
func WithTxRetryDelay(delay time.Duration) TxExecutorOption
WithTxRetryDelay is a functional option that allows us to specify the delay to wait before a transaction is retried.
type TxOptions ¶
type TxOptions interface { // ReadOnly returns true if the transaction should be read only. ReadOnly() bool }
TxOptions represents a set of options one can use to control what type of database transaction is created. Transaction can be either read or write.
func ReadTxOpt ¶ added in v1.0.10
func ReadTxOpt() TxOptions
ReadTxOpt returns a TxOptions that indicates that the transaction should be a read-only transaction.
func WriteTxOpt ¶ added in v1.0.10
func WriteTxOpt() TxOptions
WriteTxOpt returns a TxOptions that indicates that the transaction should be a write transaction.