Documentation
¶
Index ¶
- Constants
- Variables
- func IsDeadlockError(err error) bool
- func IsSchemaError(err error) bool
- func IsSerializationError(err error) bool
- func IsSerializationOrDeadlockError(err error) bool
- func MapSQLError(err error) error
- func UseLogger(logger btclog.Logger)
- type BaseDB
- type BatchedQuerier
- type BatchedTx
- type ErrDeadlockError
- type ErrSchemaError
- type ErrSerializationError
- type ErrSqlUniqueConstraintViolation
- type MigrateOpt
- type MigrationTarget
- type PostgresConfig
- type PostgresStore
- type QueriesTxOptions
- type QueryCreator
- type SqliteConfig
- type SqliteStore
- type TestPgFixture
- type TransactionExecutor
- type Tx
- 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 = 10 // DefaultInitialRetryDelay is the default initial delay between // retries. This will be used to generate a random delay between -50% // and +50% of this value, so 20 to 60 milliseconds. The retry will be // doubled after each attempt until we reach DefaultMaxRetryDelay. We // start with a random value to avoid multiple goroutines that are // created at the same time to effectively retry at the same time. DefaultInitialRetryDelay = time.Millisecond * 40 // DefaultMaxRetryDelay is the default maximum delay between retries. DefaultMaxRetryDelay = time.Second * 3 )
const ( // LatestMigrationVersion is the latest migration version of the // database. This is used to implement downgrade protection for the // daemon. // // NOTE: This MUST be updated when a new migration is added. LatestMigrationVersion = 5 )
const (
PostgresTag = "15"
)
const Subsystem = "SQLD"
Variables ¶
var ( // TargetLatest is a MigrationTarget that migrates to the latest // version available. TargetLatest = func(mig *migrate.Migrate, _ int, _ uint) error { return mig.Up() } // TargetVersion is a MigrationTarget that migrates to the given // version. TargetVersion = func(version uint) MigrationTarget { return func(mig *migrate.Migrate, _ int, _ uint) 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 = 60 * time.Minute )
var ( // DefaultStoreTimeout is the default timeout used for any interaction // with the storage/database. DefaultStoreTimeout = time.Second * 10 )
var ( // ErrMigrationDowngrade is returned when a database downgrade is // detected. ErrMigrationDowngrade = errors.New("database downgrade detected") )
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") )
Functions ¶
func IsDeadlockError ¶
IsDeadlockError returns true if the given error is a deadlock error.
func IsSchemaError ¶
IsSchemaError returns true if the given error is a schema error.
func IsSerializationError ¶
IsSerializationError returns true if the given error is a serialization error.
func IsSerializationOrDeadlockError ¶
IsSerializationOrDeadlockError returns true if the given error is either a deadlock error or a serialization error.
func MapSQLError ¶
MapSQLError attempts to interpret a given error as a database agnostic SQL error.
Types ¶
type BaseDB ¶
BaseDB is the base database struct that each implementation can embed to gain some common functionality.
func (*BaseDB) Backend ¶
func (s *BaseDB) Backend() sqlc.BackendType
Backend returns the type of the database backend used.
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 // CustomQueries is the set of custom queries that we have manually // defined in addition to the ones generated by sqlc. sqlc.CustomQueries // 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 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) error // Backend returns the type of the database backend used. Backend() sqlc.BackendType }
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 ErrDeadlockError ¶
type ErrDeadlockError struct {
DbError error
}
ErrDeadlockError is an error type which represents a database agnostic error where transactions have led to cyclic dependencies in lock acquisition.
func (ErrDeadlockError) Error ¶
func (e ErrDeadlockError) Error() string
Error returns the error message.
func (ErrDeadlockError) Unwrap ¶
func (e ErrDeadlockError) Unwrap() error
Unwrap returns the wrapped error.
type ErrSchemaError ¶
type ErrSchemaError struct {
DbError error
}
ErrSchemaError is an error type which represents a database agnostic error that the schema of the database is incorrect for the given query.
func (ErrSchemaError) Error ¶
func (e ErrSchemaError) Error() string
Error returns the error message.
func (ErrSchemaError) Unwrap ¶
func (e ErrSchemaError) Unwrap() error
Unwrap returns the wrapped error.
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 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 MigrateOpt ¶
type MigrateOpt func(*migrateOptions)
MigrateOpt is a functional option that can be passed to migrate related methods to modify behavior.
func WithLatestVersion ¶
func WithLatestVersion(version uint) MigrateOpt
WithLatestVersion allows callers to override the default latest version setting.
type MigrationTarget ¶
type MigrationTarget func(mig *migrate.Migrate, currentDbVersion int, maxMigrationVersion uint) error
MigrationTarget is a functional option that can be passed to applyMigrations to specify a target version to migrate to. `currentDbVersion` is the current (migration) version of the database, or None if unknown. `maxMigrationVersion` is the maximum migration version known to the driver, or None if unknown.
type PostgresConfig ¶
type PostgresConfig struct { SkipMigrations bool `long:"skipmigrations" description:"Skip applying migrations on startup."` Host string `long:"host" description:"Database server hostname."` Port int `long:"port" description:"Database server port."` User string `long:"user" description:"Database user."` Password string `long:"password" description:"Database user's password."` DBName string `long:"dbname" description:"Database name to use."` MaxOpenConnections int `long:"maxconnections" description:"Max open connections to keep alive to the database server."` MaxIdleConnections int `long:"maxidleconnections" description:"Max number of idle connections to keep in the connection pool."` ConnMaxLifetime time.Duration `` /* 139-byte string literal not displayed */ ConnMaxIdleTime time.Duration `` /* 137-byte string literal not displayed */ RequireSSL bool `long:"requiressl" description:"Whether to require using SSL (mode: require) when connecting to the server."` }
PostgresConfig holds the postgres database configuration.
nolint:lll
func (*PostgresConfig) DSN ¶
func (s *PostgresConfig) DSN(hidePassword bool) string
DSN returns the dns to connect to the database.
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.T) *PostgresStore
NewTestPostgresDB is a helper function that creates a Postgres database for testing.
func NewTestPostgresDBWithVersion ¶
func NewTestPostgresDBWithVersion(t *testing.T, version uint) *PostgresStore
NewTestPostgresDBWithVersion is a helper function that creates a Postgres database for testing and migrates it to the given version.
func (*PostgresStore) ExecuteMigrations ¶
func (s *PostgresStore) ExecuteMigrations(target MigrationTarget, optFuncs ...MigrateOpt) error
ExecuteMigrations runs migrations for the Postgres database, depending on the target given, either all migrations or up to a given version.
type QueriesTxOptions ¶
type QueriesTxOptions struct {
// contains filtered or unexported fields
}
QueriesTxOptions defines the set of db txn options the SQLQueries understands.
func NewQueryReadTx ¶
func NewQueryReadTx() QueriesTxOptions
NewQueryReadTx creates a new read transaction option set.
func (*QueriesTxOptions) ReadOnly ¶
func (a *QueriesTxOptions) ReadOnly() bool
ReadOnly returns true if the transaction should be read only.
NOTE: This implements the TxOptions.
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 SqliteConfig ¶
type SqliteConfig struct { // SkipMigrations if true, then all the tables will be created on start // up if they don't already exist. SkipMigrations bool `long:"skipmigrations" description:"Skip applying migrations on startup."` // SkipMigrationDbBackup if true, then a backup of the database will not // be created before applying migrations. SkipMigrationDbBackup bool `long:"skipmigrationdbbackup" description:"Skip creating a backup of the database before applying migrations."` // DatabaseFileName is the full file path where the database file can be // found. DatabaseFileName string `long:"dbfile" description:"The full path to the database."` }
SqliteConfig holds all the config arguments needed to interact with our sqlite DB.
nolint: lll
type SqliteStore ¶
type SqliteStore struct { *BaseDB // contains filtered or unexported fields }
SqliteStore is a sqlite3 based database for the Taproot Asset daemon.
func NewSqliteStore ¶
func NewSqliteStore(cfg *SqliteConfig) (*SqliteStore, error)
NewSqliteStore attempts to open a new sqlite database based on the passed config.
func NewTestSqliteDB ¶
func NewTestSqliteDB(t *testing.T) *SqliteStore
NewTestSqliteDB is a helper function that creates an SQLite database for testing.
func NewTestSqliteDBWithVersion ¶
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 NewTestSqliteDbHandleFromPath ¶
func NewTestSqliteDbHandleFromPath(t *testing.T, dbPath string) *SqliteStore
NewTestSqliteDbHandleFromPath is a helper function that creates a SQLite database handle given a database file path.
func (*SqliteStore) ExecuteMigrations ¶
func (s *SqliteStore) ExecuteMigrations(target MigrationTarget, optFuncs ...MigrateOpt) error
ExecuteMigrations runs migrations for the sqlite database, depending on the target given, either all migrations or up to a given version.
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 ¶
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) ClearDB ¶
func (f *TestPgFixture) ClearDB(t *testing.T)
ClearDB clears the database.
func (*TestPgFixture) GetConfig ¶
func (f *TestPgFixture) GetConfig() *PostgresConfig
GetConfig returns the full config of the Postgres node.
func (*TestPgFixture) GetDSN ¶
func (f *TestPgFixture) GetDSN() string
GetDSN returns the DSN (Data Source Name) for the started Postgres node.
func (*TestPgFixture) TearDown ¶
func (f *TestPgFixture) TearDown(t *testing.T)
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]) Backend ¶
func (t *TransactionExecutor[Q]) Backend() sqlc.BackendType
Backend returns the type of the database backend used.
func (*TransactionExecutor[Q]) ExecTx ¶
func (t *TransactionExecutor[Q]) ExecTx(ctx context.Context, txOptions TxOptions, txBody func(Q) error) 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 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.