sqlite

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: ISC Imports: 15 Imported by: 33

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. See the official C API introduction for an overview of the basics.

An SQLite connection is represented by a *Conn. Connections cannot be used concurrently. A typical Go program will create a pool of connections (e.g. by using zombiezen.com/go/sqlite/sqlitex.NewPool to create a *zombiezen.com/go/sqlite/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.

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 to make it easier to execute statements, see the zombiezen.com/go/sqlite/sqlitex package.

Statement Caching

Statements are prepared with the Conn.Prepare and Conn.PrepareTransient methods. When using Conn.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.

Transactions

SQLite transactions can be managed manually with this package by directly executing BEGIN / COMMIT / ROLLBACK or SAVEPOINT / RELEASE / ROLLBACK statements, but there are also helper functions available in zombiezen.com/go/sqlite/sqlitex:

Schema Migrations

For simple schema migration needs, see the zombiezen.com/go/sqlite/sqlitemigration package.

User-Defined Functions

Use Conn.CreateFunction to register Go functions for use as SQL functions.

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.) See Conn.OpenBlob for more details.

Deadlines and Cancellation

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

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

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:")
	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.NewPool("file:memory:?mode=memory", sqlitex.PoolOptions{
		PoolSize: 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, err := dbpool.Take(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusServiceUnavailable)
		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:")
	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 ErrorOffset added in v1.2.0

func ErrorOffset(err error) (offset int, ok bool)

ErrorOffset returns the byte offset of the start of the SQL token that the error references if known.

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 AggregateFunction added in v0.11.0

type AggregateFunction interface {
	// Step is called for each row
	// of an aggregate function's SQL invocation.
	// The argument Values are not valid past the return of the function.
	Step(ctx Context, rowArgs []Value) error

	// WindowInverse is called to remove
	// the oldest presently aggregated result of Step
	// from the current window.
	// The arguments are those passed to Step for the row being removed.
	// The argument Values are not valid past the return of the function.
	WindowInverse(ctx Context, rowArgs []Value) error

	// WindowValue is called to get the current value of an aggregate function.
	WindowValue(ctx Context) (Value, error)

	// Finalize is called after all of the aggregate function's input rows
	// have been stepped through.
	// No other methods will be called on the AggregateFunction after calling Finalize.
	Finalize(ctx Context)
}

An AggregateFunction is an invocation of an aggregate function. See the documentation for aggregate function callbacks and application-defined window functions for an overview.

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 Backup added in v0.12.0

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

A Backup represents a copy operation between two database connections. See https://www.sqlite.org/backup.html for more details.

Example

This example shows the basic use of a backup object.

package main

import (
	"fmt"
	"os"

	"zombiezen.com/go/sqlite"
)

func main() {
	// Open database connections.
	src, err := sqlite.OpenConn(os.Args[1])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer src.Close()
	dst, err := sqlite.OpenConn(os.Args[2])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer func() {
		if err := dst.Close(); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
	}()

	// Create Backup object.
	backup, err := sqlite.NewBackup(dst, "main", src, "main")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	// Perform online backup/copy.
	_, err1 := backup.Step(-1)
	err2 := backup.Close()
	if err1 != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err2 != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Output:

func NewBackup added in v0.12.0

func NewBackup(dst *Conn, dstName string, src *Conn, srcName string) (*Backup, error)

NewBackup creates a Backup that copies from one connection to another. The database name is "main" or "" for the main database, "temp" for the temporary database, or the name specified after the AS keyword in an ATTACH statement for an attached database. If src and dst are the same connection, NewBackup will return an error. It is the caller's responsibility to call Backup.Close on the returned Backup object.

func (*Backup) Close added in v0.12.0

func (b *Backup) Close() error

Close releases all resources associated with the backup. If Backup.Step has not yet returned (false, nil), then any active write transaction on the destination database is rolled back.

func (*Backup) PageCount added in v0.12.0

func (b *Backup) PageCount() int

PageCount returns the total number of pages in the source database at the conclusion of the most recent call to Backup.Step. The return value of PageCount before calling Backup.Step is undefined. If the source database is modified in a way that changes the size of the source database, that change is not reflected in the output until after the next call to Backup.Step.

func (*Backup) Remaining added in v0.12.0

func (b *Backup) Remaining() int

Remaining returns the number of pages still to be backed up at the conclusion of the most recent call to Backup.Step. The return value of Remaining before calling Backup.Step is undefined. If the source database is modified in a way that changes the number of pages remaining, that change is not reflected in the output until after the next call to Backup.Step.

func (*Backup) Step added in v0.12.0

func (b *Backup) Step(n int) (more bool, err error)

Step copies up to n pages from the source database to the destination database. If n is negative, all remaining source pages are copied. more will be true if there are pages still remaining to be copied. Step may return both an error and that more pages are still remaining: this indicates the error is temporary and that Step can be retried.

Example

This example shows how to use Step to prevent holding a read lock on the source database during the entire copy.

package main

import (
	"fmt"
	"os"
	"time"

	"zombiezen.com/go/sqlite"
)

func main() {
	// Open database connections.
	src, err := sqlite.OpenConn(os.Args[1])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer src.Close()
	dst, err := sqlite.OpenConn(os.Args[2])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer func() {
		if err := dst.Close(); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
	}()

	// Create Backup object.
	backup, err := sqlite.NewBackup(dst, "main", src, "main")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer func() {
		if err := backup.Close(); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
	}()

	// Each iteration of this loop copies 5 database pages,
	// waiting 250ms between iterations.
	for {
		more, err := backup.Step(5)
		if !more {
			if err != nil {
				fmt.Fprintln(os.Stderr, err)
				os.Exit(1)
			}
			break
		}
		time.Sleep(250 * time.Millisecond)
	}
}
Output:

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:")
	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: []any{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 CollatingFunc added in v0.13.0

type CollatingFunc func(a, b string) int

CollatingFunc is a collating function/sequence, that is, a function that compares two strings. The function returns a negative number if a < b, a positive number if a > b, or zero if a == b. A collating function must always return the same answer given the same inputs. The collating function must obey the following properties for all strings A, B, and C:

  1. If A==B then B==A.
  2. If A==B and B==C then A==C.
  3. If A<B then B>A.
  4. If A<B and B<C then A<C.

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 one 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:

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

This example shows how to register a basic scalar function.

If you're looking to use regular expressions in your application, use zombiezen.com/go/sqlite/ext/refunc.Register.

package main

import (
	"fmt"
	"regexp"

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

func main() {
	conn, err := sqlite.OpenConn(":memory:")
	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) Deserialize added in v0.13.0

func (c *Conn) Deserialize(dbName string, data []byte) error

Deserialize disconnects the database with the given name (e.g. "main") and reopens it as an in-memory database based on the serialized data. The database name must already exist. It is not possible to deserialize into the TEMP database.

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) Serialize added in v0.13.0

func (c *Conn) Serialize(dbName string) ([]byte, error)

Serialize serializes the database with the given name (e.g. "main" or "temp").

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:")
	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) SetCollation added in v0.13.0

func (c *Conn) SetCollation(name string, compare CollatingFunc) error

SetCollation sets the collating function for the given name.

Example
package main

import (
	"fmt"

	"golang.org/x/text/collate"
	"golang.org/x/text/language"
	"zombiezen.com/go/sqlite"
	"zombiezen.com/go/sqlite/sqlitex"
)

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

	// Override the built-in NOCASE collating sequence
	// to be Unicode aware.
	nocaseCollator := collate.New(language.Und, collate.IgnoreCase)
	if err := conn.SetCollation("NOCASE", nocaseCollator.CompareString); err != nil {
		// handle error
	}

	// Create a table that uses the NOCASE collating sequence.
	err = sqlitex.ExecuteScript(conn, `
		CREATE TABLE foo (mytext TEXT COLLATE NOCASE);

		INSERT INTO foo VALUES
			('atext'),
			('btext'),
			('ctext'),
			('ątext'),
			('ćtext');
	`, nil)
	if err != nil {
		// handle error
	}

	// The column will be implicitly ordered using its collating sequence.
	err = sqlitex.ExecuteTransient(conn, `SELECT mytext FROM foo ORDER BY mytext ASC;`, &sqlitex.ExecOptions{
		ResultFunc: func(stmt *sqlite.Stmt) error {
			fmt.Println(stmt.ColumnText(0))
			return nil
		},
	})
	if err != nil {
		// handle error
	}
}
Output:

atext
ątext
btext
ctext
ćtext

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

func (*Conn) SetModule added in v0.13.0

func (c *Conn) SetModule(name string, module *Module) error

SetModule registers or unregisters a virtual table module with the given name.

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

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.

This is the implementation used in zombiezen.com/go/sqlite/ext/refunc.

package main

import (
	"fmt"
	"regexp"

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

func main() {
	conn, err := sqlite.OpenConn(":memory:")
	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 any)

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.
	// The argument Values are not valid past the return of the function.
	Scalar func(ctx Context, args []Value) (Value, error)

	// MakeAggregate is called at the beginning of an evaluation of an aggregate function.
	MakeAggregate func(ctx Context) (AggregateFunction, 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.
	AllowIndirect bool
}

FunctionImpl describes an application-defined SQL function. Either Scalar or MakeAggregate must be set, but not both.

type IndexConstraint added in v0.13.0

type IndexConstraint struct {
	// Column is the left-hand operand.
	// Column indices start at 0.
	// -1 indicates the left-hand operand is the rowid.
	// Column should be ignored when Op is [IndexConstraintLimit] or [IndexConstraintOffset].
	Column int
	// Op is the constraint's operator.
	Op IndexConstraintOp
	// Usable indicates whether BestIndex should consider the constraint.
	// Usable may false depending on how tables are ordered in a join.
	Usable bool
	// Collation is the name of the collating sequence
	// that should be used when evaluating the constraint.
	Collation string
	// RValue is the right-hand operand, if known during statement preparation.
	// It's only valid until the end of BestIndex.
	RValue Value
	// RValueKnown indicates whether RValue is set.
	RValueKnown bool
}

IndexConstraint is a constraint term in the WHERE clause of a query that uses a virtual table.

type IndexConstraintOp added in v0.13.0

type IndexConstraintOp uint8

IndexConstraintOp is an enumeration of virtual table constraint operators used in IndexConstraint.

func (IndexConstraintOp) String added in v0.13.0

func (op IndexConstraintOp) String() string

String returns the operator symbol or keyword.

type IndexConstraintUsage added in v0.13.0

type IndexConstraintUsage struct {
	// ArgvIndex is the intended [VTableCursor] Filter argument index plus one.
	// If ArgvIndex is zero or negative,
	// then the constraint is not passed to Filter.
	// Within the [IndexOutputs] ConstraintUsage list,
	// there must be exactly one entry with an ArgvIndex of 1,
	// another of 2, another of 3, and so forth
	// to as many or as few as the [VTable] BestIndex method wants.
	ArgvIndex int
	// If Omit is true, then it is a hint to SQLite
	// that the virtual table will guarantee that the constraint will always be satisfied.
	// SQLite will always double-check that rows satisfy the constraint if Omit is false,
	// but may skip this check if Omit is true.
	Omit bool
}

IndexConstraintUsage maps a single constraint from IndexInputs Constraints to a VTableCursor Filter argument in the IndexOutputs ConstraintUsage list.

type IndexFlags added in v0.13.0

type IndexFlags uint32

IndexFlags is a bitmap of options returned in [IndexOutputs.IndexFlags].

const (
	// IndexScanUnique indicates that the virtual table
	// will only return zero or one rows given the input constraints.
	IndexScanUnique IndexFlags = lib.SQLITE_INDEX_SCAN_UNIQUE
)

type IndexID added in v0.13.0

type IndexID struct {
	Num    int32
	String string
}

IndexID is a virtual table index identifier. The meaning of its fields is defined by the virtual table implementation. String cannot contain NUL bytes.

type IndexInputs added in v0.13.0

type IndexInputs struct {
	// Constraints corresponds to the WHERE clause.
	Constraints []IndexConstraint
	// OrderBy corresponds to the ORDER BY clause.
	OrderBy []IndexOrderBy
	// ColumnsUsed is a bitmask of columns used by the statement.
	ColumnsUsed uint64
}

IndexInputs is the set of arguments that the SQLite core passes to the VTable BestIndex function.

type IndexOrderBy added in v0.13.0

type IndexOrderBy struct {
	// Column is column index.
	// Column indices start at 0.
	Column int
	// Desc is true if descending or false if ascending.
	Desc bool
}

IndexOrderBy is a term in the ORDER BY clause.

type IndexOutputs added in v0.13.0

type IndexOutputs struct {
	// ConstraintUsage is a mapping from [IndexInputs] Constraints
	// to [VTableCursor] Filter arguments.
	// The mapping is in the same order as [IndexInputs] Constraints
	// and must not contain more than len(IndexInputs.Constraints) elements.
	// If len(ConstraintUsage) < len(IndexInputs.Constraints),
	// then ConstraintUsage is treated as if the missing elements have the zero value.
	ConstraintUsage []IndexConstraintUsage
	// ID is used to identify the index in [VTableCursor] Filter.
	ID IndexID
	// OrderByConsumed is true if the output is already ordered.
	OrderByConsumed bool
	// EstimatedCost is an estimate of the cost of a particular strategy.
	// A cost of N indicates that the cost of the strategy
	// is similar to a linear scan of an SQLite table with N rows.
	// A cost of log(N) indicates that the expense of the operation
	// is similar to that of a binary search on a unique indexed field
	// of an SQLite table with N rows.
	// A negative or zero cost uses a large default cost unless UseZeroEstimates is true.
	EstimatedCost float64
	// EstimatedRows is an estimate of the number of rows
	// that will be returned by the strategy.
	// A negative or zero estimate uses 25 unless UseZeroEstimates is true.
	EstimatedRows int64
	// If UseZeroEstimates is true and EstimatedCost or EstimatedRows is zero,
	// then the zeroes will be used instead of being interpreted as defaults.
	UseZeroEstimates bool
	// IndexFlags is a bitmask of other flags about the index.
	IndexFlags IndexFlags
}

IndexOutputs is the information that the VTable BestIndex function returns to the SQLite core.

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 Module added in v0.13.0

type Module struct {
	// Connect establishes a connection to an existing virtual table.
	// This is the only required field.
	Connect VTableConnectFunc
	// Create is called to create a new instance of the virtual table
	// in response to a [CREATE VIRTUAL TABLE statement].
	// If it is nil, then the virtual table is [eponymous].
	// UseConnectAsCreate determines whether the virtual table is eponymous-only.
	//
	// [CREATE VIRTUAL TABLE statement]: https://sqlite.org/lang_createvtab.html
	// [eponymous]: https://sqlite.org/vtab.html#epovtab
	Create VTableConnectFunc
	// If UseConnectAsCreate is true and Create is nil,
	// then the virtual table is eponymous, but not eponymous-only.
	// This means that the virtual table can still be given a name
	// with CREATE VIRTUAL TABLE
	// and indicates that the virtual table has no persistent state
	// that needs to be created and destroyed.
	UseConnectAsCreate bool
}

A Module declares a virtual table that can be registered with a Conn via Conn.SetModule.

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 via OpenConn.

const (
	// OpenReadOnly opens the database in read-only mode.
	// If the database does not already exist, an error is returned.
	OpenReadOnly OpenFlags = lib.SQLITE_OPEN_READONLY
	// OpenReadWrite opens the database for reading and writing if possible,
	// or reading only if the file is write protected by the operating system.
	// If the database does not already exist,
	// an error is returned unless OpenCreate is also passed.
	OpenReadWrite OpenFlags = lib.SQLITE_OPEN_READWRITE
)

One of the following flags must be passed to OpenConn.

const (
	// OpenCreate will create the file if it does not already exist.
	// It is only valid with [OpenReadWrite].
	OpenCreate OpenFlags = lib.SQLITE_OPEN_CREATE
	// OpenURI allows the path to be interpreted as a URI.
	OpenURI OpenFlags = lib.SQLITE_OPEN_URI
	// OpenMemory will be opened as an in-memory database.
	// The path is ignored unless [OpenSharedCache] is used.
	OpenMemory OpenFlags = lib.SQLITE_OPEN_MEMORY
	// OpenSharedCache opens the database with [shared-cache].
	// This is mostly only useful for sharing in-memory databases:
	// it's [not recommended] for other purposes.
	//
	// [shared-cache]: https://www.sqlite.org/sharedcache.html
	// [not recommended]: https://www.sqlite.org/sharedcache.html#dontuse
	OpenSharedCache OpenFlags = lib.SQLITE_OPEN_SHAREDCACHE
	// OpenPrivateCache forces the database to not use shared-cache.
	OpenPrivateCache OpenFlags = lib.SQLITE_OPEN_PRIVATECACHE
	// OpenWAL enables the [write-ahead log] for the database.
	//
	// [write-ahead log]: https://www.sqlite.org/wal.html
	OpenWAL OpenFlags = lib.SQLITE_OPEN_WAL

	// OpenNoMutex has no effect.
	//
	// Deprecated: This flag is now implied.
	OpenNoMutex OpenFlags = lib.SQLITE_OPEN_NOMUTEX
	// OpenFullMutex has no effect.
	//
	// Deprecated: This flag has no equivalent and is ignored.
	OpenFullMutex OpenFlags = lib.SQLITE_OPEN_FULLMUTEX
)

Optional flags to pass to OpenConn.

func (OpenFlags) String

func (flags OpenFlags) String() string

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

type RenameVTable added in v0.13.0

type RenameVTable interface {
	VTable
	Rename(new string) error
}

A RenameVTable is a VTable that supports its non-eponymous form being renamed.

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. ErrCode 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 SavepointVTable added in v0.13.0

type SavepointVTable interface {
	TransactionVTable

	// Savepoint signals that the virtual table
	// should save its current state as savepoint N.
	Savepoint(n int) error
	// Release invalidates all savepoints greater than or equal to n.
	Release(n int) error
	// RollbackTo signals that the state of the virtual table
	// should return to what it was when Savepoint(n) was last called.
	// This invalidates all savepoints greater than n.
	RollbackTo(n int) error
}

A SavepointVTable is a VTable that supports savepoints.

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) ColumnIsNull added in v1.0.0

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

ColumnIsNull reports whether the result column holds NULL. Column indices start at 0.

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) IsNull added in v1.0.0

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

IsNull reports whether a query result value for colName is NULL.

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 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 TransactionVTable added in v0.13.0

type TransactionVTable interface {
	VTable

	// Begin begins a transaction on a virtual table.
	// Virtual table transactions do not nest,
	// so the Begin method will not be invoked more than once
	// on a single virtual table
	// without an intervening call to either Commit or Rollback.
	Begin() error
	// Sync signals the start of a two-phase commit on a virtual table.
	// This method is only invoked after a call to the Begin method
	// and prior to a Commit or Rollback.
	Sync() error
	// Commit causes a virtual table transaction to commit.
	Commit() error
	// Rollback causes a virtual table transaction to rollback.
	Rollback() error
}

A TransactionVTable is a VTable that supports transactions.

type VTable added in v0.13.0

type VTable interface {
	// BestIndex informs SQLite the best way to access the virtual table.
	// While compiling a single SQL query,
	// the SQLite core might call BestIndex multiple times with different inputs.
	// The SQLite core will then select the combination
	// that appears to give the best performance.
	BestIndex(*IndexInputs) (*IndexOutputs, error)
	// Open creates a new cursor.
	Open() (VTableCursor, error)
	// Disconnect releases any resources associated with the virtual table.
	Disconnect() error
	// Destroy is called when the table is "DROP"ed
	// to tear down any persistent data structures
	// and release any resources associated with the virtual table.
	Destroy() error
}

VTable represents a connected virtual table.

Example
package main

import (
	"fmt"
	"log"

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

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

	err = conn.SetModule("templatevtab", &sqlite.Module{
		Connect: templatevtabConnect,
	})
	if err != nil {
		log.Fatal(err)
	}
	err = sqlitex.ExecuteTransient(
		conn,
		`SELECT a, b FROM templatevtab ORDER BY rowid;`,
		&sqlitex.ExecOptions{
			ResultFunc: func(stmt *sqlite.Stmt) error {
				fmt.Printf("%4d, %4d\n", stmt.ColumnInt(0), stmt.ColumnInt(1))
				return nil
			},
		},
	)
	if err != nil {
		log.Fatal(err)
	}

}

type templatevtab struct{}

const (
	templatevarColumnA = iota
	templatevarColumnB
)

func templatevtabConnect(c *sqlite.Conn, opts *sqlite.VTableConnectOptions) (sqlite.VTable, *sqlite.VTableConfig, error) {
	vtab := new(templatevtab)
	cfg := &sqlite.VTableConfig{
		Declaration: "CREATE TABLE x(a,b)",
	}
	return vtab, cfg, nil
}

func (vt *templatevtab) BestIndex(*sqlite.IndexInputs) (*sqlite.IndexOutputs, error) {
	return &sqlite.IndexOutputs{
		EstimatedCost: 10,
		EstimatedRows: 10,
	}, nil
}

func (vt *templatevtab) Open() (sqlite.VTableCursor, error) {
	return &templatevtabCursor{rowid: 1}, nil
}

func (vt *templatevtab) Disconnect() error {
	return nil
}

func (vt *templatevtab) Destroy() error {
	return nil
}

type templatevtabCursor struct {
	rowid int64
}

func (cur *templatevtabCursor) Filter(id sqlite.IndexID, argv []sqlite.Value) error {
	cur.rowid = 1
	return nil
}

func (cur *templatevtabCursor) Next() error {
	cur.rowid++
	return nil
}

func (cur *templatevtabCursor) Column(i int, noChange bool) (sqlite.Value, error) {
	switch i {
	case templatevarColumnA:
		return sqlite.IntegerValue(1000 + cur.rowid), nil
	case templatevarColumnB:
		return sqlite.IntegerValue(2000 + cur.rowid), nil
	default:
		panic("unreachable")
	}
}

func (cur *templatevtabCursor) RowID() (int64, error) {
	return cur.rowid, nil
}

func (cur *templatevtabCursor) EOF() bool {
	return cur.rowid > 10
}

func (cur *templatevtabCursor) Close() error {
	return nil
}
Output:

1001, 2001
1002, 2002
1003, 2003
1004, 2004
1005, 2005
1006, 2006
1007, 2007
1008, 2008
1009, 2009
1010, 2010

type VTableConfig added in v0.13.0

type VTableConfig struct {
	// Declaration must be a [CREATE TABLE statement]
	// that defines the columns in the virtual table and their data type.
	// The name of the table in this CREATE TABLE statement is ignored,
	// as are all constraints.
	//
	// [CREATE TABLE statement]: https://sqlite.org/lang_createtable.html
	Declaration string

	// If ConstraintSupport is true, then the virtual table implementation
	// guarantees that if Update or DeleteRow on [WritableVTable]
	// return a [ResultConstraint] error,
	// they will do so before any modifications to internal or persistent data structures
	// have been made.
	ConstraintSupport bool

	// If AllowIndirect is false, then the virtual table may only be used from top-level SQL.
	// If AllowIndirect is true, then the virtual table 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_vtab_constraint_support.html
	// for more details.
	// This defaults to false for better security.
	AllowIndirect bool
}

VTableConfig specifies the configuration of a VTable returned by VTableConnectFunc. Declaration is the only required field.

type VTableConnectFunc added in v0.13.0

type VTableConnectFunc func(*Conn, *VTableConnectOptions) (VTable, *VTableConfig, error)

VTableConnectFunc is a [Module.Connect] or [Module.Create] callback.

type VTableConnectOptions added in v0.13.0

type VTableConnectOptions struct {
	// ModuleName is the name of the [Module] being invoked.
	ModuleName string
	// DatabaseName is the name of the database in which the new virtual table is being created.
	// The database name is "main" for the primary database,
	// or "temp" for TEMP database,
	// or the name given at the end of the ATTACH statement for attached databases.
	DatabaseName string
	// VTableName is the name of the name of the new virtual table.
	// For eponymous virtual tables, this will be the same as ModuleName.
	VTableName string
	// Arguments passed to the CREATE VIRTUAL TABLE statement.
	Args []string
}

VTableConnectOptions is the set of arguments to a VTableConnectFunc.

type VTableCursor added in v0.13.0

type VTableCursor interface {
	// Filter begins a search of a virtual table.
	// The ID is one that is returned by [VTable] BestIndex.
	// The arguments will be populated as specified by ConstraintUsage in [IndexOutputs].
	Filter(id IndexID, argv []Value) error
	// Next advances the cursor to the next row of a result set
	// initiated by a call to [VTableCursor] Filter.
	// If the cursor is already pointing at the last row when this routine is called,
	// then the cursor no longer points to valid data
	// and a subsequent call to the [VTableCursor] EOF method must return true.
	Next() error
	// Column returns the value for the i-th column of the current row.
	// Column indices start at 0.
	//
	// If noChange is true, then the column access is part of an UPDATE operation
	// during which the column value will not change.
	// This can be used as a hint to return [Unchanged] instead of fetching the value:
	// [WritableVTable] Update implementations can check [Value.NoChange] to test for this condition.
	Column(i int, noChange bool) (Value, error)
	// RowID returns the row ID of the row that the cursor is currently pointing at.
	RowID() (int64, error)
	// EOF reports if the cursor is not pointing to a valid row of data.
	EOF() bool
	// Close releases any resources associated with the cursor.
	Close() error
}

VTableCursor is a cursor over a VTable used to loop through the table.

type VTableUpdateParams added in v0.13.0

type VTableUpdateParams struct {
	OldRowID Value
	NewRowID Value
	Columns  []Value
}

VTableUpdateParams is the set of parameters to the WritableVTable Update method.

func (VTableUpdateParams) IsInsert added in v0.13.0

func (p VTableUpdateParams) IsInsert() bool

IsInsert reports whether the arguments represent an INSERT. If not, then the arguments represent an UPDATE.

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 Unchanged added in v0.13.0

func Unchanged() Value

Unchanged returns a NULL Value for which Value.NoChange reports true. This is only significant as the return value for the Column method of VTableCursor.

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) NoChange added in v0.13.0

func (v Value) NoChange() bool

NoChange reports whether a column corresponding to this value in a VTable Update method is unchanged by the UPDATE operation that the Update method call was invoked to implement and if the prior VTableCursor Column method call that was invoked to extract the value for that column returned Unchanged.

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.

type WritableVTable added in v0.13.0

type WritableVTable interface {
	VTable

	Update(params VTableUpdateParams) (rowID int64, err error)
	DeleteRow(rowID Value) error
}

A WritableVTable is a VTable that supports modifications.

Directories

Path Synopsis
cmd
ext
generateseries
Package generateseries provides a port of the [generate_series] table-valued function from the SQLite tree.
Package generateseries provides a port of the [generate_series] table-valued function from the SQLite tree.
refunc
Package refunc provides an implementation of the [REGEXP operator] that uses the Go regexp package.
Package refunc provides an implementation of the [REGEXP operator] that uses the Go regexp package.
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