Documentation ¶
Overview ¶
Package sqlite provides a Go interface to SQLite 3.
The semantics of this package are deliberately close to the SQLite3 C API, so it is helpful to be familiar with http://www.sqlite.org/c3ref/intro.html.
An SQLite connection is represented by a *sqlite.Conn. Connections cannot be used concurrently. A typical Go program will create a pool of connections (using Open to create a *sqlitex.Pool) so goroutines can borrow a connection while they need to talk to the database.
This package assumes SQLite will be used concurrently by the process through several connections, so the build options for SQLite enable multi-threading and the shared cache: https://www.sqlite.org/sharedcache.html
The implementation automatically handles shared cache locking, see the documentation on Stmt.Step for details.
The optional SQLite3 compiled in are: FTS5, RTree, JSON1, Session, GeoPoly
This is not a database/sql driver.
Statement Caching ¶
Statements are prepared with the Prepare and PrepareTransient methods. When using Prepare, statements are keyed inside a connection by the original query string used to create them. This means long-running high-performance code paths can write:
stmt, err := conn.Prepare("SELECT ...")
After all the connections in a pool have been warmed up by passing through one of these Prepare calls, subsequent calls are simply a map lookup that returns an existing statement.
Streaming Blobs ¶
The sqlite package supports the SQLite incremental I/O interface for streaming blob data into and out of the the database without loading the entire blob into a single []byte. (This is important when working either with very large blobs, or more commonly, a large number of moderate-sized blobs concurrently.)
To write a blob, first use an INSERT statement to set the size of the blob and assign a rowid:
"INSERT INTO blobs (myblob) VALUES (?);"
Use BindZeroBlob or SetZeroBlob to set the size of myblob. Then you can open the blob with:
b, err := conn.OpenBlob("", "blobs", "myblob", conn.LastInsertRowID(), true)
Deadlines and Cancellation ¶
Every connection can have a done channel associated with it using the SetInterrupt method. This is typically the channel returned by a context.Context Done method.
For example, a timeout can be associated with a connection session:
ctx := context.WithTimeout(context.Background(), 100*time.Millisecond) conn.SetInterrupt(ctx.Done())
As database connections are long-lived, the SetInterrupt method can be called multiple times to reset the associated lifetime.
When using pools, the shorthand for associating a context with a connection is:
conn := dbpool.Get(ctx) if conn == nil { // ... handle error } defer dbpool.Put(c)
Transactions ¶
SQLite transactions have to be managed manually with this package by directly calling BEGIN / COMMIT / ROLLBACK or SAVEPOINT / RELEASE/ ROLLBACK. The sqlitex has a Savepoint function that helps automate this.
A typical HTTP Handler ¶
Using a Pool to execute SQL in a concurrent HTTP handler.
var dbpool *sqlitex.Pool func main() { var err error dbpool, err = sqlitex.Open("file:memory:?mode=memory", 0, 10) if err != nil { log.Fatal(err) } http.HandleFunc("/", handle) log.Fatal(http.ListenAndServe(":8080", nil)) } func handle(w http.ResponseWriter, r *http.Request) { conn := dbpool.Get(r.Context()) if conn == nil { return } defer dbpool.Put(conn) stmt := conn.Prep("SELECT foo FROM footable WHERE id = $id;") stmt.SetText("$id", "_user_id_") for { if hasRow, err := stmt.Step(); err != nil { // ... handle error } else if !hasRow { break } foo := stmt.GetText("foo") // ... use foo } }
For helper functions that make some kinds of statements easier to write see the sqlitex package.
Example ¶
package main import ( "fmt" "zombiezen.com/go/sqlite" ) func main() { conn, err := sqlite.OpenConn(":memory:", sqlite.OpenReadWrite) if err != nil { panic(err) } defer conn.Close() stmt, _, err := conn.PrepareTransient("SELECT 'hello, world';") if err != nil { panic(err) } defer stmt.Finalize() for { row, err := stmt.Step() if err != nil { panic(err) } if !row { return } fmt.Println(stmt.ColumnText(0)) } }
Output: hello, world
Index ¶
- type Blob
- type ColumnType
- type Conn
- func (conn *Conn) AutocommitEnabled() bool
- func (c *Conn) Changes() int
- func (conn *Conn) CheckReset() string
- func (c *Conn) Close() error
- func (c *Conn) CreateFunction(name string, deterministic bool, numArgs int, ...) error
- func (c *Conn) LastInsertRowID() int64
- func (conn *Conn) OpenBlob(dbn, table, column string, row int64, write bool) (*Blob, error)
- func (conn *Conn) Prep(query string) *Stmt
- func (conn *Conn) Prepare(query string) (*Stmt, error)
- func (c *Conn) PrepareTransient(query string) (stmt *Stmt, trailingBytes int, err error)
- func (c *Conn) SetBusyTimeout(d time.Duration)
- func (conn *Conn) SetInterrupt(doneCh <-chan struct{}) (oldDoneCh <-chan struct{})
- type Context
- func (ctx Context) ResultError(err error)
- func (ctx Context) ResultFloat(v float64)
- func (ctx Context) ResultInt(v int)
- func (ctx Context) ResultInt64(v int64)
- func (ctx Context) ResultNull()
- func (ctx Context) ResultText(v string)
- func (ctx Context) ResultValue(v Value)
- func (ctx Context) ResultZeroBlob(n int64)
- func (ctx Context) SetUserData(data interface{})
- func (ctx Context) UserData() interface{}
- type OpenFlags
- type ResultCode
- type Stmt
- func (stmt *Stmt) BindBool(param int, value bool)
- func (stmt *Stmt) BindBytes(param int, value []byte)
- func (stmt *Stmt) BindFloat(param int, value float64)
- func (stmt *Stmt) BindInt64(param int, value int64)
- func (stmt *Stmt) BindNull(param int)
- func (stmt *Stmt) BindParamCount() int
- func (stmt *Stmt) BindParamName(i int) string
- func (stmt *Stmt) BindText(param int, value string)
- func (stmt *Stmt) BindZeroBlob(param int, len int64)
- func (stmt *Stmt) ClearBindings() error
- func (stmt *Stmt) ColumnBytes(col int, buf []byte) int
- func (stmt *Stmt) ColumnCount() int
- func (stmt *Stmt) ColumnDatabaseName(col int) string
- func (stmt *Stmt) ColumnFloat(col int) float64
- func (stmt *Stmt) ColumnIndex(colName string) int
- func (stmt *Stmt) ColumnInt(col int) int
- func (stmt *Stmt) ColumnInt32(col int) int32
- func (stmt *Stmt) ColumnInt64(col int) int64
- func (stmt *Stmt) ColumnLen(col int) int
- func (stmt *Stmt) ColumnName(col int) string
- func (stmt *Stmt) ColumnReader(col int) *bytes.Reader
- func (stmt *Stmt) ColumnTableName(col int) string
- func (stmt *Stmt) ColumnText(col int) string
- func (stmt *Stmt) ColumnType(col int) ColumnType
- func (stmt *Stmt) DataCount() int
- func (stmt *Stmt) Finalize() error
- func (stmt *Stmt) GetBytes(colName string, buf []byte) int
- func (stmt *Stmt) GetFloat(colName string) float64
- func (stmt *Stmt) GetInt64(colName string) int64
- func (stmt *Stmt) GetLen(colName string) int
- func (stmt *Stmt) GetReader(colName string) *bytes.Reader
- func (stmt *Stmt) GetText(colName string) string
- func (stmt *Stmt) Reset() error
- func (stmt *Stmt) SetBool(param string, value bool)
- func (stmt *Stmt) SetBytes(param string, value []byte)
- func (stmt *Stmt) SetFloat(param string, value float64)
- func (stmt *Stmt) SetInt64(param string, value int64)
- func (stmt *Stmt) SetNull(param string)
- func (stmt *Stmt) SetText(param string, value string)
- func (stmt *Stmt) SetZeroBlob(param string, len int64)
- func (stmt *Stmt) Step() (rowReturned bool, err error)
- type Value
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Blob ¶
type Blob struct {
// contains filtered or unexported fields
}
Blob provides streaming access to SQLite blobs.
func (*Blob) Close ¶
Close releases any resources associated with the blob handle. https://www.sqlite.org/c3ref/blob_close.html
func (*Blob) Read ¶
Read reads up to len(p) bytes from the blob into p. https://www.sqlite.org/c3ref/blob_read.html
type ColumnType ¶
type ColumnType int
ColumnType are codes for each of the SQLite fundamental datatypes:
64-bit signed integer 64-bit IEEE floating point number string BLOB NULL
https://www.sqlite.org/c3ref/c_blob.html
const ( TypeInteger ColumnType = lib.SQLITE_INTEGER TypeFloat ColumnType = lib.SQLITE_FLOAT TypeText ColumnType = lib.SQLITE_TEXT TypeBlob ColumnType = lib.SQLITE_BLOB TypeNull ColumnType = lib.SQLITE_NULL )
Data types.
func (ColumnType) String ¶
func (t ColumnType) String() string
String returns the SQLite constant name of the type.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is an open connection to an SQLite3 database.
A Conn can only be used by goroutine at a time.
func OpenConn ¶
OpenConn opens a single SQLite database connection with the given flags. No flags or a value of 0 defaults to the following:
OpenReadWrite OpenCreate OpenWAL OpenURI OpenNoMutex
func (*Conn) AutocommitEnabled ¶
AutocommitEnabled reports whether conn is in autocommit mode. https://sqlite.org/c3ref/get_autocommit.html
func (*Conn) CheckReset ¶
CheckReset reports whether any statement on this connection is in the process of returning results.
func (*Conn) Close ¶
Close closes the database connection using sqlite3_close and finalizes persistent prepared statements. https://www.sqlite.org/c3ref/close.html
func (*Conn) CreateFunction ¶
func (c *Conn) CreateFunction(name string, deterministic bool, numArgs int, xFunc, xStep func(Context, ...Value), xFinal func(Context)) error
CreateFunction registers a Go function with SQLite for use in SQL queries.
To define a scalar function, provide a value for xFunc and set xStep/xFinal to nil.
To define an aggregation set xFunc to nil and provide values for xStep and xFinal.
State can be stored across function calls by using the Context UserData/SetUserData methods.
func (*Conn) LastInsertRowID ¶
LastInsertRowID reports the rowid of the most recently successful INSERT.
func (*Conn) Prep ¶
Prep returns a persistent SQL statement.
Any error in preparation will panic.
Persistent prepared statements are cached by the query string in a Conn. If Finalize is not called, then subsequent calls to Prepare will return the same statement.
func (*Conn) Prepare ¶
Prepare prepares a persistent SQL statement.
Persistent prepared statements are cached by the query string in a Conn. If Finalize is not called, then subsequent calls to Prepare will return the same statement.
If the query has any unprocessed trailing bytes, Prepare returns an error.
func (*Conn) PrepareTransient ¶
PrepareTransient prepares an SQL statement that is not cached by the Conn. Subsequent calls with the same query will create new Stmts. Finalize must be called by the caller once done with the Stmt.
The number of trailing bytes not consumed from query is returned.
To run a sequence of queries once as part of a script, the sqlitex package provides an ExecScript function built on this.
func (*Conn) SetBusyTimeout ¶
SetBusyTimeout sets a busy handler that sleeps for up to d to acquire a lock.
By default, a large busy timeout (10s) is set on the assumption that Go programs use a context object via SetInterrupt to control timeouts.
func (*Conn) SetInterrupt ¶
func (conn *Conn) SetInterrupt(doneCh <-chan struct{}) (oldDoneCh <-chan struct{})
SetInterrupt assigns a channel to control connection execution lifetime.
When doneCh is closed, the connection uses sqlite3_interrupt to stop long-running queries and cancels any *Stmt.Step calls that are blocked waiting for the database write lock.
Subsequent uses of the connection will return SQLITE_INTERRUPT errors until doneCh is reset with a subsequent call to SetInterrupt.
Typically, doneCh is provided by the Done method on a context.Context. For example, a timeout can be associated with a connection session:
ctx := context.WithTimeout(context.Background(), 100*time.Millisecond) conn.SetInterrupt(ctx.Done())
Any busy statements at the time SetInterrupt is called will be reset.
SetInterrupt returns the old doneCh assigned to the connection.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is an *sqlite3_context. It is used by custom functions to return result values. An SQLite context is in no way related to a Go context.Context. https://sqlite.org/c3ref/context.html
func (Context) ResultError ¶
func (Context) ResultFloat ¶
func (Context) ResultInt64 ¶
func (Context) ResultNull ¶
func (ctx Context) ResultNull()
func (Context) ResultText ¶
func (Context) ResultValue ¶
func (Context) ResultZeroBlob ¶
func (Context) SetUserData ¶
func (ctx Context) SetUserData(data interface{})
type OpenFlags ¶
type OpenFlags uint
OpenFlags are flags used when opening a Conn.
https://www.sqlite.org/c3ref/c_open_autoproxy.html
const ( OpenReadOnly OpenFlags = lib.SQLITE_OPEN_READONLY OpenReadWrite OpenFlags = lib.SQLITE_OPEN_READWRITE OpenCreate OpenFlags = lib.SQLITE_OPEN_CREATE OpenURI OpenFlags = lib.SQLITE_OPEN_URI OpenMemory OpenFlags = lib.SQLITE_OPEN_MEMORY OpenMainDB OpenFlags = lib.SQLITE_OPEN_MAIN_DB OpenTempDB OpenFlags = lib.SQLITE_OPEN_TEMP_DB OpenTransientDB OpenFlags = lib.SQLITE_OPEN_TRANSIENT_DB OpenMainJournal OpenFlags = lib.SQLITE_OPEN_MAIN_JOURNAL OpenTempJournal OpenFlags = lib.SQLITE_OPEN_TEMP_JOURNAL OpenSubjournal OpenFlags = lib.SQLITE_OPEN_SUBJOURNAL OpenMasterJournal OpenFlags = lib.SQLITE_OPEN_MASTER_JOURNAL OpenNoMutex OpenFlags = lib.SQLITE_OPEN_NOMUTEX OpenFullMutex OpenFlags = lib.SQLITE_OPEN_FULLMUTEX OpenPrivateCache OpenFlags = lib.SQLITE_OPEN_PRIVATECACHE OpenWAL OpenFlags = lib.SQLITE_OPEN_WAL )
type ResultCode ¶
type ResultCode int32
ResultCode is an SQLite extended result code.
const ( ResultOK ResultCode = lib.SQLITE_OK ResultError ResultCode = lib.SQLITE_ERROR ResultInternal ResultCode = lib.SQLITE_INTERNAL ResultPerm ResultCode = lib.SQLITE_PERM ResultAbort ResultCode = lib.SQLITE_ABORT ResultBusy ResultCode = lib.SQLITE_BUSY ResultLocked ResultCode = lib.SQLITE_LOCKED ResultNoMem ResultCode = lib.SQLITE_NOMEM ResultReadOnly ResultCode = lib.SQLITE_READONLY ResultInterrupt ResultCode = lib.SQLITE_INTERRUPT ResultIOErr ResultCode = lib.SQLITE_IOERR ResultCorrupt ResultCode = lib.SQLITE_CORRUPT ResultNotFound ResultCode = lib.SQLITE_NOTFOUND ResultFull ResultCode = lib.SQLITE_FULL ResultCantOpen ResultCode = lib.SQLITE_CANTOPEN ResultProtocol ResultCode = lib.SQLITE_PROTOCOL ResultEmpty ResultCode = lib.SQLITE_EMPTY ResultSchema ResultCode = lib.SQLITE_SCHEMA ResultTooBig ResultCode = lib.SQLITE_TOOBIG ResultConstraint ResultCode = lib.SQLITE_CONSTRAINT ResultMismatch ResultCode = lib.SQLITE_MISMATCH ResultMisuse ResultCode = lib.SQLITE_MISUSE ResultNoLFS ResultCode = lib.SQLITE_NOLFS ResultAuth ResultCode = lib.SQLITE_AUTH ResultFormat ResultCode = lib.SQLITE_FORMAT ResultRange ResultCode = lib.SQLITE_RANGE ResultNotADB ResultCode = lib.SQLITE_NOTADB ResultNotice ResultCode = lib.SQLITE_NOTICE ResultWarning ResultCode = lib.SQLITE_WARNING ResultRow ResultCode = lib.SQLITE_ROW ResultDone ResultCode = lib.SQLITE_DONE )
Primary result codes.
const ( ResultErrorMissingCollSeq ResultCode = lib.SQLITE_ERROR_MISSING_COLLSEQ ResultErrorRetry ResultCode = lib.SQLITE_ERROR_RETRY ResultErrorSnapshot ResultCode = lib.SQLITE_ERROR_SNAPSHOT ResultIOErrRead ResultCode = lib.SQLITE_IOERR_READ ResultIOErrShortRead ResultCode = lib.SQLITE_IOERR_SHORT_READ ResultIOErrWrite ResultCode = lib.SQLITE_IOERR_WRITE ResultIOErrFsync ResultCode = lib.SQLITE_IOERR_FSYNC ResultIOErrDirFsync ResultCode = lib.SQLITE_IOERR_DIR_FSYNC ResultIOErrTruncate ResultCode = lib.SQLITE_IOERR_TRUNCATE ResultIOErrFstat ResultCode = lib.SQLITE_IOERR_FSTAT ResultIOErrUnlock ResultCode = lib.SQLITE_IOERR_UNLOCK ResultIOErrReadLock ResultCode = lib.SQLITE_IOERR_RDLOCK ResultIOErrDelete ResultCode = lib.SQLITE_IOERR_DELETE ResultIOErrBlocked ResultCode = lib.SQLITE_IOERR_BLOCKED ResultIOErrNoMem ResultCode = lib.SQLITE_IOERR_NOMEM ResultIOErrAccess ResultCode = lib.SQLITE_IOERR_ACCESS ResultIOErrCheckReservedLock ResultCode = lib.SQLITE_IOERR_CHECKRESERVEDLOCK ResultIOErrLock ResultCode = lib.SQLITE_IOERR_LOCK ResultIOErrClose ResultCode = lib.SQLITE_IOERR_CLOSE ResultIOErrDirClose ResultCode = lib.SQLITE_IOERR_DIR_CLOSE ResultIOErrSHMOpen ResultCode = lib.SQLITE_IOERR_SHMOPEN ResultIOErrSHMSize ResultCode = lib.SQLITE_IOERR_SHMSIZE ResultIOErrSHMLock ResultCode = lib.SQLITE_IOERR_SHMLOCK ResultIOErrSHMMap ResultCode = lib.SQLITE_IOERR_SHMMAP ResultIOErrSeek ResultCode = lib.SQLITE_IOERR_SEEK ResultIOErrDeleteNoEnt ResultCode = lib.SQLITE_IOERR_DELETE_NOENT ResultIOErrMMap ResultCode = lib.SQLITE_IOERR_MMAP ResultIOErrGetTempPath ResultCode = lib.SQLITE_IOERR_GETTEMPPATH ResultIOErrConvPath ResultCode = lib.SQLITE_IOERR_CONVPATH ResultIOErrVNode ResultCode = lib.SQLITE_IOERR_VNODE ResultIOErrAuth ResultCode = lib.SQLITE_IOERR_AUTH ResultIOErrBeginAtomic ResultCode = lib.SQLITE_IOERR_BEGIN_ATOMIC ResultIOErrCommitAtomic ResultCode = lib.SQLITE_IOERR_COMMIT_ATOMIC ResultIOErrRollbackAtomic ResultCode = lib.SQLITE_IOERR_ROLLBACK_ATOMIC ResultBusyRecovery ResultCode = lib.SQLITE_BUSY_RECOVERY ResultBusySnapshot ResultCode = lib.SQLITE_BUSY_SNAPSHOT ResultCantOpenNoTempDir ResultCode = lib.SQLITE_CANTOPEN_NOTEMPDIR ResultCantOpenIsDir ResultCode = lib.SQLITE_CANTOPEN_ISDIR ResultCantOpenFullPath ResultCode = lib.SQLITE_CANTOPEN_FULLPATH ResultCantOpenConvPath ResultCode = lib.SQLITE_CANTOPEN_CONVPATH ResultCorruptVTab ResultCode = lib.SQLITE_CORRUPT_VTAB ResultReadOnlyRecovery ResultCode = lib.SQLITE_READONLY_RECOVERY ResultReadOnlyCantLock ResultCode = lib.SQLITE_READONLY_CANTLOCK ResultReadOnlyRollback ResultCode = lib.SQLITE_READONLY_ROLLBACK ResultReadOnlyDBMoved ResultCode = lib.SQLITE_READONLY_DBMOVED ResultReadOnlyCantInit ResultCode = lib.SQLITE_READONLY_CANTINIT ResultReadOnlyDirectory ResultCode = lib.SQLITE_READONLY_DIRECTORY ResultAbortRollback ResultCode = lib.SQLITE_ABORT_ROLLBACK ResultConstraintCheck ResultCode = lib.SQLITE_CONSTRAINT_CHECK ResultConstraintCommitHook ResultCode = lib.SQLITE_CONSTRAINT_COMMITHOOK ResultConstraintForeignKey ResultCode = lib.SQLITE_CONSTRAINT_FOREIGNKEY ResultConstraintFunction ResultCode = lib.SQLITE_CONSTRAINT_FUNCTION ResultConstraintNotNull ResultCode = lib.SQLITE_CONSTRAINT_NOTNULL ResultConstraintPrimaryKey ResultCode = lib.SQLITE_CONSTRAINT_PRIMARYKEY ResultConstraintTrigger ResultCode = lib.SQLITE_CONSTRAINT_TRIGGER ResultConstraintUnique ResultCode = lib.SQLITE_CONSTRAINT_UNIQUE ResultConstraintVTab ResultCode = lib.SQLITE_CONSTRAINT_VTAB ResultConstraintRowID ResultCode = lib.SQLITE_CONSTRAINT_ROWID ResultNoticeRecoverWAL ResultCode = lib.SQLITE_NOTICE_RECOVER_WAL ResultNoticeRecoverRollback ResultCode = lib.SQLITE_NOTICE_RECOVER_ROLLBACK ResultWarningAutoIndex ResultCode = lib.SQLITE_WARNING_AUTOINDEX ResultAuthUser ResultCode = lib.SQLITE_AUTH_USER )
Extended result codes.
func ErrCode ¶
func ErrCode(err error) ResultCode
ErrCode returns the error's SQLite error code or ResultError if the error does not represent a SQLite error. ErrorCode returns ResultOK if and only if the error is nil.
func (ResultCode) IsSuccess ¶
func (code ResultCode) IsSuccess() bool
IsSuccess reports whether code indicates success.
func (ResultCode) Message ¶
func (code ResultCode) Message() string
Message returns the English-language text that describes the result code.
func (ResultCode) String ¶
func (code ResultCode) String() string
String returns the C constant name of the result code.
func (ResultCode) ToPrimary ¶
func (code ResultCode) ToPrimary() ResultCode
ToPrimary returns the primary result code of the given code. https://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes
type Stmt ¶
type Stmt struct {
// contains filtered or unexported fields
}
Stmt is an SQLite3 prepared statement.
A Stmt is attached to a particular Conn (and that Conn can only be used by a single goroutine).
When a Stmt is no longer needed it should be cleaned up by calling the Finalize method.
func (*Stmt) BindBool ¶
BindBool binds value (as an integer 0 or 1) to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindBytes ¶
BindBytes binds value to a numbered stmt parameter.
In-memory copies of value are made using this interface. For large blobs, consider using the streaming Blob object.
Parameter indices start at 1.
func (*Stmt) BindFloat ¶
BindFloat binds value to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindInt64 ¶
BindInt64 binds value to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindNull ¶
BindNull binds an SQL NULL value to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindParamCount ¶
BindParamCount reports the number of parameters in stmt.
func (*Stmt) BindParamName ¶
BindParamName returns the name of parameter or the empty string if the parameter is nameless or i is out of range.
Parameters indices start at 1.
func (*Stmt) BindText ¶
BindText binds value to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindZeroBlob ¶
BindNull binds a blob of zeros of length len to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) ClearBindings ¶
ClearBindings clears all bound parameter values on a statement.
func (*Stmt) ColumnBytes ¶
ColumnBytes reads a query result into buf. It reports the number of bytes read.
Column indices start at 0.
func (*Stmt) ColumnCount ¶
ColumnCount returns the number of columns in the result set returned by the prepared statement.
func (*Stmt) ColumnDatabaseName ¶
func (*Stmt) ColumnFloat ¶
ColumnFloat returns a query result as a float64.
Column indices start at 0.
func (*Stmt) ColumnIndex ¶
ColumnIndex returns the index of the column with the given name.
If there is no column with the given name ColumnIndex returns -1.
func (*Stmt) ColumnInt ¶
ColumnInt returns a query result value as an int.
Note: this method calls sqlite3_column_int64 and then converts the resulting 64-bits to an int.
Column indices start at 0.
func (*Stmt) ColumnInt32 ¶
ColumnInt32 returns a query result value as an int32.
Column indices start at 0.
func (*Stmt) ColumnInt64 ¶
ColumnInt64 returns a query result value as an int64.
Column indices start at 0.
func (*Stmt) ColumnLen ¶
ColumnLen returns the number of bytes in a query result.
Column indices start at 0.
func (*Stmt) ColumnName ¶
ColumnName returns the name assigned to a particular column in the result set of a SELECT statement.
func (*Stmt) ColumnReader ¶
ColumnReader creates a byte reader for a query result column.
The reader directly references C-managed memory that stops being valid as soon as the statement row resets.
func (*Stmt) ColumnTableName ¶
func (*Stmt) ColumnType ¶
func (stmt *Stmt) ColumnType(col int) ColumnType
ColumnType returns the datatype code for the initial data type of the result column. The returned value is one of:
SQLITE_INTEGER SQLITE_FLOAT SQLITE_TEXT SQLITE_BLOB SQLITE_NULL
Column indices start at 0.
func (*Stmt) DataCount ¶
DataCount returns the number of columns in the current row of the result set of prepared statement.
func (*Stmt) Finalize ¶
Finalize deletes a prepared statement.
Be sure to always call Finalize when done with a statement created using PrepareTransient.
Do not call Finalize on a prepared statement that you intend to prepare again in the future.
func (*Stmt) GetBytes ¶
GetBytes reads a query result for colName into buf. It reports the number of bytes read.
func (*Stmt) GetReader ¶
GetReader creates a byte reader for colName.
The reader directly references C-managed memory that stops being valid as soon as the statement row resets.
func (*Stmt) Reset ¶
Reset resets a prepared statement so it can be executed again.
Note that any parameter values bound to the statement are retained. To clear bound values, call ClearBindings.
func (*Stmt) SetBytes ¶
SetBytes binds bytes to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.
func (*Stmt) SetFloat ¶
SetFloat binds a float64 to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.
func (*Stmt) SetNull ¶
SetNull binds a null to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.
func (*Stmt) SetText ¶
SetText binds text to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.
func (*Stmt) SetZeroBlob ¶
SetZeroBlob binds a zero blob of length len to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.
func (*Stmt) Step ¶
Step moves through the statement cursor using sqlite3_step.
If a row of data is available, rowReturned is reported as true. If the statement has reached the end of the available data then rowReturned is false. Thus the status codes SQLITE_ROW and SQLITE_DONE are reported by the rowReturned bool, and all other non-OK status codes are reported as an error.
If an error value is returned, then the statement has been reset.
https://www.sqlite.org/c3ref/step.html
Shared cache ¶
As the sqlite package enables shared cache mode by default and multiple writers are common in multi-threaded programs, this Step method uses sqlite3_unlock_notify to handle any SQLITE_LOCKED errors.
Without the shared cache, SQLite will block for several seconds while trying to acquire the write lock. With the shared cache, it returns SQLITE_LOCKED immediately if the write lock is held by another connection in this process. Dealing with this correctly makes for an unpleasant programming experience, so this package does it automatically by blocking Step until the write lock is relinquished.
This means Step can block for a very long time. Use SetInterrupt to control how long Step will block.
For far more details, see:
http://www.sqlite.org/unlock_notify.html
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
zombiezen-sqlite-migrate
Module
|
|
Package fs provides a fallback for the io/fs package in Go 1.16.
|
Package fs provides a fallback for the io/fs package in Go 1.16. |
Package sqlitefile provides functions for executing SQLite statements from a file.
|
Package sqlitefile provides functions for executing SQLite statements from a file. |
Package sqlitemigration provides a connection pool type that guarantees a series of SQL scripts has been run once successfully before making connections available to the application.
|
Package sqlitemigration provides a connection pool type that guarantees a series of SQL scripts has been run once successfully before making connections available to the application. |
Package sqlitex provides utilities for working with SQLite.
|
Package sqlitex provides utilities for working with SQLite. |