Documentation ¶
Overview ¶
Package sqlite3 provides an interface to SQLite version 3 databases.
Database connections are created either by using this package directly or with the "sqlite3" database/sql driver. The direct interface, which is described below, exposes SQLite-specific features, such as incremental I/O and online backups. The driver is recommended when your application has to support multiple database engines.
Installation ¶
Minimum requirements are Go 1.1+ with CGO enabled and GCC/MinGW C compiler. The SQLite amalgamation version 3.8.5 (2014-06-04) is compiled as part of the package (see http://www.sqlite.org/amalgamation.html). Compilation options are defined at the top of sqlite3.go (#cgo CFLAGS). Dynamic linking with a shared SQLite library is not supported.
Windows users should install mingw-w64 (http://mingw-w64.sourceforge.net/), TDM64-GCC (http://tdm-gcc.tdragon.net/), or another MinGW distribution, and make sure that gcc.exe is available from the %PATH%. MSYS is not required.
Run 'go get github.com/mxk/go-sqlite/sqlite3' to download, build, and install the package.
Concurrency ¶
A single connection instance and all of its derived objects (prepared statements, backup operations, etc.) may NOT be used concurrently from multiple goroutines without external synchronization. The only exception is Conn.Interrupt(), which may be called from another goroutine to abort a long-running operation. It is safe to use separate connection instances concurrently, even if they are accessing the same database file. For example:
// ERROR (without any extra synchronization) c, _ := sqlite3.Open("sqlite.db") go use(c) go use(c) // OK c1, _ := sqlite3.Open("sqlite.db") c2, _ := sqlite3.Open("sqlite.db") go use(c1) go use(c2)
Maps ¶
Use NamedArgs map to bind values to named statement parameters (see http://www.sqlite.org/lang_expr.html#varparam). Use RowMap to retrieve the current row as a map of column/value pairs. Here is a short example with the error-handling code omitted for brevity:
c, _ := sqlite3.Open(":memory:") c.Exec("CREATE TABLE x(a, b, c)") args := sqlite3.NamedArgs{"$a": 1, "$b": "demo"} c.Exec("INSERT INTO x VALUES($a, $b, $c)", args) // $c will be NULL sql := "SELECT rowid, * FROM x" row := make(sqlite3.RowMap) for s, err := c.Query(sql); err == nil; err = s.Next() { var rowid int64 s.Scan(&rowid, row) // Assigns 1st column to rowid, the rest to row fmt.Println(rowid, row) // Prints "1 map[a:1 b:demo c:<nil>]" }
Data Types ¶
See http://www.sqlite.org/datatype3.html for a description of the SQLite data type system. The following Go data types are supported as arguments to prepared statements and may be used in NamedArgs:
Go Type SQLite Type Notes --------- ----------- ---------------------------------------------------- <nil> NULL Unbound parameters are NULL by default. int INTEGER int64 INTEGER float64 FLOAT bool INTEGER Converted as false = 0, true = 1. string TEXT SQLite makes a private copy when the value is bound. []byte BLOB SQLite makes a private copy when the value is bound. time.Time INTEGER Converted by calling Unix(). RawString TEXT SQLite uses the value directly without copying. The caller must keep a reference to the value for the duration of the query to prevent garbage collection. RawBytes BLOB Same as RawString. The value must not be modified for the duration of the query. ZeroBlob BLOB Allocates a zero-filled BLOB of the specified length (e.g. ZeroBlob(4096) allocates 4KB).
Note that the table above describes how the value is bound to the statement. The final storage class is determined according to the column affinity rules.
See http://www.sqlite.org/c3ref/column_blob.html for a description of how column values are retrieved from the results of a query. The following static Go data types are supported for retrieving column values:
Go Type Req. Type Notes ---------- --------- --------------------------------------------------- *int INTEGER *int64 INTEGER *float64 FLOAT *bool INTEGER Converted as 0 = false, otherwise true. *string TEXT The caller receives a copy of the value. *[]byte BLOB The caller receives a copy of the value. *time.Time INTEGER Converted by calling time.Unix(). Text values are not supported, but the conversion can be performed with the date and time SQL functions. *RawString TEXT The value is used directly without copying and remains valid until the next Stmt method call. *RawBytes BLOB Same as *RawString. The value must not be modified. Re-slicing is ok, but be careful with append(). io.Writer BLOB The value is written out directly into the writer.
For *interface{} and RowMap arguments, the Go data type is dynamically selected based on the SQLite storage class and column declaration prefix:
SQLite Type Col. Decl. Go Type Notes ----------- ---------- --------- ---------------------------------------- NULL <nil> INTEGER "DATE..." time.Time Converted by calling time.Unix(). INTEGER "TIME..." time.Time Converted by calling time.Unix(). INTEGER "BOOL..." bool Converted as 0 = false, otherwise true. INTEGER int64 FLOAT float64 TEXT string BLOB []byte
Database Names ¶
Methods that require a database name as one of the arguments (e.g. Conn.Path()) expect the symbolic name by which the database is known to the connection, not a path to a file. Valid database names are "main", "temp", or a name specified after the AS clause in an ATTACH statement.
Callbacks ¶
SQLite can execute callbacks for various internal events. The package provides types and methods for registering callback handlers. Unless stated otherwise in SQLite documentation, callback handlers are not reentrant and must not do anything to modify the associated database connection. This includes preparing/running any other SQL statements. The safest bet is to avoid all interactions with Conn, Stmt, and other related objects within the handler.
Codecs and Encryption ¶
SQLite has an undocumented codec API, which operates between the pager and VFS layers, and is used by the SQLite Encryption Extension (SEE) to encrypt database and journal contents. Consider purchasing a SEE license if you require production-quality encryption support (http://www.hwaci.com/sw/sqlite/see.html).
This package has an experimental API (read: unstable, may eat your data) for writing codecs in Go. The "codec" subpackage provides additional documentation and several existing codec implementations.
Codecs are registered via the RegisterCodec function for a specific key prefix. For example, the "aes-hmac" codec is initialized when a key in the format "aes-hmac:<...>" is provided to an attached database. The key format after the first colon is codec-specific. See CodecFunc for more information.
The codec API has several limitations. Codecs cannot be used for in-memory or temporary databases. Once a database is created, the page size and the amount of reserved space at the end of each page cannot be changed (i.e. "PRAGMA page_size=N; VACUUM;" will not work). Online backups will fail unless the destination database has the same page size and reserve values. Bytes 16 through 23 of page 1 (the database header, see http://www.sqlite.org/fileformat2.html) cannot be altered, so it is always possible to identify encrypted SQLite databases.
The rekey function is currently not implemented. The key can only be changed via the backup API or by dumping and restoring the database contents.
Index ¶
- Constants
- Variables
- func Complete(sql string) bool
- func Print(s *Stmt) error
- func RegisterCodec(name string, f CodecFunc)
- func ReleaseMemory(n int) int
- func SingleThread() bool
- func SoftHeapLimit(n int64) int64
- func SourceId() string
- func Status(op int, reset bool) (cur, peak int, err error)
- func Version() string
- func VersionNum() int
- type Backup
- type BlobIO
- func (b *BlobIO) Close() error
- func (b *BlobIO) Conn() *Conn
- func (b *BlobIO) Len() int
- func (b *BlobIO) Read(p []byte) (n int, err error)
- func (b *BlobIO) Reopen(row int64) error
- func (b *BlobIO) Row() int64
- func (b *BlobIO) Seek(offset int64, whence int) (ret int64, err error)
- func (b *BlobIO) Write(p []byte) (n int, err error)
- type BusyFunc
- type Codec
- type CodecCtx
- type CodecFunc
- type CommitFunc
- type Conn
- func (c *Conn) AutoCommit() bool
- func (c *Conn) Backup(srcName string, dst *Conn, dstName string) (*Backup, error)
- func (c *Conn) Begin() error
- func (c *Conn) BlobIO(db, tbl, col string, row int64, rw bool) (*BlobIO, error)
- func (c *Conn) BusyFunc(f BusyFunc) (prev BusyFunc)
- func (c *Conn) BusyTimeout(d time.Duration) (prev BusyFunc)
- func (c *Conn) Close() error
- func (c *Conn) Commit() error
- func (c *Conn) CommitFunc(f CommitFunc) (prev CommitFunc)
- func (c *Conn) Exec(sql string, args ...interface{}) error
- func (c *Conn) Interrupt()
- func (c *Conn) Key(db string, key []byte) error
- func (c *Conn) LastInsertId() int64
- func (c *Conn) Limit(id, value int) (prev int)
- func (c *Conn) Path(db string) string
- func (c *Conn) Prepare(sql string) (*Stmt, error)
- func (c *Conn) Query(sql string, args ...interface{}) (*Stmt, error)
- func (c *Conn) Rekey(db string, key []byte) error
- func (c *Conn) Rollback() error
- func (c *Conn) RollbackFunc(f RollbackFunc) (prev RollbackFunc)
- func (c *Conn) RowsAffected() int
- func (c *Conn) Status(op int, reset bool) (cur, peak int, err error)
- func (c *Conn) TotalRowsAffected() int
- func (c *Conn) UpdateFunc(f UpdateFunc) (prev UpdateFunc)
- type Driver
- type Error
- type NamedArgs
- type RawBytes
- type RawString
- type RollbackFunc
- type RowMap
- type Stmt
- func (s *Stmt) Busy() bool
- func (s *Stmt) Close() error
- func (s *Stmt) Columns() []string
- func (s *Stmt) Conn() *Conn
- func (s *Stmt) DataTypes() []uint8
- func (s *Stmt) DeclTypes() []string
- func (s *Stmt) Exec(args ...interface{}) error
- func (s *Stmt) Next() error
- func (s *Stmt) NumColumns() int
- func (s *Stmt) NumParams() int
- func (s *Stmt) Params() []string
- func (s *Stmt) Query(args ...interface{}) error
- func (s *Stmt) ReadOnly() bool
- func (s *Stmt) Reset()
- func (s *Stmt) Scan(dst ...interface{}) error
- func (s *Stmt) Status(op int, reset bool) int
- func (s *Stmt) String() string
- func (s *Stmt) Valid() bool
- type UpdateFunc
- type ZeroBlob
- Bugs
Constants ¶
const ( INTEGER = C.SQLITE_INTEGER // 1 FLOAT = C.SQLITE_FLOAT // 2 TEXT = C.SQLITE_TEXT // 3 BLOB = C.SQLITE_BLOB // 4 NULL = C.SQLITE_NULL // 5 )
Fundamental SQLite data types. These are returned by Stmt.DataTypes method. [http://www.sqlite.org/c3ref/c_blob.html]
const ( OK = C.SQLITE_OK // 0 = Successful result ERROR = C.SQLITE_ERROR // 1 = SQL error or missing database INTERNAL = C.SQLITE_INTERNAL // 2 = Internal logic error in SQLite PERM = C.SQLITE_PERM // 3 = Access permission denied ABORT = C.SQLITE_ABORT // 4 = Callback routine requested an abort BUSY = C.SQLITE_BUSY // 5 = The database file is locked LOCKED = C.SQLITE_LOCKED // 6 = A table in the database is locked NOMEM = C.SQLITE_NOMEM // 7 = A malloc() failed READONLY = C.SQLITE_READONLY // 8 = Attempt to write a readonly database INTERRUPT = C.SQLITE_INTERRUPT // 9 = Operation terminated by sqlite3_interrupt() IOERR = C.SQLITE_IOERR // 10 = Some kind of disk I/O error occurred CORRUPT = C.SQLITE_CORRUPT // 11 = The database disk image is malformed NOTFOUND = C.SQLITE_NOTFOUND // 12 = Unknown opcode in sqlite3_file_control() FULL = C.SQLITE_FULL // 13 = Insertion failed because database is full CANTOPEN = C.SQLITE_CANTOPEN // 14 = Unable to open the database file PROTOCOL = C.SQLITE_PROTOCOL // 15 = Database lock protocol error EMPTY = C.SQLITE_EMPTY // 16 = Database is empty SCHEMA = C.SQLITE_SCHEMA // 17 = The database schema changed TOOBIG = C.SQLITE_TOOBIG // 18 = String or BLOB exceeds size limit CONSTRAINT = C.SQLITE_CONSTRAINT // 19 = Abort due to constraint violation MISMATCH = C.SQLITE_MISMATCH // 20 = Data type mismatch MISUSE = C.SQLITE_MISUSE // 21 = Library used incorrectly NOLFS = C.SQLITE_NOLFS // 22 = Uses OS features not supported on host AUTH = C.SQLITE_AUTH // 23 = Authorization denied FORMAT = C.SQLITE_FORMAT // 24 = Auxiliary database format error RANGE = C.SQLITE_RANGE // 25 = 2nd parameter to sqlite3_bind out of range NOTADB = C.SQLITE_NOTADB // 26 = File opened that is not a database file NOTICE = C.SQLITE_NOTICE // 27 = Notifications from sqlite3_log() WARNING = C.SQLITE_WARNING // 28 = Warnings from sqlite3_log() ROW = C.SQLITE_ROW // 100 = sqlite3_step() has another row ready DONE = C.SQLITE_DONE // 101 = sqlite3_step() has finished executing )
General result codes returned by the SQLite API. When converted to an error, OK and ROW become nil, and DONE becomes either nil or io.EOF, depending on the context in which the statement is executed. All other codes are returned via the Error struct. [http://www.sqlite.org/c3ref/c_abort.html]
const ( IOERR_READ = C.SQLITE_IOERR_READ // (SQLITE_IOERR | (1<<8)) IOERR_SHORT_READ = C.SQLITE_IOERR_SHORT_READ // (SQLITE_IOERR | (2<<8)) IOERR_WRITE = C.SQLITE_IOERR_WRITE // (SQLITE_IOERR | (3<<8)) IOERR_FSYNC = C.SQLITE_IOERR_FSYNC // (SQLITE_IOERR | (4<<8)) IOERR_DIR_FSYNC = C.SQLITE_IOERR_DIR_FSYNC // (SQLITE_IOERR | (5<<8)) IOERR_TRUNCATE = C.SQLITE_IOERR_TRUNCATE // (SQLITE_IOERR | (6<<8)) IOERR_FSTAT = C.SQLITE_IOERR_FSTAT // (SQLITE_IOERR | (7<<8)) IOERR_UNLOCK = C.SQLITE_IOERR_UNLOCK // (SQLITE_IOERR | (8<<8)) IOERR_RDLOCK = C.SQLITE_IOERR_RDLOCK // (SQLITE_IOERR | (9<<8)) IOERR_DELETE = C.SQLITE_IOERR_DELETE // (SQLITE_IOERR | (10<<8)) IOERR_BLOCKED = C.SQLITE_IOERR_BLOCKED // (SQLITE_IOERR | (11<<8)) IOERR_NOMEM = C.SQLITE_IOERR_NOMEM // (SQLITE_IOERR | (12<<8)) IOERR_ACCESS = C.SQLITE_IOERR_ACCESS // (SQLITE_IOERR | (13<<8)) IOERR_CHECKRESERVEDLOCK = C.SQLITE_IOERR_CHECKRESERVEDLOCK // (SQLITE_IOERR | (14<<8)) IOERR_LOCK = C.SQLITE_IOERR_LOCK // (SQLITE_IOERR | (15<<8)) IOERR_CLOSE = C.SQLITE_IOERR_CLOSE // (SQLITE_IOERR | (16<<8)) IOERR_DIR_CLOSE = C.SQLITE_IOERR_DIR_CLOSE // (SQLITE_IOERR | (17<<8)) IOERR_SHMOPEN = C.SQLITE_IOERR_SHMOPEN // (SQLITE_IOERR | (18<<8)) IOERR_SHMSIZE = C.SQLITE_IOERR_SHMSIZE // (SQLITE_IOERR | (19<<8)) IOERR_SHMLOCK = C.SQLITE_IOERR_SHMLOCK // (SQLITE_IOERR | (20<<8)) IOERR_SHMMAP = C.SQLITE_IOERR_SHMMAP // (SQLITE_IOERR | (21<<8)) IOERR_SEEK = C.SQLITE_IOERR_SEEK // (SQLITE_IOERR | (22<<8)) IOERR_DELETE_NOENT = C.SQLITE_IOERR_DELETE_NOENT // (SQLITE_IOERR | (23<<8)) IOERR_MMAP = C.SQLITE_IOERR_MMAP // (SQLITE_IOERR | (24<<8)) IOERR_GETTEMPPATH = C.SQLITE_IOERR_GETTEMPPATH // (SQLITE_IOERR | (25<<8)) IOERR_CONVPATH = C.SQLITE_IOERR_CONVPATH // (SQLITE_IOERR | (26<<8)) LOCKED_SHAREDCACHE = C.SQLITE_LOCKED_SHAREDCACHE // (SQLITE_LOCKED | (1<<8)) BUSY_RECOVERY = C.SQLITE_BUSY_RECOVERY // (SQLITE_BUSY | (1<<8)) BUSY_SNAPSHOT = C.SQLITE_BUSY_SNAPSHOT // (SQLITE_BUSY | (2<<8)) CANTOPEN_NOTEMPDIR = C.SQLITE_CANTOPEN_NOTEMPDIR // (SQLITE_CANTOPEN | (1<<8)) CANTOPEN_ISDIR = C.SQLITE_CANTOPEN_ISDIR // (SQLITE_CANTOPEN | (2<<8)) CANTOPEN_FULLPATH = C.SQLITE_CANTOPEN_FULLPATH // (SQLITE_CANTOPEN | (3<<8)) CANTOPEN_CONVPATH = C.SQLITE_CANTOPEN_CONVPATH // (SQLITE_CANTOPEN | (4<<8)) CORRUPT_VTAB = C.SQLITE_CORRUPT_VTAB // (SQLITE_CORRUPT | (1<<8)) READONLY_RECOVERY = C.SQLITE_READONLY_RECOVERY // (SQLITE_READONLY | (1<<8)) READONLY_CANTLOCK = C.SQLITE_READONLY_CANTLOCK // (SQLITE_READONLY | (2<<8)) READONLY_ROLLBACK = C.SQLITE_READONLY_ROLLBACK // (SQLITE_READONLY | (3<<8)) READONLY_DBMOVED = C.SQLITE_READONLY_DBMOVED // (SQLITE_READONLY | (4<<8)) ABORT_ROLLBACK = C.SQLITE_ABORT_ROLLBACK // (SQLITE_ABORT | (2<<8)) CONSTRAINT_CHECK = C.SQLITE_CONSTRAINT_CHECK // (SQLITE_CONSTRAINT | (1<<8)) CONSTRAINT_COMMITHOOK = C.SQLITE_CONSTRAINT_COMMITHOOK // (SQLITE_CONSTRAINT | (2<<8)) CONSTRAINT_FOREIGNKEY = C.SQLITE_CONSTRAINT_FOREIGNKEY // (SQLITE_CONSTRAINT | (3<<8)) CONSTRAINT_FUNCTION = C.SQLITE_CONSTRAINT_FUNCTION // (SQLITE_CONSTRAINT | (4<<8)) CONSTRAINT_NOTNULL = C.SQLITE_CONSTRAINT_NOTNULL // (SQLITE_CONSTRAINT | (5<<8)) CONSTRAINT_PRIMARYKEY = C.SQLITE_CONSTRAINT_PRIMARYKEY // (SQLITE_CONSTRAINT | (6<<8)) CONSTRAINT_TRIGGER = C.SQLITE_CONSTRAINT_TRIGGER // (SQLITE_CONSTRAINT | (7<<8)) CONSTRAINT_UNIQUE = C.SQLITE_CONSTRAINT_UNIQUE // (SQLITE_CONSTRAINT | (8<<8)) CONSTRAINT_VTAB = C.SQLITE_CONSTRAINT_VTAB // (SQLITE_CONSTRAINT | (9<<8)) CONSTRAINT_ROWID = C.SQLITE_CONSTRAINT_ROWID // (SQLITE_CONSTRAINT |(10<<8)) NOTICE_RECOVER_WAL = C.SQLITE_NOTICE_RECOVER_WAL // (SQLITE_NOTICE | (1<<8)) NOTICE_RECOVER_ROLLBACK = C.SQLITE_NOTICE_RECOVER_ROLLBACK // (SQLITE_NOTICE | (2<<8)) WARNING_AUTOINDEX = C.SQLITE_WARNING_AUTOINDEX // (SQLITE_WARNING | (1<<8)) )
Extended result codes returned by the SQLite API. Extended result codes are enabled by default for all new Conn objects. Use Error.Code()&0xFF to convert an extended code to a general one. [http://www.sqlite.org/c3ref/c_abort_rollback.html]
const ( CREATE_INDEX = C.SQLITE_CREATE_INDEX // 1 CREATE_TABLE = C.SQLITE_CREATE_TABLE // 2 CREATE_TEMP_INDEX = C.SQLITE_CREATE_TEMP_INDEX // 3 CREATE_TEMP_TABLE = C.SQLITE_CREATE_TEMP_TABLE // 4 CREATE_TEMP_TRIGGER = C.SQLITE_CREATE_TEMP_TRIGGER // 5 CREATE_TEMP_VIEW = C.SQLITE_CREATE_TEMP_VIEW // 6 CREATE_TRIGGER = C.SQLITE_CREATE_TRIGGER // 7 CREATE_VIEW = C.SQLITE_CREATE_VIEW // 8 DELETE = C.SQLITE_DELETE // 9 DROP_INDEX = C.SQLITE_DROP_INDEX // 10 DROP_TABLE = C.SQLITE_DROP_TABLE // 11 DROP_TEMP_INDEX = C.SQLITE_DROP_TEMP_INDEX // 12 DROP_TEMP_TABLE = C.SQLITE_DROP_TEMP_TABLE // 13 DROP_TEMP_TRIGGER = C.SQLITE_DROP_TEMP_TRIGGER // 14 DROP_TEMP_VIEW = C.SQLITE_DROP_TEMP_VIEW // 15 DROP_TRIGGER = C.SQLITE_DROP_TRIGGER // 16 DROP_VIEW = C.SQLITE_DROP_VIEW // 17 INSERT = C.SQLITE_INSERT // 18 PRAGMA = C.SQLITE_PRAGMA // 19 READ = C.SQLITE_READ // 20 SELECT = C.SQLITE_SELECT // 21 TRANSACTION = C.SQLITE_TRANSACTION // 22 UPDATE = C.SQLITE_UPDATE // 23 ATTACH = C.SQLITE_ATTACH // 24 DETACH = C.SQLITE_DETACH // 25 ALTER_TABLE = C.SQLITE_ALTER_TABLE // 26 REINDEX = C.SQLITE_REINDEX // 27 ANALYZE = C.SQLITE_ANALYZE // 28 CREATE_VTABLE = C.SQLITE_CREATE_VTABLE // 29 DROP_VTABLE = C.SQLITE_DROP_VTABLE // 30 FUNCTION = C.SQLITE_FUNCTION // 31 SAVEPOINT = C.SQLITE_SAVEPOINT // 32 RECURSIVE = C.SQLITE_RECURSIVE // 33 )
Codes used by SQLite to indicate the operation type when invoking authorizer and row update callbacks. [http://www.sqlite.org/c3ref/c_alter_table.html]
const ( STATUS_MEMORY_USED = C.SQLITE_STATUS_MEMORY_USED // 0 STATUS_PAGECACHE_USED = C.SQLITE_STATUS_PAGECACHE_USED // 1 STATUS_PAGECACHE_OVERFLOW = C.SQLITE_STATUS_PAGECACHE_OVERFLOW // 2 STATUS_SCRATCH_USED = C.SQLITE_STATUS_SCRATCH_USED // 3 STATUS_SCRATCH_OVERFLOW = C.SQLITE_STATUS_SCRATCH_OVERFLOW // 4 STATUS_MALLOC_SIZE = C.SQLITE_STATUS_MALLOC_SIZE // 5 STATUS_PARSER_STACK = C.SQLITE_STATUS_PARSER_STACK // 6 STATUS_PAGECACHE_SIZE = C.SQLITE_STATUS_PAGECACHE_SIZE // 7 STATUS_SCRATCH_SIZE = C.SQLITE_STATUS_SCRATCH_SIZE // 8 STATUS_MALLOC_COUNT = C.SQLITE_STATUS_MALLOC_COUNT // 9 )
Core SQLite performance counters that can be queried with Status. [http://www.sqlite.org/c3ref/c_status_malloc_count.html]
const ( DBSTATUS_LOOKASIDE_USED = C.SQLITE_DBSTATUS_LOOKASIDE_USED // 0 DBSTATUS_CACHE_USED = C.SQLITE_DBSTATUS_CACHE_USED // 1 DBSTATUS_SCHEMA_USED = C.SQLITE_DBSTATUS_SCHEMA_USED // 2 DBSTATUS_STMT_USED = C.SQLITE_DBSTATUS_STMT_USED // 3 DBSTATUS_LOOKASIDE_HIT = C.SQLITE_DBSTATUS_LOOKASIDE_HIT // 4 DBSTATUS_LOOKASIDE_MISS_SIZE = C.SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE // 5 DBSTATUS_LOOKASIDE_MISS_FULL = C.SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL // 6 DBSTATUS_CACHE_HIT = C.SQLITE_DBSTATUS_CACHE_HIT // 7 DBSTATUS_CACHE_MISS = C.SQLITE_DBSTATUS_CACHE_MISS // 8 DBSTATUS_CACHE_WRITE = C.SQLITE_DBSTATUS_CACHE_WRITE // 9 DBSTATUS_DEFERRED_FKS = C.SQLITE_DBSTATUS_DEFERRED_FKS // 10 )
Connection performance counters that can be queried with Conn.Status. [http://www.sqlite.org/c3ref/c_dbstatus_options.html]
const ( STMTSTATUS_FULLSCAN_STEP = C.SQLITE_STMTSTATUS_FULLSCAN_STEP // 1 STMTSTATUS_SORT = C.SQLITE_STMTSTATUS_SORT // 2 STMTSTATUS_AUTOINDEX = C.SQLITE_STMTSTATUS_AUTOINDEX // 3 STMTSTATUS_VM_STEP = C.SQLITE_STMTSTATUS_VM_STEP // 4 )
Statement performance counters that can be queried with Stmt.Status. [http://www.sqlite.org/c3ref/c_stmtstatus_counter.html]
const ( LIMIT_LENGTH = C.SQLITE_LIMIT_LENGTH // 0 LIMIT_SQL_LENGTH = C.SQLITE_LIMIT_SQL_LENGTH // 1 LIMIT_COLUMN = C.SQLITE_LIMIT_COLUMN // 2 LIMIT_EXPR_DEPTH = C.SQLITE_LIMIT_EXPR_DEPTH // 3 LIMIT_COMPOUND_SELECT = C.SQLITE_LIMIT_COMPOUND_SELECT // 4 LIMIT_VDBE_OP = C.SQLITE_LIMIT_VDBE_OP // 5 LIMIT_FUNCTION_ARG = C.SQLITE_LIMIT_FUNCTION_ARG // 6 LIMIT_ATTACHED = C.SQLITE_LIMIT_ATTACHED // 7 LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH // 8 LIMIT_VARIABLE_NUMBER = C.SQLITE_LIMIT_VARIABLE_NUMBER // 9 LIMIT_TRIGGER_DEPTH = C.SQLITE_LIMIT_TRIGGER_DEPTH // 10 )
Per-connection limits that can be queried and changed with Conn.Limit. [http://www.sqlite.org/c3ref/c_limit_attached.html]
Variables ¶
var ( ErrBadConn = &Error{MISUSE, "closed or invalid connection"} ErrBadStmt = &Error{MISUSE, "closed or invalid statement"} ErrBadIO = &Error{MISUSE, "closed or invalid incremental I/O operation"} ErrBadBackup = &Error{MISUSE, "closed or invalid backup operation"} )
Errors returned for access attempts to closed or invalid objects.
var ErrBlobFull = &Error{ERROR, "incremental write failed, no space left"}
ErrBlobFull is returned by BlobIO.Write when there isn't enough space left to write the provided bytes.
Functions ¶
func Complete ¶
Complete returns true if sql appears to contain a complete statement that is ready to be parsed. This does not validate the statement syntax. [http://www.sqlite.org/c3ref/complete.html]
func Print ¶
Print prints out all rows returned by a query. This function is intended as a debugging aid and may be removed or altered in the future. Do not use it in production applications.
func RegisterCodec ¶
RegisterCodec adds a new codec to the internal registry. Function f will be called when a key in the format "<name>:<...>" is provided to an attached database.
func ReleaseMemory ¶
ReleaseMemory attempts to free n bytes of heap memory by deallocating non-essential memory held by the SQLite library. It returns the number of bytes actually freed.
This function is currently a no-op because SQLite is not compiled with the SQLITE_ENABLE_MEMORY_MANAGEMENT option. [http://www.sqlite.org/c3ref/release_memory.html]
func SingleThread ¶
func SingleThread() bool
SingleThread returns true if the SQLite library was compiled with -DSQLITE_THREADSAFE=0. In this threading mode all mutex code is omitted and the package becomes unsafe for concurrent access, even to separate database connections.
The SQLite source that's part of this package is compiled with -DSQLITE_THREADSAFE=2, so this function should always return false. It is kept for backward compatibility when dynamic linking was supported in Go 1.0. [http://www.sqlite.org/threadsafe.html]
func SoftHeapLimit ¶
SoftHeapLimit sets and/or queries the soft limit on the amount of heap memory that may be allocated by SQLite. A negative value for n keeps the current limit, while 0 removes the limit. The previous limit value is returned, with negative values indicating an error. [http://www.sqlite.org/c3ref/soft_heap_limit64.html]
func SourceId ¶
func SourceId() string
SourceId returns the check-in identifier of SQLite within its configuration management system. [http://www.sqlite.org/c3ref/c_source_id.html]
func Status ¶
Status returns the current and peak values of a core performance counter, specified by one of the STATUS constants. If reset is true, the peak value is reset back down to the current value after retrieval. [http://www.sqlite.org/c3ref/status.html]
func Version ¶
func Version() string
Version returns the SQLite version as a string in the format "X.Y.Z[.N]". [http://www.sqlite.org/c3ref/libversion.html]
func VersionNum ¶
func VersionNum() int
VersionNum returns the SQLite version as an integer in the format X*1000000 + Y*1000 + Z, where X is the major version, Y is the minor version, and Z is the release number.
Types ¶
type Backup ¶
type Backup struct {
// contains filtered or unexported fields
}
Backup is a handle to an online backup operation between two databases. [http://www.sqlite.org/c3ref/backup.html]
func (*Backup) Close ¶
Close releases all resources associated with the backup operation. It is safe to call this method prior to backup completion to abort the operation. [http://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish]
func (*Backup) Conn ¶
Conn returns the source and destination connections that are used by this backup operation. The destination connection must not be used until the backup operation is closed.
func (*Backup) Progress ¶
Progress returns the number of pages that still need to be backed up and the total number of pages in the source database. The values are updated after each call to Step and are reset to 0 after the backup is closed. The total number of pages may change if the source database is modified during the backup operation. [http://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupremaining]
type BlobIO ¶
type BlobIO struct {
// contains filtered or unexported fields
}
BlobIO is a handle to a single BLOB (binary large object) or TEXT value opened for incremental I/O. This allows the value to be treated as a file for reading and writing. The value length cannot be changed using this API; use an UPDATE statement for that. The recommended way of allocating space for a BLOB is to use the ZeroBlob type or the zeroblob() SQL function. [http://www.sqlite.org/c3ref/blob.html]
func (*BlobIO) Close ¶
Close releases all resources associated with the incremental I/O operation. It is important to check the error returned by this method, since disk I/O and other types of errors may not be reported until the changes are actually committed to the database. [http://www.sqlite.org/c3ref/blob_close.html]
func (*BlobIO) Len ¶
Len returns the length of the BLOB/TEXT value in bytes. It is not possible to read/write/seek beyond this length. The length changes to 0 if the I/O handle expires due to an update of any column in the same row. This condition is indicated by an ABORT error code returned from Read or Write. An expired handle is closed automatically and cannot be reopened. Any writes that occurred before the abort are not rolled back. [http://www.sqlite.org/c3ref/blob_bytes.html]
func (*BlobIO) Read ¶
Read implements the io.Reader interface. [http://www.sqlite.org/c3ref/blob_read.html]
func (*BlobIO) Reopen ¶
Reopen closes the current value and opens another one in the same column, specified by its ROWID. If an error is encountered, the I/O handle becomes unusable and is automatically closed. [http://www.sqlite.org/c3ref/blob_reopen.html]
type BusyFunc ¶
BusyFunc is a callback function invoked by SQLite when it is unable to acquire a lock on a table. Count is the number of times that the callback has been invoked for this locking event so far. If the function returns false, then the operation is aborted. Otherwise, the function should block for a while before returning true and letting SQLite make another locking attempt.
type Codec ¶
type Codec interface { // Reserve returns the number of bytes that should be reserved for the codec // at the end of each page. The upper limit is 255 (32 if the page size is // 512). Returning -1 leaves the current value unchanged. Reserve() int // Resize is called when the codec is first attached to the pager and for // all subsequent page size changes. It can be used to allocate the encode // buffer. Resize(pageSize, reserve int) // Encode returns an encoded copy of a page. The data outside of the reserve // area in the original page must not be modified. The codec can either copy // this data into a buffer for encoding or return the original page without // making any changes. Bytes 16 through 23 of page 1 cannot be encoded. Any // non-nil error will be interpreted by SQLite as a NOMEM condition. This is // a limitation of underlying C API. Encode(page []byte, pageNum uint32, op int) ([]byte, *Error) // Decode decodes the page in-place, but it may use the encode buffer as // scratch space. Bytes 16 through 23 of page 1 must be left at their // original values. Any non-nil error will be interpreted by SQLite as a // NOMEM condition. This is a limitation of underlying C API. Decode(page []byte, pageNum uint32, op int) *Error // Key returns the original key that was used to initialize the codec. Some // implementations may be better off returning nil or a fake value. Search // lib/sqlite3.c for "sqlite3CodecGetKey" to see how the key is used. Key() []byte // Free releases codec resources when the pager is destroyed or when the // codec attachment fails. Free() }
Codec is the interface used to encode/decode database and journal pages as they are written to and read from the disk.
The op value passed to Encode and Decode methods identifies the operation being performed. It is undocumented and changed meanings over time since the codec API was first introduced in 2004. It is believed to be a bitmask of the following values:
1 = journal page, not set for WAL, always set when decoding 2 = disk I/O, always set 4 = encode
In the current implementation, op is always 3 when decoding, 6 when encoding for the database file or the WAL, and 7 when encoding for the journal. Search lib/sqlite3.c for "CODEC1" and "CODEC2" for more information.
type CodecCtx ¶
type CodecCtx struct { Path string // Full path to the database file Name string // Database name as it is known to SQLite (e.g. "main") PageSize int // Current page size in bytes Reserve int // Current number of bytes reserved in each page Fixed bool // True if the PageSize and Reserve values cannot be changed }
CodecCtx describes the database to which a codec is being attached.
type CodecFunc ¶
CodecFunc is a codec initialization function registered for a specific key prefix via RegisterCodec. It is called when a key with a matching prefix is specified for an attached database. It returns the Codec implementation that should be used to encode and decode all database and journal pages. Returning (nil, nil) disables the codec.
type CommitFunc ¶
type CommitFunc func() (abort bool)
CommitFunc is a callback function invoked by SQLite before a transaction is committed. If the function returns true, the transaction is rolled back.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a connection handle, which may have multiple databases attached to it by using the ATTACH SQL statement. [http://www.sqlite.org/c3ref/sqlite3.html]
func Open ¶
Open creates a new connection to a SQLite database. The name can be 1) a path to a file, which is created if it does not exist, 2) a URI using the syntax described at http://www.sqlite.org/uri.html, 3) the string ":memory:", which creates a temporary in-memory database, or 4) an empty string, which creates a temporary on-disk database (deleted when closed) in the directory returned by os.TempDir(). [http://www.sqlite.org/c3ref/open.html]
func (*Conn) AutoCommit ¶
AutoCommit returns true if the database connection is in auto-commit mode (i.e. outside of an explicit transaction started by BEGIN). [http://www.sqlite.org/c3ref/get_autocommit.html]
func (*Conn) Backup ¶
Backup starts an online database backup of c.srcName into dst.dstName. Connections c and dst must be distinct. All existing contents of the destination database are overwritten.
A read lock is acquired on the source database only while it is being read during a call to Backup.Step. The source connection may be used for other purposes between these calls. The destination connection must not be used for anything until the backup is closed. [http://www.sqlite.org/backup.html]
func (*Conn) Begin ¶
Begin starts a new deferred transaction. Use c.Exec("BEGIN...") to start an immediate or an exclusive transaction. [http://www.sqlite.org/lang_transaction.html]
func (*Conn) BlobIO ¶
BlobIO opens a BLOB or TEXT value for incremental I/O, allowing the value to be treated as a file for reading and/or writing. The value is located as if by the following query:
SELECT col FROM db.tbl WHERE rowid=row
If rw is true, the value is opened with read-write access, otherwise it is read-only. It is not possible to open a column that is part of an index or primary key for writing. If foreign key constraints are enabled, it is not possible to open a column that is part of a child key for writing. [http://www.sqlite.org/c3ref/blob_open.html]
func (*Conn) BusyFunc ¶
BusyFunc registers a function that is invoked by SQLite when it is unable to acquire a lock on a table. It returns the previous busy handler, if any. The function f should return true to make another lock acquisition attempt, or false to let the operation fail with BUSY or IOERR_BLOCKED error code. [http://www.sqlite.org/c3ref/busy_handler.html]
func (*Conn) BusyTimeout ¶
BusyTimeout enables the built-in busy handler, which retries the table locking operation for the specified duration before aborting. It returns the callback function that was previously registered with Conn.BusyFunc, if any. The busy handler is disabled if d is negative or zero. [http://www.sqlite.org/c3ref/busy_timeout.html]
func (*Conn) Close ¶
Close releases all resources associated with the connection. If any prepared statements, incremental I/O operations, or backup operations are still active, the connection becomes an unusable "zombie" and is closed after all remaining statements and operations are destroyed. A BUSY error code is returned if the connection is left in this "zombie" status, which may indicate a programming error where some previously allocated resource is not properly released. [http://www.sqlite.org/c3ref/close.html]
func (*Conn) CommitFunc ¶
func (c *Conn) CommitFunc(f CommitFunc) (prev CommitFunc)
CommitFunc registers a function that is invoked by SQLite before a transaction is committed. It returns the previous commit handler, if any. If the function f returns true, the transaction is rolled back instead, causing the rollback handler to be invoked, if one is registered. [http://www.sqlite.org/c3ref/commit_hook.html]
func (*Conn) Exec ¶
Exec is a convenience method for executing one or more statements in sql. Arguments may be specified either as a list of unnamed interface{} values or as a single NamedArgs map. In unnamed mode, each statement consumes the required number of values from args. For example:
c.Exec("UPDATE x SET a=?; UPDATE x SET b=?", 1, 2) // is executed as: // UPDATE x SET a=1 // UPDATE x SET b=2
With NamedArgs, the entire map is passed to every statement in sql and unreferenced names are ignored. The following example is identical to the previous one:
args := NamedArgs{"$a": 1, "$b": 2} c.Exec("UPDATE x SET a=$a; UPDATE x SET b=$b", args)
Without any extra arguments, the statements in sql are executed by a single call to sqlite3_exec. [http://www.sqlite.org/c3ref/exec.html]
func (*Conn) Interrupt ¶
func (c *Conn) Interrupt()
Interrupt causes any pending database operation to abort and return at its earliest opportunity. It is safe to call this method from a goroutine different from the one that is currently running the database operation, but it is not safe to call this method on a connection that might close before the call returns. [http://www.sqlite.org/c3ref/interrupt.html]
func (*Conn) Key ¶
Key provides a codec key to an attached database. This method should be called right after opening the connection.
func (*Conn) LastInsertId ¶
LastInsertId returns the ROWID of the most recent successful INSERT statement. [http://www.sqlite.org/c3ref/last_insert_rowid.html]
func (*Conn) Limit ¶
Limit changes a per-connection resource usage or performance limit, specified by one of the LIMIT constants, returning its previous value. If the new value is negative, the limit is left unchanged and its current value is returned. [http://www.sqlite.org/c3ref/limit.html]
func (*Conn) Path ¶
Path returns the full file path of an attached database. An empty string is returned for temporary databases. [http://www.sqlite.org/c3ref/db_filename.html]
func (*Conn) Prepare ¶
Prepare compiles the first statement in sql. Any remaining text after the first statement is saved in Stmt.Tail. [http://www.sqlite.org/c3ref/prepare.html]
func (*Conn) Query ¶
Query is a convenience method for executing the first query in sql. It returns either a prepared statement ready for scanning or an error, which will be io.EOF if the query did not return any rows.
func (*Conn) Rekey ¶
Rekey changes the codec key for an attached database. This is not currently implemented for Go codecs.
func (*Conn) RollbackFunc ¶
func (c *Conn) RollbackFunc(f RollbackFunc) (prev RollbackFunc)
RollbackFunc registers a function that is invoked by SQLite when a transaction is rolled back. It returns the previous rollback handler, if any. [http://www.sqlite.org/c3ref/commit_hook.html]
func (*Conn) RowsAffected ¶
RowsAffected returns the number of rows that were changed, inserted, or deleted by the most recent statement. Auxiliary changes caused by triggers or foreign key actions are not counted. [http://www.sqlite.org/c3ref/changes.html]
func (*Conn) Status ¶
Status returns the current and peak values of a connection performance counter, specified by one of the DBSTATUS constants. If reset is true, the peak value is reset back down to the current value after retrieval. [http://www.sqlite.org/c3ref/db_status.html]
func (*Conn) TotalRowsAffected ¶
TotalRowsAffected returns the number of rows that were changed, inserted, or deleted since the database connection was opened, including changes caused by trigger and foreign key actions. [http://www.sqlite.org/c3ref/total_changes.html]
func (*Conn) UpdateFunc ¶
func (c *Conn) UpdateFunc(f UpdateFunc) (prev UpdateFunc)
UpdateFunc registers a function that is invoked by SQLite when a row is updated, inserted, or deleted. It returns the previous update handler, if any. [http://www.sqlite.org/c3ref/update_hook.html]
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error is returned for all SQLite API result codes other than OK, ROW, and DONE.
type NamedArgs ¶
type NamedArgs map[string]interface{}
NamedArgs is a name/value map of arguments passed to a prepared statement that uses ?NNN, :AAA, @AAA, and/or $AAA parameter formats. Name matching is case-sensitive and the prefix character (one of [?:@$]) must be included in the name. Names that are missing from the map are treated as NULL. Names that are not used in the prepared statement are ignored.
It is not possible to mix named and anonymous ("?") parameters in the same statement. [http://www.sqlite.org/lang_expr.html#varparam]
type RawBytes ¶
type RawBytes []byte
RawString and RawBytes are special string and []byte types that may be used for database input and output without the cost of an extra copy operation.
When used as an argument to a statement, the contents are bound using SQLITE_STATIC instead of SQLITE_TRANSIENT flag. This requires the contents to remain valid and unmodified until the end of statement execution. In particular, the caller must keep a reference to the value to prevent it from being garbage collected.
When used for retrieving query output, the internal string/[]byte pointer is set to reference memory belonging to SQLite. The memory remains valid until another method is called on the Stmt object and should not be modified.
type RawString ¶
type RawString string
RawString and RawBytes are special string and []byte types that may be used for database input and output without the cost of an extra copy operation.
When used as an argument to a statement, the contents are bound using SQLITE_STATIC instead of SQLITE_TRANSIENT flag. This requires the contents to remain valid and unmodified until the end of statement execution. In particular, the caller must keep a reference to the value to prevent it from being garbage collected.
When used for retrieving query output, the internal string/[]byte pointer is set to reference memory belonging to SQLite. The memory remains valid until another method is called on the Stmt object and should not be modified.
type RollbackFunc ¶
type RollbackFunc func()
RollbackFunc is a callback function invoked by SQLite when a transaction is rolled back.
type RowMap ¶
type RowMap map[string]interface{}
RowMap may be passed as the last (or only) argument to Stmt.Scan to create a map of all remaining column/value pairs in the current row. The map is not cleared before being populated with new column values. Assignment is performed in left-to-right column order, and values may be overwritten if the query returns two or more columns with identical names.
type Stmt ¶
type Stmt struct { Tail string // Uncompiled portion of the SQL string passed to Conn.Prepare // contains filtered or unexported fields }
Stmt is a prepared statement handle.
SQLite automatically recompiles prepared statements when the database schema changes. A query like "SELECT * FROM x" may return a different number of columns from one execution to the next if the table is altered. The recompilation, if required, only happens at the start of execution (during a call to Exec or Query). Statements that are already running (Busy() == true) are not recompiled. Thus, the safest way of obtaining column information is to call Exec or Query first, followed by NumColumns, Columns, DeclTypes, etc. [http://www.sqlite.org/c3ref/stmt.html]
func (*Stmt) Busy ¶
Busy returns true if the prepared statement is in the middle of execution with a row available for scanning. It is not necessary to reset a busy statement before making another call to Exec or Query.
func (*Stmt) Close ¶
Close releases all resources associated with the prepared statement. This method can be called at any point in the statement's life cycle. [http://www.sqlite.org/c3ref/finalize.html]
func (*Stmt) Columns ¶
Columns returns the names of columns produced by the prepared statement. [http://www.sqlite.org/c3ref/column_name.html]
func (*Stmt) DataTypes ¶
DataTypes returns the data type codes of columns in the current row. Possible data types are INTEGER, FLOAT, TEXT, BLOB, and NULL. These represent the actual storage classes used by SQLite to store each value before any conversion. The returned slice should not be modified. [http://www.sqlite.org/c3ref/column_blob.html]
func (*Stmt) DeclTypes ¶
DeclTypes returns the type declarations of columns produced by the prepared statement. The type declarations are normalized to upper case. [http://www.sqlite.org/c3ref/column_decltype.html]
func (*Stmt) Exec ¶
Exec executes and resets the prepared statement. No rows are returned. [http://www.sqlite.org/c3ref/step.html]
func (*Stmt) Next ¶
Next makes the next row available for scanning. io.EOF is returned and the statement is reset if no more rows are available.
func (*Stmt) NumColumns ¶
NumColumns returns the number of columns produced by the prepared statement. [http://www.sqlite.org/c3ref/column_count.html]
func (*Stmt) NumParams ¶
NumParams returns the number of bound parameters in the prepared statement. This is also the number of arguments required for calling Exec or Query without a NamedArgs map. [http://www.sqlite.org/c3ref/bind_parameter_count.html]
func (*Stmt) Params ¶
Params returns the names of bound parameters in the prepared statement. Nil is returned if the statement does not use named parameters. [http://www.sqlite.org/c3ref/bind_parameter_name.html]
func (*Stmt) Query ¶
Query executes the prepared statement and makes the first returned row available for scanning. io.EOF is returned and the statement is reset if the query does not return any rows.
func (*Stmt) ReadOnly ¶
ReadOnly returns true if the prepared statement makes no direct changes to the content of the database file. [http://www.sqlite.org/c3ref/stmt_readonly.html]
func (*Stmt) Reset ¶
func (s *Stmt) Reset()
Reset returns the prepared statement to its initial state, ready to be re-executed. This should be done when the remaining rows returned by a query are not needed, which releases some resources that would otherwise persist until the next call to Exec or Query. [http://www.sqlite.org/c3ref/reset.html]
func (*Stmt) Scan ¶
Scan retrieves data from the current row, storing successive column values into successive arguments. If the last argument is an instance of RowMap, then all remaining column/value pairs are assigned into the map. The same row may be scanned multiple times. Nil arguments are silently skipped. [http://www.sqlite.org/c3ref/column_blob.html]
func (*Stmt) Status ¶
Status returns the current value of a statement performance counter, specified by one of the STMTSTATUS constants. If reset is true, the value is reset back down to 0 after retrieval. [http://www.sqlite.org/c3ref/stmt_status.html]
func (*Stmt) String ¶
String returns the SQL text that was used to create this prepared statement. [http://www.sqlite.org/c3ref/sql.html]
type UpdateFunc ¶
UpdateFunc is a callback function invoked by SQLite when a row is updated, inserted, or deleted.
Notes ¶
Bugs ¶
The SQL statement "PRAGMA busy_timeout = n" does not clear the BusyFunc registered with the connection (if there is one). This causes the next call to Conn.BusyTimeout or Conn.BusyFunc to return a previous handler that wasn't actually being used. This doesn't affect the operation of SQLite in any way. Use Conn.BusyTimeout instead of the PRAGMA to avoid this problem if the return value is important.
If a SQLite memory allocation fails while scanning column values, the error is not reported until the next call to Stmt.Next or Stmt.Close. This behavior may change in the future to check for and return the error immediately from Stmt.Scan.