sql

package
v1.7.0-alpha.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 28, 2024 License: MIT Imports: 30 Imported by: 4

Documentation

Overview

Package sql is a generated GoMock package.

Index

Constants

View Source
const (
	SchemaPath        = "schema/schema.sql"
	UpdatedSchemaPath = "schema/schema.sql.updated"
)

Variables

View Source
var (
	// ErrClosed is returned if database is closed.
	ErrClosed = errors.New("database closed")
	// ErrNoConnection is returned if pooled connection is not available.
	ErrNoConnection = errors.New("database: no free connection")
	// ErrNotFound is returned if requested record is not found.
	ErrNotFound = errors.New("database: not found")
	// ErrObjectExists is returned if database constraints didn't allow to insert an object.
	ErrObjectExists = errors.New("database: object exists")
	// ErrTooNew is returned if database version is newer than expected.
	ErrTooNew = errors.New("database version is too new")
	// ErrOldSchema is returned when the database version differs from the expected one
	// and migrations are disabled.
	ErrOldSchema = errors.New("old database version")
)

Functions

func AppendToCachedSlice added in v1.4.0

func AppendToCachedSlice[T any](db any, key QueryCacheItemKey, v T)

AppendToCachedSlice adds a value to the slice stored in the cache by invoking the specified SliceAppender. If the entry is not cached, the function does nothing.

func GetBlobSizes added in v1.4.1

func GetBlobSizes(db Executor, cmd string, ids [][]byte) (sizes []int, err error)

GetBlobSizes returns a slice containing the sizes of blobs corresponding to the specified ids. For non-existent ids the corresponding value is -1.

func InMemory

func InMemory(opts ...Opt) *sqliteDatabase

InMemory creates an in-memory database for testing and panics if there's an error.

func IsCached added in v1.4.1

func IsCached(db any) bool

IsCached returns true if the database is cached.

func IsNull added in v1.5.0

func IsNull(stmt *Statement, col int) bool

IsNull returns true if the specified result column is null.

func LoadBlob added in v1.4.1

func LoadBlob(db Executor, cmd string, id []byte, blob *Blob) error

LoadBlob loads an encoded blob.

func LoadDBSchemaScript added in v1.7.0

func LoadDBSchemaScript(db Executor) (string, error)

LoadDBSchemaScript retrieves the database schema as text.

func Open

func Open(uri string, opts ...Opt) (*sqliteDatabase, error)

Open database with options.

Database is opened in WAL mode and pragma synchronous=normal. https://sqlite.org/wal.html https://www.sqlite.org/pragma.html#pragma_synchronous

func OpenInMemory added in v1.7.0

func OpenInMemory(opts ...Opt) (*sqliteDatabase, error)

OpenInMemory creates an in-memory database.

func Vacuum added in v1.1.10

func Vacuum(db Executor) error

func Version added in v1.5.0

func Version(uri string) (int, error)

func WithCachedSubKey added in v1.4.0

func WithCachedSubKey[T any](
	ctx context.Context,
	db any,
	key QueryCacheItemKey,
	subKey QueryCacheSubKey,
	retrieve func(ctx context.Context) (T, error),
) (T, error)

WithCachedValue retrieves the specified value identified by the key and subKey from the cache. If the entry is absent from the cache, it's populated by calling retrieve func. Note that the retrieve func should never cause UpdateSlice to be called.

func WithCachedValue added in v1.4.0

func WithCachedValue[T any](
	ctx context.Context,
	db any,
	key QueryCacheItemKey,
	retrieve func(ctx context.Context) (T, error),
) (T, error)

WithCachedValue retrieves the specified value from the cache. If the entry is absent from the cache, it's populated by calling retrieve func. Note that the retrieve func should never cause UpdateSlice to be called.

Types

type Blob added in v1.4.1

type Blob struct {
	Bytes []byte
}

Blob represents a binary blob data. It can be reused efficiently across multiple data retrieval operations, minimizing reallocations of the underlying byte slice.

func (*Blob) FromColumn added in v1.6.0

func (b *Blob) FromColumn(stmt *Statement, col int)

func (*Blob) Resize added in v1.6.0

func (b *Blob) Resize(n int)

Resize the underlying byte slice to the specified size. The returned slice has length equal n, but it might have a larger capacity. Warning: it is not guaranteed to keep the old data.

type Database

