sqlite

package module
Version: v0.9.3 Latest Latest
Warning

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

Go to latest
Published: May 30, 2022 License: ISC Imports: 16 Imported by: 6

README

zombiezen.com/go/sqlite

Go Reference

This package provides a low-level Go interface to SQLite 3. It is a fork of crawshaw.io/sqlite that uses modernc.org/sqlite, a CGo-free SQLite package. It aims to be a mostly drop-in replacement for crawshaw.io/sqlite.

This package deliberately does not provide a database/sql driver. See David Crawshaw's rationale for an in-depth explanation. If you want to use database/sql with SQLite without CGo, use modernc.org/sqlite directly.

Features

Install

go get zombiezen.com/go/sqlite

While this library does not use CGo, make sure that you are building for one of the supported architectures.

Getting Started

import (
  "fmt"

  "zombiezen.com/go/sqlite"
  "zombiezen.com/go/sqlite/sqlitex"
)

// ...

// Open an in-memory database.
conn, err := sqlite.OpenConn(":memory:", sqlite.OpenReadWrite)
if err != nil {
  return err
}
defer conn.Close()

// Execute a query.
err = sqlitex.ExecuteTransient(conn, "SELECT 'hello, world';", &sqlitex.ExecOptions{
  ResultFunc: func(stmt *sqlite.Stmt) error {
    fmt.Println(stmt.ColumnText(0))
    return nil
  },
})
if err != nil {
  return err
}

If you're creating a new application, see the package examples or the reference docs.

If you're looking to switch existing code that uses crawshaw.io/sqlite, take a look at the migration docs.

License

ISC

Documentation

Overview

Package sqlite provides a Go interface to SQLite 3.

The semantics of this package are deliberately close to the SQLite3 C API, so it is helpful to be familiar with http://www.sqlite.org/c3ref/intro.html.

An SQLite connection is represented by a *sqlite.Conn. Connections cannot be used concurrently. A typical Go program will create a pool of connections (using Open to create a *sqlitex.Pool) so goroutines can borrow a connection while they need to talk to the database.

This package assumes SQLite will be used concurrently by the process through several connections, so the build options for SQLite enable multi-threading and the shared cache: https://www.sqlite.org/sharedcache.html

The implementation automatically handles shared cache locking, see the documentation on Stmt.Step for details.

The optional SQLite 3 extensions compiled in are: session, FTS5, RTree, JSON1, and GeoPoly.

This is not a database/sql driver. For helper functions that make some kinds of statements easier to write, see the sqlitex package.

Statement Caching

Statements are prepared with the Prepare and PrepareTransient methods. When using Prepare, statements are keyed inside a connection by the original query string used to create them. This means long-running high-performance code paths can write:

stmt, err := conn.Prepare("SELECT ...")

After all the connections in a pool have been warmed up by passing through one of these Prepare calls, subsequent calls are simply a map lookup that returns an existing statement.

Streaming Blobs

The sqlite package supports the SQLite incremental I/O interface for streaming blob data into and out of the the database without loading the entire blob into a single []byte. (This is important when working either with very large blobs, or more commonly, a large number of moderate-sized blobs concurrently.)

Deadlines and Cancellation

Every connection can have a done channel associated with it using the SetInterrupt method. This is typically the channel returned by a context.Context Done method.

As database connections are long-lived, the SetInterrupt method can be called multiple times to reset the associated lifetime.

Transactions

SQLite transactions have to be managed manually with this package by directly calling BEGIN / COMMIT / ROLLBACK or SAVEPOINT / RELEASE/ ROLLBACK. The sqlitex has a Savepoint function that helps automate this.

Example
package main

import (
	"fmt"

	"zombiezen.com/go/sqlite"
	"zombiezen.com/go/sqlite/sqlitex"
)

func main() {
	// Open an in-memory database.
	conn, err := sqlite.OpenConn(":memory:", sqlite.OpenReadWrite|sqlite.OpenNoMutex)
	if err != nil {
		// handle error
	}
	defer conn.Close()

	// Execute a query.
	err = sqlitex.ExecuteTransient(conn, "SELECT 'hello, world';", &sqlitex.ExecOptions{
		ResultFunc: func(stmt *sqlite.Stmt) error {
			fmt.Println(stmt.ColumnText(0))
			return nil
		},
	})
	if err != nil {
		// handle error
	}

}
Output:

hello, world
Example (Http)

Using a Pool to execute SQL in a concurrent HTTP handler.

package main

import (
	"fmt"
	"log"
	"net/http"

	"zombiezen.com/go/sqlite/sqlitex"
)

var dbpool *sqlitex.Pool

// Using a Pool to execute SQL in a concurrent HTTP handler.
func main() {
	var err error
	dbpool, err = sqlitex.Open("file:memory:?mode=memory", 0, 10)
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", handle)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func handle(w http.ResponseWriter, r *http.Request) {
	conn := dbpool.Get(r.Context())
	if conn == nil {
		return
	}
	defer dbpool.Put(conn)
	stmt := conn.Prep("SELECT foo FROM footable WHERE id = $id;")
	stmt.SetText("$id", "_user_id_")
	for {
		if hasRow, err := stmt.Step(); err != nil {
			// ... handle error
		} else if !hasRow {
			break
		}
		foo := stmt.GetText("foo")
		// ... use foo
		fmt.Fprintln(w, foo)
	}
}
Output:

Example (WithoutX)

This is the same as the main package example, but uses the SQLite statement API instead of sqlitex.

package main

import (
	"fmt"

	"zombiezen.com/go/sqlite"
)

func main() {
	// Open an in-memory database.
	conn, err := sqlite.OpenConn(":memory:", sqlite.OpenReadWrite)
	if err != nil {
		// handle error
	}
	defer conn.Close()

	// Prepare a statement.
	stmt, _, err := conn.PrepareTransient("SELECT 'hello, world';")
	if err != nil {
		// handle error
	}
	// Transient statements must always be finalized.
	defer stmt.Finalize()

	for {
		row, err := stmt.Step()
		if err != nil {
			// handle error
		}
		if !row {
			break
		}
		fmt.Println(stmt.ColumnText(0))
	}

}
Output:

hello, world

Index

Examples

Constants

Conflict types.

View Source
const (
	// ChangesetOmit signals that no special action should be taken. The change
	// that caused the conflict will not be applied. The session module continues
	// to the next change in the changeset.
	ChangesetOmit = ConflictAction(lib.SQLITE_CHANGESET_OMIT)
	// ChangesetAbort signals that any changes applied so far should be rolled
	// back and the call to ApplyChangeset returns an error whose code
	// is ResultAbort.
	ChangesetAbort = ConflictAction(lib.SQLITE_CHANGESET_ABORT)
	// ChangesetReplace signals a different action depending on the conflict type.
	//
	// If the conflict type is ChangesetData, ChangesetReplace signals the
	// conflicting row should be updated or deleted.
	//
	// If the conflict type is ChangesetConflict, then ChangesetReplace signals
	// that the conflicting row should be removed from the database and a second
	// attempt to apply the change should be made. If this second attempt fails,
	// the original row is restored to the database before continuing.
	//
	// For all other conflict types, returning ChangesetReplace will cause
	// ApplyChangeset to roll back any changes applied so far and return an error
	// whose code is ResultMisuse.
	ChangesetReplace = ConflictAction(lib.SQLITE_CHANGESET_REPLACE)
)

Conflict actions.

View Source
const Version = lib.SQLITE_VERSION

Version is the SQLite version in the format "X.Y.Z" where X is the major version number (always 3), Y is the minor version number, and Z is the release number.

View Source
const VersionNumber = lib.SQLITE_VERSION_NUMBER

VersionNumber is an integer with the value (X*1000000 + Y*1000 + Z) where X is the major version number (always 3), Y is the minor version number, and Z is the release number.

Variables

This section is empty.

Functions

func ConcatChangesets added in v0.6.0

func ConcatChangesets(w io.Writer, changeset1, changeset2 io.Reader) error

ConcatChangesets concatenates two changesets into a single changeset.

