sqlx

package module
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2025 License: MIT Imports: 16 Imported by: 3

README

sqlx

Go Coverage license

This is Vinovest's fork of https://github.com/jmoiron/sqlx.git for ongoing support. Sqlx hasn't been updated in a while and we use it extensively, so we're going to maintain this fork with some additional features and bug fixes. You're welcome to use and contribute to this fork!

sqlx is a library which provides a set of extensions on go's standard database/sql library. The sqlx versions of sql.DB, sql.TX, sql.Stmt, et al. all leave the underlying interfaces untouched, so that their interfaces are a superset on the standard ones. This makes it relatively painless to integrate existing codebases using database/sql with sqlx.

Major additional concepts are:

  • Marshal rows into structs (with embedded struct support), maps, and slices
  • Named parameter support including prepared statements
  • Get and Select to go quickly from query to struct/slice
  • Bulk insert SQL builder
  • Generic functions One and List
  • Range function AllRows, or for prepared statements use All

In addition to the godoc API documentation, there is also some user documentation that explains how to use database/sql along with sqlx.

Changes compared to the original sqlx

1.7.0

  • Better scanning in the case of outer joins. If a struct contains a nested struct pointer, it will no longer be a scan error.

  • Made complex joins easier to scan by using the position of the field to help map duplicate column names into structs. See the joins example.

  • Improved "unsafe" mode at the DB level. "Unsafe" isn't all that unsafe, it really is just an additional check when scanning rows. If there's a column in the row result that can't be mapped to the struct, sqlx will return a "missing destination name" error. A new WithUnsafe option for Connect and Open allows you to turn this off.

1.6.0:

  • Set Go version to 1.23.

  • Added AllRows package function and All on statement types to range over rows and automatically close the result set.

  • Added functions One and List for querying with generics. Modifications to types Stmt and NamedStmt to support generics may cause some small compatibility changes that should be quick to resolve with a search and replace. Both are now type aliases to attempt to minimize the impact of this change.

  • fix for sql in-list parsing that will properly ignore question marks in comments and strings. This frequently caused a confusing error ("number of bindVars exceeds arguments").

1.5.0:

  • VALUES bulk insertions were performed by a regex previously, now sqlx will use a tokenizer to parse the query and reliably expand the query for additional bound parameters. This fixes several bugs around named parameters (e.g. :name). Where previously a colon had to be escaped using an additional colon (resulting in ::name), now the query will work as expected.

  • Rebind parsing uses the tokenizer now as well, fixing double quoting and unexpected behavior with colons in sql strings.

  • Get and GetContext will now error if the query returns more than one row. Previously, it fetched the first row and ignored the rest. Using Get on multiple rows is typically a mistake, and this change makes the behavior more consistent and avoids potential bugs.

  • Fix for multiple sql statements ("select a from test; select b from test2;") in a single call. Previously, sqlx cached the columns of the first query and used them for all subsequent queries. This could lead to incorrect results if the queries returned different columns. Now, sqlx will reset the columns for each query on NextResultSet.

  • Adds Queryable interface to unify DB and Tx.

Backwards Compatibility

Compatibility with the most recent two versions of Go is a requirement for any new changes. Compatibility beyond that is not guaranteed.

Versioning is done with Go modules. Breaking changes (eg. removing deprecated API) will get major version number bumps.

Install

go get github.com/vinovest/sqlx

Usage

There are several standalone examples in the examples directory that demonstrate various features of sqlx.

The simplified form of querying using sqlx looks like the below. Given a struct Person, querying all of the rows in the person table is as simple as:

package main

import (
    "fmt"
    
    _ "github.com/lib/pq"
    "github.com/vinovest/sqlx"
)

type Person struct {
    FirstName string `db:"first_name"`
    LastName  string `db:"last_name"`
    Email     string
}

func main() {
    db, _ := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
    people, _ := sqlx.List[Person](db, "SELECT * FROM person")
    fmt.Printf("People %#v\n", people)

    // alternatively, range over rows
    rows, _ := db.Queryx("select * from person")
    for person, err := range sqlx.AllRows[Person](rows) {
        if err != nil {
            panic(err)
        }
        fmt.Printf("%#v\n", person)
    }
}

Issues

Row headers can be ambiguous (SELECT 1 AS a, 2 AS a), and the result of Columns() does not fully qualify column names in queries like:

SELECT a.id, a.name, b.id, b.name FROM foos AS a JOIN foos AS b ON a.parent = b.id;

making a struct or map destination ambiguous. Use AS in your queries to give columns distinct names, rows.Scan to scan them manually, or SliceScan to get a slice of results.

Documentation

Overview

Package sqlx provides general purpose extensions to database/sql.

It is intended to seamlessly wrap database/sql and provide convenience methods which are useful in the development of database driven applications. None of the underlying database/sql methods are changed. Instead all extended behavior is implemented through new methods defined on wrapper types.

Additions include scanning into structs, named query support, rebinding queries for different drivers, convenient shorthands for common error handling and more.

Index

Constants

View Source
const (
	UNKNOWN = iota
	QUESTION
	DOLLAR
	NAMED
	AT
)

Bindvar types supported by Rebind, BindMap and BindStruct.

Variables

View Source
var ErrMultiRows = errors.New("sql: multiple rows returned")

ErrMultiRows is returned by functions which are expected to work with result sets that only contain a single row but multiple rows were returned. This typically indicates an issue with the query such as a missing join criteria or limit condition or the use of Get(...) when Select(...) was intended.

View Source
var NameMapper = strings.ToLower

NameMapper is used to map column names to struct field names. By default, it uses strings.ToLower to lowercase struct field names. It can be set to whatever you want, but it is encouraged to be set before sqlx is used as name-to-field mappings are cached after first use on a type.

Functions

func AllRows added in v1.6.0

func AllRows[T any](rows *Rows) iter.Seq2[T, error]

AllRows returns an iter.Seq2 for ranging over rows. The second result is an error object which may be non-nil due to scanning errors. Calling code should check error in the loop.

func BindDriver

func BindDriver(driverName string, bindType int)

BindDriver sets the BindType for driverName to bindType.

func BindNamed

func BindNamed(bindType int, query string, arg interface{}) (string, []interface{}, error)

BindNamed binds a struct or a map to a query with named parameters. DEPRECATED: use sqlx.Named` instead of this, it may be removed in future.

func BindType

func BindType(driverName string) int

BindType returns the bindtype for a given database given a drivername.

func Get

func Get(q Queryer, dest interface{}, query string, args ...interface{}) error

Get does a QueryRow using the provided Queryer, and scans the resulting row to dest. If dest is scannable, the result must only have one column. Otherwise, StructScan is used. Get will return sql.ErrNoRows like row.Scan would. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty or contains more than one row.

func GetContext

func GetContext(ctx context.Context, q QueryerContext, dest interface{}, query string, args ...interface{}) error

GetContext does a QueryRow using the provided Queryer, and scans the resulting row to dest. If dest is scannable, the result must only have one column. Otherwise, StructScan is used. Get will return sql.ErrNoRows like row.Scan would. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func In

func In(query string, args ...interface{}) (string, []interface{}, error)

In expands slice values in args, returning the modified query string and a new arg list that can be executed by a database. The `query` should use the `?` bindVar. The return value uses the `?` bindVar.

func List added in v1.6.0

func List[T any](q Queryer, query string, args ...interface{}) ([]T, error)

List executes a query using the provided Queryer, and returns a slice of T for each row.

func ListContext added in v1.6.0

func ListContext[T any](ctx context.Context, q QueryerContext, query string, args ...interface{}) ([]T, error)

ListContext executes a query using the provided Queryer, and returns a slice of T for each row.

func LoadFile

func LoadFile(e Execer, path string) (*sql.Result, error)

LoadFile exec's every statement in a file (as a single call to Exec). LoadFile may return a nil *sql.Result if errors are encountered locating or reading the file at path. LoadFile reads the entire file into memory, so it is not suitable for loading large data dumps, but can be useful for initializing schemas or loading indexes.

FIXME: this does not really work with multi-statement files for mattn/go-sqlite3 or the go-mysql-driver/mysql drivers; pq seems to be an exception here. Detecting this by requiring something with DriverName() and then attempting to split the queries will be difficult to get right, and its current driver-specific behavior is deemed at least not complex in its incorrectness.

func LoadFileContext

func LoadFileContext(ctx context.Context, e ExecerContext, path string) (*sql.Result, error)

LoadFileContext exec's every statement in a file (as a single call to Exec). LoadFileContext may return a nil *sql.Result if errors are encountered locating or reading the file at path. LoadFile reads the entire file into memory, so it is not suitable for loading large data dumps, but can be useful for initializing schemas or loading indexes.

FIXME: this does not really work with multi-statement files for mattn/go-sqlite3 or the go-mysql-driver/mysql drivers; pq seems to be an exception here. Detecting this by requiring something with DriverName() and then attempting to split the queries will be difficult to get right, and its current driver-specific behavior is deemed at least not complex in its incorrectness.

func MapScan

func MapScan(r ColScanner, dest map[string]interface{}) error

MapScan scans a single Row into the dest map[string]interface{}. Use this to get results for SQL that might not be under your control (for instance, if you're building an interface for an SQL server that executes SQL from input). Please do not use this as a primary interface! This will modify the map sent to it in place, so reuse the same map with care. Columns which occur more than once in the result will overwrite each other!

func MustExec

func MustExec(e Execer, query string, args ...interface{}) sql.Result

MustExec execs the query using e and panics if there was an error. Any placeholder parameters are replaced with supplied args.

func MustExecContext

func MustExecContext(ctx context.Context, e ExecerContext, query string, args ...interface{}) sql.Result

MustExecContext execs the query using e and panics if there was an error. Any placeholder parameters are replaced with supplied args.

func Named

func Named(query string, arg interface{}) (string, []interface{}, error)

Named takes a query using named parameters and an argument and returns a new query with a list of args that can be executed by a database. The return value uses the `?` bindvar.

func NamedExec

func NamedExec(e Ext, query string, arg interface{}) (sql.Result, error)

NamedExec uses BindStruct to get a query executable by the driver and then runs Exec on the result. Returns an error from the binding or the query execution itself.

func NamedExecContext

func NamedExecContext(ctx context.Context, e ExtContext, query string, arg interface{}) (sql.Result, error)

NamedExecContext uses BindStruct to get a query executable by the driver and then runs Exec on the result. Returns an error from the binding or the query execution itself.

func One added in v1.6.0

func One[T any](q Queryer, query string, args ...interface{}) (T, error)

One does a QueryRow using the provided Queryer, and scans the resulting row. If dest is scannable, the result must only have one column. Otherwise, StructScan is used. Get will return sql.ErrNoRows like row.Scan would. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty or contains more than one row.

func OneContext added in v1.6.0

func OneContext[T any](ctx context.Context, q QueryerContext, query string, args ...interface{}) (T, error)

OneContext does a QueryRow using the provided Queryer, and scans the resulting row to dest. If dest is scannable, the result must only have one column. Otherwise, StructScan is used. Get will return sql.ErrNoRows like row.Scan would. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func Rebind

func Rebind(bindType int, query string) string

Rebind a query from the default bindtype (QUESTION) to the target bindtype.

func Select

func Select(q Queryer, dest interface{}, query string, args ...interface{}) error

Select executes a query using the provided Queryer, and StructScans each row into dest, which must be a slice. If the slice elements are scannable, then the result set must have only one column. Otherwise, StructScan is used. The *sql.Rows are closed automatically. Any placeholder parameters are replaced with supplied args.

func SelectContext

func SelectContext(ctx context.Context, q QueryerContext, dest interface{}, query string, args ...interface{}) error

SelectContext executes a query using the provided Queryer, and StructScans each row into dest, which must be a slice. If the slice elements are scannable, then the result set must have only one column. Otherwise, StructScan is used. The *sql.Rows are closed automatically. Any placeholder parameters are replaced with supplied args.

func SliceScan

func SliceScan(r ColScanner) ([]interface{}, error)

SliceScan a row, returning a []interface{} with values similar to MapScan. This function is primarily intended for use where the number of columns is not known. Because you can pass an []interface{} directly to Scan, it's recommended that you do that as it will not have to allocate new slices per row.

func StructScan

func StructScan(rows rowsi, dest interface{}) error

StructScan all rows from an sql.Rows or an sqlx.Rows into the dest slice. StructScan will scan in the entire rows result, so if you do not want to allocate structs for the entire result, use Queryx and see sqlx.Rows.StructScan. If rows is sqlx.Rows, it will use its mapper, otherwise it will use the default.

func Transact added in v1.6.0

func Transact(db Queryable, txFunc func(context.Context, Queryable) error) error

func TransactContext added in v1.6.0

func TransactContext(ctx context.Context, db Queryable, txFunc func(context.Context, Queryable) error) error

func WithSetUnsafe added in v1.7.0

func WithSetUnsafe(v bool) func(*dbOptions)

WithSetUnsafe in unsafe mode sqlx will do its best to continue despite scan issues like missing fields

func WithUnsafe added in v1.7.0

func WithUnsafe() func(*dbOptions)

WithUnsafe in unsafe mode sqlx will do its best to continue despite scan issues like missing fields

Types

type ColScanner

type ColScanner interface {
	Columns() ([]string, error)
	Scan(dest ...interface{}) error
	Err() error
}

ColScanner is an interface used by MapScan and SliceScan

type Conn

type Conn struct {
	*sql.Conn

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Conn is a wrapper around sql.Conn with extra functionality

func (*Conn) BeginTxx

func (c *Conn) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)

BeginTxx begins a transaction and returns an *sqlx.Tx instead of an *sql.Tx.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginxContext is canceled.

func (*Conn) GetContext

func (c *Conn) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

GetContext using this Conn. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*Conn) PreparexContext

func (c *Conn) PreparexContext(ctx context.Context, query string) (*Stmt, error)

PreparexContext returns an sqlx.Stmt instead of a sql.Stmt.

The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*Conn) QueryRowxContext

func (c *Conn) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row

QueryRowxContext queries the database and returns an *sqlx.Row. Any placeholder parameters are replaced with supplied args.

func (*Conn) QueryxContext

func (c *Conn) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryxContext queries the database and returns an *sqlx.Rows. Any placeholder parameters are replaced with supplied args.

func (*Conn) Rebind

func (c *Conn) Rebind(query string) string

Rebind a query within a Conn's bindvar type.

func (*Conn) SelectContext

func (c *Conn) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

SelectContext using this Conn. Any placeholder parameters are replaced with supplied args.

type DB

type DB struct {
	*sql.DB

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

DB is a wrapper around sql.DB which keeps track of the driverName upon Open, used mostly to automatically bind named queries using the right bindvars.

func Connect

func Connect(driverName, dataSourceName string, args ...func(*dbOptions)) (*DB, error)

Connect to a database and verify with a ping.

func ConnectContext

func ConnectContext(ctx context.Context, driverName, dataSourceName string) (*DB, error)

ConnectContext to a database and verify with a ping.

func MustConnect

func MustConnect(driverName, dataSourceName string, args ...func(*dbOptions)) *DB

MustConnect connects to a database and panics on error.

func MustOpen

func MustOpen(driverName, dataSourceName string, args ...func(*dbOptions)) *DB

MustOpen is the same as sql.Open, but returns an *sqlx.DB instead and panics on error.

func NewDb

func NewDb(db *sql.DB, driverName string, args ...func(*dbOptions)) *DB

NewDb returns a new sqlx DB wrapper for a pre-existing *sql.DB. The driverName of the original database is required for named query support.

This function now accepts functional options as variadic arguments to configure the database instance. Functional options are functions that modify the internal dbOptions struct. For example:

db := sqlx.NewDb(existingDB, "mysql", sqlx.WithUnsafe())

The above example enables unsafe mode, which allows sqlx to continue despite scan issues like missing fields. You can also use WithSetUnsafe to explicitly set the unsafe mode:

db := sqlx.NewDb(existingDB, "mysql", sqlx.WithSetUnsafe(true))

You can pass multiple functional options to configure other aspects of the database as needed.

func Open

func Open(driverName, dataSourceName string, args ...func(*dbOptions)) (*DB, error)

Open is the same as sql.Open, but returns an *sqlx.DB instead.

func (*DB) BeginTxx

func (db *DB) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)

BeginTxx begins a transaction and returns an *sqlx.Tx instead of an *sql.Tx.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginxContext is canceled.

func (*DB) Beginx

func (db *DB) Beginx() (*Tx, error)

Beginx begins a transaction and returns an *sqlx.Tx instead of an *sql.Tx.

func (*DB) BindNamed

func (db *DB) BindNamed(query string, arg interface{}) (string, []interface{}, error)

BindNamed binds a query using the DB driver's bindvar type.

func (*DB) Connx

func (db *DB) Connx(ctx context.Context) (*Conn, error)

Connx returns an *sqlx.Conn instead of an *sql.Conn.

func (*DB) DriverName

func (db *DB) DriverName() string

DriverName returns the driverName passed to the Open function for this DB.

func (*DB) Get

func (db *DB) Get(dest interface{}, query string, args ...interface{}) error

Get using this DB. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty or contains more than one row.

func (*DB) GetContext

func (db *DB) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

GetContext using this DB. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*DB) MapperFunc

func (db *DB) MapperFunc(mf func(string) string)

MapperFunc sets a new mapper for this db using the default sqlx struct tag and the provided mapper function.

func (*DB) MustBegin

func (db *DB) MustBegin() *Tx

MustBegin starts a transaction, and panics on error. Returns an *sqlx.Tx instead of an *sql.Tx.

func (*DB) MustBeginTx

func (db *DB) MustBeginTx(ctx context.Context, opts *sql.TxOptions) *Tx

MustBeginTx starts a transaction, and panics on error. Returns an *sqlx.Tx instead of an *sql.Tx.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to MustBeginContext is canceled.

func (*DB) MustExec

func (db *DB) MustExec(query string, args ...interface{}) sql.Result

MustExec (panic) runs MustExec using this database. Any placeholder parameters are replaced with supplied args.

func (*DB) MustExecContext

func (db *DB) MustExecContext(ctx context.Context, query string, args ...interface{}) sql.Result

MustExecContext (panic) runs MustExec using this database. Any placeholder parameters are replaced with supplied args.

func (*DB) NamedExec

func (db *DB) NamedExec(query string, arg interface{}) (sql.Result, error)

NamedExec using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) NamedExecContext

func (db *DB) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)

NamedExecContext using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) NamedQuery

func (db *DB) NamedQuery(query string, arg interface{}) (*Rows, error)

NamedQuery using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) NamedQueryContext

func (db *DB) NamedQueryContext(ctx context.Context, query string, arg interface{}) (*Rows, error)

NamedQueryContext using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) PrepareNamed

func (db *DB) PrepareNamed(query string) (*NamedStmt, error)

PrepareNamed returns an sqlx.NamedStmt

func (*DB) PrepareNamedContext

func (db *DB) PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error)

PrepareNamedContext returns an sqlx.NamedStmt

func (*DB) Preparex

func (db *DB) Preparex(query string) (*Stmt, error)

Preparex returns an sqlx.Stmt instead of a sql.Stmt

func (*DB) PreparexContext

func (db *DB) PreparexContext(ctx context.Context, query string) (*Stmt, error)

PreparexContext returns an sqlx.Stmt instead of a sql.Stmt.

The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*DB) QueryRowx

func (db *DB) QueryRowx(query string, args ...interface{}) *Row

QueryRowx queries the database and returns an *sqlx.Row. Any placeholder parameters are replaced with supplied args.

func (*DB) QueryRowxContext

func (db *DB) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row

QueryRowxContext queries the database and returns an *sqlx.Row. Any placeholder parameters are replaced with supplied args.

func (*DB) Queryx

func (db *DB) Queryx(query string, args ...interface{}) (*Rows, error)

Queryx queries the database and returns an *sqlx.Rows. Any placeholder parameters are replaced with supplied args.

func (*DB) QueryxContext

func (db *DB) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryxContext queries the database and returns an *sqlx.Rows. Any placeholder parameters are replaced with supplied args.

func (*DB) Rebind

func (db *DB) Rebind(query string) string

Rebind transforms a query from QUESTION to the DB driver's bindvar type.

func (*DB) Select

func (db *DB) Select(dest interface{}, query string, args ...interface{}) error

Select using this DB. Any placeholder parameters are replaced with supplied args.

func (*DB) SelectContext

func (db *DB) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

SelectContext using this DB. Any placeholder parameters are replaced with supplied args.

func (*DB) Unsafe

func (db *DB) Unsafe() *DB

Unsafe returns a version of DB which will silently succeed to scan when columns in the SQL result have no fields in the destination struct. sqlx.Stmt and sqlx.Tx which are created from this DB will inherit its safety behavior.

type Execer

type Execer interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
}

Execer is an interface used by MustExec and LoadFile

type ExecerContext

type ExecerContext interface {
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}

ExecerContext is an interface used by MustExecContext and LoadFileContext

type Ext

type Ext interface {
	Queryer
	Execer
	// contains filtered or unexported methods
}

Ext is a union interface which can bind, query, and exec, used by NamedQuery and NamedExec.

type ExtContext

type ExtContext interface {
	QueryerContext
	ExecerContext
	// contains filtered or unexported methods
}

ExtContext is a union interface which can bind, query, and exec, with Context used by NamedQueryContext and NamedExecContext.

type GenericNamedStmt added in v1.6.0

type GenericNamedStmt[T any] struct {
	Params      []string
	QueryString string
	Stmt        *GenericStmt[T]
}

GenericNamedStmt is a prepared statement that executes named queries. Prepare it how you would execute a NamedQuery, but pass in a struct or map when executing. This is a generic version of NamedStmt. To preserve user code compatibility.

func PrepareNamed added in v1.6.0

func PrepareNamed[T any](p namedPreparer, query string) (*GenericNamedStmt[T], error)

func PrepareNamedContext added in v1.6.0

func PrepareNamedContext[T any](ctx context.Context, p namedPreparerContext, query string) (*GenericNamedStmt[T], error)

PrepareNamedContext prepares a named statement for use on the database. Use `PrepareContext` on the statement to ready a prepared statement to be used in a transaction.

The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back (you do not need to close it).

func (*GenericNamedStmt[T]) All added in v1.6.0

func (n *GenericNamedStmt[T]) All(arg interface{}) iter.Seq2[T, error]

All performs a query using the GenericNamedStmt and returns all rows for use with range.

func (*GenericNamedStmt[T]) AllContext added in v1.6.0

func (n *GenericNamedStmt[T]) AllContext(ctx context.Context, arg interface{}) iter.Seq2[T, error]

AllContext performs a query using the NamedStmt and returns all rows for use with range.

func (*GenericNamedStmt[T]) Close added in v1.6.0

func (n *GenericNamedStmt[T]) Close() error

Close closes the named statement.

func (*GenericNamedStmt[T]) Exec added in v1.6.0

func (n *GenericNamedStmt[T]) Exec(arg interface{}) (sql.Result, error)

Exec executes a named statement using the struct passed. Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) ExecContext added in v1.6.0

func (n *GenericNamedStmt[T]) ExecContext(ctx context.Context, arg interface{}) (sql.Result, error)

ExecContext executes a named statement using the struct passed. Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) Get added in v1.6.0

func (n *GenericNamedStmt[T]) Get(dest interface{}, arg interface{}) error

Get using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) GetContext added in v1.6.0

func (n *GenericNamedStmt[T]) GetContext(ctx context.Context, dest interface{}, arg interface{}) error

GetContext using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) List added in v1.6.0

func (n *GenericNamedStmt[T]) List(arg interface{}) ([]T, error)

List performs a query using the statement and returns all rows as a slice of T.

func (*GenericNamedStmt[T]) MustExec added in v1.6.0

func (n *GenericNamedStmt[T]) MustExec(arg interface{}) sql.Result

MustExec execs a NamedStmt, panicing on error Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) MustExecContext added in v1.6.0

func (n *GenericNamedStmt[T]) MustExecContext(ctx context.Context, arg interface{}) sql.Result

MustExecContext execs a NamedStmt, panicing on error Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) One added in v1.6.0

func (n *GenericNamedStmt[T]) One(arg interface{}) (T, error)

One get a single row using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) OneContext added in v1.6.0

func (n *GenericNamedStmt[T]) OneContext(ctx context.Context, arg interface{}) (T, error)

OneContext get a single row using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) Prepare added in v1.6.0

func (n *GenericNamedStmt[T]) Prepare(ndb Queryable) *GenericNamedStmt[T]

Prepare returns a transaction-specific prepared statement from an existing statement.

The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back (you do not need to close it).

func (*GenericNamedStmt[T]) PrepareContext added in v1.7.0

func (n *GenericNamedStmt[T]) PrepareContext(ctx context.Context, ndb Queryable) *GenericNamedStmt[T]

PrepareContext returns a transaction-specific prepared statement from an existing statement.

It's preferred to use this method over `Prepare` (without context) due to go internals, it uses the connection found in context.

The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back (you do not need to close it).

func (*GenericNamedStmt[T]) Query added in v1.6.0

func (n *GenericNamedStmt[T]) Query(arg interface{}) (*sql.Rows, error)

Query executes a named statement using the struct argument, returning rows. Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) QueryContext added in v1.6.0

func (n *GenericNamedStmt[T]) QueryContext(ctx context.Context, arg interface{}) (*sql.Rows, error)

QueryContext executes a named statement using the struct argument, returning rows. Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) QueryRow added in v1.6.0

func (n *GenericNamedStmt[T]) QueryRow(arg interface{}) *Row

QueryRow executes a named statement against the database. Because sqlx cannot create a *sql.Row with an error condition pre-set for binding errors, sqlx returns a *sqlx.Row instead. Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) QueryRowContext added in v1.6.0

func (n *GenericNamedStmt[T]) QueryRowContext(ctx context.Context, arg interface{}) *Row

QueryRowContext executes a named statement against the database. Because sqlx cannot create a *sql.Row with an error condition pre-set for binding errors, sqlx returns a *sqlx.Row instead. Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) QueryRowx added in v1.6.0

func (n *GenericNamedStmt[T]) QueryRowx(arg interface{}) *Row

QueryRowx this NamedStmt. Because of limitations with QueryRow, this is an alias for QueryRow. Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) QueryRowxContext added in v1.6.0

func (n *GenericNamedStmt[T]) QueryRowxContext(ctx context.Context, arg interface{}) *Row

QueryRowxContext this NamedStmt. Because of limitations with QueryRow, this is an alias for QueryRow. Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) Queryx added in v1.6.0

func (n *GenericNamedStmt[T]) Queryx(arg interface{}) (*Rows, error)

Queryx using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) QueryxContext added in v1.6.0

func (n *GenericNamedStmt[T]) QueryxContext(ctx context.Context, arg interface{}) (*Rows, error)

QueryxContext using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) Select added in v1.6.0

func (n *GenericNamedStmt[T]) Select(dest interface{}, arg interface{}) error

Select using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) SelectContext added in v1.6.0

func (n *GenericNamedStmt[T]) SelectContext(ctx context.Context, dest interface{}, arg interface{}) error

SelectContext using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*GenericNamedStmt[T]) Unsafe added in v1.6.0

func (n *GenericNamedStmt[T]) Unsafe() *GenericNamedStmt[T]

Unsafe creates an unsafe version of the GenericNamedStmt

type GenericStmt added in v1.6.0

type GenericStmt[T any] struct {
	*sql.Stmt

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

GenericStmt is an sqlx wrapper around sql.Stmt with extra functionality

func Preparex

func Preparex[T any](p Preparer, query string) (*GenericStmt[T], error)

Preparex prepares a statement.

func PreparexContext

func PreparexContext[T any](ctx context.Context, p PreparerContext, query string) (*GenericStmt[T], error)

PreparexContext prepares a statement.

The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*GenericStmt[T]) All added in v1.6.0

func (s *GenericStmt[T]) All(args ...interface{}) iter.Seq2[T, error]

All performs a query using the NamedStmt and returns all rows for use with range.

func (*GenericStmt[T]) Get added in v1.6.0

func (s *GenericStmt[T]) Get(dest interface{}, args ...interface{}) error

Get using the prepared statement. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty or contains more than one row.

func (*GenericStmt[T]) GetContext added in v1.6.0

func (s *GenericStmt[T]) GetContext(ctx context.Context, dest interface{}, args ...interface{}) error

GetContext using the prepared statement. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*GenericStmt[T]) List added in v1.6.0

func (s *GenericStmt[T]) List(args ...interface{}) ([]T, error)

List performs a query using the statement and returns all rows as a slice of T.

func (*GenericStmt[T]) MustExec added in v1.6.0

func (s *GenericStmt[T]) MustExec(args ...interface{}) sql.Result

MustExec (panic) using this statement. Note that the query portion of the error output will be blank, as Stmt does not expose its query. Any placeholder parameters are replaced with supplied args.

func (*GenericStmt[T]) MustExecContext added in v1.6.0

func (s *GenericStmt[T]) MustExecContext(ctx context.Context, args ...interface{}) sql.Result

MustExecContext (panic) using this statement. Note that the query portion of the error output will be blank, as Stmt does not expose its query. Any placeholder parameters are replaced with supplied args.

func (*GenericStmt[T]) One added in v1.6.0

func (s *GenericStmt[T]) One(args ...interface{}) (T, error)

One get one row using the prepared statement. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty or contains more than one row.

func (*GenericStmt[T]) Prepare added in v1.6.0

func (s *GenericStmt[T]) Prepare(ndb Queryable) *GenericStmt[T]

Prepare returns a transaction-specific prepared statement from an existing statement.

The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

func (*GenericStmt[T]) QueryRowx added in v1.6.0

func (s *GenericStmt[T]) QueryRowx(args ...interface{}) *Row

QueryRowx using this statement. Any placeholder parameters are replaced with supplied args.

func (*GenericStmt[T]) QueryRowxContext added in v1.6.0

func (s *GenericStmt[T]) QueryRowxContext(ctx context.Context, args ...interface{}) *Row

QueryRowxContext using this statement. Any placeholder parameters are replaced with supplied args.

func (*GenericStmt[T]) Queryx added in v1.6.0

func (s *GenericStmt[T]) Queryx(args ...interface{}) (*Rows, error)

Queryx using this statement. Any placeholder parameters are replaced with supplied args.

func (*GenericStmt[T]) QueryxContext added in v1.6.0

func (s *GenericStmt[T]) QueryxContext(ctx context.Context, args ...interface{}) (*Rows, error)

QueryxContext using this statement. Any placeholder parameters are replaced with supplied args.

func (*GenericStmt[T]) Select added in v1.6.0

func (s *GenericStmt[T]) Select(dest interface{}, args ...interface{}) error

Select using the prepared statement. Any placeholder parameters are replaced with supplied args.

func (*GenericStmt[T]) SelectContext added in v1.6.0

func (s *GenericStmt[T]) SelectContext(ctx context.Context, dest interface{}, args ...interface{}) error

SelectContext using the prepared statement. Any placeholder parameters are replaced with supplied args.

func (*GenericStmt[T]) Unsafe added in v1.6.0

func (s *GenericStmt[T]) Unsafe() *GenericStmt[T]

Unsafe returns a version of Stmt which will silently succeed to scan when columns in the SQL result have no fields in the destination struct.

type NamedStmt

type NamedStmt = GenericNamedStmt[any]

NamedStmt is a prepared statement that executes named queries. Prepare it how you would execute a NamedQuery, but pass in a struct or map when executing.

type Preparer

type Preparer interface {
	Prepare(query string) (*sql.Stmt, error)
}

Preparer is an interface used by Preparex.

type PreparerContext

type PreparerContext interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}

PreparerContext is an interface used by PreparexContext.

type Queryable

type Queryable interface {
	Ext
	ExecerContext
	PreparerContext
	QueryerContext
	Preparer

	GetContext(context.Context, interface{}, string, ...interface{}) error
	SelectContext(context.Context, interface{}, string, ...interface{}) error
	Get(interface{}, string, ...interface{}) error
	MustExecContext(context.Context, string, ...interface{}) sql.Result
	PreparexContext(context.Context, string) (*Stmt, error)
	QueryRowContext(context.Context, string, ...interface{}) *sql.Row
	Select(interface{}, string, ...interface{}) error
	QueryRow(string, ...interface{}) *sql.Row
	PrepareNamedContext(context.Context, string) (*NamedStmt, error)
	PrepareNamed(string) (*NamedStmt, error)
	Preparex(string) (*Stmt, error)
	NamedExec(string, interface{}) (sql.Result, error)
	NamedExecContext(context.Context, string, interface{}) (sql.Result, error)
	MustExec(string, ...interface{}) sql.Result
	NamedQuery(string, interface{}) (*Rows, error)
}

Queryable includes all methods shared by sqlx.DB and sqlx.Tx, allowing either type to be used interchangeably.

type Queryer

type Queryer interface {
	Query(query string, args ...interface{}) (*sql.Rows, error)
	Queryx(query string, args ...interface{}) (*Rows, error)
	QueryRowx(query string, args ...interface{}) *Row
}

Queryer is an interface used by Get and Select

type QueryerContext

type QueryerContext interface {
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)
	QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row
}

QueryerContext is an interface used by GetContext and SelectContext

type Row

type Row struct {
	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Row is a reimplementation of sql.Row in order to gain access to the underlying sql.Rows.Columns() data, necessary for StructScan.

func (*Row) ColumnTypes

func (r *Row) ColumnTypes() ([]*sql.ColumnType, error)

ColumnTypes returns the underlying sql.Rows.ColumnTypes(), or the deferred error

func (*Row) Columns

func (r *Row) Columns() ([]string, error)

Columns returns the underlying sql.Rows.Columns(), or the deferred error usually returned by Row.Scan()

func (*Row) Err

func (r *Row) Err() error

Err returns the error encountered while scanning.

func (*Row) MapScan

func (r *Row) MapScan(dest map[string]interface{}) error

MapScan using this Rows.

func (*Row) Scan

func (r *Row) Scan(dest ...interface{}) error

Scan is a fixed implementation of sql.Row.Scan, which does not discard the underlying error from the internal rows object if it exists. Returns ErrMultiRows if the result set contains more than one row.

func (*Row) SliceScan

func (r *Row) SliceScan() ([]interface{}, error)

SliceScan using this Rows.

func (*Row) StructScan

func (r *Row) StructScan(dest interface{}) error

StructScan a single Row into dest.

type Rows

type Rows struct {
	*sql.Rows

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Rows is a wrapper around sql.Rows which caches costly reflect operations during a looped StructScan

func NamedQuery

func NamedQuery(e Ext, query string, arg interface{}) (*Rows, error)

NamedQuery binds a named query and then runs Query on the result using the provided Ext (sqlx.Tx, sqlx.Db). It works with both structs and with map[string]interface{} types.

func NamedQueryContext

func NamedQueryContext(ctx context.Context, e ExtContext, query string, arg interface{}) (*Rows, error)

NamedQueryContext binds a named query and then runs Query on the result using the provided Ext (sqlx.Tx, sqlx.Db). It works with both structs and with map[string]interface{} types.

func (*Rows) MapScan

func (r *Rows) MapScan(dest map[string]interface{}) error

MapScan using this Rows.

func (*Rows) NextResultSet added in v1.5.1

func (r *Rows) NextResultSet() bool

NextResultSet moves to the next resultset if available and resets the field cache.

func (*Rows) SliceScan

func (r *Rows) SliceScan() ([]interface{}, error)

SliceScan using this Rows.

func (*Rows) StructScan

func (r *Rows) StructScan(dest interface{}) error

StructScan is like sql.Rows.Scan, but scans a single Row into a single Struct. Use this and iterate over Rows manually when the memory load of Select() might be prohibitive. *Rows.StructScan caches the reflect work of matching up column positions to fields to avoid that overhead per scan, which means it is not safe to run StructScan on the same Rows instance with different struct types.

type Stmt

type Stmt = GenericStmt[any]

type Tx

type Tx struct {
	*sql.Tx

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Tx is an sqlx wrapper around sql.Tx with extra functionality

func (*Tx) BindNamed

func (tx *Tx) BindNamed(query string, arg interface{}) (string, []interface{}, error)

BindNamed binds a query within a transaction's bindvar type.

func (*Tx) DriverName

func (tx *Tx) DriverName() string

DriverName returns the driverName used by the DB which began this transaction.

func (*Tx) Get

func (tx *Tx) Get(dest interface{}, query string, args ...interface{}) error

Get within a transaction. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty or contains more than one row.

func (*Tx) GetContext

func (tx *Tx) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

GetContext within a transaction and context. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*Tx) MustExec

func (tx *Tx) MustExec(query string, args ...interface{}) sql.Result

MustExec runs MustExec within a transaction. Any placeholder parameters are replaced with supplied args.

func (*Tx) MustExecContext

func (tx *Tx) MustExecContext(ctx context.Context, query string, args ...interface{}) sql.Result

MustExecContext runs MustExecContext within a transaction. Any placeholder parameters are replaced with supplied args.

func (*Tx) NamedExec

func (tx *Tx) NamedExec(query string, arg interface{}) (sql.Result, error)

NamedExec a named query within a transaction. Any named placeholder parameters are replaced with fields from arg.

func (*Tx) NamedExecContext

func (tx *Tx) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)

NamedExecContext using this Tx. Any named placeholder parameters are replaced with fields from arg.

func (*Tx) NamedQuery

func (tx *Tx) NamedQuery(query string, arg interface{}) (*Rows, error)

NamedQuery within a transaction. Any named placeholder parameters are replaced with fields from arg.

func (*Tx) NamedStmt

func (tx *Tx) NamedStmt(stmt *NamedStmt) *NamedStmt

NamedStmt returns a version of the prepared statement which runs within a transaction.

func (*Tx) NamedStmtContext

func (tx *Tx) NamedStmtContext(ctx context.Context, stmt *NamedStmt) *NamedStmt

NamedStmtContext returns a version of the prepared statement which runs within a transaction.

func (*Tx) PrepareNamed

func (tx *Tx) PrepareNamed(query string) (*NamedStmt, error)

PrepareNamed returns an sqlx.NamedStmt

func (*Tx) PrepareNamedContext

func (tx *Tx) PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error)

PrepareNamedContext returns an sqlx.NamedStmt

func (*Tx) Preparex

func (tx *Tx) Preparex(query string) (*Stmt, error)

Preparex a statement within a transaction.

func (*Tx) PreparexContext

func (tx *Tx) PreparexContext(ctx context.Context, query string) (*Stmt, error)

PreparexContext returns an sqlx.Stmt instead of a sql.Stmt.

The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*Tx) QueryRowx

func (tx *Tx) QueryRowx(query string, args ...interface{}) *Row

QueryRowx within a transaction. Any placeholder parameters are replaced with supplied args.

func (*Tx) QueryRowxContext

func (tx *Tx) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row

QueryRowxContext within a transaction and context. Any placeholder parameters are replaced with supplied args.

func (*Tx) Queryx

func (tx *Tx) Queryx(query string, args ...interface{}) (*Rows, error)

Queryx within a transaction. Any placeholder parameters are replaced with supplied args.

func (*Tx) QueryxContext

func (tx *Tx) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryxContext within a transaction and context. Any placeholder parameters are replaced with supplied args.

func (*Tx) Rebind

func (tx *Tx) Rebind(query string) string

Rebind a query within a transaction's bindvar type.

func (*Tx) Select

func (tx *Tx) Select(dest interface{}, query string, args ...interface{}) error

Select within a transaction. Any placeholder parameters are replaced with supplied args.

func (*Tx) SelectContext

func (tx *Tx) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

SelectContext within a transaction and context. Any placeholder parameters are replaced with supplied args.

func (*Tx) Stmtx

func (tx *Tx) Stmtx(stmt interface{}) *GenericStmt[any]

Stmtx returns a version of the prepared statement which runs within a transaction. Provided stmt can be either *sql.Stmt or *sqlx.Stmt.

func (*Tx) StmtxContext

func (tx *Tx) StmtxContext(ctx context.Context, stmt interface{}) *GenericStmt[any]

StmtxContext returns a version of the prepared statement which runs within a transaction. Provided stmt can be either *sql.Stmt or *sqlx.Stmt.

func (*Tx) Unsafe

func (tx *Tx) Unsafe() *Tx

Unsafe returns a version of Tx which will silently succeed to scan when columns in the SQL result have no fields in the destination struct.

Directories

Path Synopsis
Package reflectx implements extensions to the standard reflect lib suitable for implementing marshalling and unmarshalling packages.
Package reflectx implements extensions to the standard reflect lib suitable for implementing marshalling and unmarshalling packages.
Package types provides some useful types which implement the `sql.Scanner` and `driver.Valuer` interfaces, suitable for use as scan and value targets with database/sql.
Package types provides some useful types which implement the `sql.Scanner` and `driver.Valuer` interfaces, suitable for use as scan and value targets with database/sql.

Jump to

Keyboard shortcuts

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