sqlite3

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2023 License: BSD-3-Clause, MIT, Unlicense, + 1 more Imports: 22 Imported by: 0

README

go-sqlcipher

GoDoc CI

Description

Self-contained Go sqlite3 driver with an AES-256 encrypted sqlite3 database conforming to the built-in database/sql interface. It is based on:

SQLite itself is part of SQLCipher.

Version

The version tags of go-sqlcipher employ semver. As this library is based on mattn/go-sqlite3 and sqlcipher/sqlcipher, if either one receives a minor or major version update, the version number of this will also receieve a minor or major update. The CHANGELOG.md details the changes in each version.

SQLCipher 4.x is incompatible with SQLCipher 3.x!

go-sqlcipher does not implement any migration strategies at the moment. So if you upgrade a major version of go-sqlcipher, you yourself are responsible to upgrade existing database files.

See migrating databases for details.

Installation

This package can be installed with the go get command:

go get github.com/meow-io/go-sqlcipher

Documentation

To create and open encrypted database files use the following DSN parameters:

key := "2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99"
dbname := fmt.Sprintf("db?_pragma_key=x'%s'&_pragma_cipher_page_size=4096", key)
db, _ := sql.Open("sqlite3", dbname)

_pragma_key is the hex encoded 32 byte key (must be 64 characters long). _pragma_cipher_page_size is the page size of the encrypted database (set if you want a different value than the default size).

key := url.QueryEscape("secret")
dbname := fmt.Sprintf("db?_pragma_key=%s&_pragma_cipher_page_size=4096", key)
db, _ := sql.Open("sqlite3", dbname)

This uses a passphrase directly as _pragma_key with the key derivation function in SQLCipher. Do not forget the url.QueryEscape() call in your code!

See also PRAGMA key.

API documentation can be found here: http://godoc.org/github.com/meow-io/go-sqlcipher

Use the function sqlite3.IsEncrypted() to check whether a database file is encrypted or not.

Examples can be found under the ./_example directory

License

The code of the originating packages is covered by their respective licenses. See LICENSE file for details.

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 by setting ConnectHook to get the SQLiteConn.

sql.Register("sqlite3_with_hook_example",
		&sqlite3.SQLiteDriver{
				ConnectHook: func(conn *sqlite3.SQLiteConn) error {
					sqlite3conn = append(sqlite3conn, conn)
					return nil
				},
		})

You can also use database/sql.Conn.Raw (Go >= 1.13):

conn, err := db.Conn(context.Background())
// if err != nil { ... }
defer conn.Close()
err = conn.Raw(func (driverConn interface{}) error {
	sqliteConn := driverConn.(*sqlite3.SQLiteConn)
	// ... use sqliteConn
})
// if err != nil { ... }

Go SQlite3 Extensions

If you want to register Go functions as SQLite extension functions you can make a custom driver by calling RegisterFunction from ConnectHook.

regex = func(re, s string) (bool, error) {
	return regexp.MatchString(re, s)
}
sql.Register("sqlite3_extended",
		&sqlite3.SQLiteDriver{
				ConnectHook: func(conn *sqlite3.SQLiteConn) error {
					return conn.RegisterFunc("regexp", regex, true)
				},
		})

You can then use the custom driver by passing its name to sql.Open.

var i int
conn, err := sql.Open("sqlite3_extended", "./foo.db")
if err != nil {
	panic(err)
}
err = db.QueryRow(`SELECT regexp("foo.*", "seafood")`).Scan(&i)
if err != nil {
	panic(err)
}

See the documentation of RegisterFunc for more details.

Index

Examples

Constants

