db

package
v0.0.0-...-bc49051 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// EnvVarDBEngine is the environment variable used to set the Go `sql` driver.
	EnvVarDBEngine = "DB_ENGINE"
	// EnvVarDatabaseURL is the environment variable used to set the entire
	// database connection string.
	EnvVarDatabaseURL = "DATABASE_URL"
	// EnvVarDBHost is the environment variable used to set the host in a
	// database connection string.
	EnvVarDBHost = "DB_HOST"
	// EnvVarDBPort is the environment variable used to set the port in a
	// database connection string.
	EnvVarDBPort = "DB_PORT"
	// EnvVarDBName is the environment variable used to set the database name
	// in a database connection string.
	EnvVarDBName = "DB_NAME"
	// EnvVarDBSchema is the environment variable used to set the database
	// schema in a database connection string.
	EnvVarDBSchema = "DB_SCHEMA"
	// EnvVarDBApplicationName is the environment variable used to set the
	// `application_name` configuration parameter in a `lib/pq` connection
	// string.
	//
	// See: https://www.postgresql.org/docs/12/runtime-config-logging.html#GUC-APPLICATION-NAME
	EnvVarDBApplicationName = "DB_APPLICATION_NAME"
	// EnvVarDBUser is the environment variable used to set the user in a
	// database connection string.
	EnvVarDBUser = "DB_USER"
	// EnvVarDBPassword is the environment variable used to set the password
	// in a database connection string.
	EnvVarDBPassword = "DB_PASSWORD"
	// EnvVarDBConnectTimeout is is the environment variable used to set the
	// connect timeout in a database connection string.
	EnvVarDBConnectTimeout = "DB_CONNECT_TIMEOUT"
	// EnvVarDBLockTimeout is is the environment variable used to set the lock
	// timeout on a database config.
	EnvVarDBLockTimeout = "DB_LOCK_TIMEOUT"
	// EnvVarDBStatementTimeout is is the environment variable used to set the
	// statement timeout on a database config.
	EnvVarDBStatementTimeout = "DB_STATEMENT_TIMEOUT"
	// EnvVarDBSSLMode is the environment variable used to set the SSL mode in
	// a database connection string.
	EnvVarDBSSLMode = "DB_SSLMODE"
	// EnvVarDBIdleConnections is the environment variable used to set the
	// maximum number of idle connections allowed in a connection pool.
	EnvVarDBIdleConnections = "DB_IDLE_CONNECTIONS"
	// EnvVarDBMaxConnections is the environment variable used to set the
	// maximum number of connections allowed in a connection pool.
	EnvVarDBMaxConnections = "DB_MAX_CONNECTIONS"
	// EnvVarDBMaxLifetime is the environment variable used to set the maximum
	// lifetime of a connection in a connection pool.
	EnvVarDBMaxLifetime = "DB_MAX_LIFETIME"
	// EnvVarDBMaxIdleTime is the environment variable used to set the maximum
	// time a connection can be idle.
	EnvVarDBMaxIdleTime = "DB_MAX_IDLE_TIME"
	// EnvVarDBBufferPoolSize is the environment variable used to set the buffer
	// pool size on a connection in a connection pool.
	EnvVarDBBufferPoolSize = "DB_BUFFER_POOL_SIZE"
	// EnvVarDBDialect is the environment variable used to set the dialect
	// on a connection configuration (e.g. `postgres` or `cockroachdb`).
	EnvVarDBDialect = "DB_DIALECT"
)
View Source
const (
	// DefaultHost is the default database hostname, typically used
	// when developing locally.
	DefaultHost = "localhost"
	// DefaultPort is the default postgres port.
	DefaultPort = "5432"
	// DefaultDatabase is the default database to connect to, we use
	// `postgres` to not pollute the template databases.
	DefaultDatabase = "postgres"

	// DefaultSchema is the default schema to connect to
	DefaultSchema = "public"
)
View Source
const (
	// SSLModeDisable is an ssl mode.
	// Postgres Docs: "I don't care about security, and I don't want to pay the overhead of encryption."
	SSLModeDisable = "disable"
	// SSLModeAllow is an ssl mode.
	// Postgres Docs: "I don't care about security, but I will pay the overhead of encryption if the server insists on it."
	SSLModeAllow = "allow"
	// SSLModePrefer is an ssl mode.
	// Postgres Docs: "I don't care about encryption, but I wish to pay the overhead of encryption if the server supports it"
	SSLModePrefer = "prefer"
	// SSLModeRequire is an ssl mode.
	// Postgres Docs: "I want my data to be encrypted, and I accept the overhead. I trust that the network will make sure I always connect to the server I want."
	SSLModeRequire = "require"
	// SSLModeVerifyCA is an ssl mode.
	// Postgres Docs: "I want my data encrypted, and I accept the overhead. I want to be sure that I connect to a server that I trust."
	SSLModeVerifyCA = "verify-ca"
	// SSLModeVerifyFull is an ssl mode.
	// Postgres Docs: "I want my data encrypted, and I accept the overhead. I want to be sure that I connect to a server I trust, and that it's the one I specify."
	SSLModeVerifyFull = "verify-full"
)
View Source
const (
	// DefaultConnectTimeout is the default connect timeout.
	DefaultConnectTimeout = 5 * time.Second
	// DefaultIdleConnections is the default number of idle connections.
	DefaultIdleConnections = 16
	// DefaultMaxConnections is the default maximum number of connections.
	DefaultMaxConnections = 32
	// DefaultMaxLifetime is the default maximum lifetime of driver connections.
	DefaultMaxLifetime = time.Duration(0)
	// DefaultMaxIdleTime is the default maximum idle time of driver connections.
	DefaultMaxIdleTime = time.Duration(0)
	// DefaultBufferPoolSize is the default number of buffer pool entries to maintain.
	DefaultBufferPoolSize = 1024
)
View Source
const (
	// DefaultEngine is the default database engine.
	DefaultEngine = "pgx" // "postgres"
)

Variables

View Source
var (
	// ErrDestinationNotStruct is an exception class.
	ErrDestinationNotStruct = errors.New("destination object is not a struct")
	// ErrConfigUnset is an exception class.
	ErrConfigUnset = errors.New("config is unset")
	// ErrUnsafeSSLMode is an error indicating unsafe ssl mode in production.
	ErrUnsafeSSLMode = errors.New("unsafe ssl mode in prodlike environment")
	// ErrUsernameUnset is an error indicating there is no username set in a prodlike environment.
	ErrUsernameUnset = errors.New("username is unset in prodlike environment")
	// ErrPasswordUnset is an error indicating there is no password set in a prodlike environment.
	ErrPasswordUnset = errors.New("password is unset in prodlike environment")
	// ErrDurationConversion is the error returned when a duration cannot be
	// converted to multiple of some base (e.g. milliseconds or seconds)
	// without round off.
	ErrDurationConversion = errors.New("cannot convert duration")
	// ErrConnectionAlreadyOpen is an error indicating the db connection was already opened.
	ErrConnectionAlreadyOpen = errors.New("the connection is already opened")
	// ErrConnectionClosed is an error indicating the db connection hasn't been opened.
	ErrConnectionClosed = errors.New("the connection is closed, or is being used before opened")
	// ErrContextUnset is an error indicating the context on the invocation isn't set.
	ErrContextUnset = errors.New("the context is unset; cannot continue")
	// ErrCollectionNotSlice is an error returned by OutMany if the destination is not a slice.
	ErrCollectionNotSlice = errors.New("outmany destination collection is not a slice")
	// ErrInvalidIDs is an error returned by Get if the ids aren't provided.
	ErrInvalidIDs = errors.New("invalid `ids` parameter")
	// ErrNoPrimaryKey is an error returned by a number of operations that depend on a primary key.
	ErrNoPrimaryKey = errors.New("no primary key on object")
	// ErrRowsNotColumnsProvider is returned by `PopulateByName` if you do not pass in `sql.Rows` as the scanner.
	ErrRowsNotColumnsProvider = errors.New("rows is not a columns provider")
	// ErrTooManyRows is returned by Out if there is more than one row returned by the query
	ErrTooManyRows = errors.New("too many rows returned to map to single object")
	// ErrNetwork is a grouped error for network issues.
	ErrNetwork = errors.New("network error")
)

Functions

func ColumnNames

func ColumnNames(cols []*Column) []string

ColumnNames returns the string names for all the columns in the collection.

func ColumnNamesCSV

func ColumnNamesCSV(cols []*Column) string

ColumnNamesCSV returns a csv of column names.

func ColumnNamesFromAlias

func ColumnNamesFromAlias(cols []*Column, tableAlias string) []string

ColumnNamesFromAlias returns the string names for all the columns in the collection.

func ColumnNamesFromAliasCSV

func ColumnNamesFromAliasCSV(cols []*Column, tableAlias string) string

ColumnNamesCSV returns a csv of column names.

func ColumnNamesWithPrefix

func ColumnNamesWithPrefix(cols []*Column, columnPrefix string) []string

ColumnNamesWithPrefix returns the string names for all the columns in the collection with a given disambiguation prefix.

func ColumnNamesWithPrefixCSV

func ColumnNamesWithPrefixCSV(cols []*Column, columnPrefix string) string

ColumnNamesWithPrefixCSV returns a csv of column names with a given disambiguation prefix.

func ColumnNamesWithPrefixFromAlias

func ColumnNamesWithPrefixFromAlias(cols []*Column, columnPrefix, tableAlias string) []string

ColumnNamesWithPrefixFromAlias returns the string names for all the columns in the collection.

func ColumnNamesWithPrefixFromAliasCSV

func ColumnNamesWithPrefixFromAliasCSV(cols []*Column, columnPrefix, tableAlias string) string

ColumnNamesCSV returns a csv of column names.

func ColumnValues

func ColumnValues(cols []*Column, instance any) (output []any)

ColumnValues returns the reflected value for all the columns on a given instance.

func Each

func Each(rows *sql.Rows, consumer RowsConsumer) (err error)

Each iterates over a given result set, calling the rows consumer.

func ExecAffectedAny

func ExecAffectedAny(res sql.Result, err error) (bool, error)

ExecAffectedAny is a helper that returns if a given Exec result affected any rows.

func ExecErr

func ExecErr(_ sql.Result, err error) error

ExecErr is a helper that just returns the exec err.

func First

func First(rows *sql.Rows, consumer RowsConsumer) (found bool, err error)

First returns the first result of a result set to a consumer. If there are more than one row in the result, they are ignored.

func HasColumn

func HasColumn(cols []*Column, name string) bool

HasColumn returns if a column with a given name exists in the list.

func IsPopulatable

func IsPopulatable(object any) (isPopulatable bool)

IsPopulatable returns if an object is populatable

func IsScanner

func IsScanner(object any) (isScanner bool)

IsScanner returns if an scalar value is scannable

func JSON

func JSON(obj any) any

JSON returns the json representation of a given object for inserts / updates.

func PopulateByName

func PopulateByName(object any, row Rows, cols *TypeMeta) error

PopulateByName sets the values of an object from the values of a sql.Rows object using column names.

func PopulateInOrder

func PopulateInOrder(object any, row Scanner, cols []*Column) (err error)

PopulateInOrder sets the values of an object in order from a sql.Rows object. Only use this method if you're certain of the column order. It is faster than populateByName. Optionally if your object implements Populatable this process will be skipped completely, which is even faster.

func Scan

func Scan(rows *sql.Rows, args ...any) (found bool, err error)

Scan reads the first row from a resultset and scans it to a given set of args. If more than one row is returned it will return ErrTooManyRows.

func TableName

func TableName(obj any) string

TableName returns the mapped table name for a given instance; it will sniff for the `TableName()` function on the type.

func TableNameByType

func TableNameByType(t reflect.Type) string

TableNameByType returns the table name for a given reflect.Type by instantiating it and calling o.TableName(). The type must implement DatabaseMapped or an exception will be returned.

func Zero

func Zero(object any) error

Zero resets an object.

Types

type BufferPool

type BufferPool struct {
	sync.Pool
}

BufferPool is a sync.Pool of bytes.Buffer.

func NewBufferPool

func NewBufferPool(defaultBufferSize int) *BufferPool

NewBufferPool returns a new Pool, which returns bytes buffers pre-sized to a given minimum size.

The purpose of a buffer pool is to reduce the number of gc collections incurred when using bytes buffers repeatedly; instead of marking the buffer as to be collected, it is returned to the pool to be re-used.

Example:

pool := bufferutil.NewBufferPool(1024) // pre-allocate 1024 bytes per buffer.

func() {
	buf := pool.Get()
	defer pool.Put(buf)

	// do things with the buffer ...
}()

func (*BufferPool) Get

func (p *BufferPool) Get() *bytes.Buffer

Get returns a pooled bytes.Buffer instance.

func (*BufferPool) Put

func (p *BufferPool) Put(b *bytes.Buffer)

Put returns the pooled instance.

type Column

type Column struct {
	Parent       *Column
	TableName    string
	FieldName    string
	FieldType    reflect.Type
	ColumnName   string
	Index        int
	IsPrimaryKey bool
	IsUniqueKey  bool
	IsAuto       bool
	IsReadOnly   bool
	IsJSON       bool
	Inline       bool
}

Column represents a single field on a struct that is mapped to the database.

func ColumnsNotZero

func ColumnsNotZero(cols []*Column, instance any) (output []*Column)

ColumnsNotZero returns set fields on an instance that correspond to fields in the column collection.

func ColumnsZero

func ColumnsZero(cols []*Column, instance any) (output []*Column)

ColumnsZero returns unset fields on an instance that correspond to fields in the column collection.

func NewColumnFromFieldTag

func NewColumnFromFieldTag(field reflect.StructField) *Column

NewColumnFromFieldTag reads the contents of a field tag, ex: `json:"foo" db:"bar,isprimarykey,isserial"

func (Column) GetValue

func (c Column) GetValue(object any) interface{}

GetValue returns the value for a column on a given database mapped object.

func (Column) SetValue

func (c Column) SetValue(reference, value any) error

SetValue sets the field on a database mapped object to the instance of `value`.

func (Column) SetValueReflected

func (c Column) SetValueReflected(reference reflect.Value, value any) error

SetValueReflected sets the field on a reflect value object to the instance of `value`.

type ColumnMetaCacheKeyProvider

type ColumnMetaCacheKeyProvider interface {
	ColumnMetaCacheKey() string
}

ColumnMetaCacheKeyProvider is a provider for a column meta key.

type ColumnsProvider

type ColumnsProvider interface {
	Columns() ([]string, error)
}

ColumnsProvider is a type that can return columns.

type Config

type Config struct {
	// Engine is the database engine.
	Engine string `json:"engine,omitempty" yaml:"engine,omitempty"`
	// DSN is a fully formed DSN (this skips DSN formation from all other variables outside `schema`).
	DSN string `json:"dsn,omitempty" yaml:"dsn,omitempty"`
	// Host is the server to connect to.
	Host string `json:"host,omitempty" yaml:"host,omitempty"`
	// Port is the port to connect to.
	Port string `json:"port,omitempty" yaml:"port,omitempty"`
	// DBName is the database name
	Database string `json:"database,omitempty" yaml:"database,omitempty"`
	// Schema is the application schema within the database, defaults to `public`. This schema is used to set the
	// Postgres "search_path" If you want to reference tables in other schemas, you'll need to specify those schemas
	// in your queries e.g. "SELECT * FROM schema_two.table_one..."
	// Using the public schema in a production application is considered bad practice as newly created roles will have
	// visibility into this data by default. We strongly recommend specifying this option and using a schema that is
	// owned by your service's role
	// We recommend against setting a multi-schema search_path, but if you really want to, you provide multiple comma-
	// separated schema names as the value for this config, or you can dbc.Invoke().Exec a SET statement on a newly
	// opened connection such as "SET search_path = 'schema_one,schema_two';" Again, we recommend against this practice
	// and encourage you to specify schema names beyond the first in your queries.
	Schema string `json:"schema,omitempty" yaml:"schema,omitempty"`
	// ApplicationName is the name set by an application connection to a database
	// server, intended to be transmitted in the connection string. It can be
	// used to uniquely identify an application and will be included in the
	// `pg_stat_activity` view.
	//
	// See: https://www.postgresql.org/docs/12/runtime-config-logging.html#GUC-APPLICATION-NAME
	ApplicationName string `json:"applicationName,omitempty" yaml:"applicationName,omitempty"`
	// Username is the username for the connection via password auth.
	Username string `json:"username,omitempty" yaml:"username,omitempty"`
	// Password is the password for the connection via password auth.
	Password string `json:"password,omitempty" yaml:"password,omitempty"`
	// ConnectTimeout determines the maximum wait for connection. The minimum
	// allowed timeout is 2 seconds, so anything below is treated the same
	// as unset. PostgreSQL will only accept second precision so this value will be
	// rounded to the nearest second before being set on a connection string.
	// Use `Validate()` to confirm that `ConnectTimeout` is exact to second
	// precision.
	//
	// See: https://www.postgresql.org/docs/10/libpq-connect.html#LIBPQ-CONNECT-CONNECT-TIMEOUT
	ConnectTimeout time.Duration `json:"connectTimeout,omitempty" yaml:"connectTimeout,omitempty"`
	// LockTimeout is the timeout to use when attempting to acquire a lock.
	// PostgreSQL will only accept millisecond precision so this value will be
	// rounded to the nearest millisecond before being set on a connection string.
	// Use `Validate()` to confirm that `LockTimeout` is exact to millisecond
	// precision.
	//
	// See: https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-LOCK-TIMEOUT
	LockTimeout time.Duration `json:"lockTimeout,omitempty" yaml:"lockTimeout,omitempty"`
	// StatementTimeout is the timeout to use when invoking a SQL statement.
	// PostgreSQL will only accept millisecond precision so this value will be
	// rounded to the nearest millisecond before being set on a connection string.
	// Use `Validate()` to confirm that `StatementTimeout` is exact to millisecond
	// precision.
	//
	// See: https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-STATEMENT-TIMEOUT
	StatementTimeout time.Duration `json:"statementTimeout,omitempty" yaml:"statementTimeout,omitempty"`
	// SSLMode is the sslmode for the connection.
	SSLMode string `json:"sslMode,omitempty" yaml:"sslMode,omitempty"`
	// IdleConnections is the number of idle connections.
	IdleConnections int `json:"idleConnections,omitempty" yaml:"idleConnections,omitempty"`
	// MaxConnections is the maximum number of connections.
	MaxConnections int `json:"maxConnections,omitempty" yaml:"maxConnections,omitempty"`
	// MaxLifetime is the maximum time a connection can be open.
	MaxLifetime time.Duration `json:"maxLifetime,omitempty" yaml:"maxLifetime,omitempty"`
	// MaxIdleTime is the maximum time a connection can be idle.
	MaxIdleTime time.Duration `json:"maxIdleTime,omitempty" yaml:"maxIdleTime,omitempty"`
	// BufferPoolSize is the number of query composition buffers to maintain.
	BufferPoolSize int `json:"bufferPoolSize,omitempty" yaml:"bufferPoolSize,omitempty"`
	// Dialect includes hints to tweak specific sql semantics by database connection.
	Dialect string `json:"dialect,omitempty" yaml:"dialect,omitempty"`
}

Config is a set of connection config options.

func (Config) CreateDSN

func (c Config) CreateDSN() string

CreateDSN creates a postgres connection string from the config.

func (Config) CreateLoggingDSN

func (c Config) CreateLoggingDSN() string

CreateLoggingDSN creates a postgres connection string from the config suitable for logging. It will not include the password.

func (Config) IsZero

func (c Config) IsZero() bool

IsZero returns if the config is unset.

func (*Config) Resolve

func (c *Config) Resolve(ctx context.Context) error

Resolve applies any external data sources to the config.

func (Config) Validate

func (c Config) Validate() error

Validate validates that user-provided values are valid, e.g. that timeouts can be exactly rounded into a multiple of a given base value.

func (Config) ValidateProduction

func (c Config) ValidateProduction() error

ValidateProduction validates production configuration for the config.

type Connection

type Connection struct {
	Config
	// contains filtered or unexported fields
}

Connection is a

func MustNew

func MustNew(options ...Option) *Connection

MustNew returns a new connection and panics on error.

func New

func New(options ...Option) (*Connection, error)

New returns a new Connection. It will use very bare bones defaults for the config.

func (*Connection) BeginTx

func (dbc *Connection) BeginTx(ctx context.Context, opts ...func(*sql.TxOptions)) (*sql.Tx, error)

BeginTx starts a new transaction in a givent context.

func (*Connection) Close

func (dbc *Connection) Close() error

Close implements a closer.

func (*Connection) Exec

func (dbc *Connection) Exec(statement string, args ...interface{}) (sql.Result, error)

Exec is a helper stub for .Invoke(...).Exec(...).

func (*Connection) ExecContext

func (dbc *Connection) ExecContext(ctx context.Context, statement string, args ...interface{}) (sql.Result, error)

ExecContext is a helper stub for .Invoke(OptContext(ctx)).Exec(...).

func (*Connection) Invoke

func (dbc *Connection) Invoke(options ...InvocationOption) *Invocation

Invoke returns a new invocation.

func (*Connection) Open

func (dbc *Connection) Open() error

Open returns a connection object, either a cached connection object or creating a new one in the process.

func (*Connection) Prepare

func (dbc *Connection) Prepare(ctx context.Context, statement string) (stmt *sql.Stmt, err error)

Prepare prepares a statement within a given context. If a tx is provided, the tx is the target for the prepare. This will trigger tracing on prepare.

func (*Connection) Query

func (dbc *Connection) Query(statement string, args ...interface{}) *Query

Query is a helper stub for .Invoke(...).Query(...).

func (*Connection) QueryContext

func (dbc *Connection) QueryContext(ctx context.Context, statement string, args ...interface{}) *Query

QueryContext is a helper stub for .Invoke(OptContext(ctx)).Query(...).

func (*Connection) RegisterOnQuery

func (dbc *Connection) RegisterOnQuery(fn func(QueryEvent))

RegisterOnQuery adds an on query listener.

func (*Connection) Stats

func (dbc *Connection) Stats() sql.DBStats

Stats returns the stats for the connection.

func (*Connection) TypeMeta

func (dbc *Connection) TypeMeta(object any) *TypeMeta

TypeMeta returns the TypeMeta for an object.

func (*Connection) TypeMetaFromType

func (dbc *Connection) TypeMetaFromType(identifier string, t reflect.Type) *TypeMeta

TypeMetaFromType reflects a reflect.Type into a column collection. The results of this are cached for speed.

type DB

type DB interface {
	ExecContext(context.Context, string, ...any) (sql.Result, error)
	QueryContext(context.Context, string, ...any) (*sql.Rows, error)
	QueryRowContext(context.Context, string, ...any) *sql.Row
}

DB is a handler for queries.

type Dialect

type Dialect string

Dialect is the flavor of sql.

var (
	// DialectUnknown is an unknown dialect, typically inferred as DialectPostgres.
	DialectUnknown Dialect
	// DialectPostgres is the postgres dialect.
	DialectPostgres Dialect = "psql"
	// DialectCockroachDB is the crdb dialect.
	DialectCockroachDB Dialect = "cockroachdb"
	// DialectRedshift is the redshift dialect.
	DialectRedshift Dialect = "redshift"
)

func (Dialect) Is

func (d Dialect) Is(others ...Dialect) bool

Is returns if a dialect equals one of a set of dialects.

type Invocation

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

Invocation is a specific operation against a context.

func (*Invocation) All

func (i *Invocation) All(collection interface{}) (err error)

All returns all rows of an object mapped table wrapped in a transaction.

func (*Invocation) Create

func (i *Invocation) Create(object any) (err error)

Create writes an object to the database within a transaction.

func (*Invocation) CreateIfNotExists

func (i *Invocation) CreateIfNotExists(object any) (err error)

CreateIfNotExists writes an object to the database if it does not already exist within a transaction. This will _ignore_ auto columns, as they will always invalidate the assertion that there already exists a row with a given primary key set.

func (*Invocation) Delete

func (i *Invocation) Delete(object any) (deleted bool, err error)

Delete deletes an object from the database wrapped in a transaction. Returns whether or not any rows have been deleted and potentially an error.

If ErrTooManyRows is returned, it's important to note that due to https://github.com/golang/go/issues/7898 the Delete HAS BEEN APPLIED on the current transaction. Its on the developer using Delete to ensure their tags are correct and/or ensure theit Tx rolls back on this error.

func (*Invocation) Exec

func (i *Invocation) Exec(statement string, args ...interface{}) (res sql.Result, err error)

Exec executes a sql statement with a given set of arguments and returns the rows affected.

func (*Invocation) Exists

func (i *Invocation) Exists(object any) (exists bool, err error)

Exists returns a bool if a given object exists (utilizing the primary key columns if they exist) wrapped in a transaction.

func (*Invocation) Get

func (i *Invocation) Get(object any, ids ...any) (found bool, err error)

Get returns a given object based on a group of primary key ids within a transaction.

func (*Invocation) GetMany

func (i *Invocation) GetMany(collection any, ids ...any) (err error)

GetMany returns objects matching a given array of keys.

The order of the results will match the order of the keys.

func (*Invocation) Query

func (i *Invocation) Query(statement string, args ...interface{}) *Query

Query returns a new query object for a given sql query and arguments.

func (*Invocation) Update

func (i *Invocation) Update(object any) (updated bool, err error)

Update updates an object wrapped in a transaction. Returns whether or not any rows have been updated and potentially an error. If ErrTooManyRows is returned, it's important to note that due to https://github.com/golang/go/issues/7898, the Update HAS BEEN APPLIED. Its on the developer using UPDATE to ensure his tags are correct and/or execute it in a transaction and roll back on this error

func (*Invocation) Upsert

func (i *Invocation) Upsert(object any) (err error)

Upsert inserts the object if it doesn't exist already (as defined by its primary keys) or updates it atomically. It returns `found` as true if the effect was an upsert, i.e. the pk was found.

type InvocationOption

type InvocationOption func(*Invocation)

InvocationOption is an option for invocations.

func OptCancel

func OptCancel(cancel context.CancelFunc) InvocationOption

OptCancel sets the context cancel func.

func OptContext

func OptContext(ctx context.Context) InvocationOption

OptContext sets a context on an invocation.

func OptInvocationDB

func OptInvocationDB(db DB) InvocationOption

OptInvocationDB is an invocation option that sets the underlying invocation db.

func OptLabel

func OptLabel(label string) InvocationOption

OptLabel sets the Label on the invocation.

func OptTimeout

func OptTimeout(d time.Duration) InvocationOption

OptTimeout sets a command timeout for the invocation.

func OptTx

func OptTx(tx *sql.Tx) InvocationOption

OptTx is an invocation option that sets the invocation transaction.

type Logger

type Logger interface {
	Output(int, string) error
}

Logger is a type that emits log messages.

type Option

type Option func(c *Connection) error

Option is an option for database connections.

func OptConfig

func OptConfig(cfg Config) Option

OptConfig sets the config on a connection.

func OptConfigFromEnv

func OptConfigFromEnv() Option

OptConfigFromEnv sets the config on a connection from the environment.

func OptConnection

func OptConnection(conn *sql.DB) Option

OptConnection sets the underlying driver connection.

func OptDatabase

func OptDatabase(database string) Option

OptDatabase sets the connection database.

func OptDialect

func OptDialect(dialect Dialect) Option

OptDialect sets the connection dialect.

func OptEngine

func OptEngine(engine string) Option

OptEngine sets the connection engine. You must have this engine registered with database/sql.

func OptHost

func OptHost(host string) Option

OptHost sets the connection host.

func OptLog

func OptLog(log Logger) Option

OptLog enables logging on the connection.

func OptPassword

func OptPassword(password string) Option

OptPassword sets the connection ssl mode.

func OptPort

func OptPort(port string) Option

OptPort sets the connection port.

func OptSSLMode

func OptSSLMode(mode string) Option

OptSSLMode sets the connection ssl mode.

func OptSchema

func OptSchema(schema string) Option

OptSchema sets the connection schema path.

func OptUsername

func OptUsername(username string) Option

OptUsername sets the connection ssl mode.

type Populatable

type Populatable interface {
	Populate(rows Rows) error
}

Populatable is an interface that you can implement if your object is read often and is performance critical.

type Query

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

Query is the intermediate result of a query.

func (*Query) Any

func (q *Query) Any() (found bool, err error)

Any returns if there are any results for the query.

func (*Query) Do

func (q *Query) Do() (rows *sql.Rows, err error)

Do runs a given query, yielding the raw results.

func (*Query) Each

func (q *Query) Each(consumer RowsConsumer) (err error)

Each executes the consumer for each result of the query (one to many).

func (*Query) First

func (q *Query) First(consumer RowsConsumer) (found bool, err error)

First executes the consumer for the first result of a query. It returns `ErrTooManyRows` if more than one result is returned.

func (*Query) None

func (q *Query) None() (notFound bool, err error)

None returns if there are no results for the query.

func (*Query) Out

func (q *Query) Out(object any) (found bool, err error)

Out writes the query result to a single object via. reflection mapping. If there is more than one result, the first result is mapped to to object, and ErrTooManyRows is returned. Out() will apply column values for any colums in the row result to the object, potentially zeroing existing values out.

func (*Query) OutMany

func (q *Query) OutMany(collection any) (err error)

OutMany writes the query results to a slice of objects.

func (*Query) Scan

func (q *Query) Scan(args ...any) (found bool, err error)

Scan writes the results to a given set of local variables. It returns if the query produced a row, and returns `ErrTooManyRows` if there are multiple row results.

type QueryEvent

type QueryEvent struct {
	Database     string        `json:"database,omitempty"`
	Engine       string        `json:"engine,omitempty"`
	Username     string        `json:"username,omitempty"`
	Label        string        `json:"label,omitempty"`
	Body         string        `json:"body,omitempty"`
	Elapsed      time.Duration `json:"elapsed,omitempty"`
	Err          error         `json:"err,omitempty"`
	RowsAffected int64         `json:"rowsAffected,omitempty"`
}

QueryEvent represents a database query.

func (QueryEvent) String

func (e QueryEvent) String() string

WriteText writes the event text to the output.

type Rows

type Rows interface {
	Scanner
	ColumnsProvider
}

Rows provides the relevant fields to populate by name.

type RowsConsumer

type RowsConsumer func(r Rows) error

RowsConsumer is the function signature that is called from within Each().

type Scanner

type Scanner interface {
	Scan(...interface{}) error
}

Scanner is a type that can scan into variadic values.

type TableNameProvider

type TableNameProvider interface {
	TableName() string
}

TableNameProvider is a type that implements the TableName() function. The only required method is TableName() string that returns the name of the table in the database this type is mapped to.

type MyDatabaseMappedObject {
	Mycolumn `db:"my_column"`
}
func (_ MyDatabaseMappedObject) TableName() string {
	return "my_database_mapped_object"
}

If you require different table names based on alias, create another type.

type TypeMeta

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

TypeMeta represents the column metadata for a given struct.

func NewTypeMetaFromColumns

func NewTypeMetaFromColumns(columns ...Column) *TypeMeta

NewTypeMetaFromColumns returns a new TypeMeta instance from a given list of columns.

func NewTypeMetaFromColumnsWithPrefix

func NewTypeMetaFromColumnsWithPrefix(columnPrefix string, columns ...Column) *TypeMeta

NewTypeMetaFromColumnsWithPrefix makes a new TypeMeta instance from a given list of columns with a column prefix.

func TypeMetaFor

func TypeMetaFor(object any) *TypeMeta

TypeMetaFor returns the TypeMeta for an object.

func (*TypeMeta) Add

func (cc *TypeMeta) Add(c Column)

Add adds a column.

func (*TypeMeta) Autos

func (cc *TypeMeta) Autos() []*Column

Autos are columns we have to return the id of.

func (*TypeMeta) Column

func (cc *TypeMeta) Column(columnName string) (c *Column)

Column returns a column by name is present in the collection.

func (*TypeMeta) Columns

func (cc *TypeMeta) Columns() (output []*Column)

Columns returns the colummns

func (*TypeMeta) Copy

func (cc *TypeMeta) Copy() *TypeMeta

Copy creates a new TypeMeta instance and carries over an existing column prefix.

func (*TypeMeta) CopyWithColumnPrefix

func (cc *TypeMeta) CopyWithColumnPrefix(prefix string) *TypeMeta

CopyWithColumnPrefix applies a column prefix to column names and returns a new column collection.

func (*TypeMeta) HasColumn

func (cc *TypeMeta) HasColumn(columnName string) bool

HasColumn returns if a column name is present in the collection.

func (*TypeMeta) InsertColumns

func (cc *TypeMeta) InsertColumns() []*Column

InsertColumns are non-auto, non-readonly columns.

func (*TypeMeta) Len

func (cc *TypeMeta) Len() int

Len returns the number of columns.

func (*TypeMeta) Lookup

func (cc *TypeMeta) Lookup() map[string]*Column

Lookup gets the column name lookup.

func (*TypeMeta) NotAutos

func (cc *TypeMeta) NotAutos() []*Column

NotAutos are columns we don't have to return the id of.

func (*TypeMeta) NotPrimaryKeys

func (cc *TypeMeta) NotPrimaryKeys() []*Column

NotPrimaryKeys are columns we can update.

func (*TypeMeta) NotReadOnly

func (cc *TypeMeta) NotReadOnly() []*Column

NotReadOnly are columns that we have to insert upon Create().

func (*TypeMeta) NotUniqueKeys

func (cc *TypeMeta) NotUniqueKeys() []*Column

NotUniqueKeys are columns we can update.

func (*TypeMeta) PrimaryKeys

func (cc *TypeMeta) PrimaryKeys() []*Column

PrimaryKeys are columns we use as where predicates and can't update.

func (*TypeMeta) ReadOnly

func (cc *TypeMeta) ReadOnly() []*Column

ReadOnly are columns that we don't have to insert upon Create().

func (*TypeMeta) Remove

func (cc *TypeMeta) Remove(columnName string)

Remove removes a column (by column name) from the collection.

func (*TypeMeta) UniqueKeys

func (cc *TypeMeta) UniqueKeys() []*Column

UniqueKeys are columns we use as where predicates and can't update.

func (*TypeMeta) UpdateColumns

func (cc *TypeMeta) UpdateColumns() []*Column

UpdateColumns are non-primary key, non-readonly columns.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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