Index | Files | Directories

package sqlite3

import ""

Package sqlite3 provides interface to SQLite3 databases.

This works as a driver for database/sql.


go get

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>

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);
    sqlite3_result_int(context, 1);

#ifdef _WIN32
int sqlite3_extension_init(sqlite3 *db, char **errmsg,
      const sqlite3_api_routines *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.

		Extensions: []string{

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.

				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)
				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 {
err = db.QueryRow(`SELECT regexp("foo.*", "seafood")`).Scan(&i)
if err != nil {

See the documentation of RegisterFunc for more details.


Package Files

backup.go callback.go convert.go doc.go error.go sqlite3_context.go sqlite3_func_crypt.go sqlite3_load_extension.go sqlite3_opt_userauth_omit.go sqlite3_other.go sqlite3_type.go static_mock.go


const (
const ErrNoMask = 0xff

ErrNoMask is mask code.


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

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

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

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{}

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

func (destConn *SQLiteConn) Backup(dest string, srcConn *SQLiteConn, src string) (*SQLiteBackup, error)

Backup make backup from src to dest.

func (*SQLiteConn) LoadExtension

func (c *SQLiteConn) LoadExtension(lib string, entry string) error

LoadExtension load the sqlite3 extension.

func (*SQLiteConn) RegisterAggregator

func (c *SQLiteConn) RegisterAggregator(string, interface{}, bool) error

func (*SQLiteConn) RegisterAuthorizer

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

func (*SQLiteConn) RegisterCollation

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

func (*SQLiteConn) RegisterCommitHook

func (c *SQLiteConn) RegisterCommitHook(func() int)

func (*SQLiteConn) RegisterFunc

func (c *SQLiteConn) RegisterFunc(string, interface{}, bool) error

func (*SQLiteConn) RegisterRollbackHook

func (c *SQLiteConn) RegisterRollbackHook(func())

func (*SQLiteConn) RegisterUpdateHook

func (c *SQLiteConn) RegisterUpdateHook(func(int, string, string, int64))

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,

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,

func (*SQLiteContext) ResultInt

func (c *SQLiteContext) ResultInt(i int)

ResultInt sets the result of an SQL function. See: sqlite3_result_int,

func (*SQLiteContext) ResultInt64

func (c *SQLiteContext) ResultInt64(i int64)

ResultInt64 sets the result of an SQL function. See: sqlite3_result_int64,

func (*SQLiteContext) ResultNull

func (c *SQLiteContext) ResultNull()

ResultNull sets the result of an SQL function. See: sqlite3_result_null,

func (*SQLiteContext) ResultText

func (c *SQLiteContext) ResultText(s string)

ResultText sets the result of an SQL function. See: sqlite3_result_text,

func (*SQLiteContext) ResultZeroblob

func (c *SQLiteContext) ResultZeroblob(n int)

ResultZeroblob sets the result of an SQL function. See: sqlite3_result_zeroblob,

type SQLiteDriver

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

func (SQLiteDriver) Open

func (SQLiteDriver) Open(s string) (driver.Conn, error)



Package sqlite3 imports 17 packages (graph).

Version v1.14.10 (latest) | Published Dec 29, 2021 | Platform: linux/amd64 | Updated 1 week ago

Tools for package owners.