View Source
const (
	// used by authorizer and pre_update_hook
	SQLITE_DELETE = C.SQLITE_DELETE
	SQLITE_INSERT = C.SQLITE_INSERT
	SQLITE_UPDATE = C.SQLITE_UPDATE

	// used by authorzier - as return value
	SQLITE_OK     = C.SQLITE_OK
	SQLITE_IGNORE = C.SQLITE_IGNORE
	SQLITE_DENY   = C.SQLITE_DENY

	// different actions query tries to do - passed as argument to authorizer
	SQLITE_CREATE_INDEX        = C.SQLITE_CREATE_INDEX
	SQLITE_CREATE_TABLE        = C.SQLITE_CREATE_TABLE
	SQLITE_CREATE_TEMP_INDEX   = C.SQLITE_CREATE_TEMP_INDEX
	SQLITE_CREATE_TEMP_TABLE   = C.SQLITE_CREATE_TEMP_TABLE
	SQLITE_CREATE_TEMP_TRIGGER = C.SQLITE_CREATE_TEMP_TRIGGER
	SQLITE_CREATE_TEMP_VIEW    = C.SQLITE_CREATE_TEMP_VIEW
	SQLITE_CREATE_TRIGGER      = C.SQLITE_CREATE_TRIGGER
	SQLITE_CREATE_VIEW         = C.SQLITE_CREATE_VIEW
	SQLITE_CREATE_VTABLE       = C.SQLITE_CREATE_VTABLE
	SQLITE_DROP_INDEX          = C.SQLITE_DROP_INDEX
	SQLITE_DROP_TABLE          = C.SQLITE_DROP_TABLE
	SQLITE_DROP_TEMP_INDEX     = C.SQLITE_DROP_TEMP_INDEX
	SQLITE_DROP_TEMP_TABLE     = C.SQLITE_DROP_TEMP_TABLE
	SQLITE_DROP_TEMP_TRIGGER   = C.SQLITE_DROP_TEMP_TRIGGER
	SQLITE_DROP_TEMP_VIEW      = C.SQLITE_DROP_TEMP_VIEW
	SQLITE_DROP_TRIGGER        = C.SQLITE_DROP_TRIGGER
	SQLITE_DROP_VIEW           = C.SQLITE_DROP_VIEW
	SQLITE_DROP_VTABLE         = C.SQLITE_DROP_VTABLE
	SQLITE_PRAGMA              = C.SQLITE_PRAGMA
	SQLITE_READ                = C.SQLITE_READ
	SQLITE_SELECT              = C.SQLITE_SELECT
	SQLITE_TRANSACTION         = C.SQLITE_TRANSACTION
	SQLITE_ATTACH              = C.SQLITE_ATTACH
	SQLITE_DETACH              = C.SQLITE_DETACH
	SQLITE_ALTER_TABLE         = C.SQLITE_ALTER_TABLE
	SQLITE_REINDEX             = C.SQLITE_REINDEX
	SQLITE_ANALYZE             = C.SQLITE_ANALYZE
	SQLITE_FUNCTION            = C.SQLITE_FUNCTION
	SQLITE_SAVEPOINT           = C.SQLITE_SAVEPOINT
	SQLITE_COPY                = C.SQLITE_COPY
)
View Source
const (
	SQLITE_FCNTL_LOCKSTATE             = int(1)
	SQLITE_FCNTL_GET_LOCKPROXYFILE     = int(2)
	SQLITE_FCNTL_SET_LOCKPROXYFILE     = int(3)
	SQLITE_FCNTL_LAST_ERRNO            = int(4)
	SQLITE_FCNTL_SIZE_HINT             = int(5)
	SQLITE_FCNTL_CHUNK_SIZE            = int(6)
	SQLITE_FCNTL_FILE_POINTER          = int(7)
	SQLITE_FCNTL_SYNC_OMITTED          = int(8)
	SQLITE_FCNTL_WIN32_AV_RETRY        = int(9)
	SQLITE_FCNTL_PERSIST_WAL           = int(10)
	SQLITE_FCNTL_OVERWRITE             = int(11)
	SQLITE_FCNTL_VFSNAME               = int(12)
	SQLITE_FCNTL_POWERSAFE_OVERWRITE   = int(13)
	SQLITE_FCNTL_PRAGMA                = int(14)
	SQLITE_FCNTL_BUSYHANDLER           = int(15)
	SQLITE_FCNTL_TEMPFILENAME          = int(16)
	SQLITE_FCNTL_MMAP_SIZE             = int(18)
	SQLITE_FCNTL_TRACE                 = int(19)
	SQLITE_FCNTL_HAS_MOVED             = int(20)
	SQLITE_FCNTL_SYNC                  = int(21)
	SQLITE_FCNTL_COMMIT_PHASETWO       = int(22)
	SQLITE_FCNTL_WIN32_SET_HANDLE      = int(23)
	SQLITE_FCNTL_WAL_BLOCK             = int(24)
	SQLITE_FCNTL_ZIPVFS                = int(25)
	SQLITE_FCNTL_RBU                   = int(26)
	SQLITE_FCNTL_VFS_POINTER           = int(27)
	SQLITE_FCNTL_JOURNAL_POINTER       = int(28)
	SQLITE_FCNTL_WIN32_GET_HANDLE      = int(29)
	SQLITE_FCNTL_PDB                   = int(30)
	SQLITE_FCNTL_BEGIN_ATOMIC_WRITE    = int(31)
	SQLITE_FCNTL_COMMIT_ATOMIC_WRITE   = int(32)
	SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE = int(33)
	SQLITE_FCNTL_LOCK_TIMEOUT          = int(34)
	SQLITE_FCNTL_DATA_VERSION          = int(35)
	SQLITE_FCNTL_SIZE_LIMIT            = int(36)
	SQLITE_FCNTL_CKPT_DONE             = int(37)
	SQLITE_FCNTL_RESERVE_BYTES         = int(38)
	SQLITE_FCNTL_CKPT_START            = int(39)
	SQLITE_FCNTL_EXTERNAL_READER       = int(40)
	SQLITE_FCNTL_CKSM_FILE             = int(41)
)