https://www.sqlite.org/session/sqlite3changeset_concat.html

func InvertChangeset added in v0.6.0

func InvertChangeset(w io.Writer, r io.Reader) error

InvertChangeset generates an inverted changeset. Applying an inverted changeset to a database reverses the effects of applying the uninverted changeset.

This function currently assumes that the input is a valid changeset. If it is not, the results are undefined.

https://www.sqlite.org/session/sqlite3changeset_invert.html

Types

type Action added in v0.5.0

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

Action represents an action to be authorized.

func (Action) Accessor added in v0.5.0

func (action Action) Accessor() string

Accessor returns the name of the inner-most trigger or view that is responsible for the access attempt or the empty string if this access attempt is directly from top-level SQL code.

func (Action) Column added in v0.5.0

func (action Action) Column() string

Column returns the name of the column this action affects or the empty string if not applicable. For OpRead actions, this will return the empty string if a table is referenced but no column values are extracted from that table (e.g. a query like "SELECT COUNT(*) FROM tab").

func (Action) Database added in v0.5.0

func (action Action) Database() string

Database returns the name of the database (e.g. "main", "temp", etc.) this action affects or the empty string if not applicable.

func (Action) File added in v0.5.0

func (action Action) File() string

File returns the name of the file being ATTACHed or the empty string if the action does not represent an ATTACH DATABASE statement.

func (Action) Index added in v0.5.0

func (action Action) Index() string

Index returns the name of the index this action affects or the empty string if not applicable.

func (Action) Module added in v0.5.0

func (action Action) Module() string

Module returns the module name given to the virtual table statement or the empty string if the action does not represent a CREATE VIRTUAL TABLE or DROP VIRTUAL TABLE statement.

func (Action) Operation added in v0.5.0

func (action Action) Operation() string

Operation returns one of "BEGIN", "COMMIT", "RELEASE", or "ROLLBACK" for a transaction or savepoint statement or the empty string otherwise.

func (Action) Pragma added in v0.5.0

func (action Action) Pragma() string

Pragma returns the name of the action's PRAGMA command or the empty string if the action does not represent a PRAGMA command. See https://sqlite.org/pragma.html#toc for a list of possible values.

func (Action) PragmaArg added in v0.5.0

func (action Action) PragmaArg() string

PragmaArg returns the argument to the PRAGMA command or the empty string if the action does not represent a PRAGMA command or the PRAGMA command does not take an argument.

func (Action) Savepoint added in v0.5.0

func (action Action) Savepoint() string

Savepoint returns the name given to the SAVEPOINT statement or the empty string if the action does not represent a SAVEPOINT statement.

func (Action) String added in v0.5.0

func (action Action) String() string

String returns a debugging representation of the action.

func (Action) Table added in v0.5.0

func (action Action) Table() string

Table returns the name of the table this action affects or the empty string if not applicable.

func (Action) Trigger added in v0.5.0

func (action Action) Trigger() string

Trigger returns the name of the trigger this action affects or the empty string if not applicable.

func (Action) Type added in v0.5.0

func (action Action) Type() OpType

Type returns the type of action being authorized.

func (Action) View added in v0.5.0

func (action Action) View() string

View returns the name of the view this action affects or the empty string if not applicable.

type AuthResult added in v0.5.0

type AuthResult int32

AuthResult is the result of a call to an Authorizer. The zero value is AuthResultOK.

const (
	// AuthResultOK allows the SQL statement to be compiled.
	AuthResultOK AuthResult = lib.SQLITE_OK
	// AuthResultDeny causes the entire SQL statement to be rejected with an error.
	AuthResultDeny AuthResult = lib.SQLITE_DENY
	// AuthResultIgnore disallows the specific action but allow the SQL statement
	// to continue to be compiled. For OpRead, this substitutes a NULL for the
	// column value. For OpDelete, the DELETE operation proceeds but the truncate
	// optimization is disabled and all rows are deleted individually.
	AuthResultIgnore AuthResult = lib.SQLITE_IGNORE
)

Possible return values from Authorize.

func (AuthResult) String added in v0.5.0

func (result AuthResult) String() string

String returns the C constant name of the result.

type AuthorizeFunc added in v0.5.0

type AuthorizeFunc func(Action) AuthResult

AuthorizeFunc is a function that implements Authorizer.

func (AuthorizeFunc) Authorize added in v0.5.0

func (f AuthorizeFunc) Authorize(action Action) AuthResult

Authorize calls f.

type Authorizer added in v0.5.0

type Authorizer interface {
	Authorize(Action) AuthResult
}

An Authorizer is called during statement preparation to see whether an action is allowed by the application. An Authorizer must not modify the database connection, including by preparing statements.

See https://sqlite.org/c3ref/set_authorizer.html for a longer explanation.

type Blob

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

Blob provides streaming access to SQLite blobs.

Example
package main

import (
	"fmt"

	"zombiezen.com/go/sqlite"
	"zombiezen.com/go/sqlite/sqlitex"
)

func main() {
	// Create a new database with a "blobs" table with a single column, "myblob".
	conn, err := sqlite.OpenConn(":memory:", sqlite.OpenReadWrite)
	if err != nil {
		// handle error
	}
	defer conn.Close()
	err = sqlitex.ExecuteTransient(conn, `CREATE TABLE blobs (myblob blob);`, nil)
	if err != nil {
		// handle error
	}

	// Insert a new row with enough space for the data we want to insert.
	const dataToInsert = "Hello, World!"
	err = sqlitex.ExecuteTransient(
		conn,
		`INSERT INTO blobs (myblob) VALUES (zeroblob(?));`,
		&sqlitex.ExecOptions{
			Args: []interface{}{len(dataToInsert)},
		},
	)
	if err != nil {
		// handle error
	}

	// Open a handle to the "myblob" column on the row we just inserted.
	blob, err := conn.OpenBlob("", "blobs", "myblob", conn.LastInsertRowID(), true)
	if err != nil {
		// handle error
	}
	_, writeErr := blob.WriteString(dataToInsert)
	closeErr := blob.Close()
	if writeErr != nil {
		// handle error
	}
	if closeErr != nil {
		// handle error
	}

	// Read back the blob.
	var data []byte
	err = sqlitex.ExecuteTransient(conn, `SELECT myblob FROM blobs;`, &sqlitex.ExecOptions{
		ResultFunc: func(stmt *sqlite.Stmt) error {
			data = make([]byte, stmt.ColumnLen(0))
			stmt.ColumnBytes(0, data)
			return nil
		},
	})
	if err != nil {
		// handle error
	}
	fmt.Printf("%s\n", data)

}
Output:

Hello, World!

func (*Blob) Close

func (blob *Blob) Close() error

Close releases any resources associated with the blob handle. https://www.sqlite.org/c3ref/blob_close.html

func (*Blob) Read

func (blob *Blob) Read(p []byte) (int, error)

Read reads up to len(p) bytes from the blob into p. https://www.sqlite.org/c3ref/blob_read.html

func (*Blob) ReadFrom added in v0.3.0

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

ReadFrom copies data from r to the blob until EOF or error.

func (*Blob) Seek

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

Seek sets the offset for the next Read or Write and returns the offset. Seeking past the end of the blob returns an error.

func (*Blob) Size

func (blob *Blob) Size() int64

Size returns the number of bytes in the blob.

func (*Blob) Write

func (blob *Blob) Write(p []byte) (int, error)

Write writes len(p) from p to the blob. https://www.sqlite.org/c3ref/blob_write.html

func (*Blob) WriteString added in v0.3.0

func (blob *Blob) WriteString(s string) (int, error)

WriteString writes s to the blob. https://www.sqlite.org/c3ref/blob_write.html

func (*Blob) WriteTo added in v0.3.0

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

WriteTo copies the blob to w until there's no more data to write or an error occurs.

type Changegroup added in v0.6.0

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

A Changegroup is an object used to combine two or more changesets or patchesets. The zero value is an empty changegroup.

https://www.sqlite.org/session/changegroup.html

Example

This example shows how to use a changegroup to produce similar results to a call to ConcatChangesets.

package main

