Documentation
¶
Index ¶
- Constants
- Variables
- func ColumnNames(cols []*Column) []string
- func ColumnNamesCSV(cols []*Column) string
- func ColumnNamesFromAlias(cols []*Column, tableAlias string) []string
- func ColumnNamesFromAliasCSV(cols []*Column, tableAlias string) string
- func ColumnNamesWithPrefix(cols []*Column, columnPrefix string) []string
- func ColumnNamesWithPrefixCSV(cols []*Column, columnPrefix string) string
- func ColumnNamesWithPrefixFromAlias(cols []*Column, columnPrefix, tableAlias string) []string
- func ColumnNamesWithPrefixFromAliasCSV(cols []*Column, columnPrefix, tableAlias string) string
- func ColumnValues(cols []*Column, instance any) (output []any)
- func Each(rows *sql.Rows, consumer RowsConsumer) (err error)
- func ExecAffectedAny(res sql.Result, err error) (bool, error)
- func ExecErr(_ sql.Result, err error) error
- func First(rows *sql.Rows, consumer RowsConsumer) (found bool, err error)
- func HasColumn(cols []*Column, name string) bool
- func IsPopulatable(object any) (isPopulatable bool)
- func IsScanner(object any) (isScanner bool)
- func JSON(obj any) any
- func PopulateByName(object any, row Rows, cols *TypeMeta) error
- func PopulateInOrder(object any, row Scanner, cols []*Column) (err error)
- func Scan(rows *sql.Rows, args ...any) (found bool, err error)
- func TableName(obj any) string
- func TableNameByType(t reflect.Type) string
- func Zero(object any) error
- type BufferPool
- type Column
- type ColumnMetaCacheKeyProvider
- type ColumnsProvider
- type Config
- type Connection
- func (dbc *Connection) BeginTx(ctx context.Context, opts ...func(*sql.TxOptions)) (*sql.Tx, error)
- func (dbc *Connection) Close() error
- func (dbc *Connection) Exec(statement string, args ...interface{}) (sql.Result, error)
- func (dbc *Connection) ExecContext(ctx context.Context, statement string, args ...interface{}) (sql.Result, error)
- func (dbc *Connection) Invoke(options ...InvocationOption) *Invocation
- func (dbc *Connection) Open() error
- func (dbc *Connection) Prepare(ctx context.Context, statement string) (stmt *sql.Stmt, err error)
- func (dbc *Connection) Query(statement string, args ...interface{}) *Query
- func (dbc *Connection) QueryContext(ctx context.Context, statement string, args ...interface{}) *Query
- func (dbc *Connection) RegisterOnQuery(fn func(QueryEvent))
- func (dbc *Connection) Stats() sql.DBStats
- func (dbc *Connection) TypeMeta(object any) *TypeMeta
- func (dbc *Connection) TypeMetaFromType(identifier string, t reflect.Type) *TypeMeta
- type DB
- type Dialect
- type Invocation
- func (i *Invocation) All(collection interface{}) (err error)
- func (i *Invocation) Create(object any) (err error)
- func (i *Invocation) CreateIfNotExists(object any) (err error)
- func (i *Invocation) Delete(object any) (deleted bool, err error)
- func (i *Invocation) Exec(statement string, args ...interface{}) (res sql.Result, err error)
- func (i *Invocation) Exists(object any) (exists bool, err error)
- func (i *Invocation) Get(object any, ids ...any) (found bool, err error)
- func (i *Invocation) GetMany(collection any, ids ...any) (err error)
- func (i *Invocation) Query(statement string, args ...interface{}) *Query
- func (i *Invocation) Update(object any) (updated bool, err error)
- func (i *Invocation) Upsert(object any) (err error)
- type InvocationOption
- type Logger
- type Option
- func OptConfig(cfg Config) Option
- func OptConfigFromEnv() Option
- func OptConnection(conn *sql.DB) Option
- func OptDatabase(database string) Option
- func OptDialect(dialect Dialect) Option
- func OptEngine(engine string) Option
- func OptHost(host string) Option
- func OptLog(log Logger) Option
- func OptPassword(password string) Option
- func OptPort(port string) Option
- func OptSSLMode(mode string) Option
- func OptSchema(schema string) Option
- func OptUsername(username string) Option
- type Populatable
- type Query
- func (q *Query) Any() (found bool, err error)
- func (q *Query) Do() (rows *sql.Rows, err error)
- func (q *Query) Each(consumer RowsConsumer) (err error)
- func (q *Query) First(consumer RowsConsumer) (found bool, err error)
- func (q *Query) None() (notFound bool, err error)
- func (q *Query) Out(object any) (found bool, err error)
- func (q *Query) OutMany(collection any) (err error)
- func (q *Query) Scan(args ...any) (found bool, err error)
- type QueryEvent
- type Rows
- type RowsConsumer
- type Scanner
- type TableNameProvider
- type TypeMeta
- func (cc *TypeMeta) Add(c Column)
- func (cc *TypeMeta) Autos() []*Column
- func (cc *TypeMeta) Column(columnName string) (c *Column)
- func (cc *TypeMeta) Columns() (output []*Column)
- func (cc *TypeMeta) Copy() *TypeMeta
- func (cc *TypeMeta) CopyWithColumnPrefix(prefix string) *TypeMeta
- func (cc *TypeMeta) HasColumn(columnName string) bool
- func (cc *TypeMeta) InsertColumns() []*Column
- func (cc *TypeMeta) Len() int
- func (cc *TypeMeta) Lookup() map[string]*Column
- func (cc *TypeMeta) NotAutos() []*Column
- func (cc *TypeMeta) NotPrimaryKeys() []*Column
- func (cc *TypeMeta) NotReadOnly() []*Column
- func (cc *TypeMeta) NotUniqueKeys() []*Column
- func (cc *TypeMeta) PrimaryKeys() []*Column
- func (cc *TypeMeta) ReadOnly() []*Column
- func (cc *TypeMeta) Remove(columnName string)
- func (cc *TypeMeta) UniqueKeys() []*Column
- func (cc *TypeMeta) UpdateColumns() []*Column
Constants ¶
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" )
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" )
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" )
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 )
const ( // DefaultEngine is the default database engine. DefaultEngine = "pgx" // "postgres" )
Variables ¶
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 ¶
ColumnNames returns the string names for all the columns in the collection.
func ColumnNamesCSV ¶
ColumnNamesCSV returns a csv of column names.
func ColumnNamesFromAlias ¶
ColumnNamesFromAlias returns the string names for all the columns in the collection.
func ColumnNamesFromAliasCSV ¶
ColumnNamesCSV returns a csv of column names.
func ColumnNamesWithPrefix ¶
ColumnNamesWithPrefix returns the string names for all the columns in the collection with a given disambiguation prefix.
func ColumnNamesWithPrefixCSV ¶
ColumnNamesWithPrefixCSV returns a csv of column names with a given disambiguation prefix.
func ColumnNamesWithPrefixFromAlias ¶
ColumnNamesWithPrefixFromAlias returns the string names for all the columns in the collection.
func ColumnNamesWithPrefixFromAliasCSV ¶
ColumnNamesCSV returns a csv of column names.
func ColumnValues ¶
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 ¶
ExecAffectedAny is a helper that returns if a given Exec result affected any rows.
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 IsPopulatable ¶
IsPopulatable returns if an object is populatable
func PopulateByName ¶
PopulateByName sets the values of an object from the values of a sql.Rows object using column names.
func PopulateInOrder ¶
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 ¶
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 ¶
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 BufferPool ¶
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.
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 ¶
ColumnsNotZero returns set fields on an instance that correspond to fields in the column collection.
func ColumnsZero ¶
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"
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"` // 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) CreateLoggingDSN ¶
CreateLoggingDSN creates a postgres connection string from the config suitable for logging. It will not include the password.
func (Config) Validate ¶
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 ¶
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) 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 ¶
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" )
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 Option ¶
type Option func(c *Connection) error
Option is an option for database connections.
func OptConfigFromEnv ¶
func OptConfigFromEnv() Option
OptConfigFromEnv sets the config on a connection from the environment.
func OptConnection ¶
OptConnection sets the underlying driver connection.
func OptDatabase ¶
OptDatabase sets the connection database.
func OptEngine ¶
OptEngine sets the connection engine. You must have this engine registered with database/sql.
func OptPassword ¶
OptPassword sets the connection ssl mode.
func OptUsername ¶
OptUsername sets the connection ssl mode.
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) (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) Out ¶
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.
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 ¶
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 ¶
NewTypeMetaFromColumns returns a new TypeMeta instance from a given list of columns.
func NewTypeMetaFromColumnsWithPrefix ¶
NewTypeMetaFromColumnsWithPrefix makes a new TypeMeta instance from a given list of columns with a column prefix.
func TypeMetaFor ¶
TypeMetaFor returns the TypeMeta for an object.
func (*TypeMeta) Copy ¶
Copy creates a new TypeMeta instance and carries over an existing column prefix.
func (*TypeMeta) CopyWithColumnPrefix ¶
CopyWithColumnPrefix applies a column prefix to column names and returns a new column collection.
func (*TypeMeta) InsertColumns ¶
InsertColumns are non-auto, non-readonly columns.
func (*TypeMeta) NotPrimaryKeys ¶
NotPrimaryKeys are columns we can update.
func (*TypeMeta) NotReadOnly ¶
NotReadOnly are columns that we have to insert upon Create().
func (*TypeMeta) NotUniqueKeys ¶
NotUniqueKeys are columns we can update.
func (*TypeMeta) PrimaryKeys ¶
PrimaryKeys are columns we use as where predicates and can't update.
func (*TypeMeta) UniqueKeys ¶
UniqueKeys are columns we use as where predicates and can't update.
func (*TypeMeta) UpdateColumns ¶
UpdateColumns are non-primary key, non-readonly columns.