Standard File Control Opcodes See: https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html

View Source
const (
	SQLITE_LIMIT_LENGTH              = C.SQLITE_LIMIT_LENGTH
	SQLITE_LIMIT_SQL_LENGTH          = C.SQLITE_LIMIT_SQL_LENGTH
	SQLITE_LIMIT_COLUMN              = C.SQLITE_LIMIT_COLUMN
	SQLITE_LIMIT_EXPR_DEPTH          = C.SQLITE_LIMIT_EXPR_DEPTH
	SQLITE_LIMIT_COMPOUND_SELECT     = C.SQLITE_LIMIT_COMPOUND_SELECT
	SQLITE_LIMIT_VDBE_OP             = C.SQLITE_LIMIT_VDBE_OP
	SQLITE_LIMIT_FUNCTION_ARG        = C.SQLITE_LIMIT_FUNCTION_ARG
	SQLITE_LIMIT_ATTACHED            = C.SQLITE_LIMIT_ATTACHED
	SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
	SQLITE_LIMIT_VARIABLE_NUMBER     = C.SQLITE_LIMIT_VARIABLE_NUMBER
	SQLITE_LIMIT_TRIGGER_DEPTH       = C.SQLITE_LIMIT_TRIGGER_DEPTH
	SQLITE_LIMIT_WORKER_THREADS      = C.SQLITE_LIMIT_WORKER_THREADS
)

Run-Time Limit Categories. See: http://www.sqlite.org/c3ref/c_limit_attached.html

View Source
const (
	SQLITE_INTEGER = iota
	SQLITE_TEXT
	SQLITE_BLOB
	SQLITE_REAL
	SQLITE_NUMERIC
	SQLITE_TIME
	SQLITE_BOOL
	SQLITE_NULL
)
View Source
const ErrNoMask C.int = 0xff

ErrNoMask is mask code.

Variables

View Source
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

View Source
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)
	ErrLockedSharedCache      = ErrLocked.Extend(1)
	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

View Source
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 CryptEncoderSHA1

func CryptEncoderSHA1(pass []byte, hash interface{}) []byte

CryptEncoderSHA1 encodes a password with SHA1

func CryptEncoderSHA256

func CryptEncoderSHA256(pass []byte, hash interface{}) []byte

CryptEncoderSHA256 encodes a password with SHA256

func CryptEncoderSHA384

func CryptEncoderSHA384(pass []byte, hash interface{}) []byte

CryptEncoderSHA384 encodes a password with SHA384

func CryptEncoderSHA512

func CryptEncoderSHA512(pass []byte, hash interface{}) []byte

CryptEncoderSHA512 encodes a password with SHA512

func CryptEncoderSSHA1

func CryptEncoderSSHA1(salt string) func(pass []byte, hash interface{}) []byte

CryptEncoderSSHA1 encodes a password with SHA1 with the configured salt.

func CryptEncoderSSHA256

func CryptEncoderSSHA256(salt string) func(pass []byte, hash interface{}) []byte

CryptEncoderSSHA256 encodes a password with SHA256 with the configured salt

func CryptEncoderSSHA384

func CryptEncoderSSHA384(salt string) func(pass []byte, hash interface{}) []byte

CryptEncoderSSHA384 encodes a password with SHA384 with the configured salt

func CryptEncoderSSHA512

func CryptEncoderSSHA512(salt string) func(pass []byte, hash interface{}) []byte

CryptEncoderSSHA512 encodes a password with SHA512 with the configured salt

func IsEncrypted

func IsEncrypted(filename string) (bool, error)

IsEncrypted returns true, if the database with the given filename is encrypted, and false otherwise. If the database header cannot be read properly an error is returned.

Example
package main

import (
	"crypto/rand"
	"database/sql"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"path/filepath"

	sqlite3 "github.com/meow-io/go-sqlcipher"
)

var (
	db      *sql.DB
	testDir = "go-sqlcipher_test"
	tables  = `
CREATE TABLE KeyValueStore (
  KeyEntry   TEXT NOT NULL UNIQUE,
  ValueEntry TEXT NOT NULL
);`
)

func init() {

	key := url.QueryEscape("passphrase")
	tmpdir, err := ioutil.TempDir("", testDir)
	if err != nil {
		panic(err)
	}
	dbname := filepath.Join(tmpdir, "sqlcipher_test")
	dbnameWithDSN := dbname + fmt.Sprintf("?_pragma_key=%s&_pragma_cipher_page_size=4096", key)
	db, err = sql.Open("sqlite3", dbnameWithDSN)
	if err != nil {
		panic(err)
	}
	_, err = db.Exec(tables)
	if err != nil {
		panic(err)
	}
	db.Close()

	encrypted, err := sqlite3.IsEncrypted(dbname)
	if err != nil {
		panic(err)
	}
	if !encrypted {
		panic(errors.New("go-sqlcipher: DB not encrypted"))
	}

	db, err = sql.Open("sqlite3", dbnameWithDSN)
	if err != nil {
		panic(err)
	}
	_, err = db.Exec("SELECT count(*) FROM sqlite_master;")
	if err != nil {
		panic(err)
	}
}

func main() {
	// create random key
	var key [32]byte
	_, err := io.ReadFull(rand.Reader, key[:])
	if err != nil {
		log.Fatal(err)
	}
	// set DB name
	dbname := "go-sqlcipher.sqlite"
	dbnameWithDSN := dbname + fmt.Sprintf("?_pragma_key=x'%s'",
		hex.EncodeToString(key[:]))
	// create encrypted DB file
	db, err := sql.Open("sqlite3", dbnameWithDSN)
	if err != nil {
		log.Fatal(err)
	}
	defer os.Remove(dbname)
	defer db.Close()
	// create table
	_, err = db.Exec("CREATE TABLE t(x INTEGER);")
	if err != nil {
		log.Fatal(err)
	}
	// make sure database is encrypted
	encrypted, err := sqlite3.IsEncrypted(dbname)
	if err != nil {
		log.Fatal(err)
	}
	if encrypted {
		fmt.Println("DB is encrypted")
	} else {
		fmt.Println("DB is unencrypted")
	}
}
Output:

DB is encrypted

func Version

func Version() (libVersion string, libVersionNumber int, sourceID string)

Version returns SQLite library version information.

Types

type ErrNo

type ErrNo int

ErrNo inherit errno.

func (ErrNo) Error

func (err ErrNo) Error() string

Error return error message from errno.

func (ErrNo) Extend

func (err ErrNo) Extend(by int) ErrNoExtended

Extend return extended errno.

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 */
	SystemErrno  syscall.Errno /* The system errno returned by the OS through SQLite, if applicable */
	// contains filtered or unexported fields
}

Error implement sqlite error code.

func (Error) Error

func (err Error) Error() string

type SQLiteBackup

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

SQLiteBackup implement interface of Backup.

func (*SQLiteBackup) Close

func (b *SQLiteBackup) Close() error

Close close backup.

func (*SQLiteBackup) Finish

func (b *SQLiteBackup) Finish() error

Finish close 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 implements driver.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 (destConn *SQLiteConn) Backup(dest string, srcConn *SQLiteConn, src string) (*SQLiteBackup, error)

Backup make backup from src to dest.

func (*SQLiteConn) Begin

func (c *SQLiteConn) Begin() (driver.Tx, error)

Begin transaction.

func (*SQLiteConn) BeginTx

func (c *SQLiteConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error)

BeginTx implement ConnBeginTx.

func (*SQLiteConn) Close

func (c *SQLiteConn) Close() error

Close the connection.

func (*SQLiteConn) Deserialize added in v1.0.3

func (c *SQLiteConn) Deserialize(b []byte, schema string) error

Deserialize causes the connection to disconnect from the current database and then re-open as an in-memory database based on the contents of the byte slice.

See https://www.sqlite.org/c3ref/deserialize.html

func (*SQLiteConn) Exec

func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error)

Exec implements Execer.

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

func (c *SQLiteConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error)

PrepareContext implement ConnPrepareContext.

func (*SQLiteConn) Query

func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error)

Query implements Queryer.

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

func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, string) int)

RegisterAuthorizer sets the authorizer for connection.

The parameters to the callback are the operation (one of the constants SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), and 1 to 3 arguments, depending on operation. More details see: https://www.sqlite.org/c3ref/c_alter_table.html

func (*SQLiteConn) RegisterCollation

func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error

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 preupdate 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) Serialize added in v1.0.3

func (c *SQLiteConn) Serialize(schema string) ([]byte, error)

Serialize returns a byte slice that is a serialization of the database.

See https://www.sqlite.org/c3ref/serialize.html

func (*SQLiteConn) SetFileControlInt

func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error

SetFileControlInt invokes the xFileControl method on a given database. The dbName is the name of the database. It will default to "main" if left blank. The op is one of the opcodes prefixed by "SQLITE_FCNTL_". The arg argument and return code are both opcode-specific. Please see the SQLite documentation.

This method is not thread-safe as the returned error code can be changed by another call if invoked concurrently.

See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html

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 SQLiteContext

type SQLiteContext C.sqlite3_context

SQLiteContext behave sqlite3_context

func (*SQLiteContext) ResultBlob

func (c *SQLiteContext) ResultBlob(b []byte)

ResultBlob sets the result of an SQL function. See: sqlite3_result_blob, http://sqlite.org/c3ref/result_blob.html

func (*SQLiteContext) ResultBool

func (c *SQLiteContext) ResultBool(b bool)

ResultBool sets the result of an SQL function.

func (*SQLiteContext) ResultDouble

func (c *SQLiteContext) ResultDouble(d float64)

ResultDouble sets the result of an SQL function. See: sqlite3_result_double, http://sqlite.org/c3ref/result_blob.html

func (*SQLiteContext) ResultInt

func (c *SQLiteContext) ResultInt(i int)

ResultInt sets the result of an SQL function. See: sqlite3_result_int, http://sqlite.org/c3ref/result_blob.html

func (*SQLiteContext) ResultInt64

func (c *SQLiteContext) ResultInt64(i int64)

ResultInt64 sets the result of an SQL function. See: sqlite3_result_int64, http://sqlite.org/c3ref/result_blob.html

func (*SQLiteContext) ResultNull

func (c *SQLiteContext) ResultNull()

ResultNull sets the result of an SQL function. See: sqlite3_result_null, http://sqlite.org/c3ref/result_blob.html

func (*SQLiteContext) ResultText

func (c *SQLiteContext) ResultText(s string)

ResultText sets the result of an SQL function. See: sqlite3_result_text, http://sqlite.org/c3ref/result_blob.html

func (*SQLiteContext) ResultZeroblob

func (c *SQLiteContext) ResultZeroblob(n int)

ResultZeroblob sets the result of an SQL function. See: sqlite3_result_zeroblob, http://sqlite.org/c3ref/result_blob.html

type SQLiteDriver

type SQLiteDriver struct {
	Extensions  []string
	ConnectHook func(*SQLiteConn) error
}

SQLiteDriver implements driver.Driver.

func (*SQLiteDriver) Open

func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error)

Open database and return a new connection.

A pragma can take either zero or one argument. The argument is may be either in parentheses or it may be separated from the pragma name by an equal sign. The two syntaxes yield identical results. In many pragmas, the argument is a boolean. The boolean can be one of:

1 yes true on
0 no false off

You can specify a DSN string using a URI as the filename.

test.db
file:test.db?cache=shared&mode=memory
:memory:
file::memory:

mode
  Access mode of the database.
  https://www.sqlite.org/c3ref/open.html
  Values:
   - ro
   - rw
   - rwc
   - memory

