Documentation ¶
Overview ¶
Package sqlite3 provides interface to SQLite3 databases.
This works as a driver for database/sql.
Installation
go get github.com/mattn/go-sqlite3
Supported Types ¶
Currently, go-sqlite3 supports the following data types.
+------------------------------+ |go | sqlite3 | |----------|-------------------| |nil | null | |int | integer | |int64 | integer | |float64 | float | |bool | integer | |[]byte | blob | |string | text | |time.Time | timestamp/datetime| +------------------------------+
SQLite3 Extension ¶
You can write your own extension module for sqlite3. For example, below is an extension for a Regexp matcher operation.
#include <pcre.h> #include <string.h> #include <stdio.h> #include <sqlite3ext.h> SQLITE_EXTENSION_INIT1 static void regexp_func(sqlite3_context *context, int argc, sqlite3_value **argv) { if (argc >= 2) { const char *target = (const char *)sqlite3_value_text(argv[1]); const char *pattern = (const char *)sqlite3_value_text(argv[0]); const char* errstr = NULL; int erroff = 0; int vec[500]; int n, rc; pcre* re = pcre_compile(pattern, 0, &errstr, &erroff, NULL); rc = pcre_exec(re, NULL, target, strlen(target), 0, 0, vec, 500); if (rc <= 0) { sqlite3_result_error(context, errstr, 0); return; } sqlite3_result_int(context, 1); } } #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_extension_init(sqlite3 *db, char **errmsg, const sqlite3_api_routines *api) { SQLITE_EXTENSION_INIT2(api); return sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, (void*)db, regexp_func, NULL, NULL); }
It needs to be built as a so/dll shared library. And you need to register the extension module like below.
sql.Register("sqlite3_with_extensions", &sqlite3.SQLiteDriver{ Extensions: []string{ "sqlite3_mod_regexp", }, })
Then, you can use this extension.
rows, err := db.Query("select text from mytable where name regexp '^golang'")
Connection Hook ¶
You can hook and inject your code when the connection is established. database/sql doesn't provide a way to get native go-sqlite3 interfaces. So if you want, you need to set ConnectHook and get the SQLiteConn.
sql.Register("sqlite3_with_hook_example", &sqlite3.SQLiteDriver{ ConnectHook: func(conn *sqlite3.SQLiteConn) error { sqlite3conn = append(sqlite3conn, conn) return nil }, })
Go SQlite3 Extensions ¶
If you want to register Go functions as SQLite extension functions, call RegisterFunction from ConnectHook.
regex = func(re, s string) (bool, error) { return regexp.MatchString(re, s) } sql.Register("sqlite3_with_go_func", &sqlite3.SQLiteDriver{ ConnectHook: func(conn *sqlite3.SQLiteConn) error { return conn.RegisterFunc("regexp", regex, true) }, })
See the documentation of RegisterFunc for more details.
Index ¶
- Constants
- Variables
- func RegisterCryptEncoder(e CryptEncoder)
- func Version() (libVersion string, libVersionNumber int, sourceID string)
- type Auth
- type AutoVacuum
- type CacheMode
- type Config
- type CryptEncoder
- type CryptSaltedEncoder
- type ErrNo
- type ErrNoExtended
- type Error
- type JournalMode
- type LockingMode
- type Mode
- type Mutex
- type SQLiteBackup
- type SQLiteConn
- func (c *SQLiteConn) AuthEnabled() (exists bool)
- func (c *SQLiteConn) AuthUserAdd(username, password string, admin bool) error
- func (c *SQLiteConn) AuthUserChange(username, password string, admin bool) error
- func (c *SQLiteConn) AuthUserDelete(username string) error
- func (c *SQLiteConn) Authenticate(username, password string) error
- func (c *SQLiteConn) AutoCommit() bool
- func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error)
- func (c *SQLiteConn) Begin() (driver.Tx, error)
- func (c *SQLiteConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error)
- func (c *SQLiteConn) Close() error
- func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error)
- func (c *SQLiteConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error)
- func (c *SQLiteConn) GetFilename(schemaName string) string
- func (c *SQLiteConn) GetLimit(id int) int
- func (c *SQLiteConn) LoadExtension(lib string, entry string) error
- func (c *SQLiteConn) PRAGMA(name, value string) error
- func (c *SQLiteConn) Ping(ctx context.Context) error
- func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error)
- func (c *SQLiteConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error)
- func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error)
- func (c *SQLiteConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error)
- func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error
- func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error
- func (c *SQLiteConn) RegisterCommitHook(callback func() int)
- func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error
- func (c *SQLiteConn) RegisterPreUpdateHook(callback func(SQLitePreUpdateData))
- func (c *SQLiteConn) RegisterRollbackHook(callback func())
- func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64))
- func (c *SQLiteConn) SetLimit(id int, newVal int) int
- type SQLiteDriver
- type SQLitePreUpdateData
- type SQLiteResult
- type SQLiteRows
- func (rc *SQLiteRows) Close() error
- func (rc *SQLiteRows) ColumnTypeDatabaseTypeName(i int) string
- func (rc *SQLiteRows) ColumnTypeNullable(i int) (nullable, ok bool)
- func (rc *SQLiteRows) ColumnTypeScanType(i int) reflect.Type
- func (rc *SQLiteRows) Columns() []string
- func (rc *SQLiteRows) DeclTypes() []string
- func (rc *SQLiteRows) Next(dest []driver.Value) error
- type SQLiteStmt
- func (s *SQLiteStmt) Close() error
- func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error)
- func (s *SQLiteStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error)
- func (s *SQLiteStmt) NumInput() int
- func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error)
- func (s *SQLiteStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error)
- type SQLiteTx
- type SecureDelete
- type Synchronous
- type TxLock
Constants ¶
const ( // ModeReadOnly defines SQLITE_OPEN_READONLY for the database connection. ModeReadOnly = Mode(C.SQLITE_OPEN_READONLY) // ModeReadWrite defines SQLITE_OPEN_READWRITE for the database connection. ModeReadWrite = Mode(C.SQLITE_OPEN_READWRITE) // ModeReadWriteCreate defines SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ModeReadWriteCreate = Mode(C.SQLITE_OPEN_READWRITE | C.SQLITE_OPEN_CREATE) // ModeMemory defines mode=memory which will // create a pure in-memory database that never reads or writes from disk ModeMemory = Mode(C.SQLITE_OPEN_MEMORY) )
const ( CacheMode(C.SQLITE_OPEN_SHAREDCACHE) // CacheModePrivate sets the cache mode of SQLite to 'private' CacheModePrivate = CacheMode(C.SQLITE_OPEN_PRIVATECACHE) )CacheModeShared =
const ( // MutexNo will force the database connection opens // in the multi-thread threading mode as long as the // single-thread mode has not been set at compile-time or start-time. MutexNo = Mutex(C.SQLITE_OPEN_NOMUTEX) // MutexFull will force the database connection opens // in the serialized threading mode unless single-thread // was previously selected at compile-time or start-time. MutexFull = Mutex(C.SQLITE_OPEN_FULLMUTEX) )
const ( // TxLockDeferred deferred transaction behaviour. (Default) // Deferred means that no locks are acquired on the database // until the database is first accessed. // Thus with a deferred transaction, // the BEGIN statement itself does nothing to the filesystem. // Locks are not acquired until the first read or write operation. // The first read operation against a database creates a SHARED lock // and the first write operation creates a RESERVED lock. // Because the acquisition of locks is deferred until they are needed, // it is possible that another thread or process could create a separate transaction // and write to the database after the BEGIN on the current thread has executed. TxLockDeferred = TxLock("BEGIN") // TxLockImmediate immediate transaction behaviour. // If the transaction is immediate, // then RESERVED locks are acquired on all databases // as soon as the BEGIN command is executed, // without waiting for the database to be used. // After a BEGIN IMMEDIATE, no other database connection // will be able to write to the database or do a BEGIN IMMEDIATE or BEGIN EXCLUSIVE. // Other processes can continue to read from the database however. TxLockImmediate = TxLock("BEGIN IMMEDIATE") // TxLockExclusive exclusive transaction behaviour. // An exclusive transaction causes EXCLUSIVE locks to be acquired on all databases. // After a BEGIN EXCLUSIVE, no other database connection // except for read_uncommitted connections will be able to read the database // and no other connection without exception will be able to write the database // until the transaction is complete. TxLockExclusive = TxLock("BEGIN EXCLUSIVE") )
const ( // LockingModeNormal In NORMAL locking-mode // (the default unless overridden at compile-time using SQLITE_DEFAULT_LOCKING_MODE), // a database connection unlocks the database file at the conclusion // of each read or write transaction. LockingModeNormal = LockingMode("NORMAL") // LockingModeExclusive When the locking-mode is set to EXCLUSIVE, // the database connection never releases file-locks. // The first time the database is read in EXCLUSIVE mode, // a shared lock is obtained and held. // The first time the database is written, an exclusive lock is obtained and held. LockingModeExclusive = LockingMode("EXCLUSIVE") )
const ( // AutoVacuumNone setting means that auto-vacuum is disabled. // // When auto-vacuum is disabled and data is deleted data from a database, // the database file remains the same size. // Unused database file pages are added to a "freelist" and reused for subsequent inserts. // So no database file space is lost. // However, the database file does not shrink. // In this mode the VACUUM command can be used to rebuild the entire database file // and thus reclaim unused disk space. // // The database connection can be changed between full // and incremental autovacuum mode at any time. // However, changing from "none" to "full" or "incremental" // can only occur when the database is new (no tables have yet been created) // or by running the VACUUM command. To change auto-vacuum modes, // first use the auto_vacuum pragma to set the new desired mode, // then invoke the VACUUM command to reorganize the entire database file. // To change from "full" or "incremental" back to "none" // always requires running VACUUM even on an empty database. AutoVacuumNone = AutoVacuum("NONE") // AutoVacuumFull sets auto vacuum of the database to FULL. // // When the auto-vacuum mode is 1 or "full", // the freelist pages are moved to the end of the database file and the database file // is truncated to remove the freelist pages at every transaction commit. // Note, however, that auto-vacuum only truncates the freelist pages from the file. // Auto-vacuum does not defragment the database nor repack individual database pages // the way that the VACUUM command does. // In fact, because it moves pages around within the file, // auto-vacuum can actually make fragmentation worse. AutoVacuumFull = AutoVacuum("FULL") // AutoVacuumIncremental sets the auto vacuum of the database to INCREMENTAL. // // When the value of auto-vacuum is 2 or "incremental" // then the additional information needed to do auto-vacuuming is stored // in the database file but auto-vacuuming does not occur automatically // at each commit as it does with auto_vacuum=full. // In incremental mode, the separate incremental_vacuum pragma must be invoked // to cause the auto-vacuum to occur. AutoVacuumIncremental = AutoVacuum("INCREMENTAL") )
const ( // JournalModeAuto is the journal mode in which the Journal is not explicitly set. // This means that if any other program or connection already has set the journal mode // the journal mode is automatically read from the database and not forcibly set. JournalModeAuto = JournalMode("AUTO") // JournalModeDelete is the normal behavior. // In the DELETE mode, the rollback journal is deleted at the conclusion // of each transaction. // Indeed, the delete operation is the action that causes the transaction to commit. // (See the document titled Atomic Commit In SQLite for additional detail.) JournalModeDelete = JournalMode("DELETE") // JournalModeTruncate commits transactions by truncating the rollback journal // to zero-length instead of deleting it. // On many systems, truncating a file is much faster // than deleting the file since the containing directory does not need to be changed. JournalModeTruncate = JournalMode("TRUNCATE") // JournalModePersist prevents the rollback journal from being deleted // at the end of each transaction. // Instead, the header of the journal is overwritten with zeros. // This will prevent other database connections from rolling the journal back. // The PERSIST journaling mode is useful as an optimization on platforms // where deleting or truncating a file is much more expensive // than overwriting the first block of a file with zeros. // See also: PRAGMA journal_size_limit and SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT. JournalModePersist = JournalMode("PERSIST") // JournalModeMemory stores the rollback journal in volatile RAM. // This saves disk I/O but at the expense of database safety and integrity. // If the application using SQLite crashes in the middle of a transaction // when the MEMORY journaling mode is set, // then the database file will very likely go corrupt. JournalModeMemory = JournalMode("MEMORY") // JournalModeWAL uses a write-ahead log instead of a rollback journal // to implement transactions. // The WAL journaling mode is persistent; // after being set it stays in effect across multiple database connections // and after closing and reopening the database. JournalModeWAL = JournalMode("WAL") // JournalModeOff disables the rollback journal completely. // No rollback journal is ever created and hence there is never a rollback journal to delete. // The OFF journaling mode disables the atomic commit and rollback capabilities of SQLite. The ROLLBACK command no longer works; it behaves in an undefined way. Applications must avoid using the ROLLBACK command when the journal mode is OFF. If the application crashes in the middle of a transaction when the OFF journaling mode is set, then the database file will very likely go corrupt. JournalModeOff = JournalMode("OFF") )
const ( // SecureDeleteOff disables secure deletion of content. SecureDeleteOff = SecureDelete("OFF") // SecureDeleteOn will cause SQLite overwrites deleted content with zeros. SecureDeleteOn = SecureDelete("ON") // SecureDeleteFast defines the "fast" setting for secure_delete (added circa 2017-08-01) is an intermediate setting // in between "on" and "off". When secure_delete is set to "fast", // SQLite will overwrite deleted content with zeros only if doing so // does not increase the amount of I/O. In other words, // the "fast" setting uses more CPU cycles but does not use more I/O. // This has the effect of purging all old content from b-tree pages, // but leaving forensic traces on freelist pages. SecureDeleteFast = SecureDelete("FAST") )
const ( // SynchronousOff sets synchronous to OFF (0), // SQLite continues without syncing as soon as it has handed data off to the operating system. // If the application running SQLite crashes, the data will be safe, // but the database might become corrupted if the operating system crashes // or the computer loses power before that data has been written to the disk surface. // On the other hand, commits can be orders of magnitude faster with synchronous OFF. SynchronousOff = Synchronous("OFF") // SynchronousNormal sets synchronous to NORMAL (1), // the SQLite database engine will still sync at the most critical moments, // but less often than in FULL mode. // There is a very small (though non-zero) chance that a power failure // at just the wrong time could corrupt the database in journal_mode=DELETE // on an older filesystem. WAL mode is safe from corruption with synchronous=NORMAL, // and probably DELETE mode is safe too on modern filesystems. // WAL mode is always consistent with synchronous=NORMAL, // but WAL mode does lose durability. // A transaction committed in WAL mode with synchronous=NORMAL // might roll back following a power loss or system crash. // Transactions are durable across application crashes regardless // of the synchronous setting or journal mode. // The synchronous=NORMAL setting is a good choice for most applications running in WAL mode. SynchronousNormal = Synchronous("NORMAL") // SynchronousFull sets synchronous to FULL (2), // the SQLite database engine will use the xSync method of the VFS // to ensure that all content is safely written to the disk surface prior to continuing. // This ensures that an operating system crash or power failure // will not corrupt the database. FULL synchronous is very safe, // but it is also slower. ///FULL is the most commonly used synchronous setting when not in WAL mode. SynchronousFull = Synchronous("FULL") // SynchronousExtra is like FULL with the addition that the directory containing // a rollback journal is synced after that journal is unlinked to commit a transaction // in DELETE mode. EXTRA provides additional durability if the commit // is followed closely by a power loss. SynchronousExtra = Synchronous("EXTRA") )
const ( // SQLITE_DELETE authorizer action code SQLITE_DELETE = C.SQLITE_DELETE // SQLITE_INSERT authorizer action code SQLITE_INSERT = C.SQLITE_INSERT // SQLITE_UPDATE authorizer action code SQLITE_UPDATE = C.SQLITE_UPDATE )
const ( // SQLITE_LIMIT_LENGTH defines the maximum size of any string or BLOB or table row, in bytes. SQLITE_LIMIT_LENGTH = C.SQLITE_LIMIT_LENGTH // SQLITE_LIMIT_SQL_LENGTH defines the maximum length of an SQL statement, in bytes. SQLITE_LIMIT_SQL_LENGTH = C.SQLITE_LIMIT_SQL_LENGTH // SQLITE_LIMIT_COLUMN defines the maximum number of columns in a table definition // or in the result set of a SELECT or the maximum number of columns // in an index or in an ORDER BY or GROUP BY clause. SQLITE_LIMIT_COLUMN = C.SQLITE_LIMIT_COLUMN // SQLITE_LIMIT_EXPR_DEPTH defines the maximum depth of the parse tree on any expression. SQLITE_LIMIT_EXPR_DEPTH = C.SQLITE_LIMIT_EXPR_DEPTH // SQLITE_LIMIT_COMPOUND_SELECT defines the maximum number of terms in a compound SELECT statement. SQLITE_LIMIT_COMPOUND_SELECT = C.SQLITE_LIMIT_COMPOUND_SELECT // SQLITE_LIMIT_VDBE_OP defines the maximum number of instructions // in a virtual machine program used to implement an SQL statement. // If sqlite3_prepare_v2() or the equivalent tries to allocate space // for more than this many opcodes in a single prepared statement, // an SQLITE_NOMEM error is returned. SQLITE_LIMIT_VDBE_OP = C.SQLITE_LIMIT_VDBE_OP // SQLITE_LIMIT_FUNCTION_ARG defines the maximum number of arguments on a function. SQLITE_LIMIT_FUNCTION_ARG = C.SQLITE_LIMIT_FUNCTION_ARG // SQLITE_LIMIT_ATTACHED defines the maximum number of attached databases. SQLITE_LIMIT_ATTACHED = C.SQLITE_LIMIT_ATTACHED // SQLITE_LIMIT_LIKE_PATTERN_LENGTH defines the maximum length of the pattern argument to the LIKE or GLOB operators. SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH // SQLITE_LIMIT_VARIABLE_NUMBER defines the maximum index number of any parameter in an SQL statement. SQLITE_LIMIT_VARIABLE_NUMBER = C.SQLITE_LIMIT_VARIABLE_NUMBER // SQLITE_LIMIT_TRIGGER_DEPTH defines the maximum depth of recursion for triggers. SQLITE_LIMIT_TRIGGER_DEPTH = C.SQLITE_LIMIT_TRIGGER_DEPTH // SQLITE_LIMIT_WORKER_THREADS defines the maximum number // of auxiliary worker threads that a single prepared statement may start. SQLITE_LIMIT_WORKER_THREADS = C.SQLITE_LIMIT_WORKER_THREADS )
Run-Time Limit Categories. See: http://www.sqlite.org/c3ref/c_limit_attached.html
const ( PRAGMA_SSE_KEY = "key" PRAGMA_AUTO_VACUUM = "auto_vacuum" PRAGMA_CASE_SENSITIVE_LIKE = "case_sensitive_like" PRAGMA_DEFER_FOREIGN_KEYS = "defer_foreign_keys" PRAGMA_FOREIGN_KEYS = "foreign_keys" PRAGMA_IGNORE_CHECK_CONTRAINTS = "ignore_check_constraints" PRAGMA_JOURNAL_MODE = "journal_mode" PRAGMA_LOCKING_MODE = "locking_mode" PRAGMA_QUERY_ONLY = "query_only" PRAGMA_RECURSIVE_TRIGGERS = "recursive_triggers" PRAGMA_SECURE_DELETE = "secure_delete" PRAGMA_SYNCHRONOUS = "synchronous" PRAGMA_WRITABLE_SCHEMA = "writable_schema" )
const ErrNoMask C.int = 0xff
ErrNoMask is mask code.
Variables ¶
var ( ErrError = ErrNo(1) /* SQL error or missing database */ ErrInternal = ErrNo(2) /* Internal logic error in SQLite */ ErrPerm = ErrNo(3) /* Access permission denied */ ErrAbort = ErrNo(4) /* Callback routine requested an abort */ ErrBusy = ErrNo(5) /* The database file is locked */ ErrLocked = ErrNo(6) /* A table in the database is locked */ ErrNomem = ErrNo(7) /* A malloc() failed */ ErrReadonly = ErrNo(8) /* Attempt to write a readonly database */ ErrInterrupt = ErrNo(9) /* Operation terminated by sqlite3_interrupt() */ ErrIoErr = ErrNo(10) /* Some kind of disk I/O error occurred */ ErrCorrupt = ErrNo(11) /* The database disk image is malformed */ ErrNotFound = ErrNo(12) /* Unknown opcode in sqlite3_file_control() */ ErrFull = ErrNo(13) /* Insertion failed because database is full */ ErrCantOpen = ErrNo(14) /* Unable to open the database file */ ErrProtocol = ErrNo(15) /* Database lock protocol error */ ErrEmpty = ErrNo(16) /* Database is empty */ ErrSchema = ErrNo(17) /* The database schema changed */ ErrTooBig = ErrNo(18) /* String or BLOB exceeds size limit */ ErrConstraint = ErrNo(19) /* Abort due to constraint violation */ ErrMismatch = ErrNo(20) /* Data type mismatch */ ErrMisuse = ErrNo(21) /* Library used incorrectly */ ErrNoLFS = ErrNo(22) /* Uses OS features not supported on host */ ErrAuth = ErrNo(23) /* Authorization denied */ ErrFormat = ErrNo(24) /* Auxiliary database format error */ ErrRange = ErrNo(25) /* 2nd parameter to sqlite3_bind out of range */ ErrNotADB = ErrNo(26) /* File opened that is not a database file */ ErrNotice = ErrNo(27) /* Notifications from sqlite3_log() */ ErrWarning = ErrNo(28) /* Warnings from sqlite3_log() */ )
result codes from http://www.sqlite.org/c3ref/c_abort.html
var ( ErrIoErrRead = ErrIoErr.Extend(1) ErrIoErrShortRead = ErrIoErr.Extend(2) ErrIoErrWrite = ErrIoErr.Extend(3) ErrIoErrFsync = ErrIoErr.Extend(4) ErrIoErrDirFsync = ErrIoErr.Extend(5) ErrIoErrTruncate = ErrIoErr.Extend(6) ErrIoErrFstat = ErrIoErr.Extend(7) ErrIoErrUnlock = ErrIoErr.Extend(8) ErrIoErrRDlock = ErrIoErr.Extend(9) ErrIoErrDelete = ErrIoErr.Extend(10) ErrIoErrBlocked = ErrIoErr.Extend(11) ErrIoErrNoMem = ErrIoErr.Extend(12) ErrIoErrAccess = ErrIoErr.Extend(13) ErrIoErrCheckReservedLock = ErrIoErr.Extend(14) ErrIoErrLock = ErrIoErr.Extend(15) ErrIoErrClose = ErrIoErr.Extend(16) ErrIoErrDirClose = ErrIoErr.Extend(17) ErrIoErrSHMOpen = ErrIoErr.Extend(18) ErrIoErrSHMSize = ErrIoErr.Extend(19) ErrIoErrSHMLock = ErrIoErr.Extend(20) ErrIoErrSHMMap = ErrIoErr.Extend(21) ErrIoErrSeek = ErrIoErr.Extend(22) ErrIoErrDeleteNoent = ErrIoErr.Extend(23) ErrIoErrMMap = ErrIoErr.Extend(24) ErrIoErrGetTempPath = ErrIoErr.Extend(25) ErrIoErrConvPath = ErrIoErr.Extend(26) ErrBusyRecovery = ErrBusy.Extend(1) ErrBusySnapshot = ErrBusy.Extend(2) ErrCantOpenNoTempDir = ErrCantOpen.Extend(1) ErrCantOpenIsDir = ErrCantOpen.Extend(2) ErrCantOpenFullPath = ErrCantOpen.Extend(3) ErrCantOpenConvPath = ErrCantOpen.Extend(4) ErrCorruptVTab = ErrCorrupt.Extend(1) ErrReadonlyRecovery = ErrReadonly.Extend(1) ErrReadonlyCantLock = ErrReadonly.Extend(2) ErrReadonlyRollback = ErrReadonly.Extend(3) ErrReadonlyDbMoved = ErrReadonly.Extend(4) ErrAbortRollback = ErrAbort.Extend(2) ErrConstraintCheck = ErrConstraint.Extend(1) ErrConstraintCommitHook = ErrConstraint.Extend(2) ErrConstraintForeignKey = ErrConstraint.Extend(3) ErrConstraintFunction = ErrConstraint.Extend(4) ErrConstraintNotNull = ErrConstraint.Extend(5) ErrConstraintPrimaryKey = ErrConstraint.Extend(6) ErrConstraintTrigger = ErrConstraint.Extend(7) ErrConstraintUnique = ErrConstraint.Extend(8) ErrConstraintVTab = ErrConstraint.Extend(9) ErrConstraintRowID = ErrConstraint.Extend(10) ErrNoticeRecoverWAL = ErrNotice.Extend(1) ErrNoticeRecoverRollback = ErrNotice.Extend(2) ErrWarningAutoIndex = ErrWarning.Extend(1) )
result codes from http://www.sqlite.org/c3ref/c_abort_rollback.html
var SQLiteTimestampFormats = []string{
"2006-01-02 15:04:05.999999999-07:00",
"2006-01-02T15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02T15:04:05.999999999",
"2006-01-02 15:04:05",
"2006-01-02T15:04:05",
"2006-01-02 15:04",
"2006-01-02T15:04",
"2006-01-02",
}
SQLiteTimestampFormats is timestamp formats understood by both this module and SQLite. The first format in the slice will be used when saving time values into the database. When parsing a string from a timestamp or datetime column, the formats are tried in order.
Functions ¶
func RegisterCryptEncoder ¶
func RegisterCryptEncoder(e CryptEncoder)
RegisterCryptEncoder will register a CryptEncoder to the sqlite3 driver which will automatically be found when used from a DSN string
Types ¶
type Auth ¶
type Auth struct { // Username for authentication Username string // Password for authentication Password string // Salt for encryption Salt string // CryptEncoder used for the password encryption Encoder CryptEncoder }
Auth holds the authentication configuration for the SQLite UserAuth module.
type AutoVacuum ¶
type AutoVacuum string
AutoVacuum defines the auto vacuum status of the database. The default setting for auto-vacuum is 0 or "none", unless the SQLITE_DEFAULT_AUTOVACUUM compile-time option is used. SQLITE_DEFAULT_AUTOVACUUM can be controlled within the package using build tags. See README for more information.
Auto-vacuuming is only possible if the database stores some additional information that allows each database page to be traced backwards to its referrer. Therefore, auto-vacuuming must be turned on before any tables are created. It is not possible to enable or disable auto-vacuum after a table has been created.
func (AutoVacuum) String ¶
func (av AutoVacuum) String() string
type Config ¶
type Config struct { // Database Database string // Mode of the SQLite database Mode Mode // CacheMode of the SQLite Connection Cache CacheMode // Mutex flag SQLITE_OPEN_MUTEX_NO, SQLITE_OPEN_MUTEX_FULL // Defaults to SQLITE_OPEN_MUTEX_FULL Mutex Mutex // The immutable parameter is a boolean query parameter that indicates // that the database file is stored on read-only media. When immutable is set, // SQLite assumes that the database file cannot be changed, // even by a process with higher privilege, // and so the database is opened read-only and all locking and change detection is disabled. // Caution: Setting the immutable property on a database file that // does in fact change can result in incorrect query results and/or SQLITE_CORRUPT errors. Immutable bool // TimeZone location TimeZone *time.Location // TransactionLock behaviour TransactionLock TxLock // LockingMode behaviour LockingMode LockingMode // Authentication holds the UserAuth configuration Authentication *Auth // AutoVacuum sets the auto vacuum status of the database // Defaults to NONE AutoVacuum AutoVacuum // BusyTimeout defines the time a connection will wait when the // connection is BUSY and locked by an other connection. // BusyTimeout is defined in milliseconds BusyTimeout time.Duration // CaseSensitiveLike controls the behaviour of the LIKE operator. // Default or disabled the LIKE operation is case-insensitive. // When enabling this options behaviour of LIKE will become case-sensitive. CaseSensitiveLike bool // DeferForeignKeys when enabled will cause the enforcement // of all foreign key constraints is delayed until // the outermost transaction is committed. // The defer_foreign_keys pragma defaults to false // so that foreign key constraints are only deferred // if they are created as "DEFERRABLE INITIALLY DEFERRED". // The defer_foreign_keys pragma is automatically switched off at each COMMIT or ROLLBACK. // Hence, the defer_foreign_keys pragma must be separately enabled for each transaction. // This pragma is only meaningful if foreign key constraints are enabled, of course. DeferForeignKeys bool // ForeignKeyConstraints enable or disable the enforcement of foreign key constraints. ForeignKeyConstraints bool // IgnoreCheckConstraints enables or disables the enforcement of CHECK constraints. // The default setting is off, meaning that CHECK constraints are enforced by default. IgnoreCheckConstraints bool // JournalMode sets the journal mode for databases associated with the current database connection. JournalMode JournalMode // QueryOnly prevents all changes to the database when set to true. QueryOnly bool // RecursiveTriggers enable or disable the recursive trigger capability. RecursiveTriggers bool // SecureDelete enables or disables or sets the secure deletion within the database. SecureDelete SecureDelete // Synchronous Mode of the database Synchronous Synchronous // WriteableSchema enables of disables the ability to using UPDATE, INSERT, DELETE // Warning: misuse of this pragma can easily result in a corrupt database file. WriteableSchema bool // Extensions Extensions []string // ConnectHook ConnectHook func(*SQLiteConn) error }
Config is configuration parsed from a DSN string. If a new Config is created instead of being parsed from a DSN string, the NewConfig function should be used, which sets default values. Manual usage is allowed
func (*Config) Connect ¶
Connect implements driver.Connector interface. Connect returns a connection to the database.
type CryptEncoder ¶
CryptEncoder provides the interface for implementing a sqlite_crypt encoder.
func NewSHA256Encoder ¶
func NewSHA256Encoder() CryptEncoder
NewSHA256Encoder returns a new SHA256 Encoder.
func NewSHA384Encoder ¶
func NewSHA384Encoder() CryptEncoder
NewSHA384Encoder returns a new SHA384 Encoder.
func NewSHA512Encoder ¶
func NewSHA512Encoder() CryptEncoder
NewSHA512Encoder returns a new SHA512 Encoder.
type CryptSaltedEncoder ¶
type CryptSaltedEncoder interface { CryptEncoder Salt() string }
CryptSaltedEncoder provides the interface for a encoder to return its configured salt.
func NewSSHA1Encoder ¶
func NewSSHA1Encoder(salt string) CryptSaltedEncoder
NewSSHA1Encoder returns a new salted SHA1 Encoder.
func NewSSHA256Encoder ¶
func NewSSHA256Encoder(salt string) CryptSaltedEncoder
NewSSHA256Encoder returns a new salted SHA256 Encoder.
func NewSSHA384Encoder ¶
func NewSSHA384Encoder(salt string) CryptSaltedEncoder
NewSSHA384Encoder returns a new salted SHA384 Encoder.
func NewSSHA512Encoder ¶
func NewSSHA512Encoder(salt string) CryptSaltedEncoder
NewSSHA512Encoder returns a new salted SHA512 Encoder.
type ErrNoExtended ¶
type ErrNoExtended int
ErrNoExtended is extended errno.
func (ErrNoExtended) Error ¶
func (err ErrNoExtended) Error() string
Error return error message that is extended code.
type Error ¶
type Error struct { Code ErrNo /* The error code returned by SQLite */ ExtendedCode ErrNoExtended /* The extended error code returned by SQLite */ // contains filtered or unexported fields }
Error implement sqlite error code.
type JournalMode ¶
type JournalMode string
JournalMode defines the journal mode associated with the current database connection.
Note that the journal_mode for an in-memory database is either MEMORY or OFF and can not be changed to a different value. An attempt to change the journal_mode of an in-memory database to any setting other than MEMORY or OFF is ignored. Note also that the journal_mode cannot be changed while a transaction is active.
func (JournalMode) String ¶
func (j JournalMode) String() string
type LockingMode ¶
type LockingMode string
LockingMode defines the database locking mode. In NORMAL locking-mode (the default unless overridden at compile-time using SQLITE_DEFAULT_LOCKING_MODE), a database connection unlocks the database file at the conclusion of each read or write transaction. When the locking-mode is set to EXCLUSIVE, the database connection never releases file-locks. The first time the database is read in EXCLUSIVE mode, a shared lock is obtained and held. The first time the database is written, an exclusive lock is obtained and held.
Database locks obtained by a connection in EXCLUSIVE mode may be released either by closing the database connection, or by setting the locking-mode back to NORMAL. Simply setting the locking-mode to NORMAL is not enough - locks are not released until the next time the database file is accessed.
There are three reasons to set the locking-mode to EXCLUSIVE.
The application wants to prevent other processes from accessing the database file. The number of system calls for filesystem operations is reduced, possibly resulting in a small performance increase. WAL databases can be accessed in EXCLUSIVE mode without the use of shared memory. (Additional information) When the locking_mode pragma specifies a particular database, for example:
PRAGMA main.locking_mode=EXCLUSIVE; Then the locking mode applies only to the named database. If no database name qualifier precedes the "locking_mode" keyword then the locking mode is applied to all databases, including any new databases added by subsequent ATTACH commands.
The "temp" database (in which TEMP tables and indices are stored) and in-memory databases always uses exclusive locking mode. The locking mode of temp and in-memory databases cannot be changed. All other databases use the normal locking mode by default and are affected by this pragma.
If the locking mode is EXCLUSIVE when first entering WAL journal mode, then the locking mode cannot be changed to NORMAL until after exiting WAL journal mode. If the locking mode is NORMAL when first entering WAL journal mode, then the locking mode can be changed between NORMAL and EXCLUSIVE and back again at any time and without needing to exit WAL journal mode.
func (LockingMode) String ¶
func (l LockingMode) String() string
type SQLiteBackup ¶
type SQLiteBackup struct {
// contains filtered or unexported fields
}
SQLiteBackup implement interface of Backup.
func (*SQLiteBackup) PageCount ¶
func (b *SQLiteBackup) PageCount() int
PageCount return count of pages.
func (*SQLiteBackup) Remaining ¶
func (b *SQLiteBackup) Remaining() int
Remaining return whether have the rest for backup.
func (*SQLiteBackup) Step ¶
func (b *SQLiteBackup) Step(p int) (bool, error)
Step to backs up for one step. Calls the underlying `sqlite3_backup_step` function. This function returns a boolean indicating if the backup is done and an error signalling any other error. Done is returned if the underlying C function returns SQLITE_DONE (Code 101)
type SQLiteConn ¶
type SQLiteConn struct {
// contains filtered or unexported fields
}
SQLiteConn implement sql.Conn.
func (*SQLiteConn) AuthEnabled ¶
func (c *SQLiteConn) AuthEnabled() (exists bool)
AuthEnabled checks if the database is protected by user authentication
func (*SQLiteConn) AuthUserAdd ¶
func (c *SQLiteConn) AuthUserAdd(username, password string, admin bool) error
AuthUserAdd can be used (by an admin user only) to create a new user. When called on a no-authentication-required database, this routine converts the database into an authentication- required database, automatically makes the added user an administrator, and logs in the current connection as that user. The AuthUserAdd only works for the "main" database, not for any ATTACH-ed databases. Any call to AuthUserAdd by a non-admin user results in an error.
func (*SQLiteConn) AuthUserChange ¶
func (c *SQLiteConn) AuthUserChange(username, password string, admin bool) error
AuthUserChange can be used to change a users login credentials or admin privilege. Any user can change their own login credentials. Only an admin user can change another users login credentials or admin privilege setting. No user may change their own admin privilege setting.
func (*SQLiteConn) AuthUserDelete ¶
func (c *SQLiteConn) AuthUserDelete(username string) error
AuthUserDelete can be used (by an admin user only) to delete a user. The currently logged-in user cannot be deleted, which guarantees that there is always an admin user and hence that the database cannot be converted into a no-authentication-required database.
func (*SQLiteConn) Authenticate ¶
func (c *SQLiteConn) Authenticate(username, password string) error
Authenticate will perform an authentication of the provided username and password against the database.
If a database contains the SQLITE_USER table, then the call to Authenticate must be invoked with an appropriate username and password prior to enable read and write access to the database.
Return SQLITE_OK on success or SQLITE_ERROR if the username/password combination is incorrect or unknown.
If the SQLITE_USER table is not present in the database file, then this interface is a harmless no-op returnning SQLITE_OK.
func (*SQLiteConn) AutoCommit ¶
func (c *SQLiteConn) AutoCommit() bool
AutoCommit return which currently auto commit or not.
func (*SQLiteConn) Backup ¶
func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error)
Backup make backup from src to dest.
func (*SQLiteConn) ExecContext ¶
func (c *SQLiteConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error)
ExecContext implement ExecerContext.
func (*SQLiteConn) GetFilename ¶
func (c *SQLiteConn) GetFilename(schemaName string) string
GetFilename returns the absolute path to the file containing the requested schema. When passed an empty string, it will instead use the database's default schema: "main". See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html
func (*SQLiteConn) GetLimit ¶
func (c *SQLiteConn) GetLimit(id int) int
GetLimit returns the current value of a run-time limit. See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
func (*SQLiteConn) LoadExtension ¶
func (c *SQLiteConn) LoadExtension(lib string, entry string) error
LoadExtension load the sqlite3 extension.
func (*SQLiteConn) PRAGMA ¶
func (c *SQLiteConn) PRAGMA(name, value string) error
PRAGMA executes a PRAGMA statement
func (*SQLiteConn) Ping ¶
func (c *SQLiteConn) Ping(ctx context.Context) error
Ping implement Pinger.
func (*SQLiteConn) Prepare ¶
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error)
Prepare the query string. Return a new statement.
func (*SQLiteConn) PrepareContext ¶
PrepareContext implement ConnPrepareContext.
func (*SQLiteConn) QueryContext ¶
func (c *SQLiteConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error)
QueryContext implement QueryerContext.
func (*SQLiteConn) RegisterAggregator ¶
func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error
RegisterAggregator makes a Go type available as a SQLite aggregation function.
Because aggregation is incremental, it's implemented in Go with a type that has 2 methods: func Step(values) accumulates one row of data into the accumulator, and func Done() ret finalizes and returns the aggregate value. "values" and "ret" may be any type supported by RegisterFunc.
RegisterAggregator takes as implementation a constructor function that constructs an instance of the aggregator type each time an aggregation begins. The constructor must return a pointer to a type, or an interface that implements Step() and Done().
The constructor function and the Step/Done methods may optionally return an error in addition to their other return values.
See _example/go_custom_funcs for a detailed example.
func (*SQLiteConn) RegisterCollation ¶
RegisterCollation makes a Go function available as a collation.
cmp receives two UTF-8 strings, a and b. The result should be 0 if a==b, -1 if a < b, and +1 if a > b.
cmp must always return the same result given the same inputs. Additionally, it must have the following properties for all strings A, B and C: if A==B then B==A; if A==B and B==C then A==C; if A<B then B>A; if A<B and B<C then A<C.
If cmp does not obey these constraints, sqlite3's behavior is undefined when the collation is used.
func (*SQLiteConn) RegisterCommitHook ¶
func (c *SQLiteConn) RegisterCommitHook(callback func() int)
RegisterCommitHook sets the commit hook for a connection.
If the callback returns non-zero the transaction will become a rollback.
If there is an existing commit hook for this connection, it will be removed. If callback is nil the existing hook (if any) will be removed without creating a new one.
func (*SQLiteConn) RegisterFunc ¶
func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error
RegisterFunc makes a Go function available as a SQLite function.
The Go function can have arguments of the following types: any numeric type except complex, bool, []byte, string and interface{}. interface{} arguments are given the direct translation of the SQLite data type: int64 for INTEGER, float64 for FLOAT, []byte for BLOB, string for TEXT.
The function can additionally be variadic, as long as the type of the variadic argument is one of the above.
If pure is true. SQLite will assume that the function's return value depends only on its inputs, and make more aggressive optimizations in its queries.
See _example/go_custom_funcs for a detailed example.
func (*SQLiteConn) RegisterPreUpdateHook ¶
func (c *SQLiteConn) RegisterPreUpdateHook(callback func(SQLitePreUpdateData))
RegisterPreUpdateHook sets the pre-update hook for a connection.
The callback is passed a SQLitePreUpdateData struct with the data for the update, as well as methods for fetching copies of impacted data.
If there is an existing update hook for this connection, it will be removed. If callback is nil the existing hook (if any) will be removed without creating a new one.
func (*SQLiteConn) RegisterRollbackHook ¶
func (c *SQLiteConn) RegisterRollbackHook(callback func())
RegisterRollbackHook sets the rollback hook for a connection.
If there is an existing rollback hook for this connection, it will be removed. If callback is nil the existing hook (if any) will be removed without creating a new one.
func (*SQLiteConn) RegisterUpdateHook ¶
func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64))
RegisterUpdateHook sets the update hook for a connection.
The parameters to the callback are the operation (one of the constants SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), the database name, the table name, and the rowid.
If there is an existing update hook for this connection, it will be removed. If callback is nil the existing hook (if any) will be removed without creating a new one.
func (*SQLiteConn) SetLimit ¶
func (c *SQLiteConn) SetLimit(id int, newVal int) int
SetLimit changes the value of a run-time limits. Then this method returns the prior value of the limit. See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
type SQLiteDriver ¶
type SQLiteDriver struct { Config *Config Extensions []string ConnectHook func(*SQLiteConn) error // contains filtered or unexported fields }
SQLiteDriver implement sql.Driver.
func (*SQLiteDriver) Open ¶
func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error)
Open database and return a new connection.
func (*SQLiteDriver) OpenConnector ¶
func (d *SQLiteDriver) OpenConnector(dsn string) (driver.Connector, error)
OpenConnector will call OpenConnector to obtain a Connector and then invoke that Connector's Conn method to obtain each needed connection, instead of invoking the Driver's Open method for each connection. The two-step sequence allows drivers to parse the name just once and also provides access to per-Conn contexts.
type SQLitePreUpdateData ¶
type SQLitePreUpdateData struct { Conn *SQLiteConn Op int DatabaseName string TableName string OldRowID int64 NewRowID int64 }
SQLitePreUpdateData represents all of the data available during a pre-update hook call.
func (*SQLitePreUpdateData) Count ¶
func (d *SQLitePreUpdateData) Count() int
Count returns the number of columns in the row
func (*SQLitePreUpdateData) Depth ¶
func (d *SQLitePreUpdateData) Depth() int
Depth returns the source path of the write, see sqlite3_preupdate_depth()
func (*SQLitePreUpdateData) New ¶
func (d *SQLitePreUpdateData) New(dest ...interface{}) error
New populates dest with the replacement row data. This works similar to database/sql's Rows.Scan()
func (*SQLitePreUpdateData) Old ¶
func (d *SQLitePreUpdateData) Old(dest ...interface{}) error
Old populates dest with the row data to be replaced. This works similar to database/sql's Rows.Scan()
type SQLiteResult ¶
type SQLiteResult struct {
// contains filtered or unexported fields
}
SQLiteResult implement sql.Result.
func (*SQLiteResult) LastInsertId ¶
func (r *SQLiteResult) LastInsertId() (int64, error)
LastInsertId teturn last inserted ID.
func (*SQLiteResult) RowsAffected ¶
func (r *SQLiteResult) RowsAffected() (int64, error)
RowsAffected return how many rows affected.
type SQLiteRows ¶
type SQLiteRows struct {
// contains filtered or unexported fields
}
SQLiteRows implement sql.Rows.
func (*SQLiteRows) ColumnTypeDatabaseTypeName ¶
func (rc *SQLiteRows) ColumnTypeDatabaseTypeName(i int) string
ColumnTypeDatabaseTypeName implement RowsColumnTypeDatabaseTypeName.
func (*SQLiteRows) ColumnTypeNullable ¶
func (rc *SQLiteRows) ColumnTypeNullable(i int) (nullable, ok bool)
ColumnTypeNullable implement RowsColumnTypeNullable.
func (*SQLiteRows) ColumnTypeScanType ¶
func (rc *SQLiteRows) ColumnTypeScanType(i int) reflect.Type
ColumnTypeScanType implement RowsColumnTypeScanType. This can only be successfull retrieved while within Next() The underlying SQLite function depends upon sqlite_step to be called.
func (*SQLiteRows) DeclTypes ¶
func (rc *SQLiteRows) DeclTypes() []string
DeclTypes return column types.
type SQLiteStmt ¶
type SQLiteStmt struct {
// contains filtered or unexported fields
}
SQLiteStmt implement sql.Stmt.
func (*SQLiteStmt) ExecContext ¶
func (s *SQLiteStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error)
ExecContext implement ExecerContext.
func (*SQLiteStmt) NumInput ¶
func (s *SQLiteStmt) NumInput() int
NumInput return a number of parameters.
func (*SQLiteStmt) QueryContext ¶
func (s *SQLiteStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error)
QueryContext implement QueryerContext.
type SQLiteTx ¶
type SQLiteTx struct {
// contains filtered or unexported fields
}
SQLiteTx implemen sql.Tx.
type SecureDelete ¶
type SecureDelete string
SecureDelete defines the secure-delete setting.
When secure_delete is on, SQLite overwrites deleted content with zeros. The default setting for secure_delete is determined by the SQLITE_SECURE_DELETE compile-time option and is normally off. The off setting for secure_delete improves performance by reducing the number of CPU cycles and the amount of disk I/O. Applications that wish to avoid leaving forensic traces after content is deleted or updated should enable the secure_delete pragma prior to performing the delete or update, or else run VACUUM after the delete or update.
func (SecureDelete) String ¶
func (sd SecureDelete) String() string
type Synchronous ¶
type Synchronous string
Synchronous sync setting of the database connection.
func (Synchronous) String ¶
func (s Synchronous) String() string
Source Files ¶
- backup.go
- callback.go
- config.go
- connection.go
- connection_go18.go
- connector.go
- const.go
- crypt.go
- doc.go
- driver.go
- driver_go110.go
- error.go
- extensions.go
- func.go
- hooks.go
- limit.go
- opt_preupdate_hook.go
- opt_preupdate_hook_omit.go
- opt_userauth_omit.go
- os_other.go
- pragma.go
- result.go
- statement.go
- statement_go18.go
- time.go
- transaction.go
- util.go