import (
	"bytes"
	"io"

	"zombiezen.com/go/sqlite"
)

func main() {
	// Get changesets from somewhere.
	var changeset1, changeset2 io.Reader

	// Create a changegroup.
	grp := new(sqlite.Changegroup)
	defer grp.Clear()

	// Add changesets to the changegroup.
	if err := grp.Add(changeset1); err != nil {
		// Handle error
	}
	if err := grp.Add(changeset2); err != nil {
		// Handle error
	}

	// Write the changegroup to a buffer.
	output := new(bytes.Buffer)
	if _, err := grp.WriteTo(output); err != nil {
		// Handle error
	}
}
Output:

func NewChangegroup deprecated added in v0.6.0

func NewChangegroup() (*Changegroup, error)

NewChangegroup returns a new changegroup. The caller is responsible for calling Clear on the returned changegroup.

https://www.sqlite.org/session/sqlite3changegroup_new.html

Deprecated: Use new(sqlite.Changegroup) instead, which does not require calling Clear until Add is called.

func (*Changegroup) Add added in v0.6.0

func (cg *Changegroup) Add(r io.Reader) error

Add adds all changes within the changeset (or patchset) read from r to the changegroup. Once Add has been called, it is the caller's responsibility to call Clear.

https://www.sqlite.org/session/sqlite3changegroup_add.html

func (*Changegroup) Clear added in v0.6.0

func (cg *Changegroup) Clear()

Clear empties the changegroup and releases any resources associated with the changegroup. This method may be called multiple times.

func (*Changegroup) WriteTo added in v0.6.0

func (cg *Changegroup) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes the current contents of the changegroup to w.

https://www.sqlite.org/session/sqlite3changegroup_output.html

type ChangesetIterator added in v0.6.0

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

ChangesetIterator is an iterator over a changeset.

func NewChangesetIterator added in v0.6.0

func NewChangesetIterator(r io.Reader) (*ChangesetIterator, error)

NewChangesetIterator returns a new iterator over the contents of the changeset. The caller is responsible for calling Finalize on the returned iterator.

https://www.sqlite.org/session/sqlite3changeset_start.html

func (*ChangesetIterator) Close added in v0.6.0

func (iter *ChangesetIterator) Close() error

Close releases any resources associated with the iterator created with NewChangesetIterator.

func (*ChangesetIterator) ConflictValue added in v0.6.0

func (iter *ChangesetIterator) ConflictValue(col int) (Value, error)

ConflictValue obtains the conflicting row value from an iterator. Column indices start at 0. The returned value is valid until the iterator is finalized.

https://www.sqlite.org/session/sqlite3changeset_conflict.html

func (*ChangesetIterator) ForeignKeyConflicts added in v0.6.0

func (iter *ChangesetIterator) ForeignKeyConflicts() (int, error)

ForeignKeyConflicts returns the number of foreign key constraint violations.

https://www.sqlite.org/session/sqlite3changeset_fk_conflicts.html

func (*ChangesetIterator) New added in v0.6.0

func (iter *ChangesetIterator) New(col int) (Value, error)

New obtains the new row value from an iterator. Column indices start at 0. The returned value is valid until the iterator is finalized.

https://www.sqlite.org/session/sqlite3changeset_new.html

func (*ChangesetIterator) Next added in v0.6.0

func (iter *ChangesetIterator) Next() (rowReturned bool, err error)

Next advances the iterator to the next change in the changeset. It is an error to call Next on an iterator passed to an ApplyChangeset conflict handler.

https://www.sqlite.org/session/sqlite3changeset_next.html

func (*ChangesetIterator) Old added in v0.6.0

func (iter *ChangesetIterator) Old(col int) (Value, error)

Old obtains the old row value from an iterator. Column indices start at 0. The returned value is valid until the iterator is finalized.

https://www.sqlite.org/session/sqlite3changeset_old.html

func (*ChangesetIterator) Operation added in v0.6.0

func (iter *ChangesetIterator) Operation() (*ChangesetOperation, error)

Operation obtains the current operation from the iterator.

https://www.sqlite.org/session/sqlite3changeset_op.html

func (*ChangesetIterator) PrimaryKey added in v0.6.0

func (iter *ChangesetIterator) PrimaryKey() ([]bool, error)

PrimaryKey returns a map of columns that make up the primary key.

https://www.sqlite.org/session/sqlite3changeset_pk.html

type ChangesetOperation added in v0.6.0

type ChangesetOperation struct {
	// Type is one of OpInsert, OpDelete, or OpUpdate.
	Type OpType
	// TableName is the name of the table affected by the change.
	TableName string
	// NumColumns is the number of columns in the table affected by the change.
	NumColumns int
	// Indirect is true if the session object "indirect" flag was set when the
	// change was made or the change was made by an SQL trigger or foreign key
	// action instead of directly as a result of a users SQL statement.
	Indirect bool
}

ChangesetOperation holds information about a change in a changeset.

type ColumnType

type ColumnType int

ColumnType are codes for each of the SQLite fundamental datatypes:

64-bit signed integer
64-bit IEEE floating point number
string
BLOB
NULL

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

const (
	TypeInteger ColumnType = lib.SQLITE_INTEGER
	TypeFloat   ColumnType = lib.SQLITE_FLOAT
	TypeText    ColumnType = lib.SQLITE_TEXT
	TypeBlob    ColumnType = lib.SQLITE_BLOB
	TypeNull    ColumnType = lib.SQLITE_NULL
)

Data types.

func (ColumnType) String

func (t ColumnType) String() string

String returns the SQLite constant name of the type.

type ConflictAction added in v0.6.0

type ConflictAction int32

ConflictAction is an enumeration of actions that can be taken in response to a changeset conflict. The zero value is ChangesetOmit.

https://www.sqlite.org/session/c_changeset_abort.html

func (ConflictAction) String added in v0.6.0

func (code ConflictAction) String() string

String returns the C constant name of the conflict action.

type ConflictHandler added in v0.6.0

type ConflictHandler func(ConflictType, *ChangesetIterator) ConflictAction

A ConflictHandler function determines the action to take to resolve a conflict while applying a changeset.

https://www.sqlite.org/session/sqlite3changeset_apply.html

type ConflictType added in v0.6.0

type ConflictType int32

ConflictType is an enumeration of changeset conflict types.

https://www.sqlite.org/session/c_changeset_conflict.html

func (ConflictType) String added in v0.6.0

func (code ConflictType) String() string

String returns the C constant name of the conflict type.

type Conn

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

Conn is an open connection to an SQLite3 database.

A Conn can only be used by goroutine at a time.

func OpenConn

func OpenConn(path string, flags ...OpenFlags) (*Conn, error)

OpenConn opens a single SQLite database connection with the given flags. No flags or a value of 0 defaults to the following:

OpenReadWrite
OpenCreate
OpenWAL
OpenURI
OpenNoMutex

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

func (*Conn) ApplyChangeset added in v0.6.0

func (c *Conn) ApplyChangeset(r io.Reader, filterFn func(tableName string) bool, conflictFn ConflictHandler) error

ApplyChangeset applies a changeset to the database.

If filterFn is not nil and the changeset includes changes for a table for which the function reports false, then the changes are ignored. If filterFn is nil, then all changes are applied.

If a changeset will not apply cleanly, then conflictFn will be called to resolve the conflict. See https://www.sqlite.org/session/sqlite3changeset_apply.html for more details.

func (*Conn) ApplyInverseChangeset added in v0.6.0

func (c *Conn) ApplyInverseChangeset(r io.Reader, filterFn func(tableName string) bool, conflictFn ConflictHandler) error

ApplyInverseChangeset applies the inverse of a changeset to the database. See ApplyChangeset and InvertChangeset for more details.

func (*Conn) AutocommitEnabled

func (c *Conn) AutocommitEnabled() bool

AutocommitEnabled reports whether conn is in autocommit mode. https://sqlite.org/c3ref/get_autocommit.html

func (*Conn) Changes

func (c *Conn) Changes() int

Changes reports the number of rows affected by the most recent statement.

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

func (*Conn) CheckReset

