sqlite3

package module
v0.8.7 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2023 License: MIT Imports: 21 Imported by: 1

README

Go bindings to SQLite using Wazero

Go Reference Go Report Go Coverage

Go module github.com/ianatha/go-sqlite3 wraps a WASM build of SQLite, and uses wazero to provide cgo-free SQLite bindings.

Caveats

This module replaces the SQLite OS Interface (aka VFS) with a pure Go implementation. This has benefits, but also comes with some drawbacks.

Write-Ahead Logging

Because WASM does not support shared memory, WAL support is limited.

To work around this limitation, SQLite is patched to always use EXCLUSIVE locking mode for WAL databases.

Because connection pooling is incompatible with EXCLUSIVE locking mode, to open WAL databases you should disable connection pooling by calling db.SetMaxOpenConns(1).

POSIX Advisory Locks

POSIX advisory locks, which SQLite uses, are broken by design.

On Linux, macOS and illumos, this module uses OFD locks to synchronize access to database files. OFD locks are fully compatible with process-associated POSIX advisory locks.

On BSD Unixes, this module uses BSD locks. BSD locks may not be compatible with process-associated POSIX advisory locks (they are on FreeBSD).

Testing

The pure Go VFS is tested by running SQLite's mptest on Linux, macOS and Windows; BSD code paths are tested on macOS using the sqlite3_bsd build tag. Performance is tested by running speedtest1.

Roadmap
  • advanced SQLite features
    • custom functions
    • nested transactions
    • incremental BLOB I/O
    • online backup
    • session extension
  • custom VFSes
Alternatives

Documentation

Overview

Package sqlite3 wraps the C SQLite API.

Example
package main

import (
	"fmt"
	"log"

	"github.com/ianatha/go-sqlite3"
	_ "github.com/ianatha/go-sqlite3/embed"
)

const memory = ":memory:"

func main() {
	db, err := sqlite3.Open(memory)
	if err != nil {
		log.Fatal(err)
	}

	err = db.Exec(`CREATE TABLE IF NOT EXISTS users (id INT, name VARCHAR(10))`)
	if err != nil {
		log.Fatal(err)
	}

	err = db.Exec(`INSERT INTO users (id, name) VALUES (0, 'go'), (1, 'zig'), (2, 'whatever')`)
	if err != nil {
		log.Fatal(err)
	}

	stmt, _, err := db.Prepare(`SELECT id, name FROM users`)
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	for stmt.Step() {
		fmt.Println(stmt.ColumnInt(0), stmt.ColumnText(1))
	}
	if err := stmt.Err(); err != nil {
		log.Fatal(err)
	}

	err = stmt.Close()
	if err != nil {
		log.Fatal(err)
	}

	err = db.Close()
	if err != nil {
		log.Fatal(err)
	}
}
Output:

0 go
1 zig
2 whatever

Index

Examples

Constants

View Source
const (
	TimeFormatDefault TimeFormat = "" // time.RFC3339Nano

	// Text formats
	TimeFormat1  TimeFormat = "2006-01-02"
	TimeFormat2  TimeFormat = "2006-01-02 15:04"
	TimeFormat3  TimeFormat = "2006-01-02 15:04:05"
	TimeFormat4  TimeFormat = "2006-01-02 15:04:05.000"
	TimeFormat5  TimeFormat = "2006-01-02T15:04"
	TimeFormat6  TimeFormat = "2006-01-02T15:04:05"
	TimeFormat7  TimeFormat = "2006-01-02T15:04:05.000"
	TimeFormat8  TimeFormat = "15:04"
	TimeFormat9  TimeFormat = "15:04:05"
	TimeFormat10 TimeFormat = "15:04:05.000"

	TimeFormat2TZ  = TimeFormat2 + "Z07:00"
	TimeFormat3TZ  = TimeFormat3 + "Z07:00"
	TimeFormat4TZ  = TimeFormat4 + "Z07:00"
	TimeFormat5TZ  = TimeFormat5 + "Z07:00"
	TimeFormat6TZ  = TimeFormat6 + "Z07:00"
	TimeFormat7TZ  = TimeFormat7 + "Z07:00"
	TimeFormat8TZ  = TimeFormat8 + "Z07:00"
	TimeFormat9TZ  = TimeFormat9 + "Z07:00"
	TimeFormat10TZ = TimeFormat10 + "Z07:00"

	// Numeric formats
	TimeFormatJulianDay TimeFormat = "julianday"
	TimeFormatUnix      TimeFormat = "unixepoch"
	TimeFormatUnixFrac  TimeFormat = "unixepoch_frac"
	TimeFormatUnixMilli TimeFormat = "unixepoch_milli" // not an SQLite format
	TimeFormatUnixMicro TimeFormat = "unixepoch_micro" // not an SQLite format
	TimeFormatUnixNano  TimeFormat = "unixepoch_nano"  // not an SQLite format

	// Auto
	TimeFormatAuto TimeFormat = "auto"
)

TimeFormats recognized by SQLite to encode/decode time values.

https://www.sqlite.org/lang_datefunc.html

Variables

View Source
var (
	Binary []byte // WASM binary to load.
	Path   string // Path to load the binary from.
)

Configure SQLite WASM.

Importing package embed initializes these with an appropriate build of SQLite:

import _ "github.com/ianatha/go-sqlite3/embed"

Functions

This section is empty.

Types

type AggregateFunction

type AggregateFunction interface {
	// Step is invoked to add a row to the current window.
	// The function arguments, if any, corresponding to the row being added are passed to Step.
	Step(ctx Context, arg ...Value)

	// Value is invoked to return the current value of the aggregate.
	Value(ctx Context)
}

AggregateFunction is the interface an aggregate function should implement.

https://www.sqlite.org/appfunc.html

type Backup

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

Backup is an handle to an ongoing online backup operation.

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

func (*Backup) Close

func (b *Backup) Close() error

Close finishes a backup operation.

It is safe to close a nil, zero or closed Backup.

https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish

func (*Backup) PageCount

func (b *Backup) PageCount() int

PageCount returns the total number of pages in the source database at the conclusion of the most recent Backup.Step.

https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backuppagecount

func (*Backup) Remaining

func (b *Backup) Remaining() int

Remaining returns the number of pages still to be backed up at the conclusion of the most recent Backup.Step.

https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupremaining

func (*Backup) Step

func (b *Backup) Step(nPage int) (done bool, err error)

Step copies up to nPage pages between the source and destination databases. If nPage is negative, all remaining source pages are copied.

https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep

type Blob

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

Blob is an handle to an open BLOB.

It implements io.ReadWriteSeeker for incremental BLOB I/O.

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

func (*Blob) Close

func (b *Blob) Close() error

Close closes a BLOB handle.

It is safe to close a nil, zero or closed Blob.

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

func (*Blob) Read

func (b *Blob) Read(p []byte) (n int, err error)

Read implements the io.Reader interface.

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

func (*Blob) ReadFrom

func (b *Blob) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements the io.ReaderFrom interface.

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

func (*Blob) Reopen

func (b *Blob) Reopen(row int64) error

Reopen moves a BLOB handle to a new row of the same database table.

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

func (*Blob) Seek

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

Seek implements the io.Seeker interface.

func (*Blob) Size

func (b *Blob) Size() int64

Size returns the size of the BLOB in bytes.

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

func (*Blob) Write

func (b *Blob) Write(p []byte) (n int, err error)

Write implements the io.Writer interface.

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

func (*Blob) WriteTo

func (b *Blob) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements the io.WriterTo interface.

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

type Conn

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

Conn is a database connection handle. A Conn is not safe for concurrent use by multiple goroutines.

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

func Open

func Open(filename string) (*Conn, error)

Open calls OpenFlags with OPEN_READWRITE, OPEN_CREATE, OPEN_URI and OPEN_NOFOLLOW.

func OpenFlags

func OpenFlags(filename string, flags OpenFlag) (*Conn, error)

OpenFlags opens an SQLite database file as specified by the filename argument.

If none of the required flags is used, a combination of OPEN_READWRITE and OPEN_CREATE is used. If a URI filename is used, PRAGMA statements to execute can be specified using "_pragma":

sqlite3.Open("file:demo.db?_pragma=busy_timeout(10000)")

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

func (*Conn) AnyCollationNeeded

func (c *Conn) AnyCollationNeeded()

AnyCollationNeeded registers a fake collating function for any unknown collating sequence. The fake collating function works like BINARY.

This extension can be used to load schemas that contain one or more unknown collating sequences.

func (*Conn) Backup

func (src *Conn) Backup(srcDB, dstURI string) error

Backup backs up srcDB on the src connection to the "main" database in dstURI.

Backup opens the SQLite database file dstURI, and blocks until the entire backup is complete. Use Conn.BackupInit for incremental backup.

https://www.sqlite.org/backup.html

func (*Conn) BackupInit

func (src *Conn) BackupInit(srcDB, dstURI string) (*Backup, error)

BackupInit initializes a backup operation to copy the content of one database into another.

BackupInit opens the SQLite database file dstURI, then initializes a backup that copies the contents of srcDB on the src connection to the "main" database in dstURI.

https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit

func (*Conn) Begin

func (c *Conn) Begin() Tx

Begin starts a deferred transaction.

https://www.sqlite.org/lang_transaction.html

func (*Conn) BeginExclusive

func (c *Conn) BeginExclusive() (Tx, error)

BeginExclusive starts an exclusive transaction.

https://www.sqlite.org/lang_transaction.html

func (*Conn) BeginImmediate

func (c *Conn) BeginImmediate() (Tx, error)

BeginImmediate starts an immediate transaction.

https://www.sqlite.org/lang_transaction.html

func (*Conn) Changes

func (c *Conn) Changes() int64

Changes returns the number of rows modified, inserted or deleted by the most recently completed INSERT, UPDATE or DELETE statement on the database connection.

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

func (*Conn) Close

func (c *Conn) Close() error

Close closes the database connection.

If the database connection is associated with unfinalized prepared statements, open blob handles, and/or unfinished backup objects, Close will leave the database connection open and return BUSY.

It is safe to close a nil, zero or closed Conn.

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

func (*Conn) CreateCollation

func (c *Conn) CreateCollation(name string, fn func(a, b []byte) int) error

CreateCollation defines a new collating sequence.

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

Example
db, err := sqlite3.Open(":memory:")
if err != nil {
	log.Fatal(err)
}
defer db.Close()

err = db.Exec(`CREATE TABLE IF NOT EXISTS words (word VARCHAR(10))`)
if err != nil {
	log.Fatal(err)
}

err = db.Exec(`INSERT INTO words (word) VALUES ('côte'), ('cote'), ('coter'), ('coté'), ('cotée'), ('côté')`)
if err != nil {
	log.Fatal(err)
}

err = db.CreateCollation("french", collate.New(language.French).Compare)
if err != nil {
	log.Fatal(err)
}

stmt, _, err := db.Prepare(`SELECT word FROM words ORDER BY word COLLATE french`)
if err != nil {
	log.Fatal(err)
}
defer stmt.Close()

for stmt.Step() {
	fmt.Println(stmt.ColumnText(0))
}
if err := stmt.Err(); err != nil {
	log.Fatal(err)
}
Output:

cote
coté
côte
côté
cotée
coter

func (*Conn) CreateFunction

func (c *Conn) CreateFunction(name string, nArg int, flag FunctionFlag, fn func(ctx Context, arg ...Value)) error

CreateFunction defines a new scalar SQL function.

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

Example
db, err := sqlite3.Open(":memory:")
if err != nil {
	log.Fatal(err)
}
defer db.Close()

err = db.Exec(`CREATE TABLE IF NOT EXISTS words (word VARCHAR(10))`)
if err != nil {
	log.Fatal(err)
}

err = db.Exec(`INSERT INTO words (word) VALUES ('côte'), ('cote'), ('coter'), ('coté'), ('cotée'), ('côté')`)
if err != nil {
	log.Fatal(err)
}

err = db.CreateFunction("upper", 1, sqlite3.DETERMINISTIC|sqlite3.INNOCUOUS, func(ctx sqlite3.Context, arg ...sqlite3.Value) {
	ctx.ResultBlob(bytes.ToUpper(arg[0].RawBlob()))
})
if err != nil {
	log.Fatal(err)
}

stmt, _, err := db.Prepare(`SELECT upper(word) FROM words`)
if err != nil {
	log.Fatal(err)
}
defer stmt.Close()

for stmt.Step() {
	fmt.Println(stmt.ColumnText(0))
}
if err := stmt.Err(); err != nil {
	log.Fatal(err)
}
Output:

COTE
COTÉ
CÔTE
CÔTÉ
COTÉE
COTER

func (*Conn) CreateWindowFunction

func (c *Conn) CreateWindowFunction(name string, nArg int, flag FunctionFlag, fn func() AggregateFunction) error

CreateWindowFunction defines a new aggregate or aggregate window SQL function. If fn returns a WindowFunction, then an aggregate window function is created.

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

Example
package main

import (
	"fmt"
	"log"
	"unicode"

	"github.com/ianatha/go-sqlite3"
	_ "github.com/ianatha/go-sqlite3/embed"
)

func main() {
	db, err := sqlite3.Open(":memory:")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	err = db.Exec(`CREATE TABLE IF NOT EXISTS words (word VARCHAR(10))`)
	if err != nil {
		log.Fatal(err)
	}

	err = db.Exec(`INSERT INTO words (word) VALUES ('côte'), ('cote'), ('coter'), ('coté'), ('cotée'), ('côté')`)
	if err != nil {
		log.Fatal(err)
	}

	err = db.CreateWindowFunction("count_ascii", 1, sqlite3.INNOCUOUS, newASCIICounter)
	if err != nil {
		log.Fatal(err)
	}

	stmt, _, err := db.Prepare(`SELECT count_ascii(word) OVER (ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) FROM words`)
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	for stmt.Step() {
		fmt.Println(stmt.ColumnInt(0))
	}
	if err := stmt.Err(); err != nil {
		log.Fatal(err)
	}
}

type countASCII struct{ result int }

func newASCIICounter() sqlite3.AggregateFunction {
	return &countASCII{}
}

func (f *countASCII) Value(ctx sqlite3.Context) {
	ctx.ResultInt(f.result)
}

func (f *countASCII) Step(ctx sqlite3.Context, arg ...sqlite3.Value) {
	if f.isASCII(arg[0]) {
		f.result++
	}
}

func (f *countASCII) Inverse(ctx sqlite3.Context, arg ...sqlite3.Value) {
	if f.isASCII(arg[0]) {
		f.result--
	}
}

func (f *countASCII) isASCII(arg sqlite3.Value) bool {
	if arg.Type() != sqlite3.TEXT {
		return false
	}
	for _, c := range arg.RawBlob() {
		if c > unicode.MaxASCII {
			return false
		}
	}
	return true
}
Output:

1
2
2
1
0
0

func (*Conn) Exec

func (c *Conn) Exec(sql string) error

Exec is a convenience function that allows an application to run multiple statements of SQL without having to use a lot of code.

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

func (*Conn) GetAutocommit

func (c *Conn) GetAutocommit() bool

GetAutocommit tests the connection for auto-commit mode.

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

func (*Conn) LastInsertRowID

func (c *Conn) LastInsertRowID() int64

LastInsertRowID returns the rowid of the most recent successful INSERT on the database connection.

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

func (*Conn) OpenBlob

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

OpenBlob opens a BLOB for incremental I/O.

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

func (*Conn) Pragma

func (c *Conn) Pragma(str string) ([]string, error)

Pragma executes a PRAGMA statement and returns any results.

https://www.sqlite.org/pragma.html

func (*Conn) Prepare

func (c *Conn) Prepare(sql string) (stmt *Stmt, tail string, err error)

Prepare calls Conn.PrepareFlags with no flags.

func (*Conn) PrepareFlags

func (c *Conn) PrepareFlags(sql string, flags PrepareFlag) (stmt *Stmt, tail string, err error)

PrepareFlags compiles the first SQL statement in sql; tail is left pointing to what remains uncompiled. If the input text contains no SQL (if the input is an empty string or a comment), both stmt and err will be nil.

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

func (*Conn) Restore

func (dst *Conn) Restore(dstDB, srcURI string) error

Restore restores dstDB on the dst connection from the "main" database in srcURI.

Restore opens the SQLite database file srcURI, and blocks until the entire restore is complete.

https://www.sqlite.org/backup.html

func (*Conn) Savepoint

func (c *Conn) Savepoint() Savepoint

Savepoint establishes a new transaction savepoint.

https://www.sqlite.org/lang_savepoint.html

func (*Conn) SetInterrupt

func (c *Conn) SetInterrupt(ctx context.Context) (old context.Context)

SetInterrupt interrupts a long-running query when a context is done.

Subsequent uses of the connection will return INTERRUPT until the context is reset by another call to SetInterrupt.

To associate a timeout with a connection:

ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
conn.SetInterrupt(ctx)
defer cancel()

SetInterrupt returns the old context assigned to the connection.

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

type Context

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

Context is the context in which an SQL function executes. An SQLite Context is in no way related to a Go context.Context.

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

func (Context) GetAuxData

func (c Context) GetAuxData(n int) any

GetAuxData returns metadata for argument n of the function.

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

func (Context) ResultBlob

func (c Context) ResultBlob(value []byte)

ResultBlob sets the result of the function to a []byte. Returning a nil slice is the same as calling Context.ResultNull.

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

func (Context) ResultBool

func (c Context) ResultBool(value bool)

ResultBool sets the result of the function to a bool. SQLite does not have a separate boolean storage class. Instead, boolean values are stored as integers 0 (false) and 1 (true).

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

func (Context) ResultError

func (c Context) ResultError(err error)

ResultError sets the result of the function an error.

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

func (Context) ResultFloat

func (c Context) ResultFloat(value float64)

ResultFloat sets the result of the function to a float64.

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

func (Context) ResultInt

func (c Context) ResultInt(value int)

ResultInt sets the result of the function to an int.

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

func (Context) ResultInt64

func (c Context) ResultInt64(value int64)

ResultInt64 sets the result of the function to an int64.

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

func (Context) ResultNull

func (c Context) ResultNull()

ResultNull sets the result of the function to NULL.

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

func (Context) ResultText

func (c Context) ResultText(value string)

ResultText sets the result of the function to a string.

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

func (Context) ResultTime

func (c Context) ResultTime(value time.Time, format TimeFormat)

ResultTime sets the result of the function to a time.Time.

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

func (Context) ResultZeroBlob

func (c Context) ResultZeroBlob(n int64)

BindZeroBlob sets the result of the function to a zero-filled, length n BLOB.

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

func (Context) SetAuxData

func (c Context) SetAuxData(n int, data any)

SetAuxData saves metadata for argument n of the function.

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

Example
db, err := sqlite3.Open(":memory:")
if err != nil {
	log.Fatal(err)
}
defer db.Close()

err = db.Exec(`CREATE TABLE IF NOT EXISTS words (word VARCHAR(10))`)
if err != nil {
	log.Fatal(err)
}

err = db.Exec(`INSERT INTO words (word) VALUES ('côte'), ('cote'), ('coter'), ('coté'), ('cotée'), ('côté')`)
if err != nil {
	log.Fatal(err)
}

err = db.CreateFunction("regexp", 2, sqlite3.DETERMINISTIC|sqlite3.INNOCUOUS, func(ctx sqlite3.Context, arg ...sqlite3.Value) {
	re, ok := ctx.GetAuxData(0).(*regexp.Regexp)
	if !ok {
		r, err := regexp.Compile(arg[0].Text())
		if err != nil {
			ctx.ResultError(err)
			return
		}
		ctx.SetAuxData(0, r)
		re = r
	}
	ctx.ResultBool(re.Match(arg[1].RawBlob()))
})
if err != nil {
	log.Fatal(err)
}

stmt, _, err := db.Prepare(`SELECT word FROM words WHERE word REGEXP '^\p{L}+e$'`)
if err != nil {
	log.Fatal(err)
}
defer stmt.Close()

for stmt.Step() {
	fmt.Println(stmt.ColumnText(0))
}
if err := stmt.Err(); err != nil {
	log.Fatal(err)
}
Output:

cote
côte
cotée

type Datatype

type Datatype uint32

Datatype is a fundamental datatype of SQLite.

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

const (
	INTEGER Datatype = 1
	FLOAT   Datatype = 2
	TEXT    Datatype = 3
	BLOB    Datatype = 4
	NULL    Datatype = 5
)

func (Datatype) String

func (t Datatype) String() string

String implements the fmt.Stringer interface.

type DriverConn

type DriverConn interface {
	driver.Conn
	driver.ConnBeginTx
	driver.ExecerContext
	driver.ConnPrepareContext

	SetInterrupt(ctx context.Context) (old context.Context)

	Savepoint() Savepoint
	Backup(srcDB, dstURI string) error
	Restore(dstDB, srcURI string) error
	OpenBlob(db, table, column string, row int64, write bool) (*Blob, error)
}

DriverConn is implemented by the SQLite database/sql driver connection.

It can be used to access advanced SQLite features like savepoints, online backup and incremental BLOB I/O.

Example
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"

	"github.com/ianatha/go-sqlite3"
	_ "github.com/ianatha/go-sqlite3/driver"
	_ "github.com/ianatha/go-sqlite3/embed"
)

var db *sql.DB

func main() {
	var err error
	db, err = sql.Open("sqlite3", "demo.db")
	if err != nil {
		log.Fatal(err)
	}
	defer os.Remove("demo.db")
	defer db.Close()

	ctx := context.Background()

	conn, err := db.Conn(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	_, err = conn.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS test (col)`)
	if err != nil {
		log.Fatal(err)
	}

	res, err := conn.ExecContext(ctx, `INSERT INTO test VALUES (?)`, sqlite3.ZeroBlob(11))
	if err != nil {
		log.Fatal(err)
	}

	id, err := res.LastInsertId()
	if err != nil {
		log.Fatal(err)
	}

	err = conn.Raw(func(driverConn any) error {
		conn := driverConn.(sqlite3.DriverConn)
		savept := conn.Savepoint()
		defer savept.Release(&err)

		blob, err := conn.OpenBlob("main", "test", "col", id, true)
		if err != nil {
			return err
		}
		defer blob.Close()

		_, err = fmt.Fprint(blob, "Hello BLOB!")
		return err
	})
	if err != nil {
		log.Fatal(err)
	}

	var msg string
	err = conn.QueryRowContext(ctx, `SELECT col FROM test`).Scan(&msg)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(msg)
}
Output:

Hello BLOB!

type Error

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

Error wraps an SQLite Error Code.

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

func (*Error) As

func (e *Error) As(err any) bool

As converts this error to an ErrorCode or ExtendedErrorCode.

func (*Error) Code

func (e *Error) Code() ErrorCode

Code returns the primary error code for this error.

https://www.sqlite.org/rescode.html

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) ExtendedCode

func (e *Error) ExtendedCode() ExtendedErrorCode

ExtendedCode returns the extended error code for this error.

https://www.sqlite.org/rescode.html

func (*Error) Is

func (e *Error) Is(err error) bool

Is tests whether this error matches a given ErrorCode or ExtendedErrorCode.

It makes it possible to do:

if errors.Is(err, sqlite3.BUSY) {
	// ... handle BUSY
}

func (*Error) SQL

func (e *Error) SQL() string

SQL returns the SQL starting at the token that triggered a syntax error.

func (*Error) Temporary

func (e *Error) Temporary() bool

Temporary returns true for BUSY errors.

func (*Error) Timeout

func (e *Error) Timeout() bool

Timeout returns true for BUSY_TIMEOUT errors.

type ErrorCode

type ErrorCode uint8

ErrorCode is a result code that Error.Code might return.

https://www.sqlite.org/rescode.html

const (
	ERROR      ErrorCode = 1  /* Generic error */
	INTERNAL   ErrorCode = 2  /* Internal logic error in SQLite */
	PERM       ErrorCode = 3  /* Access permission denied */
	ABORT      ErrorCode = 4  /* Callback routine requested an abort */
	BUSY       ErrorCode = 5  /* The database file is locked */
	LOCKED     ErrorCode = 6  /* A table in the database is locked */
	NOMEM      ErrorCode = 7  /* A malloc() failed */
	READONLY   ErrorCode = 8  /* Attempt to write a readonly database */
	INTERRUPT  ErrorCode = 9  /* Operation terminated by sqlite3_interrupt() */
	IOERR      ErrorCode = 10 /* Some kind of disk I/O error occurred */
	CORRUPT    ErrorCode = 11 /* The database disk image is malformed */
	NOTFOUND   ErrorCode = 12 /* Unknown opcode in sqlite3_file_control() */
	FULL       ErrorCode = 13 /* Insertion failed because database is full */
	CANTOPEN   ErrorCode = 14 /* Unable to open the database file */
	PROTOCOL   ErrorCode = 15 /* Database lock protocol error */
	EMPTY      ErrorCode = 16 /* Internal use only */
	SCHEMA     ErrorCode = 17 /* The database schema changed */
	TOOBIG     ErrorCode = 18 /* String or BLOB exceeds size limit */
	CONSTRAINT ErrorCode = 19 /* Abort due to constraint violation */
	MISMATCH   ErrorCode = 20 /* Data type mismatch */
	MISUSE     ErrorCode = 21 /* Library used incorrectly */
	NOLFS      ErrorCode = 22 /* Uses OS features not supported on host */
	AUTH       ErrorCode = 23 /* Authorization denied */
	FORMAT     ErrorCode = 24 /* Not used */
	RANGE      ErrorCode = 25 /* 2nd parameter to sqlite3_bind out of range */
	NOTADB     ErrorCode = 26 /* File opened that is not a database file */
	NOTICE     ErrorCode = 27 /* Notifications from sqlite3_log() */
	WARNING    ErrorCode = 28 /* Warnings from sqlite3_log() */
)

func (ErrorCode) Error

func (e ErrorCode) Error() string

Error implements the error interface.

func (ErrorCode) Temporary

func (e ErrorCode) Temporary() bool

Temporary returns true for BUSY errors.

type ExtendedErrorCode

type ExtendedErrorCode uint16

ExtendedErrorCode is a result code that Error.ExtendedCode might return.

https://www.sqlite.org/rescode.html

const (
	ERROR_MISSING_COLLSEQ   ExtendedErrorCode = xErrorCode(ERROR) | (1 << 8)
	ERROR_RETRY             ExtendedErrorCode = xErrorCode(ERROR) | (2 << 8)
	ERROR_SNAPSHOT          ExtendedErrorCode = xErrorCode(ERROR) | (3 << 8)
	IOERR_READ              ExtendedErrorCode = xErrorCode(IOERR) | (1 << 8)
	IOERR_SHORT_READ        ExtendedErrorCode = xErrorCode(IOERR) | (2 << 8)
	IOERR_WRITE             ExtendedErrorCode = xErrorCode(IOERR) | (3 << 8)
	IOERR_FSYNC             ExtendedErrorCode = xErrorCode(IOERR) | (4 << 8)
	IOERR_DIR_FSYNC         ExtendedErrorCode = xErrorCode(IOERR) | (5 << 8)
	IOERR_TRUNCATE          ExtendedErrorCode = xErrorCode(IOERR) | (6 << 8)
	IOERR_FSTAT             ExtendedErrorCode = xErrorCode(IOERR) | (7 << 8)
	IOERR_UNLOCK            ExtendedErrorCode = xErrorCode(IOERR) | (8 << 8)
	IOERR_RDLOCK            ExtendedErrorCode = xErrorCode(IOERR) | (9 << 8)
	IOERR_DELETE            ExtendedErrorCode = xErrorCode(IOERR) | (10 << 8)
	IOERR_BLOCKED           ExtendedErrorCode = xErrorCode(IOERR) | (11 << 8)
	IOERR_NOMEM             ExtendedErrorCode = xErrorCode(IOERR) | (12 << 8)
	IOERR_ACCESS            ExtendedErrorCode = xErrorCode(IOERR) | (13 << 8)
	IOERR_CHECKRESERVEDLOCK ExtendedErrorCode = xErrorCode(IOERR) | (14 << 8)
	IOERR_LOCK              ExtendedErrorCode = xErrorCode(IOERR) | (15 << 8)
	IOERR_CLOSE             ExtendedErrorCode = xErrorCode(IOERR) | (16 << 8)
	IOERR_DIR_CLOSE         ExtendedErrorCode = xErrorCode(IOERR) | (17 << 8)
	IOERR_SHMOPEN           ExtendedErrorCode = xErrorCode(IOERR) | (18 << 8)
	IOERR_SHMSIZE           ExtendedErrorCode = xErrorCode(IOERR) | (19 << 8)
	IOERR_SHMLOCK           ExtendedErrorCode = xErrorCode(IOERR) | (20 << 8)
	IOERR_SHMMAP            ExtendedErrorCode = xErrorCode(IOERR) | (21 << 8)
	IOERR_SEEK              ExtendedErrorCode = xErrorCode(IOERR) | (22 << 8)
	IOERR_DELETE_NOENT      ExtendedErrorCode = xErrorCode(IOERR) | (23 << 8)
	IOERR_MMAP              ExtendedErrorCode = xErrorCode(IOERR) | (24 << 8)
	IOERR_GETTEMPPATH       ExtendedErrorCode = xErrorCode(IOERR) | (25 << 8)
	IOERR_CONVPATH          ExtendedErrorCode = xErrorCode(IOERR) | (26 << 8)
	IOERR_VNODE             ExtendedErrorCode = xErrorCode(IOERR) | (27 << 8)
	IOERR_AUTH              ExtendedErrorCode = xErrorCode(IOERR) | (28 << 8)
	IOERR_BEGIN_ATOMIC      ExtendedErrorCode = xErrorCode(IOERR) | (29 << 8)
	IOERR_COMMIT_ATOMIC     ExtendedErrorCode = xErrorCode(IOERR) | (30 << 8)
	IOERR_ROLLBACK_ATOMIC   ExtendedErrorCode = xErrorCode(IOERR) | (31 << 8)
	IOERR_DATA              ExtendedErrorCode = xErrorCode(IOERR) | (32 << 8)
	IOERR_CORRUPTFS         ExtendedErrorCode = xErrorCode(IOERR) | (33 << 8)
	LOCKED_SHAREDCACHE      ExtendedErrorCode = xErrorCode(LOCKED) | (1 << 8)
	LOCKED_VTAB             ExtendedErrorCode = xErrorCode(LOCKED) | (2 << 8)
	BUSY_RECOVERY           ExtendedErrorCode = xErrorCode(BUSY) | (1 << 8)
	BUSY_SNAPSHOT           ExtendedErrorCode = xErrorCode(BUSY) | (2 << 8)
	BUSY_TIMEOUT            ExtendedErrorCode = xErrorCode(BUSY) | (3 << 8)
	CANTOPEN_NOTEMPDIR      ExtendedErrorCode = xErrorCode(CANTOPEN) | (1 << 8)
	CANTOPEN_ISDIR          ExtendedErrorCode = xErrorCode(CANTOPEN) | (2 << 8)
	CANTOPEN_FULLPATH       ExtendedErrorCode = xErrorCode(CANTOPEN) | (3 << 8)
	CANTOPEN_CONVPATH       ExtendedErrorCode = xErrorCode(CANTOPEN) | (4 << 8)
	CANTOPEN_DIRTYWAL       ExtendedErrorCode = xErrorCode(CANTOPEN) | (5 << 8) /* Not Used */
	CANTOPEN_SYMLINK        ExtendedErrorCode = xErrorCode(CANTOPEN) | (6 << 8)
	CORRUPT_VTAB            ExtendedErrorCode = xErrorCode(CORRUPT) | (1 << 8)
	CORRUPT_SEQUENCE        ExtendedErrorCode = xErrorCode(CORRUPT) | (2 << 8)
	CORRUPT_INDEX           ExtendedErrorCode = xErrorCode(CORRUPT) | (3 << 8)
	READONLY_RECOVERY       ExtendedErrorCode = xErrorCode(READONLY) | (1 << 8)
	READONLY_CANTLOCK       ExtendedErrorCode = xErrorCode(READONLY) | (2 << 8)
	READONLY_ROLLBACK       ExtendedErrorCode = xErrorCode(READONLY) | (3 << 8)
	READONLY_DBMOVED        ExtendedErrorCode = xErrorCode(READONLY) | (4 << 8)
	READONLY_CANTINIT       ExtendedErrorCode = xErrorCode(READONLY) | (5 << 8)
	READONLY_DIRECTORY      ExtendedErrorCode = xErrorCode(READONLY) | (6 << 8)
	ABORT_ROLLBACK          ExtendedErrorCode = xErrorCode(ABORT) | (2 << 8)
	CONSTRAINT_CHECK        ExtendedErrorCode = xErrorCode(CONSTRAINT) | (1 << 8)
	CONSTRAINT_COMMITHOOK   ExtendedErrorCode = xErrorCode(CONSTRAINT) | (2 << 8)
	CONSTRAINT_FOREIGNKEY   ExtendedErrorCode = xErrorCode(CONSTRAINT) | (3 << 8)
	CONSTRAINT_FUNCTION     ExtendedErrorCode = xErrorCode(CONSTRAINT) | (4 << 8)
	CONSTRAINT_NOTNULL      ExtendedErrorCode = xErrorCode(CONSTRAINT) | (5 << 8)
	CONSTRAINT_PRIMARYKEY   ExtendedErrorCode = xErrorCode(CONSTRAINT) | (6 << 8)
	CONSTRAINT_TRIGGER      ExtendedErrorCode = xErrorCode(CONSTRAINT) | (7 << 8)
	CONSTRAINT_UNIQUE       ExtendedErrorCode = xErrorCode(CONSTRAINT) | (8 << 8)
	CONSTRAINT_VTAB         ExtendedErrorCode = xErrorCode(CONSTRAINT) | (9 << 8)
	CONSTRAINT_ROWID        ExtendedErrorCode = xErrorCode(CONSTRAINT) | (10 << 8)
	CONSTRAINT_PINNED       ExtendedErrorCode = xErrorCode(CONSTRAINT) | (11 << 8)
	CONSTRAINT_DATATYPE     ExtendedErrorCode = xErrorCode(CONSTRAINT) | (12 << 8)
	NOTICE_RECOVER_WAL      ExtendedErrorCode = xErrorCode(NOTICE) | (1 << 8)
	NOTICE_RECOVER_ROLLBACK ExtendedErrorCode = xErrorCode(NOTICE) | (2 << 8)
	NOTICE_RBU              ExtendedErrorCode = xErrorCode(NOTICE) | (3 << 8)
	WARNING_AUTOINDEX       ExtendedErrorCode = xErrorCode(WARNING) | (1 << 8)
	AUTH_USER               ExtendedErrorCode = xErrorCode(AUTH) | (1 << 8)
)

func (ExtendedErrorCode) As

func (e ExtendedErrorCode) As(err any) bool

As converts this error to an ErrorCode.

func (ExtendedErrorCode) Error

func (e ExtendedErrorCode) Error() string

Error implements the error interface.

func (ExtendedErrorCode) Is

func (e ExtendedErrorCode) Is(err error) bool

Is tests whether this error matches a given ErrorCode.

func (ExtendedErrorCode) Temporary

func (e ExtendedErrorCode) Temporary() bool

Temporary returns true for BUSY errors.

func (ExtendedErrorCode) Timeout

func (e ExtendedErrorCode) Timeout() bool

Timeout returns true for BUSY_TIMEOUT errors.

type FunctionFlag

type FunctionFlag uint32

FunctionFlag is a flag that can be passed to Conn.PrepareFlags.

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

const (
	DETERMINISTIC FunctionFlag = 0x000000800
	DIRECTONLY    FunctionFlag = 0x000080000
	SUBTYPE       FunctionFlag = 0x000100000
	INNOCUOUS     FunctionFlag = 0x000200000
)

type OpenFlag

type OpenFlag uint32

OpenFlag is a flag for the OpenFlags function.

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

const (
	OPEN_READONLY     OpenFlag = 0x00000001 /* Ok for sqlite3_open_v2() */
	OPEN_READWRITE    OpenFlag = 0x00000002 /* Ok for sqlite3_open_v2() */
	OPEN_CREATE       OpenFlag = 0x00000004 /* Ok for sqlite3_open_v2() */
	OPEN_URI          OpenFlag = 0x00000040 /* Ok for sqlite3_open_v2() */
	OPEN_MEMORY       OpenFlag = 0x00000080 /* Ok for sqlite3_open_v2() */
	OPEN_NOMUTEX      OpenFlag = 0x00008000 /* Ok for sqlite3_open_v2() */
	OPEN_FULLMUTEX    OpenFlag = 0x00010000 /* Ok for sqlite3_open_v2() */
	OPEN_SHAREDCACHE  OpenFlag = 0x00020000 /* Ok for sqlite3_open_v2() */
	OPEN_PRIVATECACHE OpenFlag = 0x00040000 /* Ok for sqlite3_open_v2() */
	OPEN_NOFOLLOW     OpenFlag = 0x01000000 /* Ok for sqlite3_open_v2() */
	OPEN_EXRESCODE    OpenFlag = 0x02000000 /* Extended result codes */
)

type PrepareFlag

type PrepareFlag uint32

PrepareFlag is a flag that can be passed to Conn.PrepareFlags.

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

const (
	PREPARE_PERSISTENT PrepareFlag = 0x01
	PREPARE_NORMALIZE  PrepareFlag = 0x02
	PREPARE_NO_VTAB    PrepareFlag = 0x04
)

type Savepoint

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

Savepoint is a marker within a transaction that allows for partial rollback.

https://www.sqlite.org/lang_savepoint.html

func (Savepoint) Release

func (s Savepoint) Release(errp *error)

Release releases the savepoint rolling back any changes if *error points to a non-nil error.

This is meant to be deferred:

func doWork(conn *sqlite3.Conn) (err error) {
	savept := conn.Savepoint()
	defer savept.Release(&err)

	// ... do work in the transaction
}

func (Savepoint) Rollback

func (s Savepoint) Rollback() error

Rollback rolls the transaction back to the savepoint, even if the connection has been interrupted. Rollback does not release the savepoint.

https://www.sqlite.org/lang_transaction.html

type Stmt

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

Stmt is a prepared statement object.

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

func (*Stmt) BindBlob

func (s *Stmt) BindBlob(param int, value []byte) error

BindBlob binds a []byte to the prepared statement. The leftmost SQL parameter has an index of 1. Binding a nil slice is the same as calling Stmt.BindNull.

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

func (*Stmt) BindBool

func (s *Stmt) BindBool(param int, value bool) error

BindBool binds a bool to the prepared statement. The leftmost SQL parameter has an index of 1. SQLite does not have a separate boolean storage class. Instead, boolean values are stored as integers 0 (false) and 1 (true).

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

func (*Stmt) BindCount

func (s *Stmt) BindCount() int

BindCount returns the number of SQL parameters in the prepared statement.

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

func (*Stmt) BindFloat

func (s *Stmt) BindFloat(param int, value float64) error

BindFloat binds a float64 to the prepared statement. The leftmost SQL parameter has an index of 1.

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

func (*Stmt) BindIndex

func (s *Stmt) BindIndex(name string) int

BindIndex returns the index of a parameter in the prepared statement given its name.

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

func (*Stmt) BindInt

func (s *Stmt) BindInt(param int, value int) error

BindInt binds an int to the prepared statement. The leftmost SQL parameter has an index of 1.

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

func (*Stmt) BindInt64

func (s *Stmt) BindInt64(param int, value int64) error

BindInt64 binds an int64 to the prepared statement. The leftmost SQL parameter has an index of 1.

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

func (*Stmt) BindName

func (s *Stmt) BindName(param int) string

BindName returns the name of a parameter in the prepared statement. The leftmost SQL parameter has an index of 1.

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

func (*Stmt) BindNull

func (s *Stmt) BindNull(param int) error

BindNull binds a NULL to the prepared statement. The leftmost SQL parameter has an index of 1.

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

func (*Stmt) BindText

func (s *Stmt) BindText(param int, value string) error

BindText binds a string to the prepared statement. The leftmost SQL parameter has an index of 1.

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

func (*Stmt) BindTime

func (s *Stmt) BindTime(param int, value time.Time, format TimeFormat) error

BindTime binds a time.Time to the prepared statement. The leftmost SQL parameter has an index of 1.

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

func (*Stmt) BindZeroBlob

func (s *Stmt) BindZeroBlob(param int, n int64) error

BindZeroBlob binds a zero-filled, length n BLOB to the prepared statement. The leftmost SQL parameter has an index of 1.

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

func (*Stmt) ClearBindings

func (s *Stmt) ClearBindings() error

ClearBindings resets all bindings on the prepared statement.

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

func (*Stmt) Close

func (s *Stmt) Close() error

Close destroys the prepared statement object.

It is safe to close a nil, zero or closed Stmt.

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

func (*Stmt) ColumnBlob

func (s *Stmt) ColumnBlob(col int, buf []byte) []byte

ColumnBlob appends to buf and returns the value of the result column as a []byte. The leftmost column of the result set has the index 0.

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

func (*Stmt) ColumnBool

func (s *Stmt) ColumnBool(col int) bool

ColumnBool returns the value of the result column as a bool. The leftmost column of the result set has the index 0. SQLite does not have a separate boolean storage class. Instead, boolean values are retrieved as integers, with 0 converted to false and any other value to true.

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

func (*Stmt) ColumnCount

func (s *Stmt) ColumnCount() int

ColumnCount returns the number of columns in a result set.

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

func (*Stmt) ColumnFloat

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

ColumnFloat returns the value of the result column as a float64. The leftmost column of the result set has the index 0.

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

func (*Stmt) ColumnInt

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

ColumnInt returns the value of the result column as an int. The leftmost column of the result set has the index 0.

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

func (*Stmt) ColumnInt64

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

ColumnInt64 returns the value of the result column as an int64. The leftmost column of the result set has the index 0.

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

func (*Stmt) ColumnName

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

ColumnName returns the name of the result column. The leftmost column of the result set has the index 0.

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

func (*Stmt) ColumnRawBlob

func (s *Stmt) ColumnRawBlob(col int) []byte

ColumnRawBlob returns the value of the result column as a []byte. The []byte is owned by SQLite and may be invalidated by subsequent calls to Stmt methods. The leftmost column of the result set has the index 0.

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

func (*Stmt) ColumnRawText

func (s *Stmt) ColumnRawText(col int) []byte

ColumnRawText returns the value of the result column as a []byte. The []byte is owned by SQLite and may be invalidated by subsequent calls to Stmt methods. The leftmost column of the result set has the index 0.

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

func (*Stmt) ColumnText

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

ColumnText returns the value of the result column as a string. The leftmost column of the result set has the index 0.

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

func (*Stmt) ColumnTime

func (s *Stmt) ColumnTime(col int, format TimeFormat) time.Time

ColumnTime returns the value of the result column as a time.Time. The leftmost column of the result set has the index 0.

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

func (*Stmt) ColumnType

func (s *Stmt) ColumnType(col int) Datatype

ColumnType returns the initial Datatype of the result column. The leftmost column of the result set has the index 0.

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

func (*Stmt) Err

func (s *Stmt) Err() error

Err gets the last error occurred during Stmt.Step. Err returns nil after Stmt.Reset is called.

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

func (*Stmt) Exec

func (s *Stmt) Exec() error

Exec is a convenience function that repeatedly calls Stmt.Step until it returns false, then calls Stmt.Reset to reset the statement and get any error that occurred.

func (*Stmt) Reset

func (s *Stmt) Reset() error

Reset resets the prepared statement object.

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

func (*Stmt) Step

func (s *Stmt) Step() bool

Step evaluates the SQL statement. If the SQL statement being executed returns any data, then true is returned each time a new row of data is ready for processing by the caller. The values may be accessed using the Column access functions. Step is called again to retrieve the next row of data. If an error has occurred, Step returns false; call Stmt.Err or Stmt.Reset to get the error.

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

type TimeFormat

type TimeFormat string

TimeFormat specifies how to encode/decode time values.

See the documentation for the TimeFormatDefault constant for formats recognized by SQLite.

https://www.sqlite.org/lang_datefunc.html

func (TimeFormat) Decode

func (f TimeFormat) Decode(v any) (time.Time, error)

Decode decodes a time value using this format.

The time value can be a string, an int64, or a float64.

Formats TimeFormat8 through TimeFormat10 (and TimeFormat8TZ through TimeFormat10TZ) assume a date of 2000-01-01.

The timezone indicator and fractional seconds are always optional for formats TimeFormat2 through TimeFormat10 (and TimeFormat2TZ through TimeFormat10TZ).

TimeFormatAuto implements (and extends) the SQLite auto modifier. Julian day numbers are safe to use for historical dates, from 4712BC through 9999AD. Unix timestamps (expressed in seconds, milliseconds, microseconds, or nanoseconds) are safe to use for current events, from at least 1980 through at least 2260. Unix timestamps before 1980 and after 9999 may be misinterpreted as julian day numbers, or have the wrong time unit.

https://www.sqlite.org/lang_datefunc.html

func (TimeFormat) Encode

func (f TimeFormat) Encode(t time.Time) any

Encode encodes a time value using this format.

TimeFormatDefault and TimeFormatAuto encode using time.RFC3339Nano, with nanosecond accuracy, and preserving any timezone offset.

This is the format used by the database/sql driver: database/sql.Row.Scan will decode as time.Time values encoded with time.RFC3339Nano.

Time values encoded with time.RFC3339Nano cannot be sorted as strings to produce a time-ordered sequence.

Assuming that the time zones of the time values are the same (e.g., all in UTC), and expressed using the same string (e.g., all "Z" or all "+00:00"), use the TIME collating sequence to produce a time-ordered sequence.

Otherwise, use TimeFormat7 for time-ordered encoding.

Formats TimeFormat1 through TimeFormat10 convert time values to UTC before encoding.

Returns a string for the text formats, a float64 for TimeFormatJulianDay and TimeFormatUnixFrac, or an int64 for the other numeric formats.

https://www.sqlite.org/lang_datefunc.html

type Tx

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

Tx is an in-progress database transaction.

https://www.sqlite.org/lang_transaction.html

func (Tx) Commit

func (tx Tx) Commit() error

Commit commits the transaction.

https://www.sqlite.org/lang_transaction.html

func (Tx) End

func (tx Tx) End(errp *error)

End calls either Tx.Commit or Tx.Rollback depending on whether *error points to a nil or non-nil error.

This is meant to be deferred:

func doWork(conn *sqlite3.Conn) (err error) {
	tx := conn.Begin()
	defer tx.End(&err)

	// ... do work in the transaction
}

https://www.sqlite.org/lang_transaction.html

func (Tx) Rollback

func (tx Tx) Rollback() error

Rollback rolls back the transaction, even if the connection has been interrupted.

https://www.sqlite.org/lang_transaction.html

type Value

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

Value is any value that can be stored in a database table.

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

func (Value) Blob

func (v Value) Blob(buf []byte) []byte

Blob appends to buf and returns the value as a []byte.

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

func (Value) Bool

func (v Value) Bool() bool

Bool returns the value as a bool. SQLite does not have a separate boolean storage class. Instead, boolean values are retrieved as integers, with 0 converted to false and any other value to true.

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

func (Value) Float

func (v Value) Float() float64

Float returns the value as a float64.

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

func (Value) Int

func (v Value) Int() int

Int returns the value as an int.

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

func (Value) Int64

func (v Value) Int64() int64

Int64 returns the value as an int64.

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

func (Value) RawBlob

func (v Value) RawBlob() []byte

RawBlob returns the value as a []byte. The []byte is owned by SQLite and may be invalidated by subsequent calls to Value methods.

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

func (Value) RawText

func (v Value) RawText() []byte

RawText returns the value as a []byte. The []byte is owned by SQLite and may be invalidated by subsequent calls to Value methods.

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

func (Value) Text

func (v Value) Text() string

Text returns the value as a string.

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

func (Value) Time

func (v Value) Time(format TimeFormat) time.Time

Time returns the value as a time.Time.

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

func (Value) Type

func (v Value) Type() Datatype

Type returns the initial Datatype of the value.

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

type WindowFunction

type WindowFunction interface {
	AggregateFunction

	// Inverse is invoked to remove the oldest presently aggregated result of Step from the current window.
	// The function arguments, if any, are those passed to Step for the row being removed.
	Inverse(ctx Context, arg ...Value)
}

WindowFunction is the interface an aggregate window function should implement.

https://www.sqlite.org/windowfunctions.html

type ZeroBlob

type ZeroBlob int64

ZeroBlob represents a zero-filled, length n BLOB that can be used as an argument to database/sql.DB.Exec and similar methods.

Directories

Path Synopsis
Package driver provides a database/sql driver for SQLite.
Package driver provides a database/sql driver for SQLite.
Package embed embeds SQLite into your application.
Package embed embeds SQLite into your application.
ext
unicode
Package unicode provides an alternative to the SQLite ICU extension.
Package unicode provides an alternative to the SQLite ICU extension.
gormlite module
internal
vfs
Package vfs wraps the C SQLite VFS API.
Package vfs wraps the C SQLite VFS API.
memdb
Package memdb implements the "memdb" SQLite VFS.
Package memdb implements the "memdb" SQLite VFS.
readervfs
Package readervfs implements an SQLite VFS for immutable databases.
Package readervfs implements an SQLite VFS for immutable databases.

Jump to

Keyboard shortcuts

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