type Database interface {
	Executor
	QueryCache
	Close() error
	QueryCount() int
	QueryCache() QueryCache
	Tx(ctx context.Context) (Transaction, error)
	WithTx(ctx context.Context, exec func(Transaction) error) error
	TxImmediate(ctx context.Context) (Transaction, error)
	WithTxImmediate(ctx context.Context, exec func(Transaction) error) error
	Intercept(key string, fn Interceptor)
	RemoveInterceptor(key string)
}

Database represents a database.

type Decoder

type Decoder func(*Statement) bool

Decoder for sqlite rows.

type Encoder

type Encoder func(*Statement)

Encoder for parameters. Both positional parameters: select block from blocks where id = ?1;

and named parameters are supported: select blocks from blocks where id = @id;

For complete information see https://www.sqlite.org/c3ref/bind_blob.html.

type Executor

type Executor interface {
	Exec(string, Encoder, Decoder) (int, error)
}

Executor is an interface for executing raw statement.

type Interceptor added in v1.7.0

type Interceptor func(query string) error

Interceptor is invoked on every query after it's added to a database using PushIntercept. The query will fail if Interceptor returns an error.

type LocalDatabase added in v1.7.0

type LocalDatabase interface {
	Database
	IsLocalDatabase()
}

LocalDatabase is a Database used for local node data.

type Migration added in v1.3.0

type Migration interface {
	Apply(db Executor, logger *zap.Logger) error
	Rollback() error
	Name() string
	Order() int
}

Migration is interface for migrations provider.

type MigrationList added in v1.7.0

type MigrationList []Migration

MigrationList denotes a list of migrations.

func LoadSQLMigrations added in v1.7.0

func LoadSQLMigrations(fsys fs.FS) (MigrationList, error)

func (MigrationList) AddMigration added in v1.7.0

func (l MigrationList) AddMigration(migration Migration) MigrationList

AddMigration adds a Migration to the MigrationList, overriding the migration with the same order number if it already exists. The function returns updated migration list. The state of the original migration list is undefined after calling this function.

func (MigrationList) Version added in v1.7.0

func (l MigrationList) Version() int

Version returns database version for the specified migration list.

type MockMigration added in v1.3.0

type MockMigration struct {
	// contains filtered or unexported fields
}

MockMigration is a mock of Migration interface.

func NewMockMigration added in v1.3.0

func NewMockMigration(ctrl *gomock.Controller) *MockMigration

NewMockMigration creates a new mock instance.

func (*MockMigration) Apply added in v1.3.0

func (m *MockMigration) Apply(db Executor, logger *zap.Logger) error

Apply mocks base method.

func (*MockMigration) EXPECT added in v1.3.0

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockMigration) Name added in v1.3.0

func (m *MockMigration) Name() string

Name mocks base method.

func (*MockMigration) Order added in v1.3.0

func (m *MockMigration) Order() int

Order mocks base method.

func (*MockMigration) Rollback added in v1.3.0

func (m *MockMigration) Rollback() error

Rollback mocks base method.

type MockMigrationApplyCall added in v1.4.0

type MockMigrationApplyCall struct {
	*gomock.Call
}

MockMigrationApplyCall wrap *gomock.Call

func (*MockMigrationApplyCall) Do added in v1.4.0

Do rewrite *gomock.Call.Do

func (*MockMigrationApplyCall) DoAndReturn added in v1.4.0

DoAndReturn rewrite *gomock.Call.DoAndReturn

func (*MockMigrationApplyCall) Return added in v1.4.0

Return rewrite *gomock.Call.Return

type MockMigrationMockRecorder added in v1.3.0

type MockMigrationMockRecorder struct {
	// contains filtered or unexported fields
}

MockMigrationMockRecorder is the mock recorder for MockMigration.

func (*MockMigrationMockRecorder) Apply added in v1.3.0

func (mr *MockMigrationMockRecorder) Apply(db, logger any) *MockMigrationApplyCall

Apply indicates an expected call of Apply.

func (*MockMigrationMockRecorder) Name added in v1.3.0

Name indicates an expected call of Name.

func (*MockMigrationMockRecorder) Order added in v1.3.0

Order indicates an expected call of Order.

func (*MockMigrationMockRecorder) Rollback added in v1.3.0

Rollback indicates an expected call of Rollback.

type MockMigrationNameCall added in v1.4.0

type MockMigrationNameCall struct {
	*gomock.Call
}

MockMigrationNameCall wrap *gomock.Call

func (*MockMigrationNameCall) Do added in v1.4.0

Do rewrite *gomock.Call.Do

func (*MockMigrationNameCall) DoAndReturn added in v1.4.0

func (c *MockMigrationNameCall) DoAndReturn(f func() string) *MockMigrationNameCall