func (c *Conn) CheckReset() string

CheckReset reports whether any statement on this connection is in the process of returning results.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the database connection using sqlite3_close and finalizes persistent prepared statements. https://www.sqlite.org/c3ref/close.html

func (*Conn) CreateFunction

func (c *Conn) CreateFunction(name string, impl *FunctionImpl) error

CreateFunction registers a Go function with SQLite for use in SQL queries.

https://sqlite.org/appfunc.html

Example
package main

import (
	"fmt"
	"regexp"

	"zombiezen.com/go/sqlite"
	"zombiezen.com/go/sqlite/sqlitex"
)

func main() {
	conn, err := sqlite.OpenConn(":memory:", sqlite.OpenReadWrite)
	if err != nil {
		// handle error
	}
	defer conn.Close()

	// Add a regexp(pattern, string) function.
	err = conn.CreateFunction("regexp", &sqlite.FunctionImpl{
		NArgs:         2,
		Deterministic: true,
		Scalar: func(ctx sqlite.Context, args []sqlite.Value) (sqlite.Value, error) {
			re, err := regexp.Compile(args[0].Text())
			if err != nil {
				return sqlite.Value{}, fmt.Errorf("regexp: %w", err)
			}
			found := 0
			if re.MatchString(args[1].Text()) {
				found = 1
			}
			return sqlite.IntegerValue(int64(found)), nil
		},
	})
	if err != nil {
		// handle error
	}

	matches, err := sqlitex.ResultBool(conn.Prep(`SELECT regexp('fo+', 'foo');`))
	if err != nil {
		// handle error
	}
	fmt.Println("First matches:", matches)

	matches, err = sqlitex.ResultBool(conn.Prep(`SELECT regexp('fo+', 'bar');`))
	if err != nil {
		// handle error
	}
	fmt.Println("Second matches:", matches)

}
Output:

First matches: true
Second matches: false

func (*Conn) CreateSession added in v0.6.0

func (c *Conn) CreateSession(db string) (*Session, error)

CreateSession creates a new session object. If db is "", then a default of "main" is used. It is the caller's responsibility to call Delete when the session is no longer needed.

https://www.sqlite.org/session/sqlite3session_create.html

func (*Conn) LastInsertRowID

func (c *Conn) LastInsertRowID() int64

LastInsertRowID reports the rowid of the most recently successful INSERT.

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

func (*Conn) Limit added in v0.5.0

func (c *Conn) Limit(id Limit, value int32) int32

Limit sets a runtime limit on the connection. The the previous value of the limit is returned. Pass a negative value to check the limit without changing it.

https://sqlite.org/c3ref/limit.html

func (*Conn) OpenBlob

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

OpenBlob opens a blob in a particular {database,table,column,row}.

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

func (*Conn) Prep

func (c *Conn) Prep(query string) *Stmt

Prep returns a persistent SQL statement.

Any error in preparation will panic.

Persistent prepared statements are cached by the query string in a Conn. If Finalize is not called, then subsequent calls to Prepare will return the same statement.

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

func (*Conn) Prepare

func (c *Conn) Prepare(query string) (*Stmt, error)

Prepare prepares a persistent SQL statement.

Persistent prepared statements are cached by the query string in a Conn. If Finalize is not called, then subsequent calls to Prepare will return the same statement.

If the query has any unprocessed trailing bytes, Prepare returns an error.

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

func (*Conn) PrepareTransient

func (c *Conn) PrepareTransient(query string) (stmt *Stmt, trailingBytes int, err error)

PrepareTransient prepares an SQL statement that is not cached by the Conn. Subsequent calls with the same query will create new Stmts. Finalize must be called by the caller once done with the Stmt.

The number of trailing bytes not consumed from query is returned.

To run a sequence of queries once as part of a script, the sqlitex package provides an ExecScript function built on this.

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

func (*Conn) SetAuthorizer added in v0.5.0

func (c *Conn) SetAuthorizer(auth Authorizer) error

SetAuthorizer registers an authorizer for the database connection. SetAuthorizer(nil) clears any authorizer previously set.

Example
package main

import (
	"fmt"

	"zombiezen.com/go/sqlite"
)

func main() {
	// Create a new database.
	conn, err := sqlite.OpenConn(":memory:", sqlite.OpenReadWrite)
	if err != nil {
		// handle error
	}
	defer conn.Close()

	// Set an authorizer that prevents any mutations.
	err = conn.SetAuthorizer(sqlite.AuthorizeFunc(func(action sqlite.Action) sqlite.AuthResult {
		typ := action.Type()
		if typ == sqlite.OpSelect ||
			typ == sqlite.OpRead ||
			// Permit function calls.
			typ == sqlite.OpFunction ||
			// Permit transactions.
			typ == sqlite.OpTransaction ||
			typ == sqlite.OpSavepoint {
			return sqlite.AuthResultOK
		}
		return sqlite.AuthResultDeny
	}))
	if err != nil {
		// handle error
	}

	// Authorizers operate during statement preparation, so this will succeed:
	stmt, _, err := conn.PrepareTransient(`SELECT 'Hello, World!';`)
	if err != nil {
		panic(err)
	} else {
		fmt.Println("Read-only statement prepared!")
		if err := stmt.Finalize(); err != nil {
			panic(err)
		}
	}

	// But this will not:
	stmt, _, err = conn.PrepareTransient(`CREATE TABLE foo (id INTEGER PRIMARY KEY);`)
	if err != nil {
		fmt.Println("Prepare CREATE TABLE failed with code", sqlite.ErrCode(err))
	} else if err := stmt.Finalize(); err != nil {
		panic(err)
	}
}
Output:

Read-only statement prepared!
Prepare CREATE TABLE failed with code SQLITE_AUTH

func (*Conn) SetBlockOnBusy added in v0.9.0

func (c *Conn) SetBlockOnBusy()

SetBlockOnBusy sets a busy handler that waits to acquire a lock until the connection is interrupted (see SetInterrupt).

By default, connections are opened with SetBlockOnBusy, with the assumption that programs use SetInterrupt to control timeouts.

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

func (*Conn) SetBusyTimeout

func (c *Conn) SetBusyTimeout(d time.Duration)

SetBusyTimeout sets a busy handler that sleeps for up to d to acquire a lock. Passing a non-positive value will turn off all busy handlers.

By default, connections are opened with SetBlockOnBusy, with the assumption that programs use SetInterrupt to control timeouts.

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

func (*Conn) SetDefensive added in v0.5.0

func (c *Conn) SetDefensive(enabled bool) error

SetDefensive sets the "defensive" flag for a database connection. When the defensive flag is enabled, language features that allow ordinary SQL to deliberately corrupt the database file are disabled. The disabled features include but are not limited to the following:

The PRAGMA writable_schema=ON statement.
The PRAGMA journal_mode=OFF statement.
Writes to the sqlite_dbpage virtual table.
Direct writes to shadow tables.

func (*Conn) SetInterrupt

func (c *Conn) SetInterrupt(doneCh <-chan struct{}) (oldDoneCh <-chan struct{})

SetInterrupt assigns a channel to control connection execution lifetime.

When doneCh is closed, the connection uses sqlite3_interrupt to stop long-running queries and cancels any *Stmt.Step calls that are blocked waiting for the database write lock.

Subsequent uses of the connection will return SQLITE_INTERRUPT errors until doneCh is reset with a subsequent call to SetInterrupt.

Any busy statements at the time SetInterrupt is called will be reset.

SetInterrupt returns the old doneCh assigned to the connection.

Example
package main

import (
	"context"
	"time"

	"zombiezen.com/go/sqlite"
)

func main() {
	conn, err := sqlite.OpenConn(":memory:", sqlite.OpenReadWrite)
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	// You can use the Done() channel from a context to set deadlines and timeouts
	// on queries.
	ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
	defer cancel()
	conn.SetInterrupt(ctx.Done())
}
Output:

type Context

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

Context is a SQL function execution context. It is in no way related to a Go context.Context. https://sqlite.org/c3ref/context.html

func (Context) AuxData added in v0.4.0

