sqlite

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2021 License: BSD-3-Clause, ISC Imports: 12 Imported by: 68

README

zombiezen.com/go/sqlite

This package provides a low-level Go interface to SQLite 3. It is a fork of crawshaw.io/sqlite that uses modernc.org/sqlite. It aims to be a mostly drop-in replacement for crawshaw.io/sqlite.

License

Mostly ISC, with some code borrowed from modernc.org/sqlite, which is under a BSD 3-Clause license. See LICENSE for details.

Source files in this repository use SPDX-License-Identifier tags to indicate the applicable license.

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

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

func (blob *Blob) Close() error

Close releases any resources associated with the blob handle. https://www.sqlite.org/c3ref/blob_close.html

func (*Blob) Read

func (blob *Blob) Read(p []byte) (int, error)

Read reads up to len(p) bytes from the blob into p. https://www.sqlite.org/c3ref/blob_read.html

func (*Blob) Seek

func (blob *Blob) Seek(offset int64, whence int) (int64, error)

Seek sets the offset for the next Read or Write and returns the offset. Seeking past the end of the blob returns an error.

func (*Blob) Size

func (blob *Blob) Size() int64

Size returns the number of bytes in the blob.

func (*Blob) Write

func (blob *Blob) Write(p []byte) (int, error)

Write writes len(p) from p to the blob. https://www.sqlite.org/c3ref/blob_write.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

func OpenConn(path string, flags ...OpenFlags) (*Conn, error)

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

https://www.sqlite.org/c3ref/open.html

func (*Conn) AutocommitEnabled

func (conn *Conn) AutocommitEnabled() bool

AutocommitEnabled reports whether conn is in autocommit mode. https://sqlite.org/c3ref/get_autocommit.html

func (*Conn) Changes

func (c *Conn) Changes() int

Changes reports the number of rows affected by the most recent statement.

https://www.sqlite.org/c3ref/changes.html

func (*Conn) CheckReset

func (conn *Conn) CheckReset() string

CheckReset reports whether any statement on this connection is in the process of returning results.

func (*Conn) Close

func (c *Conn) Close() error

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.

https://sqlite.org/c3ref/create_function.html

func (*Conn) LastInsertRowID

func (c *Conn) LastInsertRowID() int64

LastInsertRowID reports the rowid of the most recently successful INSERT.

https://www.sqlite.org/c3ref/last_insert_rowid.html

func (*Conn) OpenBlob

func (conn *Conn) OpenBlob(dbn, table, column string, row int64, write bool) (*Blob, error)

OpenBlob opens a blob in a particular {database,table,column,row}.

https://www.sqlite.org/c3ref/blob_open.html

func (*Conn) Prep

func (conn *Conn) Prep(query string) *Stmt

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.

https://www.sqlite.org/c3ref/prepare.html

func (*Conn) Prepare

func (conn *Conn) Prepare(query string) (*Stmt, error)

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.

https://www.sqlite.org/c3ref/prepare.html

func (*Conn) PrepareTransient

func (c *Conn) PrepareTransient(query string) (stmt *Stmt, trailingBytes int, err error)

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.

https://www.sqlite.org/c3ref/prepare.html

func (*Conn) SetBusyTimeout

func (c *Conn) SetBusyTimeout(d time.Duration)

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.

https://www.sqlite.org/c3ref/busy_timeout.html

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 (ctx Context) ResultError(err error)

func (Context) ResultFloat

func (ctx Context) ResultFloat(v float64)

func (Context) ResultInt

func (ctx Context) ResultInt(v int)

func (Context) ResultInt64

func (ctx Context) ResultInt64(v int64)

func (Context) ResultNull

func (ctx Context) ResultNull()

func (Context) ResultText

func (ctx Context) ResultText(v string)

func (Context) ResultValue

func (ctx Context) ResultValue(v Value)

func (Context) ResultZeroBlob

func (ctx Context) ResultZeroBlob(n int64)

