Documentation ¶
Overview ¶
Package sqlitex provides utilities for working with SQLite.
Index ¶
- Variables
- func Exec(conn *sqlite.Conn, query string, resultFn func(stmt *sqlite.Stmt) error, ...) error
- func ExecFS(conn *sqlite.Conn, fsys fs.FS, filename string, opts *ExecOptions) error
- func ExecScript(conn *sqlite.Conn, queries string) (err error)
- func ExecScriptFS(conn *sqlite.Conn, fsys fs.FS, filename string, opts *ExecOptions) (err error)
- func ExecTransient(conn *sqlite.Conn, query string, resultFn func(stmt *sqlite.Stmt) error, ...) (err error)
- func ExecTransientFS(conn *sqlite.Conn, fsys fs.FS, filename string, opts *ExecOptions) error
- func InsertRandID(stmt *sqlite.Stmt, param string, min, max int64) (int64, error)
- func PrepareTransientFS(conn *sqlite.Conn, fsys fs.FS, filename string) (*sqlite.Stmt, error)
- func ResultBool(stmt *sqlite.Stmt) (bool, error)
- func ResultFloat(stmt *sqlite.Stmt) (float64, error)
- func ResultInt(stmt *sqlite.Stmt) (int, error)
- func ResultInt64(stmt *sqlite.Stmt) (int64, error)
- func ResultText(stmt *sqlite.Stmt) (string, error)
- func Save(conn *sqlite.Conn) (releaseFn func(*error))
- type ExecOptions
- type Pool
Constants ¶
This section is empty.
Variables ¶
var PoolCloseTimeout = 5 * time.Second
PoolCloseTimeout is the
Functions ¶
func Exec ¶
func Exec(conn *sqlite.Conn, query string, resultFn func(stmt *sqlite.Stmt) error, args ...interface{}) error
Exec executes an SQLite query.
For each result row, the resultFn is called. Result values can be read by resultFn using stmt.Column* methods. If resultFn returns an error then iteration ceases and Exec returns the error value.
Any args provided to Exec are bound to numbered parameters of the query using the Stmt Bind* methods. Basic reflection on args is used to map:
integers to BindInt64 floats to BindFloat []byte to BindBytes string to BindText bool to BindBool
All other kinds are printed using fmt.Sprintf("%v", v) and passed to BindText.
Exec is implemented using the Stmt prepare mechanism which allows better interactions with Go's type system and avoids pitfalls of passing a Go closure to cgo.
As Exec is implemented using Conn.Prepare, subsequent calls to Exec with the same statement will reuse the cached statement object.
Typical use:
conn := dbpool.Get() defer dbpool.Put(conn) if err := sqlitex.Exec(conn, "INSERT INTO t (a, b, c, d) VALUES (?, ?, ?, ?);", nil, "a1", 1, 42, 1); err != nil { // handle err } var a []string var b []int64 fn := func(stmt *sqlite.Stmt) error { a = append(a, stmt.ColumnText(0)) b = append(b, stmt.ColumnInt64(1)) return nil } err := sqlutil.Exec(conn, "SELECT a, b FROM t WHERE c = ? AND d = ?;", fn, 42, 1) if err != nil { // handle err }
func ExecFS ¶ added in v0.2.0
ExecFS executes the single statement in the given SQL file. ExecFS is implemented using Conn.Prepare, so subsequent calls to ExecFS with the same statement will reuse the cached statement object.
func ExecScript ¶
ExecScript executes a script of SQL statements.
The script is wrapped in a SAVEPOINT transaction, which is rolled back on any error.
func ExecScriptFS ¶ added in v0.2.0
ExecScriptFS executes a script of SQL statements from a file.
The script is wrapped in a SAVEPOINT transaction, which is rolled back on any error.
func ExecTransient ¶
func ExecTransient(conn *sqlite.Conn, query string, resultFn func(stmt *sqlite.Stmt) error, args ...interface{}) (err error)
ExecTransient executes an SQLite query without caching the underlying query. The interface is exactly the same as Exec.
It is the spiritual equivalent of sqlite3_exec.
func ExecTransientFS ¶ added in v0.2.0
ExecTransientFS executes the single statement in the given SQL file without caching the underlying query.
func InsertRandID ¶
InsertRandID executes stmt with a random value in the range [min, max) for $param.
func PrepareTransientFS ¶ added in v0.2.0
PrepareTransientFS prepares an SQL statement from a file that is not cached by the Conn. Subsequent calls with the same query will create new Stmts. The caller is responsible for calling Finalize on the returned Stmt when the Stmt is no longer needed.
func Save ¶
Save creates a named SQLite transaction using SAVEPOINT.
On success Savepoint returns a releaseFn that will call either RELEASE or ROLLBACK depending on whether the parameter *error points to a nil or non-nil error. This is designed to be deferred.
Example:
func doWork(conn *sqlite.Conn) (err error) { defer sqlitex.Save(conn)(&err) // ... do work in the transaction }
Types ¶
type ExecOptions ¶ added in v0.2.0
type ExecOptions struct { // Args is the set of positional arguments to bind to the statement. The first // element in the slice is ?1. See https://sqlite.org/lang_expr.html for more // details. Args []interface{} // Named is the set of named arguments to bind to the statement. Keys must // start with ':', '@', or '$'. See https://sqlite.org/lang_expr.html for more // details. Named map[string]interface{} // ResultFunc is called for each result row. If ResultFunc returns an error // then iteration ceases and Exec returns the error value. ResultFunc func(stmt *sqlite.Stmt) error }
ExecOptions is the set of optional arguments executing a statement.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool is a pool of SQLite connections.
It is safe for use by multiple goroutines concurrently.
Typically, a goroutine that needs to use an SQLite *Conn Gets it from the pool and defers its return:
conn := dbpool.Get(nil) defer dbpool.Put(conn)
As Get may block, a context can be used to return if a task is cancelled. In this case the Conn returned will be nil:
conn := dbpool.Get(ctx) if conn == nil { return context.Canceled } defer dbpool.Put(conn)
func Open ¶
Open opens a fixed-size pool of SQLite connections. A flags value of 0 defaults to:
SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE SQLITE_OPEN_WAL SQLITE_OPEN_URI SQLITE_OPEN_NOMUTEX
func (*Pool) Close ¶
Close interrupts and closes all the connections in the Pool.
Close blocks until all connections are returned to the Pool.
Close will panic if not all connections are returned before PoolCloseTimeout.
func (*Pool) Get ¶
Get returns an SQLite connection from the Pool.
If no Conn is available, Get will block until at least one Conn is returned with Put, or until either the Pool is closed or the context is canceled. If no Conn can be obtained, nil is returned.
The provided context is also used to control the execution lifetime of the connection. See Conn.SetInterrupt for details.
Applications must ensure that all non-nil Conns returned from Get are returned to the same Pool with Put.
Although ctx historically may be nil, this is not a recommended design pattern.