cache
  SQLite Shared-Cache Mode
  https://www.sqlite.org/sharedcache.html
  Values:
    - shared
    - private

immutable=Boolean
  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.

go-sqlite3 adds the following query parameters to those used by SQLite:

_loc=XXX
  Specify location of time format. It's possible to specify "auto".

_mutex=XXX
  Specify mutex mode. XXX can be "no", "full".

_txlock=XXX
  Specify locking behavior for transactions.  XXX can be "immediate",
  "deferred", "exclusive".

_auto_vacuum=X | _vacuum=X
  0 | none - Auto Vacuum disabled
  1 | full - Auto Vacuum FULL
  2 | incremental - Auto Vacuum Incremental

_busy_timeout=XXX"| _timeout=XXX
  Specify value for sqlite3_busy_timeout.

_case_sensitive_like=Boolean | _cslike=Boolean
  https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
  Default or disabled the LIKE operation is case-insensitive.
  When enabling this options behaviour of LIKE will become case-sensitive.

_defer_foreign_keys=Boolean | _defer_fk=Boolean
  Defer Foreign Keys until outermost transaction is committed.

_foreign_keys=Boolean | _fk=Boolean
  Enable or disable enforcement of foreign keys.

_ignore_check_constraints=Boolean
  This pragma enables or disables the enforcement of CHECK constraints.
  The default setting is off, meaning that CHECK constraints are enforced by default.

_journal_mode=MODE | _journal=MODE
  Set journal mode for the databases associated with the current connection.
  https://www.sqlite.org/pragma.html#pragma_journal_mode

_locking_mode=X | _locking=X
  Sets the database connection locking-mode.
  The locking-mode is either NORMAL or EXCLUSIVE.
  https://www.sqlite.org/pragma.html#pragma_locking_mode

_query_only=Boolean
  The query_only pragma prevents all changes to database files when enabled.

_recursive_triggers=Boolean | _rt=Boolean
  Enable or disable recursive triggers.

_secure_delete=Boolean|FAST
  When secure_delete is on, SQLite overwrites deleted content with zeros.
  https://www.sqlite.org/pragma.html#pragma_secure_delete

_synchronous=X | _sync=X
  Change the setting of the "synchronous" flag.
  https://www.sqlite.org/pragma.html#pragma_synchronous

_writable_schema=Boolean
  When this pragma is on, the SQLITE_MASTER tables in which database
  can be changed using ordinary UPDATE, INSERT, and DELETE statements.
  Warning: misuse of this pragma can easily result in a corrupt database file.

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.

type SQLiteResult

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

SQLiteResult implements sql.Result.

func (*SQLiteResult) LastInsertId

func (r *SQLiteResult) LastInsertId() (int64, error)

LastInsertId return 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 implements driver.Rows.

func (*SQLiteRows) Close

func (rc *SQLiteRows) Close() error

Close the 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.

func (*SQLiteRows) Columns

func (rc *SQLiteRows) Columns() []string

Columns return column names.

func (*SQLiteRows) DeclTypes

func (rc *SQLiteRows) DeclTypes() []string

DeclTypes return column types.

func (*SQLiteRows) Next

func (rc *SQLiteRows) Next(dest []driver.Value) error

Next move cursor to next. Attempts to honor context timeout from QueryContext call.

type SQLiteStmt

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

SQLiteStmt implements driver.Stmt.

func (*SQLiteStmt) Close

func (s *SQLiteStmt) Close() error

Close the statement.

func (*SQLiteStmt) Exec

func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error)

Exec execute the statement with arguments. Return result object.

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

func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error)

Query the statement with arguments. Return records.

func (*SQLiteStmt) QueryContext

func (s *SQLiteStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error)

QueryContext implement QueryerContext.

func (*SQLiteStmt) Readonly

func (s *SQLiteStmt) Readonly() bool

Readonly reports if this statement is considered readonly by SQLite.

See: https://sqlite.org/c3ref/stmt_readonly.html

type SQLiteTx

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

SQLiteTx implements driver.Tx.

func (*SQLiteTx) Commit

func (tx *SQLiteTx) Commit() error

Commit transaction.

func (*SQLiteTx) Rollback

func (tx *SQLiteTx) Rollback() error

Rollback transaction.

Directories

Path Synopsis
_example
util

Jump to

Keyboard shortcuts

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