func (Context) SetUserData

func (ctx Context) SetUserData(data interface{})

func (Context) UserData

func (ctx Context) UserData() interface{}

type OpenFlags

type OpenFlags uint

OpenFlags are flags used when opening a Conn.

https://www.sqlite.org/c3ref/c_open_autoproxy.html

func (OpenFlags) String

func (flags OpenFlags) String() string

String returns a pipe-separated list of the C constant names set in flags.

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
	ResultLockedSharedCache      ResultCode = lib.SQLITE_LOCKED_SHAREDCACHE
	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

func (stmt *Stmt) BindBool(param int, value bool)

BindBool binds value (as an integer 0 or 1) to a numbered stmt parameter.

Parameter indices start at 1.

https://www.sqlite.org/c3ref/bind_blob.html

func (*Stmt) BindBytes

func (stmt *Stmt) BindBytes(param int, value []byte)

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.

https://www.sqlite.org/c3ref/bind_blob.html

func (*Stmt) BindFloat

func (stmt *Stmt) BindFloat(param int, value float64)

BindFloat binds value to a numbered stmt parameter.

Parameter indices start at 1.

https://www.sqlite.org/c3ref/bind_blob.html

func (*Stmt) BindInt64

func (stmt *Stmt) BindInt64(param int, value int64)

BindInt64 binds value to a numbered stmt parameter.

Parameter indices start at 1.

https://www.sqlite.org/c3ref/bind_blob.html

func (*Stmt) BindNull

func (stmt *Stmt) BindNull(param int)

BindNull binds an SQL NULL value to a numbered stmt parameter.

Parameter indices start at 1.

https://www.sqlite.org/c3ref/bind_blob.html

func (*Stmt) BindParamCount

func (stmt *Stmt) BindParamCount() int

BindParamCount reports the number of parameters in stmt.

https://www.sqlite.org/c3ref/bind_parameter_count.html

func (*Stmt) BindParamName

func (stmt *Stmt) BindParamName(i int) string

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.

https://www.sqlite.org/c3ref/bind_parameter_name.html

func (*Stmt) BindText

func (stmt *Stmt) BindText(param int, value string)

BindText binds value to a numbered stmt parameter.

Parameter indices start at 1.

https://www.sqlite.org/c3ref/bind_blob.html

func (*Stmt) BindZeroBlob

func (stmt *Stmt) BindZeroBlob(param int, len int64)

BindNull binds a blob of zeros of length len to a numbered stmt parameter.

Parameter indices start at 1.

https://www.sqlite.org/c3ref/bind_blob.html

func (*Stmt) ClearBindings

func (stmt *Stmt) ClearBindings() error

ClearBindings clears all bound parameter values on a statement.

https://www.sqlite.org/c3ref/clear_bindings.html

func (*Stmt) ColumnBytes

func (stmt *Stmt) ColumnBytes(col int, buf []byte) int

ColumnBytes reads a query result into buf. It reports the number of bytes read.

Column indices start at 0.

https://www.sqlite.org/c3ref/column_blob.html

func (*Stmt) ColumnCount

func (stmt *Stmt) ColumnCount() int

ColumnCount returns the number of columns in the result set returned by the prepared statement.

https://sqlite.org/c3ref/column_count.html

func (*Stmt) ColumnDatabaseName

func (stmt *Stmt) ColumnDatabaseName(col int) string

func (*Stmt) ColumnFloat

func (stmt *Stmt) ColumnFloat(col int) float64

ColumnFloat returns a query result as a float64.

Column indices start at 0.

https://www.sqlite.org/c3ref/column_blob.html

func (*Stmt) ColumnIndex

func (stmt *Stmt) ColumnIndex(colName string) int

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

func (stmt *Stmt) ColumnInt(col int) int

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.

https://www.sqlite.org/c3ref/column_blob.html

func (*Stmt) ColumnInt32

func (stmt *Stmt) ColumnInt32(col int) int32

ColumnInt32 returns a query result value as an int32.

Column indices start at 0.

https://www.sqlite.org/c3ref/column_blob.html

func (*Stmt) ColumnInt64

func (stmt *Stmt) ColumnInt64(col int) int64

ColumnInt64 returns a query result value as an int64.

Column indices start at 0.

https://www.sqlite.org/c3ref/column_blob.html

func (*Stmt) ColumnLen

func (stmt *Stmt) ColumnLen(col int) int

ColumnLen returns the number of bytes in a query result.

Column indices start at 0.

https://www.sqlite.org/c3ref/column_blob.html

func (*Stmt) ColumnName

func (stmt *Stmt) ColumnName(col int) string

ColumnName returns the name assigned to a particular column in the result set of a SELECT statement.

https://sqlite.org/c3ref/column_name.html

func (*Stmt) ColumnReader

func (stmt *Stmt) ColumnReader(col int) *bytes.Reader

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 *Stmt) ColumnTableName(col int) string

func (*Stmt) ColumnText

func (stmt *Stmt) ColumnText(col int) string

ColumnText returns a query result as a string.

Column indices start at 0.

https://www.sqlite.org/c3ref/column_blob.html

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.

https://www.sqlite.org/c3ref/column_blob.html

func (*Stmt) DataCount

func (stmt *Stmt) DataCount() int

DataCount returns the number of columns in the current row of the result set of prepared statement.

https://sqlite.org/c3ref/data_count.html

func (*Stmt) Finalize

func (stmt *Stmt) Finalize() error

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.

https://www.sqlite.org/c3ref/finalize.html

func (*Stmt) GetBytes

func (stmt *Stmt) GetBytes(colName string, buf []byte) int

GetBytes reads a query result for colName into buf. It reports the number of bytes read.

func (*Stmt) GetFloat

func (stmt *Stmt) GetFloat(colName string) float64

GetFloat returns a query result value for colName as a float64.

func (*Stmt) GetInt64

func (stmt *Stmt) GetInt64(colName string) int64

GetInt64 returns a query result value for colName as an int64.

func (*Stmt) GetLen

func (stmt *Stmt) GetLen(colName string) int

GetLen returns the number of bytes in a query result for colName.

func (*Stmt) GetReader

func (stmt *Stmt) GetReader(colName string) *bytes.Reader

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) GetText

func (stmt *Stmt) GetText(colName string) string

GetText returns a query result value for colName as a string.

func (*Stmt) Reset

func (stmt *Stmt) Reset() error

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.

https://www.sqlite.org/c3ref/reset.html

func (*Stmt) SetBool

func (stmt *Stmt) SetBool(param string, value bool)

SetBool binds a value (as a 0 or 1) to a parameter using a column name.

func (*Stmt) SetBytes

func (stmt *Stmt) SetBytes(param string, value []byte)

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

func (stmt *Stmt) SetFloat(param string, value float64)

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) SetInt64

func (stmt *Stmt) SetInt64(param string, value int64)

SetInt64 binds an int64 to a parameter using a column name.

func (*Stmt) SetNull

func (stmt *Stmt) SetNull(param string)

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

func (stmt *Stmt) SetText(param string, value string)

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

func (stmt *Stmt) SetZeroBlob(param string, len int64)

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

func (stmt *Stmt) Step() (rowReturned bool, err error)

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

type Value

type Value struct {
	// contains filtered or unexported fields
}

func (Value) Blob

func (v Value) Blob() []byte

func (Value) Float

func (v Value) Float() float64

func (Value) Int

func (v Value) Int() int

func (Value) Int64

func (v Value) Int64() int64

func (Value) IsNil

func (v Value) IsNil() bool

func (Value) Len

func (v Value) Len() int

func (Value) Text

func (v Value) Text() string

func (Value) Type

func (v Value) Type() ColumnType

Directories

Path Synopsis
cmd
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.

Jump to

Keyboard shortcuts

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