DoAndReturn rewrite *gomock.Call.DoAndReturn

func (*MockMigrationNameCall) Return added in v1.4.0

Return rewrite *gomock.Call.Return

type MockMigrationOrderCall added in v1.4.0

type MockMigrationOrderCall struct {
	*gomock.Call
}

MockMigrationOrderCall wrap *gomock.Call

func (*MockMigrationOrderCall) Do added in v1.4.0

Do rewrite *gomock.Call.Do

func (*MockMigrationOrderCall) DoAndReturn added in v1.4.0

func (c *MockMigrationOrderCall) DoAndReturn(f func() int) *MockMigrationOrderCall

DoAndReturn rewrite *gomock.Call.DoAndReturn

func (*MockMigrationOrderCall) Return added in v1.4.0

Return rewrite *gomock.Call.Return

type MockMigrationRollbackCall added in v1.4.0

type MockMigrationRollbackCall struct {
	*gomock.Call
}

MockMigrationRollbackCall wrap *gomock.Call

func (*MockMigrationRollbackCall) Do added in v1.4.0

Do rewrite *gomock.Call.Do

func (*MockMigrationRollbackCall) DoAndReturn added in v1.4.0

func (c *MockMigrationRollbackCall) DoAndReturn(f func() error) *MockMigrationRollbackCall

DoAndReturn rewrite *gomock.Call.DoAndReturn

func (*MockMigrationRollbackCall) Return added in v1.4.0

Return rewrite *gomock.Call.Return

type Opt

type Opt func(c *conf)

Opt for configuring database.

func WithAllowSchemaDrift added in v1.7.0

func WithAllowSchemaDrift(allow bool) Opt

WithAllowSchemaDrift prevents Open from failing upon schema drift when schema drift checks are enabled. A warning is printed instead.

func WithConnections

func WithConnections(n int) Opt

WithConnections overwrites number of pooled connections.

func WithDatabaseSchema added in v1.7.0

func WithDatabaseSchema(schema *Schema) Opt

WithSchema specifies database schema script.

func WithExclusive added in v1.7.0

func WithExclusive() Opt

WithExclusive specifies that the database is to be open in exclusive mode. This means that no other processes can open the database at the same time. If the database is already open by any process, this Open will fail. Any subsequent attempts by other processes to open the database will fail until this db handle is closed. In Exclusive mode, the database supports just one concurrent connection.

func WithForceMigrations added in v1.7.0

func WithForceMigrations(force bool) Opt

WithForceMigrations forces database to run all the migrations instead of using a schema snapshot in case of a fresh database.

func WithLatencyMetering

func WithLatencyMetering(enable bool) Opt

WithLatencyMetering enables metric that track latency for every database query. Note that it will be a significant amount of data, and should not be enabled on multiple nodes by default.

func WithLogger added in v1.3.6

func WithLogger(logger *zap.Logger) Opt

WithLogger specifies logger for the database.

func WithMigrationsDisabled added in v1.7.0

func WithMigrationsDisabled() Opt

WithMigrationsDisabled disables migrations for the database. The migrations are enabled by default.

func WithNoCheckSchemaDrift added in v1.7.0

func WithNoCheckSchemaDrift() Opt

WithNoCheckSchemaDrift disables schema drift checks.

func WithQueryCache added in v1.4.0

func WithQueryCache(enable bool) Opt

WithQueryCache enables in-memory caching of results of some queries.

func WithQueryCacheSizes added in v1.4.0

func WithQueryCacheSizes(sizes map[QueryCacheKind]int) Opt

WithQueryCacheSizes sets query cache sizes for the specified cache kinds.

func WithTemp added in v1.7.0

func WithTemp() Opt

WithTemp specifies temporary database mode. For the temporary database, the migrations are always run in place, and vacuuming is nover done. PRAGMA journal_mode=OFF and PRAGMA synchronous=OFF are used.

func WithVacuumState added in v1.3.0

func WithVacuumState(i int) Opt

WithVacuumState will execute vacuum if database version before the migration was less or equal to the provided value.

type QueryCache added in v1.4.0

type QueryCache interface {
	// IsCached returns true if the requests are being cached.
	IsCached() bool
	// GetValue retrieves the specified key+subKey value from the cache. If
	// the entry is absent from cache, it's populated by calling retrieve func.
	// Note that the retrieve func should never cause UpdateSlice to be
	// called for this cache.
	GetValue(
		ctx context.Context,
		key QueryCacheItemKey,
		subKey QueryCacheSubKey,
		retrieve UntypedRetrieveFunc,
	) (any, error)
	// UpdateSlice updates the slice stored in the cache by invoking the
	// specified SliceAppender. If the entry is not cached, the method does
	// nothing.
	UpdateSlice(key QueryCacheItemKey, update SliceAppender)
	// ClearCache empties the cache.
	ClearCache()
}

