Documentation ¶
Index ¶
- Variables
- func RegisterDriver(name string, d driver.DriverContext)
- type Batch
- type BatchConfig
- type BatchOperationMode
- type BatchRemove
- type BatchResults
- type Column
- type Connection
- func (c *Connection) BeginTX(ctx context.Context, options *TXOptions) (TX, error)
- func (c *Connection) Close() error
- func (c *Connection) Connection() driver.Conn
- func (c *Connection) Exec(ctx context.Context, query string, args ...any) (Result, error)
- func (c *Connection) NewBatch(ctx context.Context, cfg *BatchConfig) (Batch, error)
- func (c *Connection) Ping(ctx context.Context) error
- func (c *Connection) Prepare(_ context.Context, _ string) (Statement, error)
- func (c *Connection) Query(ctx context.Context, query string, args ...any) (Rows, error)
- func (c *Connection) QueryRow(ctx context.Context, query string, args ...any) Row
- type ConnectionConfig
- type DB
- type NamedArg
- type RawBytes
- type Result
- type Row
- type Rows
- type Scanner
- type Statement
- type TX
- type TXAccessMode
- type TXIsolationLevel
- type TXOptions
Constants ¶
This section is empty.
Variables ¶
var ( ErrDBClosed = errors.New("db is closed") ErrMissingPoolConfig = errors.New("no pool config provided") ErrMissingConnectionConfig = errors.New("no connection config provided") ErrMissingDriverName = errors.New("driver name is a mandatory config") ErrMissingURL = errors.New("url is a mandatory config") ErrPoolSpaceNotAvailable = errors.New("no space available to create new connections") ErrORMClosed = errors.New("orm is closed") ErrPoolClosed = errors.New("closed pool") ErrRowsClosed = errors.New("rows are closed") ErrNoRows = errors.New("no rows in result set") ErrNoRowsAffected = errors.New("no rows affected") ErrRowsScanWithoutNext = errors.New("scan called without calling next") ErrRowsUnexpectedScanValues = errors.New("unexpected scan values") ErrRowsUnexpectedScan = errors.New("unexpected scan") ErrRowsUnsupportedScan = errors.New("unsupported scan") ErrTXClosed = errors.New("transaction has already been committed or rolled back") ErrTXOptionsInvalidIsolationLevel = errors.New("invalid transaction isolation level") ErrTXOptionsInvalidAccessMode = errors.New("invalid transaction access mode") ErrNamedArgNoLetterBegin = errors.New("name does not begin with a letter") ErrConvertingArgumentToNamedArg = errors.New("unable to convert argument to named arg") ErrNilPointer = errors.New("destination pointer is nil") ErrNotAPointer = errors.New("destination is not a pointer") ErrBadConnection = errors.New("bad connection") ErrScanToStructureNotEnabled = errors.New("scanning to a structure not enabled") ErrBatchProcessing = errors.New("batch is processing") ErrBatchClosed = errors.New("batch is closed") )
errors
Functions ¶
func RegisterDriver ¶
func RegisterDriver(name string, d driver.DriverContext)
RegisterDriver is used to register a driver.
Types ¶
type Batch ¶
type Batch interface { // QueueQuery queues a query that returns rows once executed, typically a SELECT. // The args are for any placeholder parameters in the query. QueueQuery(ctx context.Context, query string, args ...any) BatchRemove // QueueQueryRow queues a query that is expected to return at most one row. // When executed, it always returns a non-nil value. Errors are deferred until // [Row]'s Scan method is called. // If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. // Otherwise, [*Row.Scan] scans the first selected row and discards // the rest. QueueQueryRow(ctx context.Context, query string, args ...any) BatchRemove // QueueExec queues a query that just executes without returning any rows. // The args are for any placeholder parameters in the query. QueueExec(ctx context.Context, query string, args ...any) BatchRemove // Do is used to execute all the queued queries. // It returns the result as an iterator, providing specific methods for all the above operations. Do(ctx context.Context) (BatchResults, error) // Close is used to close the batch, releasing the connection(making it available for use somewhere else). // If Close is called before Do, then all the queued queries will be removed. Close(ctx context.Context) error }
Batch is used as the set of functionalities for a batch operation on the database.
type BatchConfig ¶
type BatchConfig struct{}
BatchConfig is used as the set of configurations for batch.
type BatchOperationMode ¶
type BatchOperationMode string
BatchOperationMode is used to specify the type of the operation.
const ( BatchOperationModeQueryRow BatchOperationMode = "QUERY_ROW" BatchOperationModeQuery BatchOperationMode = "QUERY" BatchOperationModeExec BatchOperationMode = "EXEC" )
batch operation modes
type BatchRemove ¶
type BatchRemove func()
BatchRemove can be called to remove the corresponding queued operation from the batch. It is a noop if the batch is already processing([Batch.Do] has already been called) or batch is already closed([Batch.Close] has already been called).
type BatchResults ¶
type BatchResults interface{}
BatchResults is used as the results for the batch.
type Column ¶
type Column struct {
// contains filtered or unexported fields
}
Column is used to provide the details around the columns of the values part of the result set.
func (*Column) DatabaseTypeName ¶
DatabaseTypeName returns the database system name of the column type. If an empty string is returned, then the driver type name is not supported. Consult your driver documentation for a list of driver data types. Column.Length specifiers are not included. Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", and "BIGINT".
func (*Column) Length ¶
Length returns the column type length for variable length column types such as text and binary field types. If the type length is unbounded the value will be math.MaxInt64 (any database limits will still apply). If the column type is not variable length, such as an int, or if not supported by the driver ok is false.
func (*Column) Nullable ¶
Nullable reports whether the column may be null. If a driver does not support this property ok will be false.
func (*Column) PrecisionScale ¶
PrecisionScale returns the scale and precision of a decimal type. If not applicable or if not supported ok is false.
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection is used as the connection created.
func (*Connection) BeginTX ¶
BeginTX starts a transaction.
The provided context is used until the transaction is committed or rolled back. If the context is canceled, the `alphasql` package will roll back the transaction. [TX.Commit] will return an error if the context provided to BeginTX is canceled.
The provided TXOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.
func (*Connection) Close ¶
func (c *Connection) Close() error
Close invalidates and potentially stops any current prepared statements and transactions, marking this connection as no longer in use.
Because the sql package maintains a free pool of connections and only calls Close when there's a surplus of idle connections, it shouldn't be necessary for drivers to do their own connection caching.
Drivers must ensure all network calls made by Close do not block indefinitely (e.g. apply a timeout).
func (*Connection) Connection ¶
func (c *Connection) Connection() driver.Conn
Connection is used to get the underlying driver connection.
func (*Connection) Exec ¶
Exec executes a query without returning any rows. The args are for any placeholder parameters in the query.
func (*Connection) NewBatch ¶
func (c *Connection) NewBatch(ctx context.Context, cfg *BatchConfig) (Batch, error)
NewBatch is used to provide a way to batch queries to save round-trip.
func (*Connection) Ping ¶
func (c *Connection) Ping(ctx context.Context) error
Ping verifies a Connection to the database is still alive, establishing a Connection if necessary.
func (*Connection) Prepare ¶
Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's [Statement.Close] method when the statement is no longer needed.
func (*Connection) Query ¶
Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.
func (*Connection) QueryRow ¶
QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until alphasql.Row's Scan method is called. If the query selects no rows, the [*Row.Scan] will return ErrNoRows. Otherwise, [*Row.Scan] scans the first selected row and discards the rest.
type ConnectionConfig ¶
ConnectionConfig is the set of parameters needed to initialise the connection.
func (*ConnectionConfig) Copy ¶
func (c *ConnectionConfig) Copy() *ConnectionConfig
Copy is used to copy the connection config.
func (*ConnectionConfig) ValidateAndDefault ¶
func (c *ConnectionConfig) ValidateAndDefault() error
ValidateAndDefault is used to validate and set the defaults for the mandatory parameters not passed.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is the instance that will be used to start new connections.
func Open ¶
func Open(ctx context.Context, cfg *ConnectionConfig) (*DB, error)
Open is used to open a new DB instance to manage the connections.
type NamedArg ¶
NamedArg is a named argument. NamedArg values may be used as arguments to Connection.Query or Connection.QueryRow or Connection.Exec and bind to the corresponding named parameter in the SQL statement.
For a more concise way to create NamedArg values, see the Named function.
type RawBytes ¶
type RawBytes []byte
RawBytes is a byte slice that holds a reference to memory owned by the database itself. After a [Rows.Scan] into a RawBytes, the slice is only valid until the next call to [Rows.Next], [Rows.Scan], or [Rows.Close].
type Row ¶
type Row interface { // Scan copies the columns from the matched row into the values // pointed at by dest. See the documentation on [Rows.Scan] for details. // If more than one row matches the query, // Scan uses the first row and discards the rest. If no row matches // the query, Scan returns [ErrNoRows]. Scan(ctx context.Context, values ...any) error Columns() []Column // Error provides a way for wrapping packages to check for // query errors without calling [Row.Scan]. // Error returns the error, if any, that was encountered while running the query. // If this error is not nil, this error will also be returned from [Row.Scan]. Error() error }
type Rows ¶
type Rows interface { // Next prepares the next result row for reading with the [Rows.Scan] method. It // returns true on success, or false if there is no next result row or an error // happened while preparing it. [Rows.Err] should be consulted to distinguish between // the two cases. // // Every call to [Rows.Scan], even the first one, must be preceded by a call to [Rows.Next]. Next(ctx context.Context) bool // NextResultSet prepares the next result set for reading. It reports whether // there is further result sets, or false if there is no further result set // or if there is an error advancing to it. The [Rows.Err] method should be consulted // to distinguish between the two cases. // // After calling NextResultSet, the [Rows.Next] method should always be called before // scanning. If there are further result sets they may not have rows in the result // set. NextResultSet(ctx context.Context) bool // Error returns the error, if any, that was encountered during iteration. // Error may be called after an explicit or implicit [Rows.Close]. Error() error // Close closes the [Rows], preventing further enumeration. If [Rows.Next] is called // and returns false and there are no further result sets, // the [Rows] are closed automatically, and it will suffice to check the // result of [Rows.Err]. Close is idempotent and does not affect the result of [Rows.Error]. Close(ctx context.Context) error // Scan copies the columns in the current row into the values pointed // at by dest. The number of values in dest must be the same as the // number of columns in [Rows]. // // Scan converts columns read from the database into the following // common Go types and special types provided by the sql package: // // *string // *[]byte // *int, *int8, *int16, *int32, *int64 // *uint, *uint8, *uint16, *uint32, *uint64 // *bool // *float32, *float64 // *interface{} // *RawBytes // *Rows (cursor value) // any type implementing Scanner (see Scanner docs) // // In the most simple case, if the type of the value from the source // column is an integer, bool or string type T and dest is of type *T, // Scan simply assigns the value through the pointer. // // Scan also converts between string and numeric types, as long as no // information would be lost. While Scan stringifies all numbers // scanned from numeric database columns into *string, scans into // numeric types are checked for overflow. For example, a float64 with // value 300 or a string with value "300" can scan into an uint16, but // not into an uint8, though float64(255) or "255" can scan into an // uint8. One exception is that scans of some float64 numbers to // strings may lose information when stringing. In general, scan // floating point columns into *float64. // // If a dest argument has type *[]byte, Scan saves in that argument a // copy of the corresponding data. The copy is owned by the caller and // can be modified and held indefinitely. The copy can be avoided by // using an argument of type [*RawBytes] instead; see the documentation // for [RawBytes] for restrictions on its use. // // If an argument has type *interface{}, Scan copies the value // provided by the underlying driver without conversion. When scanning // from a source value of type []byte to *interface{}, a copy of the // slice is made and the caller owns the result. // // Source values of type [time.Time] may be scanned into values of type // *time.Time, *interface{}, *string, or *[]byte. When converting to // the latter two, [time.RFC3339Nano] is used. // // Source values of type bool may be scanned into types *bool, // *interface{}, *string, *[]byte, or [*RawBytes]. // // For scanning into *bool, the source may be true, false, 1, 0, or // string inputs parseable by [strconv.ParseBool]. // // Scan can also convert a cursor returned from a query, such as // "select cursor(select * from my_table) from dual", into a // [Rows] value that can itself be scanned from. The parent // select query will close any cursor [Rows] if the parent [Rows] is closed. // // If any of the first arguments implementing [driver.Scanner] returns an error, // that error will be wrapped in the returned error. Scan(values ...any) error // Columns are used to provide the current set of columns in the result set. // Similar to how until [Rows.Next] is not called, [Rows.Scan] won't work, [Rows.Columns] // will also return stale or nil data until [Rows.Next] is called. // Even though the result set has changed, until [Rows.Next] is called, the column list won't be updated. Columns() []Column }
Rows is the result of a query. Its cursor starts before the first row of the result set. Use [Rows.Next] to advance from row to row.
type Scanner ¶
type Scanner interface { // Scan assigns a value from a database driver. // // The src value will be of one of the following types: // // int64 // float64 // bool // []byte // string // time.Time // nil - for NULL values // // An error should be returned if the value cannot be stored // without loss of information. // // Reference types such as []byte are only valid until the next call to Scan // and should not be retained. Their underlying memory is owned by the driver. // If retention is necessary, copy their values before the next call to Scan. Scan(src any) error }
Scanner is an interface used by [Rows.Scan].
type Statement ¶
type Statement interface { Close(ctx context.Context) error NumberOfInputs() int Exec(ctx context.Context, args ...any) (Result, error) Query(ctx context.Context, args ...any) (Rows, error) QueryRow(ctx context.Context, args ...any) (Row, error) }
Statement is a prepared statement. A Statement is safe for concurrent use by multiple goroutines.
If a Statement is prepared on a TX or Connection, it will be bound to a single underlying connection forever. If the TX or Connection closes, the Statement will become unusable and all operations will return an error.
type TX ¶
type TX interface { Commit(ctx context.Context) error Rollback(ctx context.Context) error Query(ctx context.Context, query string, args ...any) (Rows, error) QueryRow(ctx context.Context, query string, args ...any) Row Exec(ctx context.Context, query string, args ...any) (Result, error) Prepare(ctx context.Context, query string) (Statement, error) Statement(ctx context.Context, s Statement) (Statement, error) KeepConnectionOnRollback() bool }
TX is an in-progress database transaction.
A transaction must end with a call to [TX.Commit] or [TX.Rollback].
After a call to [TX.Commit] or [TX.Rollback], all operations on the transaction fail with ErrTXClosed.
The statements prepared for a transaction by calling the transaction's [TX.Prepare] are closed by the call to [TX.Commit] or [TX.Rollback].
type TXAccessMode ¶
type TXAccessMode string
TXAccessMode is the transaction access mode (read write or read only)
const ( TXAccessModeReadWrite TXAccessMode = "read write" TXAccessModeReadOnly TXAccessMode = "read only" )
Transaction access modes
type TXIsolationLevel ¶
type TXIsolationLevel int
TXIsolationLevel is the transaction isolation level used in TXOptions.
const ( TXIsolationLevelDefault TXIsolationLevel = iota TXIsolationLevelReadUncommitted TXIsolationLevelReadCommitted TXIsolationLevelWriteCommitted TXIsolationLevelRepeatableRead TXIsolationLevelSnapshot TXIsolationLevelSerializable TXIsolationLevelLinearizable )
Various isolation levels that drivers may support in Connection.BeginTX. If a driver does not support a given isolation level an error may be returned.
See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.
type TXOptions ¶
type TXOptions struct { IsolationLevel TXIsolationLevel AccessMode TXAccessMode }
TXOptions holds the transaction options to be used in Connection.BeginTX.