func (ctx Context) AuxData(arg int) interface{}

AuxData returns the auxiliary data associated with the given argument, with zero being the leftmost argument, or nil if no such data is present.

Auxiliary data may be used by (non-aggregate) SQL functions to associate metadata with argument values. If the same value is passed to multiple invocations of the same SQL function during query execution, under some circumstances the associated metadata may be preserved. An example of where this might be useful is in a regular-expression matching function. The compiled version of the regular expression can be stored as metadata associated with the pattern string. Then as long as the pattern string remains the same, the compiled regular expression can be reused on multiple invocations of the same function.

For more details, see https://www.sqlite.org/c3ref/get_auxdata.html

Example

This example shows the same regexp function as in the CreateFunction example, but it uses auxiliary data to avoid recompiling the regular expression.

package main

import (
	"fmt"
	"regexp"

	"zombiezen.com/go/sqlite"
	"zombiezen.com/go/sqlite/sqlitex"
)

func main() {
	conn, err := sqlite.OpenConn(":memory:", sqlite.OpenReadWrite)
	if err != nil {
		// handle error
	}
	defer conn.Close()

	// Add a regexp(pattern, string) function.
	usedAux := false
	err = conn.CreateFunction("regexp", &sqlite.FunctionImpl{
		NArgs:         2,
		Deterministic: true,
		Scalar: func(ctx sqlite.Context, args []sqlite.Value) (sqlite.Value, error) {
			// First: attempt to retrieve the compiled regexp from a previous call.
			re, ok := ctx.AuxData(0).(*regexp.Regexp)
			if ok {
				usedAux = true
			} else {
				// Auxiliary data not present. Either this is the first call with this
				// argument, or SQLite has discarded the auxiliary data.
				var err error
				re, err = regexp.Compile(args[0].Text())
				if err != nil {
					return sqlite.Value{}, fmt.Errorf("regexp: %w", err)
				}
				// Store the auxiliary data for future calls.
				ctx.SetAuxData(0, re)
			}

			found := 0
			if re.MatchString(args[1].Text()) {
				found = 1
			}
			return sqlite.IntegerValue(int64(found)), nil
		},
	})
	if err != nil {
		// handle error
	}

	const query = `WITH test_strings(i, s) AS (VALUES (1, 'foo'), (2, 'bar')) ` +
		`SELECT i, regexp('fo+', s) FROM test_strings ORDER BY i;`
	err = sqlitex.ExecuteTransient(conn, query, &sqlitex.ExecOptions{
		ResultFunc: func(stmt *sqlite.Stmt) error {
			fmt.Printf("Match %d: %t\n", stmt.ColumnInt(0), stmt.ColumnInt(1) != 0)
			return nil
		},
	})
	if err != nil {
		// handle error
	}
	if usedAux {
		fmt.Println("Used aux data to speed up query!")
	}
}
Output:

Match 1: true
Match 2: false
Used aux data to speed up query!

func (Context) Conn added in v0.4.0

func (ctx Context) Conn() *Conn

Conn returns the database connection that is calling the SQL function.

func (Context) SetAuxData added in v0.4.0

func (ctx Context) SetAuxData(arg int, data interface{})

SetAuxData sets the auxiliary data associated with the given argument, with zero being the leftmost argument. SQLite is free to discard the metadata at any time, including during the call to SetAuxData.

Auxiliary data may be used by (non-aggregate) SQL functions to associate metadata with argument values. If the same value is passed to multiple invocations of the same SQL function during query execution, under some circumstances the associated metadata may be preserved. An example of where this might be useful is in a regular-expression matching function. The compiled version of the regular expression can be stored as metadata associated with the pattern string. Then as long as the pattern string remains the same, the compiled regular expression can be reused on multiple invocations of the same function.

For more details, see https://www.sqlite.org/c3ref/get_auxdata.html

type FunctionImpl added in v0.2.0

type FunctionImpl struct {
	// NArgs is the required number of arguments that the function accepts.
	// If NArgs is negative, then the function is variadic.
	//
	// Multiple function implementations may be registered with the same name
	// with different numbers of required arguments.
	NArgs int

	// Scalar is called when a scalar function is invoked in SQL.
	Scalar func(ctx Context, args []Value) (Value, error)

	// AggregateStep is called for each row of an aggregate function's
	// SQL invocation.
	AggregateStep func(ctx Context, rowArgs []Value)
	// AggregateFinal is called after all of the aggregate function's input rows
	// have been stepped through to construct the result.
	//
	// Use closure variables to pass information between AggregateStep and
	// AggregateFinal. The AggregateFinal function should also reset any shared
	// variables to their initial states before returning.
	AggregateFinal func(ctx Context) (Value, error)

	// If Deterministic is true, the function must always give the same output
	// when the input parameters are the same. This enables functions to be used
	// in additional contexts like the WHERE clause of partial indexes and enables
	// additional optimizations.
	//
	// See https://sqlite.org/c3ref/c_deterministic.html#sqlitedeterministic for
	// more details.
	Deterministic bool

	// If AllowIndirect is false, then the function may only be invoked from
	// top-level SQL. If AllowIndirect is true, then the function can be used in
	// VIEWs, TRIGGERs, and schema structures (e.g. CHECK constraints and DEFAULT
	// clauses).
	//
	// This is the inverse of SQLITE_DIRECTONLY. See
	// https://sqlite.org/c3ref/c_deterministic.html#sqlitedirectonly for more
	// details. This defaults to false for better security by default.
	AllowIndirect bool
}

FunctionImpl describes an application-defined SQL function. Either Scalar or both AggregateStep and AggregateFinal must be set.

type Limit added in v0.5.0

type Limit int32

Limit is a category of performance limits.

https://sqlite.org/c3ref/c_limit_attached.html

const (
	LimitLength            Limit = lib.SQLITE_LIMIT_LENGTH
	LimitSQLLength         Limit = lib.SQLITE_LIMIT_SQL_LENGTH
	LimitColumn            Limit = lib.SQLITE_LIMIT_COLUMN
	LimitExprDepth         Limit = lib.SQLITE_LIMIT_EXPR_DEPTH
	LimitCompoundSelect    Limit = lib.SQLITE_LIMIT_COMPOUND_SELECT
	LimitVDBEOp            Limit = lib.SQLITE_LIMIT_VDBE_OP
	LimitFunctionArg       Limit = lib.SQLITE_LIMIT_FUNCTION_ARG
	LimitAttached          Limit = lib.SQLITE_LIMIT_ATTACHED
	LimitLikePatternLength Limit = lib.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
	LimitVariableNumber    Limit = lib.SQLITE_LIMIT_VARIABLE_NUMBER
	LimitTriggerDepth      Limit = lib.SQLITE_LIMIT_TRIGGER_DEPTH
	LimitWorkerThreads     Limit = lib.SQLITE_LIMIT_WORKER_THREADS
)

Limit categories.

func (Limit) String added in v0.5.0

func (limit Limit) String() string

String returns the limit's C constant name.

type OpType added in v0.5.0

type OpType int32

OpType is an enumeration of SQLite statements and authorizable actions.

const (
	OpCreateIndex       OpType = lib.SQLITE_CREATE_INDEX
	OpCreateTable       OpType = lib.SQLITE_CREATE_TABLE
	OpCreateTempIndex   OpType = lib.SQLITE_CREATE_TEMP_INDEX
	OpCreateTempTable   OpType = lib.SQLITE_CREATE_TEMP_TABLE
	OpCreateTempTrigger OpType = lib.SQLITE_CREATE_TEMP_TRIGGER
	OpCreateTempView    OpType = lib.SQLITE_CREATE_TEMP_VIEW
	OpCreateTrigger     OpType = lib.SQLITE_CREATE_TRIGGER
	OpCreateView        OpType = lib.SQLITE_CREATE_VIEW
	OpDelete            OpType = lib.SQLITE_DELETE
	OpDropIndex         OpType = lib.SQLITE_DROP_INDEX
	OpDropTable         OpType = lib.SQLITE_DROP_TABLE
	OpDropTempIndex     OpType = lib.SQLITE_DROP_TEMP_INDEX
	OpDropTempTable     OpType = lib.SQLITE_DROP_TEMP_TABLE
	OpDropTempTrigger   OpType = lib.SQLITE_DROP_TEMP_TRIGGER
	OpDropTempView      OpType = lib.SQLITE_DROP_TEMP_VIEW
	OpDropTrigger       OpType = lib.SQLITE_DROP_TRIGGER
	OpDropView          OpType = lib.SQLITE_DROP_VIEW
	OpInsert            OpType = lib.SQLITE_INSERT
	OpPragma            OpType = lib.SQLITE_PRAGMA
	OpRead              OpType = lib.SQLITE_READ
	OpSelect            OpType = lib.SQLITE_SELECT
	OpTransaction       OpType = lib.SQLITE_TRANSACTION
	OpUpdate            OpType = lib.SQLITE_UPDATE
	OpAttach            OpType = lib.SQLITE_ATTACH
	OpDetach            OpType = lib.SQLITE_DETACH
	OpAlterTable        OpType = lib.SQLITE_ALTER_TABLE
	OpReindex           OpType = lib.SQLITE_REINDEX
	OpAnalyze           OpType = lib.SQLITE_ANALYZE
	OpCreateVTable      OpType = lib.SQLITE_CREATE_VTABLE
	OpDropVTable        OpType = lib.SQLITE_DROP_VTABLE
	OpFunction          OpType = lib.SQLITE_FUNCTION
	OpSavepoint         OpType = lib.SQLITE_SAVEPOINT
	OpCopy              OpType = lib.SQLITE_COPY
	OpRecursive         OpType = lib.SQLITE_RECURSIVE
)

Operation types

func (OpType) String added in v0.5.0

func (op OpType) String() string

String returns the C constant name of the operation type.

type OpenFlags

type OpenFlags uint

OpenFlags are flags used when opening a Conn.

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

func (OpenFlags) String

func (flags OpenFlags) String() string

String returns a pipe-separated list of the C constant names set in flags.

type ResultCode

type ResultCode int32

ResultCode is an SQLite extended result code.

const (
	ResultOK         ResultCode = lib.SQLITE_OK
	ResultError      ResultCode = lib.SQLITE_ERROR
	ResultInternal   ResultCode = lib.SQLITE_INTERNAL
	ResultPerm       ResultCode = lib.SQLITE_PERM
	ResultAbort      ResultCode = lib.SQLITE_ABORT
	ResultBusy       ResultCode = lib.SQLITE_BUSY
	ResultLocked     ResultCode = lib.SQLITE_LOCKED
	ResultNoMem      ResultCode = lib.SQLITE_NOMEM
	ResultReadOnly   ResultCode = lib.SQLITE_READONLY
	ResultInterrupt  ResultCode = lib.SQLITE_INTERRUPT
	ResultIOErr      ResultCode = lib.SQLITE_IOERR
	ResultCorrupt    ResultCode = lib.SQLITE_CORRUPT
	ResultNotFound   ResultCode = lib.SQLITE_NOTFOUND
	ResultFull       ResultCode = lib.SQLITE_FULL
	ResultCantOpen   ResultCode = lib.SQLITE_CANTOPEN
	ResultProtocol   ResultCode = lib.SQLITE_PROTOCOL
	ResultEmpty      ResultCode = lib.SQLITE_EMPTY
	ResultSchema     ResultCode = lib.SQLITE_SCHEMA
	ResultTooBig     ResultCode = lib.SQLITE_TOOBIG
	ResultConstraint ResultCode = lib.SQLITE_CONSTRAINT
	ResultMismatch   ResultCode = lib.SQLITE_MISMATCH
	ResultMisuse     ResultCode = lib.SQLITE_MISUSE
	ResultNoLFS      ResultCode = lib.SQLITE_NOLFS
	ResultAuth       ResultCode = lib.SQLITE_AUTH
	ResultFormat     ResultCode = lib.SQLITE_FORMAT
	ResultRange      ResultCode = lib.SQLITE_RANGE
	ResultNotADB     ResultCode = lib.SQLITE_NOTADB
	ResultNotice     ResultCode = lib.SQLITE_NOTICE
	ResultWarning    ResultCode = lib.SQLITE_WARNING
	ResultRow        ResultCode = lib.SQLITE_ROW
	ResultDone       ResultCode = lib.SQLITE_DONE
)

Primary result codes.

const (
	ResultErrorMissingCollSeq    ResultCode = lib.SQLITE_ERROR_MISSING_COLLSEQ
	ResultErrorRetry             ResultCode = lib.SQLITE_ERROR_RETRY
	ResultErrorSnapshot          ResultCode = lib.SQLITE_ERROR_SNAPSHOT
	ResultIOErrRead              ResultCode = lib.SQLITE_IOERR_READ
	ResultIOErrShortRead         ResultCode = lib.SQLITE_IOERR_SHORT_READ
	ResultIOErrWrite             ResultCode = lib.SQLITE_IOERR_WRITE
	ResultIOErrFsync             ResultCode = lib.SQLITE_IOERR_FSYNC
	ResultIOErrDirFsync          ResultCode = lib.SQLITE_IOERR_DIR_FSYNC
	ResultIOErrTruncate          ResultCode = lib.SQLITE_IOERR_TRUNCATE
	ResultIOErrFstat             ResultCode = lib.SQLITE_IOERR_FSTAT
	ResultIOErrUnlock            ResultCode = lib.SQLITE_IOERR_UNLOCK
	ResultIOErrReadLock          ResultCode = lib.SQLITE_IOERR_RDLOCK
	ResultIOErrDelete            ResultCode = lib.SQLITE_IOERR_DELETE
	ResultIOErrBlocked           ResultCode = lib.SQLITE_IOERR_BLOCKED
	ResultIOErrNoMem             ResultCode = lib.SQLITE_IOERR_NOMEM
	ResultIOErrAccess            ResultCode = lib.SQLITE_IOERR_ACCESS
	ResultIOErrCheckReservedLock ResultCode = lib.SQLITE_IOERR_CHECKRESERVEDLOCK
	ResultIOErrLock              ResultCode = lib.SQLITE_IOERR_LOCK
	ResultIOErrClose             ResultCode = lib.SQLITE_IOERR_CLOSE
	ResultIOErrDirClose          ResultCode = lib.SQLITE_IOERR_DIR_CLOSE
	ResultIOErrSHMOpen           ResultCode = lib.SQLITE_IOERR_SHMOPEN
	ResultIOErrSHMSize           ResultCode = lib.SQLITE_IOERR_SHMSIZE
	ResultIOErrSHMLock           ResultCode = lib.SQLITE_IOERR_SHMLOCK
	ResultIOErrSHMMap            ResultCode = lib.SQLITE_IOERR_SHMMAP
	ResultIOErrSeek              ResultCode = lib.SQLITE_IOERR_SEEK
	ResultIOErrDeleteNoEnt       ResultCode = lib.SQLITE_IOERR_DELETE_NOENT
	ResultIOErrMMap              ResultCode = lib.SQLITE_IOERR_MMAP
	ResultIOErrGetTempPath       ResultCode = lib.SQLITE_IOERR_GETTEMPPATH
	ResultIOErrConvPath          ResultCode = lib.SQLITE_IOERR_CONVPATH
	ResultIOErrVNode             ResultCode = lib.SQLITE_IOERR_VNODE
	ResultIOErrAuth              ResultCode = lib.SQLITE_IOERR_AUTH
	ResultIOErrBeginAtomic       ResultCode = lib.SQLITE_IOERR_BEGIN_ATOMIC
	ResultIOErrCommitAtomic      ResultCode = lib.SQLITE_IOERR_COMMIT_ATOMIC
	ResultIOErrRollbackAtomic    ResultCode = lib.SQLITE_IOERR_ROLLBACK_ATOMIC
	ResultLockedSharedCache      ResultCode = lib.SQLITE_LOCKED_SHAREDCACHE
	ResultBusyRecovery           ResultCode = lib.SQLITE_BUSY_RECOVERY
	ResultBusySnapshot           ResultCode = lib.SQLITE_BUSY_SNAPSHOT
	ResultCantOpenNoTempDir      ResultCode = lib.SQLITE_CANTOPEN_NOTEMPDIR
	ResultCantOpenIsDir          ResultCode = lib.SQLITE_CANTOPEN_ISDIR
	ResultCantOpenFullPath       ResultCode = lib.SQLITE_CANTOPEN_FULLPATH
	ResultCantOpenConvPath       ResultCode = lib.SQLITE_CANTOPEN_CONVPATH
	ResultCorruptVTab            ResultCode = lib.SQLITE_CORRUPT_VTAB
	ResultReadOnlyRecovery       ResultCode = lib.SQLITE_READONLY_RECOVERY
	ResultReadOnlyCantLock       ResultCode = lib.SQLITE_READONLY_CANTLOCK
	ResultReadOnlyRollback       ResultCode = lib.SQLITE_READONLY_ROLLBACK
	ResultReadOnlyDBMoved        ResultCode = lib.SQLITE_READONLY_DBMOVED
	ResultReadOnlyCantInit       ResultCode = lib.SQLITE_READONLY_CANTINIT
	ResultReadOnlyDirectory      ResultCode = lib.SQLITE_READONLY_DIRECTORY
	ResultAbortRollback          ResultCode = lib.SQLITE_ABORT_ROLLBACK
	ResultConstraintCheck        ResultCode = lib.SQLITE_CONSTRAINT_CHECK
	ResultConstraintCommitHook   ResultCode = lib.SQLITE_CONSTRAINT_COMMITHOOK
	ResultConstraintForeignKey   ResultCode = lib.SQLITE_CONSTRAINT_FOREIGNKEY
	ResultConstraintFunction     ResultCode = lib.SQLITE_CONSTRAINT_FUNCTION
	ResultConstraintNotNull      ResultCode = lib.SQLITE_CONSTRAINT_NOTNULL
	ResultConstraintPrimaryKey   ResultCode = lib.SQLITE_CONSTRAINT_PRIMARYKEY
	ResultConstraintTrigger      ResultCode = lib.SQLITE_CONSTRAINT_TRIGGER
	ResultConstraintUnique       ResultCode = lib.SQLITE_CONSTRAINT_UNIQUE
	ResultConstraintVTab         ResultCode = lib.SQLITE_CONSTRAINT_VTAB
	ResultConstraintRowID        ResultCode = lib.SQLITE_CONSTRAINT_ROWID
	ResultNoticeRecoverWAL       ResultCode = lib.SQLITE_NOTICE_RECOVER_WAL
	ResultNoticeRecoverRollback  ResultCode = lib.SQLITE_NOTICE_RECOVER_ROLLBACK
	ResultWarningAutoIndex       ResultCode = lib.SQLITE_WARNING_AUTOINDEX
	ResultAuthUser               ResultCode = lib.SQLITE_AUTH_USER
)