QueryCache stores results of SQL queries and data derived from these results. Presently, the cached entries are never removed, but eventually, it might become an LRU cache.

var NullQueryCache QueryCache = (*queryCache)(nil)

type QueryCacheItemKey added in v1.7.0

type QueryCacheItemKey struct {
	Kind QueryCacheKind
	Key  string
}

func QueryCacheKey added in v1.4.0

func QueryCacheKey(kind QueryCacheKind, key string) QueryCacheItemKey

QueryCacheKey creates a key for QueryCache.

type QueryCacheKind added in v1.4.0

type QueryCacheKind string

type QueryCacheSubKey added in v1.4.0

type QueryCacheSubKey string

QueryCacheSubKey denotes a cache subkey. The empty subkey refers to the main key. All other subkeys are cleared by UpdateSlice for the key. The subkeys are intended to store data derived from the query results, such as serialized responses.

type RetrieveFunc added in v1.4.0

type RetrieveFunc[T any] func() (T, error)

RetrieveFunc retrieves a value to be stored in the cache.

type Schema added in v1.7.0

type Schema struct {
	Script     string
	Migrations MigrationList
	// contains filtered or unexported fields
}

Schema represents database schema.

func (*Schema) Apply added in v1.7.0

func (s *Schema) Apply(db Database) error

Apply applies the schema to the database.

func (*Schema) CheckDBVersion added in v1.7.0

func (s *Schema) CheckDBVersion(logger *zap.Logger, db Database) (before, after int, err error)

func (*Schema) Diff added in v1.7.0

func (s *Schema) Diff(actualScript string) string

Diff diffs the database schema against the actual schema. If there's no differences, it returns an empty string.

func (*Schema) Migrate added in v1.7.0

func (s *Schema) Migrate(logger *zap.Logger, db Database, before, vacuumState int) error

Migrate performs database migration. In case if migrations are disabled, the database version is checked but no migrations are run, and if the database is too old and migrations are disabled, an error is returned.

func (*Schema) MigrateTempDB added in v1.7.0

func (s *Schema) MigrateTempDB(logger *zap.Logger, db Database, before int) error

MigrateTempDB performs database migration on the temporary database. It doesn't use transactions and the temporary database should be considered invalid and discarded if it fails. The database is switched into synchronous mode with WAL journal enabled and synced after the migrations are completed before setting the database version, which triggers file sync.

func (*Schema) SkipMigrations added in v1.7.0

func (s *Schema) SkipMigrations(i ...int)

SkipMigrations skips the specified migrations.

func (*Schema) WriteToFile added in v1.7.0

func (s *Schema) WriteToFile(basedir string) error

WriteToFile writes the schema to the corresponding updated schema file.

type SchemaGen added in v1.7.0

type SchemaGen struct {
	// contains filtered or unexported fields
}

SchemaGen generates database schema files.

func NewSchemaGen added in v1.7.0

func NewSchemaGen(logger *zap.Logger, schema *Schema, opts ...SchemaGenOpt) *SchemaGen

NewSchemaGen creates a new SchemaGen instance.

func (*SchemaGen) Generate added in v1.7.0

func (g *SchemaGen) Generate(outputFile string) error

Generate generates database schema and writes it to the specified file. If an empty string is specified as outputFile, os.Stdout is used for output.

type SchemaGenOpt added in v1.7.0

type SchemaGenOpt func(g *SchemaGen)

SchemaGenOpt represents a schema generator option.

type SliceAppender added in v1.4.0

type SliceAppender func(s any) any

SliceAppender modifies slice value stored in the cache, appending the specified item to it and returns the updated slice.

type StateDatabase added in v1.7.0

type StateDatabase interface {
	Database
	IsStateDatabase()
}

StateDatabase is a Database used for Spacemesh state.

type Statement

type Statement = sqlite.Stmt

Statement is an sqlite statement.

type Transaction added in v1.7.0

type Transaction interface {
	Executor
	Commit() error
	Release() error
}

Transaction represents a transaction.

type UntypedRetrieveFunc added in v1.4.0

type UntypedRetrieveFunc func(ctx context.Context) (any, error)

UntypedRetrieveFunc retrieves a value to be cached.

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL