Documentation ¶
Overview ¶
Package db provides a basic abstraction layer above normal database/sql that makes it easier to interact with the database and organize database related code. It is not intended to replace actual sql (you write queries yourself in sql). It also includes some helpers to organize creating a connection to a database from a config file or object.
Index ¶
- Constants
- func ColumnNamesCSV(object DatabaseMapped) string
- func Error(err error) error
- func IsConfigUnset(err error) bool
- func IsConnectionClosed(err error) bool
- func IsPasswordUnset(err error) bool
- func IsStatementCacheUnset(err error) bool
- func IsUnsafeSSLMode(err error) bool
- func IsUsernameUnset(err error) bool
- func OpenDefault(conn *Connection) error
- func OptionalTx(txs ...*sql.Tx) *sql.Tx
- func ParamTokens(startAt, count int) string
- func PopulateByName(object interface{}, row Rows, cols *ColumnCollection) error
- func PopulateInOrder(object DatabaseMapped, row Scanner, cols *ColumnCollection) (err error)
- func SetDefault(conn *Connection)
- func TableName(obj DatabaseMapped) string
- func TableNameByType(t reflect.Type) string
- func Tx(txs ...*sql.Tx) *sql.Tx
- type Annotations
- type Any
- type BufferPool
- type Column
- type ColumnCollection
- func (cc *ColumnCollection) Add(c Column)
- func (cc *ColumnCollection) Autos() *ColumnCollection
- func (cc *ColumnCollection) ColumnNames() []string
- func (cc *ColumnCollection) ColumnNamesCSV() string
- func (cc *ColumnCollection) ColumnNamesCSVFromAlias(tableAlias string) string
- func (cc *ColumnCollection) ColumnNamesFromAlias(tableAlias string) []string
- func (cc *ColumnCollection) ColumnValues(instance interface{}) []interface{}
- func (cc *ColumnCollection) Columns() []Column
- func (cc *ColumnCollection) ConcatWith(other *ColumnCollection) *ColumnCollection
- func (cc ColumnCollection) Copy() *ColumnCollection
- func (cc ColumnCollection) CopyWithColumnPrefix(prefix string) *ColumnCollection
- func (cc *ColumnCollection) FirstOrDefault() *Column
- func (cc *ColumnCollection) HasColumn(columnName string) bool
- func (cc *ColumnCollection) Len() int
- func (cc *ColumnCollection) Lookup() map[string]*Column
- func (cc *ColumnCollection) NotAutos() *ColumnCollection
- func (cc *ColumnCollection) NotPrimaryKeys() *ColumnCollection
- func (cc *ColumnCollection) NotReadOnly() *ColumnCollection
- func (cc *ColumnCollection) NotUniqueKeys() *ColumnCollection
- func (cc *ColumnCollection) PrimaryKeys() *ColumnCollection
- func (cc *ColumnCollection) ReadOnly() *ColumnCollection
- func (cc *ColumnCollection) Remove(columnName string)
- func (cc *ColumnCollection) String() string
- func (cc *ColumnCollection) UniqueKeys() *ColumnCollection
- func (cc *ColumnCollection) UpdateColumns() *ColumnCollection
- func (cc *ColumnCollection) WriteColumns() *ColumnCollection
- type ColumnMetaCacheKeyProvider
- type ColumnsProvider
- type Config
- func (c Config) CreateDSN() string
- func (c Config) GetBufferPoolSize(inherited ...int) int
- func (c Config) GetDSN(inherited ...string) string
- func (c Config) GetDatabase(inherited ...string) string
- func (c Config) GetEngine(inherited ...string) string
- func (c Config) GetHost(inherited ...string) string
- func (c Config) GetIdleConnections(inherited ...int) int
- func (c Config) GetMaxConnections(inherited ...int) int
- func (c Config) GetMaxLifetime(inherited ...time.Duration) time.Duration
- func (c Config) GetPassword(inherited ...string) string
- func (c Config) GetPort(inherited ...string) string
- func (c Config) GetSSLMode(inherited ...string) string
- func (c Config) GetSchema(inherited ...string) string
- func (c Config) GetUseStatementCache(inherited ...bool) bool
- func (c Config) GetUsername(inherited ...string) string
- func (c Config) MustResolve() *Config
- func (c Config) Resolve() (*Config, error)
- func (c Config) ValidateProduction() error
- func (c *Config) WithDSN(dsn string) *Config
- func (c *Config) WithDatabase(database string) *Config
- func (c *Config) WithEngine(engine string) *Config
- func (c *Config) WithHost(host string) *Config
- func (c *Config) WithPassword(password string) *Config
- func (c *Config) WithPort(port string) *Config
- func (c *Config) WithSSLMode(sslMode string) *Config
- func (c *Config) WithSchema(schema string) *Config
- func (c *Config) WithUsername(username string) *Config
- type Connection
- func (dbc *Connection) Background() context.Context
- func (dbc *Connection) Begin(opts ...*sql.TxOptions) (*sql.Tx, error)
- func (dbc *Connection) BeginContext(context context.Context, opts ...*sql.TxOptions) (*sql.Tx, error)
- func (dbc *Connection) Close() error
- func (dbc *Connection) Config() *Config
- func (dbc *Connection) Connection() *sql.DB
- func (dbc *Connection) Create(object DatabaseMapped) error
- func (dbc *Connection) CreateContext(context context.Context, object DatabaseMapped) error
- func (dbc *Connection) CreateIfNotExists(object DatabaseMapped) error
- func (dbc *Connection) CreateIfNotExistsContext(context context.Context, object DatabaseMapped) error
- func (dbc *Connection) CreateIfNotExistsInTx(object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) CreateIfNotExistsInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) CreateInTx(object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) CreateInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) CreateMany(objects interface{}) error
- func (dbc *Connection) CreateManyContext(context context.Context, objects interface{}) error
- func (dbc *Connection) CreateManyInTx(objects interface{}, tx *sql.Tx) (err error)
- func (dbc *Connection) CreateManyInTxContext(context context.Context, objects interface{}, tx *sql.Tx) (err error)
- func (dbc *Connection) Delete(object DatabaseMapped) error
- func (dbc *Connection) DeleteContext(context context.Context, object DatabaseMapped) error
- func (dbc *Connection) DeleteInTx(object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) DeleteInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) Exec(statement string, args ...interface{}) error
- func (dbc *Connection) ExecContext(context context.Context, statement string, args ...interface{}) error
- func (dbc *Connection) ExecContextWithLabel(context context.Context, statement, label string, args ...interface{}) error
- func (dbc *Connection) ExecInTx(statement string, tx *sql.Tx, args ...interface{}) (err error)
- func (dbc *Connection) ExecInTxContext(context context.Context, statement string, tx *sql.Tx, args ...interface{}) (err error)
- func (dbc *Connection) ExecInTxContextWithLabel(context context.Context, statement, label string, tx *sql.Tx, ...) (err error)
- func (dbc *Connection) ExecWithLabel(statement, label string, args ...interface{}) error
- func (dbc *Connection) Exists(object DatabaseMapped) (bool, error)
- func (dbc *Connection) ExistsContext(context context.Context, object DatabaseMapped) (bool, error)
- func (dbc *Connection) ExistsInTx(object DatabaseMapped, tx *sql.Tx) (exists bool, err error)
- func (dbc *Connection) ExistsInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (exists bool, err error)
- func (dbc *Connection) Get(object DatabaseMapped, ids ...interface{}) error
- func (dbc *Connection) GetAll(collection interface{}) error
- func (dbc *Connection) GetAllContext(context context.Context, collection interface{}) error
- func (dbc *Connection) GetAllInTx(collection interface{}, tx *sql.Tx) error
- func (dbc *Connection) GetAllInTxContext(context context.Context, collection interface{}, tx *sql.Tx) error
- func (dbc *Connection) GetContext(context context.Context, object DatabaseMapped, ids ...interface{}) error
- func (dbc *Connection) GetInTx(object DatabaseMapped, tx *sql.Tx, args ...interface{}) error
- func (dbc *Connection) GetInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx, ...) error
- func (dbc *Connection) Invoke(context context.Context, txs ...*sql.Tx) *Invocation
- func (dbc *Connection) Logger() *logger.Logger
- func (dbc *Connection) Open() error
- func (dbc *Connection) Ping() error
- func (dbc *Connection) PingContext(context context.Context) (err error)
- func (dbc *Connection) PrepareContext(context context.Context, statementID, statement string, txs ...*sql.Tx) (stmt *sql.Stmt, err error)
- func (dbc *Connection) Query(statement string, args ...interface{}) *Query
- func (dbc *Connection) QueryContext(context context.Context, statement string, args ...interface{}) *Query
- func (dbc *Connection) QueryContextWithLabel(context context.Context, statement, label string, args ...interface{}) *Query
- func (dbc *Connection) QueryInTx(statement string, tx *sql.Tx, args ...interface{}) (result *Query)
- func (dbc *Connection) QueryInTxContext(context context.Context, statement string, tx *sql.Tx, args ...interface{}) (result *Query)
- func (dbc *Connection) QueryInTxContextWithLabel(context context.Context, statement, label string, tx *sql.Tx, ...) (result *Query)
- func (dbc *Connection) QueryInTxWithLabel(statement, label string, tx *sql.Tx, args ...interface{}) (result *Query)
- func (dbc *Connection) QueryWithLabel(statement, label string, args ...interface{}) *Query
- func (dbc *Connection) StatementCache() *StatementCache
- func (dbc *Connection) StatementInterceptor() StatementInterceptor
- func (dbc *Connection) Tracer() Tracer
- func (dbc *Connection) Truncate(object DatabaseMapped) error
- func (dbc *Connection) TruncateContext(context context.Context, object DatabaseMapped) error
- func (dbc *Connection) TruncateInTx(object DatabaseMapped, tx *sql.Tx) error
- func (dbc *Connection) TruncateInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) error
- func (dbc *Connection) Update(object DatabaseMapped) error
- func (dbc *Connection) UpdateContext(context context.Context, object DatabaseMapped) error
- func (dbc *Connection) UpdateInTx(object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) UpdateInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) Upsert(object DatabaseMapped) error
- func (dbc *Connection) UpsertContext(context context.Context, object DatabaseMapped) error
- func (dbc *Connection) UpsertInTx(object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) UpsertInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
- func (dbc *Connection) WithConfig(cfg *Config) *Connection
- func (dbc *Connection) WithLogger(log *logger.Logger) *Connection
- func (dbc *Connection) WithStatementInterceptor(interceptor StatementInterceptor) *Connection
- func (dbc *Connection) WithTracer(tracer Tracer) *Connection
- type DatabaseMapped
- type Invocation
- func (i *Invocation) Cancel() func()
- func (i *Invocation) Context() context.Context
- func (i *Invocation) Create(object DatabaseMapped) (err error)
- func (i *Invocation) CreateIfNotExists(object DatabaseMapped) (err error)
- func (i *Invocation) CreateMany(objects interface{}) (err error)
- func (i *Invocation) Delete(object DatabaseMapped) (err error)
- func (i *Invocation) Exec(statement string, args ...interface{}) (err error)
- func (i *Invocation) Exists(object DatabaseMapped) (exists bool, err error)
- func (i *Invocation) Get(object DatabaseMapped, ids ...interface{}) (err error)
- func (i *Invocation) GetAll(collection interface{}) (err error)
- func (i *Invocation) Label() string
- func (i *Invocation) Prepare(statement string) (stmt *sql.Stmt, err error)
- func (i *Invocation) Query(statement string, args ...interface{}) *Query
- func (i *Invocation) StartTime() time.Time
- func (i *Invocation) StatementInterceptor() StatementInterceptor
- func (i *Invocation) Truncate(object DatabaseMapped) (err error)
- func (i *Invocation) Tx() *sql.Tx
- func (i *Invocation) Update(object DatabaseMapped) (err error)
- func (i *Invocation) Upsert(object DatabaseMapped) (err error)
- func (i *Invocation) WithCancel(cancel func()) *Invocation
- func (i *Invocation) WithContext(context context.Context) *Invocation
- func (i *Invocation) WithLabel(label string) *Invocation
- func (i *Invocation) WithStatementInterceptor(interceptor StatementInterceptor) *Invocation
- func (i *Invocation) WithTx(tx *sql.Tx) *Invocation
- type Labels
- type Populatable
- type Query
- func (q *Query) Any() (hasRows bool, err error)
- func (q *Query) Each(consumer RowsConsumer) (err error)
- func (q *Query) Execute() (rows *sql.Rows, err error)
- func (q *Query) First(consumer RowsConsumer) (err error)
- func (q *Query) None() (hasRows bool, err error)
- func (q *Query) Out(object interface{}) (err error)
- func (q *Query) OutMany(collection interface{}) (err error)
- func (q *Query) Scan(args ...interface{}) (err error)
- type Rows
- type RowsConsumer
- type Scanner
- type StatementCache
- func (sc *StatementCache) Close() (err error)
- func (sc *StatementCache) Connection() *sql.DB
- func (sc *StatementCache) Enabled() bool
- func (sc *StatementCache) HasStatement(statementID string) bool
- func (sc *StatementCache) InvalidateStatement(statementID string) (err error)
- func (sc *StatementCache) PrepareContext(context context.Context, statementID, statement string) (*sql.Stmt, error)
- func (sc *StatementCache) WithConnection(conn *sql.DB) *StatementCache
- func (sc *StatementCache) WithEnabled(enabled bool) *StatementCache
- type StatementInterceptor
- type TableNameProvider
- type TraceFinisher
- type Tracer
- type Values
Constants ¶
const ( // DefaultEngine is the default database engine. DefaultEngine = "postgres" // EnvVarDatabaseURL is an environment variable. EnvVarDatabaseURL = "DATABASE_URL" // 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" // 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" // DefaultUseStatementCache is the default if we should enable the statement cache. DefaultUseStatementCache = true // 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) // DefaultBufferPoolSize is the default number of buffer pool entries to maintain. DefaultBufferPoolSize = 1024 )
const ( // ErrDestinationNotStruct is an exception class. ErrDestinationNotStruct exception.Class = "db: destination object is not a struct" // ErrConfigUnset is an exception class. ErrConfigUnset exception.Class = "db: config is unset" // ErrUnsafeSSLMode is an error indicating unsafe ssl mode in production. ErrUnsafeSSLMode exception.Class = "db: unsafe ssl mode in prodlike environment" // ErrUsernameUnset is an error indicating there is no username set in a prodlike environment. ErrUsernameUnset exception.Class = "db: username is unset in prodlike environment" // ErrPasswordUnset is an error indicating there is no password set in a prodlike environment. ErrPasswordUnset exception.Class = "db: password is unset in prodlike environment" // ErrConnectionAlreadyOpen is an error indicating the db connection was already opened. ErrConnectionAlreadyOpen exception.Class = "db: the connection is already opened" // ErrConnectionClosed is an error indicating the db connection hasn't been opened. ErrConnectionClosed exception.Class = "db: the connection is closed" // ErrStatementCacheUnset is an error indicating the statement cache is unset. ErrStatementCacheUnset exception.Class = "db: the statement cache is unset" // ErrStatementLabelUnset is an error indicating the statement cache is unset. ErrStatementLabelUnset exception.Class = "db: the statement label is unset" // ErrCollectionNotSlice is an error returned by OutMany if the destination is not a slice. ErrCollectionNotSlice exception.Class = "db: outmany destination collection is not a slice" // ErrInvalidIDs is an error returned by Get if the ids aren't provided. ErrInvalidIDs exception.Class = "db: invalid `ids` parameter" // ErrNoPrimaryKey is an error returned by a number of operations that depend on a primary key. ErrNoPrimaryKey exception.Class = "db: no primary key on object" // ErrRowsNotColumnsProvider is returned by `PopulateByName` if you do not pass in `sql.Rows` as the scanner. ErrRowsNotColumnsProvider exception.Class = "db: rows is not a columns provider" )
const (
//DBNilError is a common error
DBNilError = "connection is nil"
)
Variables ¶
This section is empty.
Functions ¶
func ColumnNamesCSV ¶
func ColumnNamesCSV(object DatabaseMapped) string
ColumnNamesCSV returns a csv of column names.
func Error ¶ added in v0.3.2
Error returns a new exception by parsing (potentially) a driver error into relevant pieces.
func IsConfigUnset ¶
IsConfigUnset returns if the error is an `ErrConfigUnset`.
func IsConnectionClosed ¶
IsConnectionClosed returns if the error is an `ErrConnectionClosed`.
func IsPasswordUnset ¶
IsPasswordUnset returns if an error is an `ErrPasswordUnset`.
func IsStatementCacheUnset ¶
IsStatementCacheUnset returns if the error is an `ErrConnectionClosed`.
func IsUnsafeSSLMode ¶
IsUnsafeSSLMode returns if an error is an `ErrUnsafeSSLMode`.
func IsUsernameUnset ¶
IsUsernameUnset returns if an error is an `ErrUsernameUnset`.
func OpenDefault ¶
func OpenDefault(conn *Connection) error
OpenDefault sets the default connection and opens it.
func OptionalTx ¶
OptionalTx returns the first of a variadic set of txs. It is useful if you want to have a tx an optional parameter.
func ParamTokens ¶
ParamTokens returns a csv token string in the form "$1,$2,$3...$N" if passed (1, N).
func PopulateByName ¶
func PopulateByName(object interface{}, row Rows, cols *ColumnCollection) error
PopulateByName sets the values of an object from the values of a sql.Rows object using column names.
func PopulateInOrder ¶
func PopulateInOrder(object DatabaseMapped, row Scanner, cols *ColumnCollection) (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 SetDefault ¶
func SetDefault(conn *Connection)
SetDefault sets an alias created with `CreateDbAlias` as default. This lets you refer to it later via. `Default()`
spiffy.CreateDbAlias("main", spiffy.NewDbConnection("localhost", "test_db", "", "")) spiffy.SetDefault("main") execErr := spiffy.Default().Execute("select 'ok!')
This will then let you refer to the alias via. `Default()`
func TableName ¶
func TableName(obj DatabaseMapped) string
TableName returns the mapped table name for a given instance; it will sniff for the `TableName()` function on the type.
func TableNameByType ¶
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.
Types ¶
type Annotations ¶
Annotations is a loose type alias to map[string]string.
type BufferPool ¶
BufferPool is a sync.Pool of bytes.Buffer.
func NewBufferPool ¶
func NewBufferPool(bufferSize int) *BufferPool
NewBufferPool returns a new BufferPool.
func (*BufferPool) Get ¶
func (bp *BufferPool) Get() *bytes.Buffer
Get returns a pooled bytes.Buffer instance.
func (*BufferPool) Put ¶
func (bp *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 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 DatabaseMapped) interface{}
GetValue returns the value for a column on a given database mapped object.
type ColumnCollection ¶
type ColumnCollection struct {
// contains filtered or unexported fields
}
ColumnCollection represents the column metadata for a given struct.
func Columns ¶
func Columns(object DatabaseMapped) *ColumnCollection
Columns returns the cached column metadata for an object.
func NewColumnCollection ¶
func NewColumnCollection() *ColumnCollection
NewColumnCollection returns a new empty column collection.
func NewColumnCollectionWithPrefix ¶
func NewColumnCollectionWithPrefix(columnPrefix string) *ColumnCollection
NewColumnCollectionWithPrefix makes a new column collection with a column prefix.
func (*ColumnCollection) Autos ¶
func (cc *ColumnCollection) Autos() *ColumnCollection
Autos are columns we have to return the id of.
func (*ColumnCollection) ColumnNames ¶
func (cc *ColumnCollection) ColumnNames() []string
ColumnNames returns the string names for all the columns in the collection.
func (*ColumnCollection) ColumnNamesCSV ¶
func (cc *ColumnCollection) ColumnNamesCSV() string
ColumnNamesCSV returns a csv of column names.
func (*ColumnCollection) ColumnNamesCSVFromAlias ¶
func (cc *ColumnCollection) ColumnNamesCSVFromAlias(tableAlias string) string
ColumnNamesCSVFromAlias returns the string names for all the columns in the collection.
func (*ColumnCollection) ColumnNamesFromAlias ¶
func (cc *ColumnCollection) ColumnNamesFromAlias(tableAlias string) []string
ColumnNamesFromAlias returns the string names for all the columns in the collection.
func (*ColumnCollection) ColumnValues ¶
func (cc *ColumnCollection) ColumnValues(instance interface{}) []interface{}
ColumnValues returns the reflected value for all the columns on a given instance.
func (*ColumnCollection) Columns ¶
func (cc *ColumnCollection) Columns() []Column
Columns returns the colummns
func (*ColumnCollection) ConcatWith ¶
func (cc *ColumnCollection) ConcatWith(other *ColumnCollection) *ColumnCollection
ConcatWith merges a collection with another collection.
func (ColumnCollection) Copy ¶
func (cc ColumnCollection) Copy() *ColumnCollection
Copy creates a new column collection instance and carries over an existing column prefix.
func (ColumnCollection) CopyWithColumnPrefix ¶
func (cc ColumnCollection) CopyWithColumnPrefix(prefix string) *ColumnCollection
CopyWithColumnPrefix applies a column prefix to column names and returns a new column collection.
func (*ColumnCollection) FirstOrDefault ¶
func (cc *ColumnCollection) FirstOrDefault() *Column
FirstOrDefault returns the first column in the collection or `nil` if the collection is empty.
func (*ColumnCollection) HasColumn ¶
func (cc *ColumnCollection) HasColumn(columnName string) bool
HasColumn returns if a column name is present in the collection.
func (*ColumnCollection) Len ¶
func (cc *ColumnCollection) Len() int
Len returns the number of columns.
func (*ColumnCollection) Lookup ¶
func (cc *ColumnCollection) Lookup() map[string]*Column
Lookup gets the column name lookup.
func (*ColumnCollection) NotAutos ¶
func (cc *ColumnCollection) NotAutos() *ColumnCollection
NotAutos are columns we don't have to return the id of.
func (*ColumnCollection) NotPrimaryKeys ¶
func (cc *ColumnCollection) NotPrimaryKeys() *ColumnCollection
NotPrimaryKeys are columns we can update.
func (*ColumnCollection) NotReadOnly ¶
func (cc *ColumnCollection) NotReadOnly() *ColumnCollection
NotReadOnly are columns that we have to insert upon Create().
func (*ColumnCollection) NotUniqueKeys ¶
func (cc *ColumnCollection) NotUniqueKeys() *ColumnCollection
NotUniqueKeys are columns we can update.
func (*ColumnCollection) PrimaryKeys ¶
func (cc *ColumnCollection) PrimaryKeys() *ColumnCollection
PrimaryKeys are columns we use as where predicates and can't update.
func (*ColumnCollection) ReadOnly ¶
func (cc *ColumnCollection) ReadOnly() *ColumnCollection
ReadOnly are columns that we don't have to insert upon Create().
func (*ColumnCollection) Remove ¶
func (cc *ColumnCollection) Remove(columnName string)
Remove removes a column (by column name) from the collection.
func (*ColumnCollection) String ¶
func (cc *ColumnCollection) String() string
func (*ColumnCollection) UniqueKeys ¶
func (cc *ColumnCollection) UniqueKeys() *ColumnCollection
UniqueKeys are columns we use as where predicates and can't update.
func (*ColumnCollection) UpdateColumns ¶
func (cc *ColumnCollection) UpdateColumns() *ColumnCollection
UpdateColumns are non-readonly, non-serial columns.
func (*ColumnCollection) WriteColumns ¶
func (cc *ColumnCollection) WriteColumns() *ColumnCollection
WriteColumns are non-auto, non-primary key, non-readonly columns.
type ColumnMetaCacheKeyProvider ¶
type ColumnMetaCacheKeyProvider interface {
ColumnMetaCacheKey() string
}
ColumnMetaCacheKeyProvider is a provider for a column meta key.
type ColumnsProvider ¶
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" env:"DB_ENGINE"` // DSN is a fully formed DSN (this skips DSN formation from all other variables outside `schema`). DSN string `json:"dsn,omitempty" yaml:"dsn,omitempty" env:"DATABASE_URL"` // Host is the server to connect to. Host string `json:"host,omitempty" yaml:"host,omitempty" env:"DB_HOST"` // Port is the port to connect to. Port string `json:"port,omitempty" yaml:"port,omitempty" env:"DB_PORT"` // DBName is the database name Database string `json:"database,omitempty" yaml:"database,omitempty" env:"DB_NAME"` // Schema is the application schema within the database, defaults to `public`. Schema string `json:"schema,omitempty" yaml:"schema,omitempty" env:"DB_SCHEMA"` // Username is the username for the connection via password auth. Username string `json:"username,omitempty" yaml:"username,omitempty" env:"DB_USER"` // Password is the password for the connection via password auth. Password string `json:"password,omitempty" yaml:"password,omitempty" env:"DB_PASSWORD"` // SSLMode is the sslmode for the connection. SSLMode string `json:"sslMode,omitempty" yaml:"sslMode,omitempty" env:"DB_SSLMODE"` // UseStatementCache indicates if we should use the prepared statement cache. UseStatementCache *bool `json:"useStatementCache,omitempty" yaml:"useStatementCache,omitempty" env:"DB_USE_STATEMENT_CACHE"` // IdleConnections is the number of idle connections. IdleConnections int `json:"idleConnections,omitempty" yaml:"idleConnections,omitempty" env:"DB_IDLE_CONNECTIONS"` // MaxConnections is the maximum number of connections. MaxConnections int `json:"maxConnections,omitempty" yaml:"maxConnections,omitempty" env:"DB_MAX_CONNECTIONS"` // MaxLifetime is the maximum time a connection can be open. MaxLifetime time.Duration `json:"maxLifetime,omitempty" yaml:"maxLifetime,omitempty" env:"DB_MAX_LIFETIME"` // BufferPoolSize is the number of query composition buffers to maintain. BufferPoolSize int `json:"bufferPoolSize,omitempty" yaml:"bufferPoolSize,omitempty" env:"DB_BUFFER_POOL_SIZE"` }
Config is a set of connection config options.
func MustNewConfigFromEnv ¶
func MustNewConfigFromEnv() *Config
MustNewConfigFromEnv returns a new config from the environment, it will panic if there is an error.
func NewConfigFromDSN ¶
NewConfigFromDSN creates a new config from a dsn.
func NewConfigFromEnv ¶
NewConfigFromEnv returns a new config from the environment. The environment variable mappings are as follows:
- DATABSE_URL = DSN //note that this has precedence over other vars (!!)
- DB_HOST = Host
- DB_PORT = Port
- DB_NAME = Database
- DB_SCHEMA = Schema
- DB_USER = Username
- DB_PASSWORD = Password
- DB_SSLMODE = SSLMode
func (Config) GetBufferPoolSize ¶
GetBufferPoolSize returns the number of query buffers to maintain or a default.
func (Config) GetDSN ¶
GetDSN returns the postgres dsn (fully quallified url) for the config. If unset, it's generated from the host, port and database.
func (Config) GetDatabase ¶
GetDatabase returns the connection database or a default.
func (Config) GetIdleConnections ¶
GetIdleConnections returns the number of idle connections or a default.
func (Config) GetMaxConnections ¶
GetMaxConnections returns the maximum number of connections or a default.
func (Config) GetMaxLifetime ¶
GetMaxLifetime returns the maximum lifetime of a driver connection.
func (Config) GetPassword ¶
GetPassword returns the connection password or a default.
func (Config) GetPort ¶
GetPort returns the port for a connection if it is not the standard postgres port.
func (Config) GetSSLMode ¶
GetSSLMode returns the connection ssl mode. It defaults to unset, which will then use the lib/pq defaults.
func (Config) GetUseStatementCache ¶
GetUseStatementCache returns if we should enable the statement cache or a default.
func (Config) GetUsername ¶
GetUsername returns the connection username or a default.
func (Config) MustResolve ¶
MustResolve creates a DSN and reparses it, in case some values need to be coalesced, and panics if there is an error.
func (Config) Resolve ¶
Resolve creates a DSN and reparses it, in case some values need to be coalesced.
func (Config) ValidateProduction ¶
ValidateProduction validates production configuration for the config.
func (*Config) WithDatabase ¶
WithDatabase sets the config database and returns a reference to the config.
func (*Config) WithEngine ¶
WithEngine sets the databse engine.
func (*Config) WithPassword ¶
WithPassword sets the config password and returns a reference to the config.
func (*Config) WithSSLMode ¶
WithSSLMode sets the config sslMode and returns a reference to the config.
func (*Config) WithSchema ¶
WithSchema sets the config schema and returns a reference to the config.
func (*Config) WithUsername ¶
WithUsername sets the config username and returns a reference to the config.
type Connection ¶
Connection is the basic wrapper for connection parameters and saves a reference to the created sql.Connection.
func Default ¶
func Default() *Connection
Default returns a reference to the DbConnection set as default.
spiffy.Default().Exec("select 'ok!")
func MustNewFromConfig ¶
func MustNewFromConfig(cfg *Config) *Connection
MustNewFromConfig returns a new connection from a config and panics if there is an error.
func MustNewFromEnv ¶
func MustNewFromEnv() *Connection
MustNewFromEnv creates a new db connection from environment variables. It will panic if there is an error.
func New ¶
func New() *Connection
New returns a new Connection. It will use very bare bones defaults for the config.
func NewFromConfig ¶
func NewFromConfig(cfg *Config) (*Connection, error)
NewFromConfig returns a new connection from a config.
func NewFromEnv ¶
func NewFromEnv() (*Connection, error)
NewFromEnv will returns a new connection from a config set from environment variables.
func (*Connection) Background ¶
func (dbc *Connection) Background() context.Context
Background returns an empty context.Context.
func (*Connection) BeginContext ¶
func (dbc *Connection) BeginContext(context context.Context, opts ...*sql.TxOptions) (*sql.Tx, error)
BeginContext starts a new transaction in a givent context.
func (*Connection) Connection ¶
func (dbc *Connection) Connection() *sql.DB
Connection returns the underlying driver connection.
func (*Connection) Create ¶
func (dbc *Connection) Create(object DatabaseMapped) error
Create writes an object to the database.
func (*Connection) CreateContext ¶
func (dbc *Connection) CreateContext(context context.Context, object DatabaseMapped) error
CreateContext writes an object to the database.
func (*Connection) CreateIfNotExists ¶
func (dbc *Connection) CreateIfNotExists(object DatabaseMapped) error
CreateIfNotExists writes an object to the database if it does not already exist.
func (*Connection) CreateIfNotExistsContext ¶
func (dbc *Connection) CreateIfNotExistsContext(context context.Context, object DatabaseMapped) error
CreateIfNotExistsContext writes an object to the database if it does not already exist.
func (*Connection) CreateIfNotExistsInTx ¶
func (dbc *Connection) CreateIfNotExistsInTx(object DatabaseMapped, tx *sql.Tx) (err error)
CreateIfNotExistsInTx writes an object to the database if it does not already exist within a transaction.
func (*Connection) CreateIfNotExistsInTxContext ¶
func (dbc *Connection) CreateIfNotExistsInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
CreateIfNotExistsInTxContext writes an object to the database if it does not already exist within a transaction.
func (*Connection) CreateInTx ¶
func (dbc *Connection) CreateInTx(object DatabaseMapped, tx *sql.Tx) (err error)
CreateInTx writes an object to the database within a transaction.
func (*Connection) CreateInTxContext ¶
func (dbc *Connection) CreateInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
CreateInTxContext writes an object to the database within a transaction.
func (*Connection) CreateMany ¶
func (dbc *Connection) CreateMany(objects interface{}) error
CreateMany writes many an objects to the database.
func (*Connection) CreateManyContext ¶
func (dbc *Connection) CreateManyContext(context context.Context, objects interface{}) error
CreateManyContext writes many an objects to the database.
func (*Connection) CreateManyInTx ¶
func (dbc *Connection) CreateManyInTx(objects interface{}, tx *sql.Tx) (err error)
CreateManyInTx writes many an objects to the database within a transaction.
func (*Connection) CreateManyInTxContext ¶
func (dbc *Connection) CreateManyInTxContext(context context.Context, objects interface{}, tx *sql.Tx) (err error)
CreateManyInTxContext writes many an objects to the database within a transaction.
func (*Connection) Delete ¶
func (dbc *Connection) Delete(object DatabaseMapped) error
Delete deletes an object from the database.
func (*Connection) DeleteContext ¶
func (dbc *Connection) DeleteContext(context context.Context, object DatabaseMapped) error
DeleteContext deletes an object from the database.
func (*Connection) DeleteInTx ¶
func (dbc *Connection) DeleteInTx(object DatabaseMapped, tx *sql.Tx) (err error)
DeleteInTx deletes an object from the database wrapped in a transaction.
func (*Connection) DeleteInTxContext ¶
func (dbc *Connection) DeleteInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
DeleteInTxContext deletes an object from the database wrapped in a transaction.
func (*Connection) Exec ¶
func (dbc *Connection) Exec(statement string, args ...interface{}) error
Exec runs the statement without creating a QueryResult.
func (*Connection) ExecContext ¶
func (dbc *Connection) ExecContext(context context.Context, statement string, args ...interface{}) error
ExecContext runs the statement without creating a QueryResult.
func (*Connection) ExecContextWithLabel ¶
func (dbc *Connection) ExecContextWithLabel(context context.Context, statement, label string, args ...interface{}) error
ExecContextWithLabel runs the statement without creating a QueryResult.
func (*Connection) ExecInTx ¶
func (dbc *Connection) ExecInTx(statement string, tx *sql.Tx, args ...interface{}) (err error)
ExecInTx runs a statement within a transaction.
func (*Connection) ExecInTxContext ¶
func (dbc *Connection) ExecInTxContext(context context.Context, statement string, tx *sql.Tx, args ...interface{}) (err error)
ExecInTxContext runs a statement within a transaction with a context.
func (*Connection) ExecInTxContextWithLabel ¶
func (dbc *Connection) ExecInTxContextWithLabel(context context.Context, statement, label string, tx *sql.Tx, args ...interface{}) (err error)
ExecInTxContextWithLabel runs a statement within a transaction with a label and a context.
func (*Connection) ExecWithLabel ¶
func (dbc *Connection) ExecWithLabel(statement, label string, args ...interface{}) error
ExecWithLabel runs the statement without creating a QueryResult.
func (*Connection) Exists ¶
func (dbc *Connection) Exists(object DatabaseMapped) (bool, error)
Exists returns a bool if a given object exists (utilizing the primary key columns if they exist).
func (*Connection) ExistsContext ¶
func (dbc *Connection) ExistsContext(context context.Context, object DatabaseMapped) (bool, error)
ExistsContext returns a bool if a given object exists (utilizing the primary key columns if they exist).
func (*Connection) ExistsInTx ¶
func (dbc *Connection) ExistsInTx(object DatabaseMapped, tx *sql.Tx) (exists bool, err error)
ExistsInTx returns a bool if a given object exists (utilizing the primary key columns if they exist) wrapped in a transaction.
func (*Connection) ExistsInTxContext ¶
func (dbc *Connection) ExistsInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (exists bool, err error)
ExistsInTxContext returns a bool if a given object exists (utilizing the primary key columns if they exist) wrapped in a transaction.
func (*Connection) Get ¶
func (dbc *Connection) Get(object DatabaseMapped, ids ...interface{}) error
Get returns a given object based on a group of primary key ids.
func (*Connection) GetAll ¶
func (dbc *Connection) GetAll(collection interface{}) error
GetAll returns all rows of an object mapped table.
func (*Connection) GetAllContext ¶
func (dbc *Connection) GetAllContext(context context.Context, collection interface{}) error
GetAllContext returns all rows of an object mapped table.
func (*Connection) GetAllInTx ¶
func (dbc *Connection) GetAllInTx(collection interface{}, tx *sql.Tx) error
GetAllInTx returns all rows of an object mapped table wrapped in a transaction.
func (*Connection) GetAllInTxContext ¶
func (dbc *Connection) GetAllInTxContext(context context.Context, collection interface{}, tx *sql.Tx) error
GetAllInTxContext returns all rows of an object mapped table wrapped in a transaction.
func (*Connection) GetContext ¶
func (dbc *Connection) GetContext(context context.Context, object DatabaseMapped, ids ...interface{}) error
GetContext returns a given object based on a group of primary key ids using the given context.
func (*Connection) GetInTx ¶
func (dbc *Connection) GetInTx(object DatabaseMapped, tx *sql.Tx, args ...interface{}) error
GetInTx returns a given object based on a group of primary key ids within a transaction.
func (*Connection) GetInTxContext ¶
func (dbc *Connection) GetInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx, args ...interface{}) error
GetInTxContext returns a given object based on a group of primary key ids within a transaction and a given context.
func (*Connection) Invoke ¶
func (dbc *Connection) Invoke(context context.Context, txs ...*sql.Tx) *Invocation
Invoke returns a new invocation.
func (*Connection) Logger ¶
func (dbc *Connection) Logger() *logger.Logger
Logger returns the diagnostics agent.
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) PingContext ¶
func (dbc *Connection) PingContext(context context.Context) (err error)
PingContext checks the db connection.
func (*Connection) PrepareContext ¶
func (dbc *Connection) PrepareContext(context context.Context, statementID, statement string, txs ...*sql.Tx) (stmt *sql.Stmt, err error)
PrepareContext prepares a statement potentially returning a cached version of the statement.
func (*Connection) Query ¶
func (dbc *Connection) Query(statement string, args ...interface{}) *Query
Query runs the selected statement and returns a Query.
func (*Connection) QueryContext ¶
func (dbc *Connection) QueryContext(context context.Context, statement string, args ...interface{}) *Query
QueryContext runs the selected statement and returns a Query.
func (*Connection) QueryContextWithLabel ¶
func (dbc *Connection) QueryContextWithLabel(context context.Context, statement, label string, args ...interface{}) *Query
QueryContextWithLabel runs the selected statement and returns a Query.
func (*Connection) QueryInTx ¶
func (dbc *Connection) QueryInTx(statement string, tx *sql.Tx, args ...interface{}) (result *Query)
QueryInTx runs the selected statement in a transaction and returns a Query.
func (*Connection) QueryInTxContext ¶
func (dbc *Connection) QueryInTxContext(context context.Context, statement string, tx *sql.Tx, args ...interface{}) (result *Query)
QueryInTxContext runs the selected statement in a transaction and returns a Query.
func (*Connection) QueryInTxContextWithLabel ¶
func (dbc *Connection) QueryInTxContextWithLabel(context context.Context, statement, label string, tx *sql.Tx, args ...interface{}) (result *Query)
QueryInTxContextWithLabel runs the selected statement in a transaction and returns a Query.
func (*Connection) QueryInTxWithLabel ¶
func (dbc *Connection) QueryInTxWithLabel(statement, label string, tx *sql.Tx, args ...interface{}) (result *Query)
QueryInTxWithLabel runs the selected statement in a transaction and returns a Query.
func (*Connection) QueryWithLabel ¶
func (dbc *Connection) QueryWithLabel(statement, label string, args ...interface{}) *Query
QueryWithLabel runs the selected statement and returns a Query.
func (*Connection) StatementCache ¶
func (dbc *Connection) StatementCache() *StatementCache
StatementCache returns the statement cache.
func (*Connection) StatementInterceptor ¶ added in v0.3.1
func (dbc *Connection) StatementInterceptor() StatementInterceptor
StatementInterceptor returns the statement interceptor.
func (*Connection) Truncate ¶
func (dbc *Connection) Truncate(object DatabaseMapped) error
Truncate fully removes an tables rows in a single opertation.
func (*Connection) TruncateContext ¶
func (dbc *Connection) TruncateContext(context context.Context, object DatabaseMapped) error
TruncateContext fully removes an tables rows in a single opertation.
func (*Connection) TruncateInTx ¶
func (dbc *Connection) TruncateInTx(object DatabaseMapped, tx *sql.Tx) error
TruncateInTx applies a truncation in a transaction.
func (*Connection) TruncateInTxContext ¶
func (dbc *Connection) TruncateInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) error
TruncateInTxContext applies a truncation in a transaction.
func (*Connection) Update ¶
func (dbc *Connection) Update(object DatabaseMapped) error
Update updates an object.
func (*Connection) UpdateContext ¶
func (dbc *Connection) UpdateContext(context context.Context, object DatabaseMapped) error
UpdateContext updates an object.
func (*Connection) UpdateInTx ¶
func (dbc *Connection) UpdateInTx(object DatabaseMapped, tx *sql.Tx) (err error)
UpdateInTx updates an object wrapped in a transaction.
func (*Connection) UpdateInTxContext ¶
func (dbc *Connection) UpdateInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
UpdateInTxContext updates an object wrapped in a transaction.
func (*Connection) Upsert ¶
func (dbc *Connection) Upsert(object DatabaseMapped) error
Upsert inserts the object if it doesn't exist already (as defined by its primary keys) or updates it.
func (*Connection) UpsertContext ¶
func (dbc *Connection) UpsertContext(context context.Context, object DatabaseMapped) error
UpsertContext inserts the object if it doesn't exist already (as defined by its primary keys) or updates it.
func (*Connection) UpsertInTx ¶
func (dbc *Connection) UpsertInTx(object DatabaseMapped, tx *sql.Tx) (err error)
UpsertInTx inserts the object if it doesn't exist already (as defined by its primary keys) or updates it wrapped in a transaction.
func (*Connection) UpsertInTxContext ¶
func (dbc *Connection) UpsertInTxContext(context context.Context, object DatabaseMapped, tx *sql.Tx) (err error)
UpsertInTxContext inserts the object if it doesn't exist already (as defined by its primary keys) or updates it wrapped in a transaction.
func (*Connection) WithConfig ¶
func (dbc *Connection) WithConfig(cfg *Config) *Connection
WithConfig sets the config.
func (*Connection) WithLogger ¶
func (dbc *Connection) WithLogger(log *logger.Logger) *Connection
WithLogger sets the connection's diagnostic agent.
func (*Connection) WithStatementInterceptor ¶ added in v0.3.1
func (dbc *Connection) WithStatementInterceptor(interceptor StatementInterceptor) *Connection
WithStatementInterceptor sets the connection statement interceptor.
func (*Connection) WithTracer ¶
func (dbc *Connection) WithTracer(tracer Tracer) *Connection
WithTracer sets the connection tracer and returns a reference.
type DatabaseMapped ¶
type DatabaseMapped interface{}
DatabaseMapped is the interface that any objects passed into database mapped methods like Create, Update, Delete, Get, GetAll etc.
type Invocation ¶
type Invocation struct {
// contains filtered or unexported fields
}
Invocation is a specific operation against a context.
func (*Invocation) Cancel ¶
func (i *Invocation) Cancel() func()
Cancel returns the optional cancel callback.
func (*Invocation) Context ¶
func (i *Invocation) Context() context.Context
Context returns the underlying context.
func (*Invocation) Create ¶
func (i *Invocation) Create(object DatabaseMapped) (err error)
Create writes an object to the database within a transaction.
func (*Invocation) CreateIfNotExists ¶
func (i *Invocation) CreateIfNotExists(object DatabaseMapped) (err error)
CreateIfNotExists writes an object to the database if it does not already exist within a transaction.
func (*Invocation) CreateMany ¶
func (i *Invocation) CreateMany(objects interface{}) (err error)
CreateMany writes many objects to the database in a single insert. Important; this will not use cached statements ever because the generated query is different for each cardinality of objects.
func (*Invocation) Delete ¶
func (i *Invocation) Delete(object DatabaseMapped) (err error)
Delete deletes an object from the database wrapped in a transaction.
func (*Invocation) Exec ¶
func (i *Invocation) Exec(statement string, args ...interface{}) (err error)
Exec executes a sql statement with a given set of arguments.
func (*Invocation) Exists ¶
func (i *Invocation) Exists(object DatabaseMapped) (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 DatabaseMapped, ids ...interface{}) (err error)
Get returns a given object based on a group of primary key ids within a transaction.
func (*Invocation) GetAll ¶
func (i *Invocation) GetAll(collection interface{}) (err error)
GetAll returns all rows of an object mapped table wrapped in a transaction.
func (*Invocation) Label ¶
func (i *Invocation) Label() string
Label returns the statement / plan cache label for the context.
func (*Invocation) Prepare ¶
func (i *Invocation) Prepare(statement string) (stmt *sql.Stmt, err error)
Prepare returns a cached or newly prepared statment plan for a given sql statement.
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) StartTime ¶
func (i *Invocation) StartTime() time.Time
StartTime returns the invocation start time.
func (*Invocation) StatementInterceptor ¶ added in v0.3.1
func (i *Invocation) StatementInterceptor() StatementInterceptor
StatementInterceptor returns the statement interceptor.
func (*Invocation) Truncate ¶
func (i *Invocation) Truncate(object DatabaseMapped) (err error)
Truncate completely empties a table in a single command.
func (*Invocation) Update ¶
func (i *Invocation) Update(object DatabaseMapped) (err error)
Update updates an object wrapped in a transaction.
func (*Invocation) Upsert ¶
func (i *Invocation) Upsert(object DatabaseMapped) (err error)
Upsert inserts the object if it doesn't exist already (as defined by its primary keys) or updates it wrapped in a transaction.
func (*Invocation) WithCancel ¶
func (i *Invocation) WithCancel(cancel func()) *Invocation
WithCancel sets an optional cancel callback.
func (*Invocation) WithContext ¶
func (i *Invocation) WithContext(context context.Context) *Invocation
WithContext sets the context and returns a reference to the invocation.
func (*Invocation) WithLabel ¶
func (i *Invocation) WithLabel(label string) *Invocation
WithLabel instructs the query generator to get or create a cached prepared statement.
func (*Invocation) WithStatementInterceptor ¶ added in v0.3.1
func (i *Invocation) WithStatementInterceptor(interceptor StatementInterceptor) *Invocation
WithStatementInterceptor sets the connection statement interceptor.
type Populatable ¶
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) 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) (err error)
First executes the consumer for the first result of a query.
type Rows ¶
type Rows interface { Scanner ColumnsProvider }
Rows provides the relevant fields to populate by name.
type RowsConsumer ¶
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 StatementCache ¶
type StatementCache struct {
// contains filtered or unexported fields
}
StatementCache is a cache of prepared statements.
func NewStatementCache ¶
func NewStatementCache() *StatementCache
NewStatementCache returns a new `StatementCache`.
func (*StatementCache) Close ¶
func (sc *StatementCache) Close() (err error)
Close implements io.Closer.
func (*StatementCache) Connection ¶
func (sc *StatementCache) Connection() *sql.DB
Connection returns the underlying connection.
func (*StatementCache) Enabled ¶
func (sc *StatementCache) Enabled() bool
Enabled returns if the statement cache is enabled.
func (*StatementCache) HasStatement ¶
func (sc *StatementCache) HasStatement(statementID string) bool
HasStatement returns if the cache contains a statement.
func (*StatementCache) InvalidateStatement ¶
func (sc *StatementCache) InvalidateStatement(statementID string) (err error)
InvalidateStatement removes a statement from the cache.
func (*StatementCache) PrepareContext ¶
func (sc *StatementCache) PrepareContext(context context.Context, statementID, statement string) (*sql.Stmt, error)
PrepareContext returns a cached expression for a statement, or creates and caches a new one.
func (*StatementCache) WithConnection ¶
func (sc *StatementCache) WithConnection(conn *sql.DB) *StatementCache
WithConnection sets the statement cache connection.
func (*StatementCache) WithEnabled ¶
func (sc *StatementCache) WithEnabled(enabled bool) *StatementCache
WithEnabled sets if the cache is enabled.
type StatementInterceptor ¶ added in v0.3.1
StatementInterceptor is an interceptor for statements.
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 TraceFinisher ¶
type TraceFinisher interface {
Finish(error)
}
TraceFinisher is a type that can finish traces.
type Tracer ¶
type Tracer interface { Ping(context.Context, *Connection) TraceFinisher Prepare(context.Context, *Connection, string) TraceFinisher Query(context.Context, *Connection, *Invocation, string) TraceFinisher }
Tracer is a type that can implement traces. If any of the methods return a nil finisher, they will be skipped.