Extended result codes.

func ErrCode

func ErrCode(err error) ResultCode

ErrCode returns the error's SQLite error code or ResultError if the error does not represent a SQLite error. ErrorCode returns ResultOK if and only if the error is nil.

func (ResultCode) IsSuccess

func (code ResultCode) IsSuccess() bool

IsSuccess reports whether code indicates success.

func (ResultCode) Message

func (code ResultCode) Message() string

Message returns the English-language text that describes the result code.

func (ResultCode) String

func (code ResultCode) String() string

String returns the C constant name of the result code.

func (ResultCode) ToError added in v0.9.0

func (code ResultCode) ToError() error

ToError converts an error code into an error for which ErrCode(code.ToError()) == code. If the code indicates success, ToError returns nil.

func (ResultCode) ToPrimary

func (code ResultCode) ToPrimary() ResultCode

ToPrimary returns the primary result code of the given code. https://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes

type Session added in v0.6.0

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

A Session tracks database changes made by a Conn. It is used to build changesets.

For more details: https://www.sqlite.org/sessionintro.html

func (*Session) Attach added in v0.6.0

func (s *Session) Attach(tableName string) error

Attach attaches a table to the session object. Changes made to the table will be tracked by the session. An empty tableName attaches all the tables in the database.

func (*Session) Delete added in v0.6.0

func (s *Session) Delete()

Delete releases any resources associated with the session. It must be called before closing the Conn the session is attached to.

func (*Session) Diff added in v0.6.0

func (s *Session) Diff(srcDB, tableName string) error

Diff appends the difference between two tables (srcDB and the session DB) to the session. The two tables must have the same name and schema.

https://www.sqlite.org/session/sqlite3session_diff.html

func (*Session) Disable added in v0.6.0

func (s *Session) Disable()

Disable disables recording of changes.

https://www.sqlite.org/session/sqlite3session_enable.html

func (*Session) Enable added in v0.6.0

func (s *Session) Enable()

Enable enables recording of changes after a previous call to Disable. New sessions start enabled.

https://www.sqlite.org/session/sqlite3session_enable.html

func (*Session) WriteChangeset added in v0.6.0

func (s *Session) WriteChangeset(w io.Writer) error

WriteChangeset generates a changeset from a session.

https://www.sqlite.org/session/sqlite3session_changeset.html

func (*Session) WritePatchset added in v0.6.0

func (s *Session) WritePatchset(w io.Writer) error

WritePatchset generates a patchset from a session.

https://www.sqlite.org/session/sqlite3session_patchset.html

type Stmt

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

Stmt is an SQLite3 prepared statement.

A Stmt is attached to a particular Conn (and that Conn can only be used by a single goroutine).

When a Stmt is no longer needed it should be cleaned up by calling the Finalize method.

func (*Stmt) BindBool

func (stmt *Stmt) BindBool(param int, value bool)

BindBool binds value (as an integer 0 or 1) to a numbered stmt parameter.

Parameter indices start at 1.

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

func (*Stmt) BindBytes

func (stmt *Stmt) BindBytes(param int, value []byte)

BindBytes binds value to a numbered stmt parameter.

In-memory copies of value are made using this interface. For large blobs, consider using the streaming Blob object.

Parameter indices start at 1.

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

func (*Stmt) BindFloat

func (stmt *Stmt) BindFloat(param int, value float64)

BindFloat binds value to a numbered stmt parameter.

Parameter indices start at 1.

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

func (*Stmt) BindInt64

func (stmt *Stmt) BindInt64(param int, value int64)

BindInt64 binds value to a numbered stmt parameter.

Parameter indices start at 1.

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

func (*Stmt) BindNull

func (stmt *Stmt) BindNull(param int)

BindNull binds an SQL NULL value to a numbered stmt parameter.

Parameter indices start at 1.

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

func (*Stmt) BindParamCount

func (stmt *Stmt) BindParamCount() int

BindParamCount reports the number of parameters in stmt.

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

func (*Stmt) BindParamName

func (stmt *Stmt) BindParamName(i int) string

BindParamName returns the name of parameter or the empty string if the parameter is nameless or i is out of range.

Parameters indices start at 1.

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

func (*Stmt) BindText

func (stmt *Stmt) BindText(param int, value string)

BindText binds value to a numbered stmt parameter.

Parameter indices start at 1.

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

func (*Stmt) BindZeroBlob

func (stmt *Stmt) BindZeroBlob(param int, len int64)

BindZeroBlob binds a blob of zeros of length len to a numbered stmt parameter.

Parameter indices start at 1.

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

func (*Stmt) ClearBindings

func (stmt *Stmt) ClearBindings() error

ClearBindings clears all bound parameter values on a statement.

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

func (*Stmt) ColumnBool added in v0.9.0

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

ColumnBool reports whether a query result value is non-zero.

Column indices start at 0.

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

func (*Stmt) ColumnBytes

func (stmt *Stmt) ColumnBytes(col int, buf []byte) int

ColumnBytes reads a query result into buf. It reports the number of bytes read.

Column indices start at 0.

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

func (*Stmt) ColumnCount

func (stmt *Stmt) ColumnCount() int

ColumnCount returns the number of columns in the result set returned by the prepared statement.

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

func (*Stmt) ColumnDatabaseName

func (stmt *Stmt) ColumnDatabaseName(col int) string

func (*Stmt) ColumnFloat

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

ColumnFloat returns a query result as a float64.

Column indices start at 0.

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

func (*Stmt) ColumnIndex

func (stmt *Stmt) ColumnIndex(colName string) int

ColumnIndex returns the index of the column with the given name.

If there is no column with the given name ColumnIndex returns -1.

func (*Stmt) ColumnInt

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

ColumnInt returns a query result value as an int.

Note: this method calls sqlite3_column_int64 and then converts the resulting 64-bits to an int.

Column indices start at 0.

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

func (*Stmt) ColumnInt32

func (stmt *Stmt) ColumnInt32(col int) int32

ColumnInt32 returns a query result value as an int32.

Column indices start at 0.

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

func (*Stmt) ColumnInt64

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

ColumnInt64 returns a query result value as an int64.

Column indices start at 0.

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

func (*Stmt) ColumnLen

func (stmt *Stmt) ColumnLen(col int) int

ColumnLen returns the number of bytes in a query result.

Column indices start at 0.

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

func (*Stmt) ColumnName

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

ColumnName returns the name assigned to a particular column in the result set of a SELECT statement.

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

func (*Stmt) ColumnReader

func (stmt *Stmt) ColumnReader(col int) *bytes.Reader

ColumnReader creates a byte reader for a query result column.

The reader directly references C-managed memory that stops being valid as soon as the statement row resets.

func (*Stmt) ColumnTableName

func (stmt *Stmt) ColumnTableName(col int) string

func (*Stmt) ColumnText

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

ColumnText returns a query result as a string.

Column indices start at 0.

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

func (*Stmt) ColumnType

func (stmt *Stmt) ColumnType(col int) ColumnType

ColumnType returns the datatype code for the initial data type of the result column. The returned value is one of:

SQLITE_INTEGER
SQLITE_FLOAT
SQLITE_TEXT
SQLITE_BLOB
SQLITE_NULL

Column indices start at 0.

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

func (*Stmt) DataCount

func (stmt *Stmt) DataCount() int

DataCount returns the number of columns in the current row of the result set of prepared statement.

https://sqlite.org/c3ref/data_count.html

func (*Stmt) Finalize

func (stmt *Stmt) Finalize() error

Finalize deletes a prepared statement.

Be sure to always call Finalize when done with a statement created using PrepareTransient.

Do not call Finalize on a prepared statement that you intend to prepare again in the future.

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

func (*Stmt) GetBool added in v0.9.0

func (stmt *Stmt) GetBool(colName string) bool

GetBool reports whether the query result value for colName is non-zero.

func (*Stmt) GetBytes

func (stmt *Stmt) GetBytes(colName string, buf []byte) int

GetBytes reads a query result for colName into buf. It reports the number of bytes read.

func (*Stmt) GetFloat

func (stmt *Stmt) GetFloat(colName string) float64

GetFloat returns a query result value for colName as a float64.

func (*Stmt) GetInt64

func (stmt *Stmt) GetInt64(colName string) int64

GetInt64 returns a query result value for colName as an int64.

func (*Stmt) GetLen

func (stmt *Stmt) GetLen(colName string) int

GetLen returns the number of bytes in a query result for colName.

func (*Stmt) GetReader

func (stmt *Stmt) GetReader(colName string) *bytes.Reader

GetReader creates a byte reader for colName.

The reader directly references C-managed memory that stops being valid as soon as the statement row resets.

func (*Stmt) GetText

func (stmt *Stmt) GetText(colName string) string

GetText returns a query result value for colName as a string.

func (*Stmt) Reset

func (stmt *Stmt) Reset() error

Reset resets a prepared statement so it can be executed again.

Note that any parameter values bound to the statement are retained. To clear bound values, call ClearBindings.

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

func (*Stmt) SetBool

func (stmt *Stmt) SetBool(param string, value bool)

SetBool binds a value (as a 0 or 1) to a parameter using a column name.

func (*Stmt) SetBytes

func (stmt *Stmt) SetBytes(param string, value []byte)

SetBytes binds bytes to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.

func (*Stmt) SetFloat

func (stmt *Stmt) SetFloat(param string, value float64)

SetFloat binds a float64 to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.

func (*Stmt) SetInt64

func (stmt *Stmt) SetInt64(param string, value int64)

SetInt64 binds an int64 to a parameter using a column name.

func (*Stmt) SetNull

func (stmt *Stmt) SetNull(param string)

SetNull binds a null to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.

func (*Stmt) SetText

func (stmt *Stmt) SetText(param string, value string)

SetText binds text to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.

func (*Stmt) SetZeroBlob

func (stmt *Stmt) SetZeroBlob(param string, len int64)

SetZeroBlob binds a zero blob of length len to a parameter using a column name. An invalid parameter name will cause the call to Step to return an error.

func (*Stmt) Step

func (stmt *Stmt) Step() (rowReturned bool, err error)

Step moves through the statement cursor using sqlite3_step.

If a row of data is available, rowReturned is reported as true. If the statement has reached the end of the available data then rowReturned is false. Thus the status codes SQLITE_ROW and SQLITE_DONE are reported by the rowReturned bool, and all other non-OK status codes are reported as an error.

If an error value is returned, then the statement has been reset.

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

Shared cache

As the sqlite package enables shared cache mode by default and multiple writers are common in multi-threaded programs, this Step method uses sqlite3_unlock_notify to handle any SQLITE_LOCKED errors.

Without the shared cache, SQLite will block for several seconds while trying to acquire the write lock. With the shared cache, it returns SQLITE_LOCKED immediately if the write lock is held by another connection in this process. Dealing with this correctly makes for an unpleasant programming experience, so this package does it automatically by blocking Step until the write lock is relinquished.

This means Step can block for a very long time. Use SetInterrupt to control how long Step will block.

For far more details, see:

http://www.sqlite.org/unlock_notify.html

type Value

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

Value represents a value that can be stored in a database table. The zero value is NULL. The accessor methods on Value may perform automatic conversions and thus methods on Value must not be called concurrently.

func BlobValue added in v0.2.0

func BlobValue(b []byte) Value

BlobValue returns a new blob Value, copying the bytes from the given byte slice.

func FloatValue added in v0.2.0

func FloatValue(f float64) Value

FloatValue returns a new Value representing the given floating-point number.

func IntegerValue added in v0.2.0

func IntegerValue(i int64) Value

IntegerValue returns a new Value representing the given integer.

func TextValue added in v0.2.0

func TextValue(s string) Value

TextValue returns a new Value representing the given string.

func (Value) Blob

func (v Value) Blob() []byte

Blob returns a copy of the value as a blob.

func (Value) Float

func (v Value) Float() float64

Float returns the value as floating-point number

func (Value) Int

func (v Value) Int() int

Int returns the value as an integer.

func (Value) Int64

func (v Value) Int64() int64

Int64 returns the value as a 64-bit integer.

func (Value) Text

func (v Value) Text() string

Text returns the value as a string.

func (Value) Type

func (v Value) Type() ColumnType

Type returns the data type of the value. The result of Type is undefined if an automatic type conversion has occurred due to calling one of the other accessor methods.

Directories

Path Synopsis
cmd
Package fs provides a fallback for the io/fs package in Go 1.16.
Package fs provides a fallback for the io/fs package in Go 1.16.
Package shell provides a minimal SQLite REPL, similar to the built-in one.
Package shell provides a minimal SQLite REPL, similar to the built-in one.
Package sqlitefile provides bytes buffers backed by a temporary SQLite table.
Package sqlitefile provides bytes buffers backed by a temporary SQLite table.
Package sqlitemigration provides a connection pool type that guarantees a series of SQL scripts has been run once successfully before making connections available to the application.
Package sqlitemigration provides a connection pool type that guarantees a series of SQL scripts has been run once successfully before making connections available to the application.
Package sqlitex provides utilities for working with SQLite.
Package sqlitex provides utilities for working with SQLite.

Jump to

Keyboard shortcuts

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