sqlite

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 17 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-sqlite

SQLite for Go, whose operations map directly onto API calls. You write the SQL; the library binds it and scans the results into your types. Pure Go, without cgo, with the same semantics as go-pg for PostgreSQL.

Documentation: https://pkg.go.dev/github.com/mutablelogic/go-sqlite

Operations map onto API calls

Each operation is an API call. A request type selects the rows, and a response type reads them:

Operation API call Interfaces Connection
Insert a row, and return it POST or PUT Writer, and a Reader of what's returned writer
Update rows, and optionally return them PATCH Selector and Writer, and a Reader writer
Delete rows, and optionally return them DELETE Selector, and a Reader writer
Get a row GET Selector and Reader a reader
List rows, and count them GET Selector, and a Reader or ListReader a reader

So a handler is one call, and sqlite.HTTPError turns its errors into HTTP errors, such as not found or conflict:

// GET /objects/{id}
func (h *Handler) Get(w http.ResponseWriter, r *http.Request, id int64) error {
  var obj MyObject
  if err := h.db.Get(r.Context(), &obj, MyObject{Id: id}); err != nil {
    return httpresponse.Error(w, sqlite.HTTPError(err))
  }
  return httpresponse.JSON(w, http.StatusOK, 2, obj)
}

// POST /objects
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) error {
  var req MyObject
  if err := httprequest.Read(r, &req); err != nil {
    return httpresponse.Error(w, err)
  }
  var obj MyObject
  if err := h.db.Insert(r.Context(), &obj, req); err != nil {
    return httpresponse.Error(w, sqlite.HTTPError(err))
  }
  return httpresponse.JSON(w, http.StatusCreated, 2, obj)
}

A handler for go-pg, against PostgreSQL, has the same shape, with pg.HTTPError.

SQL first, not an ORM

There's no query builder, no generated SQL, and no mapping of struct tags to tables. Your types return the SQL for each operation, and bind its arguments:

func (obj MyObject) Select(bind *sqlite.Bind, op sqlite.Op) (string, error) {
  bind.Set("id", obj.Id)
  switch op {
  case sqlite.Get:
    return `SELECT id, name FROM mytable WHERE id = @id`, nil
  case sqlite.Delete:
    return `DELETE FROM mytable WHERE id = @id RETURNING id, name`, nil
  }
  return "", sqlite.ErrNotImplemented
}
  • What runs is what you read. Queries can be reviewed as they are, and tested in the sqlite3 shell, with .parameter set @key value for their arguments, once their ${key} substitutions are replaced.
  • All of SQLite: full-text search, JSON, window functions, common table expressions, RETURNING and UPSERT, with nothing to wait for or work around.
  • Queries in files: keep them in .sql files, by name, as saved queries, with ${key} substitutions for names, such as a schema.
  • Thin types: a Selector binds and returns SQL, a Reader scans a row, and a Writer binds values. Nothing else needs to know about the database.

Features

  • One writer and many readers, with WAL, so reads don't wait for writes, and writes don't fail with "database is locked".
  • Transactions, nested as savepoints, and bulk operations, which reuse their statements.
  • Values: Go values to SQLite's, and back, including JSON, times, durations and UUIDs.
  • Extensions, such as full-text search, and functions written in Go, which SQL calls.
  • Tracing, with OpenTelemetry.
  • Changes: rows which are written, published to a broadcaster once they're committed.

For a working example, see filesearch: a command-line tool which indexes and searches files, with transactions, saved queries and full-text search.

Interfaces

Each operation:

  1. Calls the Writer and the Selector, which bind their parameters, and return the SQL.
  2. Waits for a connection: the writer, which writes one statement or transaction at a time, or one of the readers, which read at once.
  3. Replaces the SQL's ${key} substitutions, and binds its @key arguments.
  4. Executes it, and calls the Reader with each row it returns.
Selector
type Selector interface {
  // Bind row selection variables, returning the SQL statement required for the operation.
  // The operation is Get, Update, Delete or List.
  Select(*Bind, Op) (string, error)
}

A Selector selects rows from a table, for Get, List, Update and Delete operations.

Reader
type Reader interface {
  // Scan a row into the receiver
  Scan(Row) error
}

type ListReader interface {
  Reader

  // Scan a count of all the rows into the receiver
  ScanCount(Row) error
}

A Reader translates a row into a Go type. When there are several rows, Scan is called with each. Get calls it with the first row only. A ListReader is also given the count of all the rows a List selects, without its offset and limit.

Writer
type Writer interface {
  // Bind insert parameters, returning the SQL statement required for the insert
  Insert(*Bind) (string, error)

  // Bind update parameters
  Update(*Bind) error
}

A Writer binds a Go type's fields to SQL parameters, for Insert and Update operations.

Opening a Database

The ncruces package opens databases with ncruces/go-sqlite3, which is SQLite compiled to WebAssembly:

import (
  sqlite "github.com/mutablelogic/go-sqlite"
  ncruces "github.com/mutablelogic/go-sqlite/ncruces"
)

func main() {
  db, err := ncruces.Open(ctx, "index.db", sqlite.WithMaxReaders(4))
  if err != nil {
    panic(err)
  }
  defer db.Close()

  // ...
}
  • Files are created when they don't exist. Their journal is a write-ahead log, so reads see what's committed while a transaction writes.
  • In memory: sqlite.Memory, which is one connection, which writes and reads.
  • Pragmas: foreign keys are on, synchronous is NORMAL, and the busy timeout is 10s.

The options are:

  • sqlite.WithMaxReaders(int) - The most connections which read at once. The default is 4.
  • sqlite.WithPragma(string, string) - Set a pragma on each connection, such as cache_size, of -4000.
  • sqlite.WithFunction(string, bool, sqlite.Fn) - Add a user-defined function, called from SQL. See Functions.
  • sqlite.WithBind(string, any) - Set a bind variable for every query.
  • sqlite.WithTracer(trace.Tracer) - Set an OpenTelemetry tracer. See Tracing.

Executing Statements

To execute a statement, use Exec:

if err := db.Exec(ctx, `CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`); err != nil {
  panic(err)
}

Values are bound with With, which returns a connection with them. See Bindings.

if err := db.With("table", "test", "name", name).Exec(ctx, `INSERT INTO ${"table"} (name) VALUES (@name)`); err != nil {
  panic(err)
}

A query is one statement, or several, which are executed in turn.

Bindings

A Bind is a set of named values, which a statement uses in two ways:

  • Arguments: @key, :key and $key are bound by SQLite, so a value is never SQL. Use these for values.
  • Substitutions: ${key} is replaced with the value, as it is, before the statement is prepared. Use these for SQL, such as a table's name, or a clause:
    • ${key} - The value, as it is, such as ORDER BY name.
    • ${"key"} - The value, as an identifier, such as "my table", with its " escaped.
    • ${'key'} - The value, as a string, such as 'it''s'. A []string is a list of them, 'a','b', such as for IN (${'list'}).

Binds are layered:

  • Every query: sqlite.WithBind(key, value), when the database is opened.
  • A connection: conn.With(key, value, ...) returns a connection with them, as well as its own. Transactions within it have them too.
  • An operation: a Selector or Writer sets them on the Bind it's given, which is a copy, so operations don't change each other's.

Within a Selector or Writer:

  • bind.Set(key, value) - Set a value, and return its argument, @key.
  • bind.Get(key), bind.Has(key) and bind.Del(key) - Get, check and delete a value.
  • bind.Append(key, value) and bind.Join(key, sep) - Build a list, such as of a WHERE clause's conditions, and join it.
  • bind.Query(key) - The SQL of a saved query. See Saved Queries.

For example, a Selector which filters rows by what's set:

func (req MyListRequest) Select(bind *sqlite.Bind, op sqlite.Op) (string, error) {
  if req.Name != "" {
    bind.Append("where", "name = "+bind.Set("name", req.Name))
  }
  if len(req.Tags) > 0 {
    bind.Append("where", "tag IN (SELECT value FROM json_each("+bind.Set("tags", req.Tags)+"))")
  }
  if bind.Has("where") {
    bind.Set("where", "WHERE "+bind.Join("where", " AND "))
  } else {
    bind.Set("where", "")
  }
  req.OffsetLimit.Bind(bind, 100)
  return `SELECT name FROM mytable ${where} ORDER BY name`, nil
}

The conditions are SQL, which is substituted, and their values are arguments, which are bound. req.Tags, a []string, is bound as JSON, which json_each reads.

Implementing Get

To get a row, implement a Selector and a Reader:

type MyObject struct {
  Id   int64
  Name string
}

// Reader - scan the row into the object
func (obj *MyObject) Scan(row sqlite.Row) error {
  return row.Scan(&obj.Id, &obj.Name)
}

// Selector - select the row
func (obj MyObject) Select(bind *sqlite.Bind, op sqlite.Op) (string, error) {
  switch op {
  case sqlite.Get:
    bind.Set("id", obj.Id)
    return `SELECT id, name FROM mytable WHERE id = @id`, nil
  }
  return "", sqlite.ErrNotImplemented
}

func main() {
  // ...
  var obj MyObject
  if err := db.Get(ctx, &obj, MyObject{Id: 1}); errors.Is(err, sqlite.ErrNotFound) {
    // No row
  } else if err != nil {
    panic(err)
  }
}

Implementing List

List rows, a page at a time, with an offset and limit:

type MyListRequest struct {
  sqlite.OffsetLimit
  Name string
  Tags []string
}

type MyList struct {
  Count uint64
  Names []string
}

// Reader - called with each row; note it's a pointer receiver
func (list *MyList) Scan(row sqlite.Row) error {
  var name string
  if err := row.Scan(&name); err != nil {
    return err
  }
  list.Names = append(list.Names, name)
  return nil
}

// ListReader - optionally, the count of all the rows
func (list *MyList) ScanCount(row sqlite.Row) error {
  return row.Scan(&list.Count)
}

// Selector - select the rows, and bind the offset and limit, of at most 100
func (req MyListRequest) Select(bind *sqlite.Bind, op sqlite.Op) (string, error) {
  switch op {
  case sqlite.List:
    req.OffsetLimit.Bind(bind, 100)
    return `SELECT name FROM mytable ORDER BY name`, nil
  }
  return "", sqlite.ErrNotImplemented
}
  • The offset and limit are ${offsetlimit}, which List adds after the query, so don't include them in it.
  • The count is of the query, without them, and is read in the same transaction as the rows.
  • No rows isn't an error.

Implementing Insert

To insert a row, implement a Writer:

// Writer - bind insert parameters
func (obj MyObject) Insert(bind *sqlite.Bind) (string, error) {
  bind.Set("name", obj.Name)
  return `INSERT INTO mytable (name) VALUES (@name) RETURNING id, name`, nil
}

// Writer - bind update parameters
func (obj MyObject) Update(bind *sqlite.Bind) error {
  bind.Set("name", obj.Name)
  return nil
}

func main() {
  // ...
  obj := MyObject{Name: "hello"}
  if err := db.Insert(ctx, &obj, obj); err != nil {
    panic(err)
  }
  fmt.Println("Inserted with ID:", obj.Id)
}

The RETURNING clause returns the inserted row, including generated values, such as its INTEGER PRIMARY KEY.

Implementing Patch

To update rows, implement a Selector, of Update, and a Writer:

func (obj MyObject) Select(bind *sqlite.Bind, op sqlite.Op) (string, error) {
  bind.Set("id", obj.Id)
  switch op {
  case sqlite.Get:
    return `SELECT id, name FROM mytable WHERE id = @id`, nil
  case sqlite.Update:
    return `UPDATE mytable SET name = @name WHERE id = @id RETURNING id, name`, nil
  case sqlite.Delete:
    return `DELETE FROM mytable WHERE id = @id RETURNING id, name`, nil
  }
  return "", sqlite.ErrNotImplemented
}

func main() {
  // ...
  obj := MyObject{Id: 1, Name: "updated"}
  if err := db.Update(ctx, &obj, obj, obj); err != nil {
    panic(err)
  }
}

The Writer's Update is called before the Selector, so the Selector can choose its SQL from what's updated.

Implementing Delete

To delete rows, implement a Selector, of Delete, as above:

var deleted MyObject
if err := db.Delete(ctx, &deleted, MyObject{Id: 1}); err != nil {
  panic(err)
}
fmt.Println("Deleted:", deleted.Name)

The RETURNING clause is optional. Without it, pass a nil Reader.

Saved Queries

Queries can be kept in a file of SQL, apart from the Go which uses them, with a key before each:

-- mytable.create
-- The table of names, which is created once
CREATE TABLE IF NOT EXISTS mytable (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL -- not empty
);

-- mytable.get
SELECT id, name FROM ${"table"} WHERE id = @id;

-- mytable.insert
INSERT INTO ${"table"} (name) VALUES (@name) RETURNING id, name;
  • Keys are two or more names, separated by dots, such as mytable.get, on a line of their own, after --. A comment line of one word, such as -- change, isn't a key.
  • Each key has a statement. A key without one is an error.
  • Comments are removed: lines which are only a comment, such as a description, and comments at the end of lines. -- within strings, quoted identifiers and block comments is kept.
  • The ; which ends each statement is removed, so it can be within another, such as List's count.
  • Keys are unique in a file. A duplicate is an error.

The queries are read with NewQueries, and bound to a connection with WithQueries, so its operations have them:

//go:embed queries.sql
var sql string

queries, err := sqlite.NewQueries(strings.NewReader(sql))
if err != nil {
  panic(err)
}
conn := db.WithQueries(queries).With("table", "mytable")

// Create the table
if err := conn.Exec(ctx, queries.Query("mytable.create")); err != nil {
  panic(err)
}

A Selector or Writer returns a query by its key, with bind.Query, which also names its span, when it's traced:

func (obj MyObject) Select(bind *sqlite.Bind, op sqlite.Op) (string, error) {
  switch op {
  case sqlite.Get:
    bind.Set("id", obj.Id)
    return bind.Query("mytable.get"), nil
  }
  return "", sqlite.ErrNotImplemented
}

Its ${key} substitutions are replaced once, as it's executed, so a value with a $ in it, such as a path, is kept as it is.

Transactions

Transactions are executed within a function, with Tx:

if err := db.Tx(ctx, func(conn sqlite.Conn) error {
  if err := conn.Exec(ctx, `INSERT INTO test (name) VALUES ('hello')`); err != nil {
    return err
  }
  return conn.Insert(ctx, &obj, obj)
}); err != nil {
  panic(err)
}
  • Committed when the function returns nil, and rolled back when it returns an error, panics, or its context is done.
  • Begun immediately, on the writer, so another transaction waits for it.
  • Nested: a transaction within one is a savepoint, which is rolled back on its own.
  • Use its conn: within a transaction, the pool's writer waits for it to end. Reads on the pool don't wait, and see what's committed before it.

Bulk is a transaction, as Tx is, which prepares each statement once, and reuses it, such as for many inserts. It's about twice as fast:

err := db.Bulk(ctx, func(conn sqlite.Conn) error {
  for _, obj := range objs {
    if err := conn.Insert(ctx, nil, obj); err != nil {
      return err
    }
  }
  return nil
})

Values

The values package converts Go values to SQLite's, and back:

Go SQLite
nil, and nil pointers NULL
bool INTEGER, 0 or 1
integers, and floats INTEGER and REAL
string TEXT
[]byte, and arrays of bytes BLOB
time.Time TEXT, of RFC 3339, or NULL when it's zero
time.Duration INTEGER, of nanoseconds
driver.Valuer its value
encoding.TextMarshaler, such as uuid.UUID and netip.Addr TEXT
encoding.BinaryMarshaler BLOB
json.Marshaler, slices, maps and structs TEXT, of JSON
  • Named types, such as type Status string, are of their kind, and pointers are of their values.
  • Scanning reverses it, into those types, and sql.Scanner and any. A value which doesn't fit, NULL into a value which isn't a pointer, slice, map or time, and text which isn't a number or time, are errors.
  • Times are read as SQLite's date and time functions read them: RFC 3339 or YYYY-MM-DD HH:MM:SS text, Unix seconds, or Julian days. A zero time is NULL, and NULL is a zero time, so a nullable column round-trips a time.Time without a pointer.
  • JSON is text, so SQLite's json functions read it, such as json_each.

Extensions

Importing a subfolder of ncruces adds its extension to each connection:

import (
  _ "github.com/mutablelogic/go-sqlite/ncruces/fts5"
)
  • ncruces/fts5 - Full-text search, of fts5 virtual tables.
  • ncruces/rtree - Spatial indexes, of rtree and geopoly virtual tables.
  • ncruces/vec1 - Vector search, of vec1 virtual tables.

For example, with fts5:

db.Exec(ctx, `CREATE VIRTUAL TABLE docs USING fts5(title, body)`)
db.Get(ctx, &doc, Search{Query: "rain"}) // SELECT rowid, title FROM docs WHERE docs MATCH @query ORDER BY rank

Functions

sqlite.WithFunction adds user-defined functions, called from SQL:

db, err := ncruces.Open(ctx, path,
  sqlite.WithFunction("double", true, sqlite.Func1(func(n int64) (int64, error) {
    return n * 2, nil
  })),
  sqlite.WithFunction("elapsed", true, sqlite.Func2(func(from, to time.Time) (time.Duration, error) {
    return to.Sub(from), nil
  })),
)
SELECT double(21)                                          -- 42
SELECT elapsed('2026-11-18 11:00', '2026-11-18 12:30')     -- 5400000000000, 90 minutes
  • Arity: Func0, Func1, Func2 and Func3 are of no, one, two and three arguments. FuncN is of any number of one type, such as FuncN(func(args ...any) (any, error)).
  • Arguments are scanned, as rows are, so they're of any type a row is scanned into, such as time.Time, a slice, of JSON, or a pointer, which is nil when it's NULL. An argument which isn't of its type is an error, which says which.
  • Results are converted as Values are.
  • Errors are the query's.
  • Deterministic functions always return the same result for the same arguments, so they can be used in indexes.

Schema Versions

sqlite.Version and sqlite.SetVersion read and set SQLite's user_version, so a schema is created, and then migrated, as it changes:

err := db.Tx(ctx, func(conn sqlite.Conn) error {
  version, err := sqlite.Version(ctx, conn)
  if err != nil {
    return err
  }
  if version < 1 {
    // ...create the schema...
    if err := sqlite.SetVersion(ctx, conn, 1); err != nil {
      return err
    }
  }
  if version < 2 {
    // ...migrate it from version 1...
    if err := sqlite.SetVersion(ctx, conn, 2); err != nil {
      return err
    }
  }
  return nil
})

Each step sets its own version, so a database which is already newer isn't changed, and one which fails part way is rolled back to the version it was.

Errors

Errors are of these kinds, with errors.Is:

  • sqlite.ErrNotFound - Get found no row, or Insert, Update or Delete, with a Reader, returned none.
  • sqlite.ErrConflict and sqlite.ErrUniqueViolation - A unique or primary key constraint.
  • sqlite.ErrBadParameter - A foreign key, not null or check constraint, with ErrForeignKeyViolation, ErrNotNullViolation or ErrCheckViolation, or a value which can't be bound.
  • sqlite.ErrNotAvailable - The database is busy, locked, or closed.
  • sqlite.ErrDatabase - Any of SQLite's errors.

When a query is interrupted, or stops waiting for a lock, as its context is done, the error is also the context's, such as context.DeadlineExceeded.

For example, sqlite.HTTPError converts an error to an HTTP error, of its status, which a handler returns, with go-server's httpresponse:

func (h *Handler) Get(w http.ResponseWriter, r *http.Request, id int64) error {
  var obj MyObject
  if err := h.db.Get(r.Context(), &obj, MyObject{Id: id}); err != nil {
    return httpresponse.Error(w, sqlite.HTTPError(err))
  }
  return httpresponse.JSON(w, http.StatusOK, 2, obj)
}
Error Status
sqlite.ErrNotFound 404 Not Found
sqlite.ErrBadParameter, such as a foreign key, not null or check constraint 400 Bad Request
sqlite.ErrConflict, such as a unique constraint 409 Conflict
sqlite.ErrNotImplemented 501 Not Implemented
sqlite.ErrNotAvailable, such as a busy or closed database 503 Service Unavailable
Others 500 Internal Server Error

Tracing

sqlite.WithTracer sets an OpenTelemetry tracer, of a span for each query:

import (
  otel "go.opentelemetry.io/otel"
)

db, err := ncruces.Open(ctx, path,
  sqlite.WithTracer(otel.Tracer("myapp")),
)

A span's parent is the operation's context, so a query is within the span of the request which made it.

  • Named by the query's name, of bind.Query, such as mytable.get, or sqlite.query.
  • Transactions: sqlite.transaction, sqlite.commit and sqlite.rollback, of savepoints too. Opening the database is sqlite.open.
  • Attributes: db.system, db.statement, and the arguments it bound, as arg. and their names.
  • Errors are the span's, except not found.

For example, a Get of a saved query, mytable.get, which binds @id, is a span:

mytable.get
  db.system     sqlite
  db.statement  SELECT id, name FROM "mytable" WHERE id = @id
  arg.id        1

Changes

Consumers often need to know when data changes, without polling for it. For example, a web page can update as soon as a row is added. Or a server can stream changes to its clients, or refresh a cache.

sqlite.WithBroadcaster publishes each row which is inserted, updated or deleted, once it's committed. It works with go-server's broadcaster, or anything with a non-blocking Publish(schema.Change) int:

import (
  broadcaster "github.com/mutablelogic/go-server/broadcaster"
)

changes := broadcaster.New()
db, err := ncruces.Open(ctx, path,
  sqlite.WithBroadcaster(changes, "mytable"),
)
  • A change is its action (create, update or delete), its database (main), its table, and its rowid as Row.
  • Tables: the tables named, or all of them. The shadow tables of virtual tables, such as fts5's, are left out.
  • Committed: changes are published after the transaction commits, so a watcher reads what changed. Rolled-back transactions and savepoints publish nothing.
  • Once per row: a row written several times in a transaction is one change. Created then deleted is none.
  • Many rows: over sqlite.MaxChanges rows of a table in one transaction are one change of the table, without a Row.
  • Every row: rows deleted by a foreign key's cascade, by a DELETE without a WHERE, or replaced by INSERT OR REPLACE, are published. A row whose rowid changes is a delete and a create.
  • Publish is called while the writer is held, so it mustn't block or query the database. A watcher reads changes on its own goroutine, as go-server's broadcaster's do.
  • Failed statements: in a transaction, rows undone by a failed statement aren't published, and rows kept by INSERT OR FAIL are.
  • Not seen: writes by other processes, and of tables WITHOUT ROWID. Savepoints written by hand in SQL aren't tracked, so their rolled-back rows are still published.

License & Distribution

This software is licensed under the Apache License 2.0.

go-sqlite
https://github.com/mutablelogic/go-sqlite/
Copyright (c) 2017-2026 The go-sqlite authors, All rights reserved.

Under the Apache License 2.0, you are free to use, modify, and distribute this software for any purpose, including commercial applications. Attribution requirement: when redistributing this software or derivative works, in source or binary form, include the copyright notice above, and a copy of the LICENSE and NOTICE files. If you modify the code, you must state your changes. See the Apache License 2.0 for complete terms.

When distributing binaries which include this software, also comply with the licenses of the libraries which are compiled into them. Their copyright notices are in the NOTICE file.

Library License
SQLite, including its fts5, rtree and vec1 extensions Public domain
ncruces/go-sqlite3 MIT
ncruces/go-sqlite3-wasm, SQLite translated to Go MIT-0, with the original licenses of what's translated
ncruces/julianday MIT
OpenTelemetry for Go Apache 2.0
go-server Apache 2.0
xxhash MIT
golang.org/x/sys BSD 3-clause

The test package, which is for tests, also uses testify (MIT), the OpenTelemetry SDK and logr (Apache 2.0), google/uuid (BSD 3-clause) and yaml (MIT and Apache 2.0).

Documentation

Overview

Package sqlite is a SQLite client, of the same shape as go-pg's: queries are bound to a connection, and objects are read and written by the Reader, Writer and Selector interfaces. An implementation, such as package ncruces, opens a database as a PoolConn.

Index

Constants

View Source
const (
	// MaxChanges is the most rows of a table, of a transaction, which are
	// published as changes of each, rather than one change of the table
	MaxChanges = 1000

	// DefaultReaders is the most connections which read at once
	DefaultReaders = 4

	// DefaultBusyTimeout is how long, in milliseconds, a connection waits
	// for another which is writing
	DefaultBusyTimeout = "10000"

	// Memory is the path of a database in memory, which is one connection's,
	// so it's both written and read on one
	Memory = ":memory:"
)
View Source
const (
	// TraceSpanNameArg is the bind var which names a query's span
	TraceSpanNameArg = "otelspan"
)

Variables

This section is empty.

Functions

func HTTPError added in v1.1.1

func HTTPError(err error) error

HTTPError returns the error as an HTTP error, of its status.

func NewDatabaseError added in v1.1.1

func NewDatabaseError(err error, kinds ...Err) error

NewDatabaseError returns an implementation's error, such as SQLite's, which is ErrDatabase, and the kinds of error it is, such as ErrConflict and ErrUniqueViolation

func SetVersion added in v1.1.1

func SetVersion(ctx context.Context, conn Conn, version int64) error

SetVersion sets the version of the database's schema, such as within the transaction which migrates it.

func Statement added in v1.1.1

func Statement(sql string) string

Statement returns the SQL of one statement, without its comments, or the ; which ends it, so it's within another, such as a subquery, or is followed by more, such as a limit.

func Version added in v1.1.1

func Version(ctx context.Context, conn Conn) (int64, error)

Version returns the version of the database's schema, which is 0 until it's set, so a schema can be created, and then migrated, as it changes.

Types

type Bind added in v1.1.1

type Bind struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Bind represents a set of variables and arguments to be used in a query. The vars are substituted in the query string itself, as ${key}, while the args are passed as arguments to the query, as @key.

func NewBind added in v1.1.1

func NewBind(pairs ...any) *Bind

NewBind creates a new Bind object with the given name/value pairs. Returns nil if the number of arguments is not even.

func (*Bind) Append added in v1.1.1

func (bind *Bind) Append(key string, value any) bool

Append appends a bind var to a list. Returns false if the key is not a list, or the value is not a list.

func (*Bind) Copy added in v1.1.1

func (bind *Bind) Copy(pairs ...any) *Bind

Copy creates a copy of the bind object with additional name/value pairs.

func (*Bind) Del added in v1.1.1

func (bind *Bind) Del(key string)

Del deletes a bind var.

func (*Bind) Expand added in v1.1.1

func (bind *Bind) Expand(query string) (string, map[string]any)

Expand returns the query with its ${key} substitutions replaced, and the vars, of one copy, which its @key arguments are bound to

func (*Bind) Get added in v1.1.1

func (bind *Bind) Get(key string) any

Get returns a bind var by key.

func (*Bind) Has added in v1.1.1

func (bind *Bind) Has(key string) bool

Has returns true if there is a bind var with the given key.

func (*Bind) Join added in v1.1.1

func (bind *Bind) Join(key, sep string) string

Join joins a bind var with a separator when it is a []any and returns the result as a string. Returns an empty string if the key does not exist.

func (*Bind) MarshalJSON added in v1.1.1

func (bind *Bind) MarshalJSON() ([]byte, error)

func (*Bind) Query added in v1.1.1

func (bind *Bind) Query(name string) string

Query looks up a named query, which was loaded via WithQueries, such as "index.object.get", sets the span name for OpenTelemetry tracing, and returns its SQL, whose ${key} substitutions are replaced once, when it's executed, so a value which has a $ in it, such as a path, isn't replaced again. It returns an empty string when there's no query of the name.

func (*Bind) Replace added in v1.1.1

func (bind *Bind) Replace(query string) string

Replace returns a query string with ${subtitution} replaced by the values:

  • ${key} => value
  • ${'key'} => 'value'
  • ${"key"} => "value"
  • ${1} => $1

Anything else is kept as it is, such as $key, @key and :key, which are SQLite's parameters, and are bound as arguments, rather than substituted.

func (*Bind) Set added in v1.1.1

func (bind *Bind) Set(key string, value any) string

Set sets a bind var and returns the parameter name.

func (*Bind) String added in v1.1.1

func (bind *Bind) String() string

func (*Bind) WithQueries added in v1.1.1

func (bind *Bind) WithQueries(queries ...*Queries) *Bind

WithQueries returns a copy of the bind object, with the queries of each set, by their keys, which Query returns

type Conn added in v1.1.1

type Conn interface {
	// Return a new connection with bound parameters
	With(...any) Conn

	// Return a new connection with bound queries
	WithQueries(...*Queries) Conn

	// Perform a transaction within a function, on the connection which
	// writes, which is begun immediately, so it isn't upgraded to write
	// later, when another transaction may be writing
	Tx(context.Context, func(Conn) error) error

	// Perform a bulk operation within a function, in a transaction, whose
	// statements are prepared once
	Bulk(context.Context, func(Conn) error) error

	// Execute a query
	Exec(context.Context, string) error

	// Perform an insert
	Insert(context.Context, Reader, Writer) error

	// Perform an update
	Update(context.Context, Reader, Selector, Writer) error

	// Perform a delete
	Delete(context.Context, Reader, Selector) error

	// Perform a get, on a connection which reads, unless in a transaction
	Get(context.Context, Reader, Selector) error

	// Perform a list, on a connection which reads, unless in a transaction.
	// If the reader is a ListReader, then the count of items is also
	// calculated
	List(context.Context, Reader, Selector) error
}

Conn is a connection, with bound parameters and queries.

type DatabaseError added in v1.1.1

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

DatabaseError is an implementation's error, which is ErrDatabase, and the kinds of error it is, such as ErrConflict and ErrUniqueViolation, with errors.Is

func (*DatabaseError) Error added in v1.1.1

func (e *DatabaseError) Error() string

Error returns the error's message

func (*DatabaseError) Is added in v1.1.1

func (e *DatabaseError) Is(target error) bool

Is returns true when the error is of the kind, or the implementation's error is

func (*DatabaseError) Unwrap added in v1.1.1

func (e *DatabaseError) Unwrap() error

Unwrap returns the implementation's error

type Err added in v1.1.1

type Err int

Err is a kind of error, which SQLite's errors are mapped to

const (
	ErrSuccess Err = iota
	ErrNotFound
	ErrNotImplemented
	ErrBadParameter
	ErrNotAvailable
	ErrConflict
	ErrDatabase
	ErrUniqueViolation
	ErrForeignKeyViolation
	ErrNotNullViolation
	ErrCheckViolation
	ErrInternalServerError
)

func (Err) Error added in v1.1.1

func (e Err) Error() string

Error returns the string representation of the error.

func (Err) With added in v1.1.1

func (e Err) With(a ...any) error

With returns the error with additional context appended.

func (Err) Withf added in v1.1.1

func (e Err) Withf(format string, a ...any) error

Withf returns the error with formatted context appended. As with fmt.Errorf, the format may use %w to wrap errors, so that they can still be matched with errors.Is and errors.As.

type Fn added in v1.1.1

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

Fn is a function, of its arguments, which SQL calls, which Func0, Func1, Func2, Func3 and FuncN make, of a Go function, of typed arguments and result

func Func0 added in v1.1.1

func Func0[T any](fn func() (T, error)) Fn

Func0 returns a function, of no arguments, and its result, which is set as values.Set sets it, such as a []string, which is JSON

func Func1 added in v1.1.1

func Func1[A, T any](fn func(A) (T, error)) Fn

Func1 returns a function, of one argument, which is scanned as values.Scan scans it, such as a time.Time, or a *int64, which is nil when it's NULL, and its result

func Func2 added in v1.1.1

func Func2[A, B, T any](fn func(A, B) (T, error)) Fn

Func2 returns a function, of two arguments, and its result

func Func3 added in v1.1.1

func Func3[A, B, C, T any](fn func(A, B, C) (T, error)) Fn

Func3 returns a function, of three arguments, and its result

func FuncN added in v1.1.1

func FuncN[A, T any](fn func(...A) (T, error)) Fn

FuncN returns a function, of any number of arguments, of one type, such as any, which is an int64, a float64, a string, a []byte or nil, and its result

type Function added in v1.1.1

type Function struct {
	Name          string
	Args          int  // The number of arguments, or -1 for any
	Deterministic bool // The same arguments always return the same result

	// Fn is called with the arguments, which it scans, and returns its
	// result, which is set as values.Set sets it, or an error
	Fn func(args []values.Value) (any, error)
}

Function is a function, which SQL calls by its name, which an implementation creates on each connection

type ListReader added in v1.1.1

type ListReader interface {
	Reader

	// Scan count into the result
	ScanCount(Row) error
}

ListReader scans database rows and counts total results.

type OffsetLimit added in v1.1.1

type OffsetLimit struct {
	Offset uint64  `json:"offset,omitempty" help:"Offset within the result set" jsonschema:"Offset for pagination" example:"0"`
	Limit  *uint64 `json:"limit,omitempty" help:"Number of items to return" jsonschema:"Limit for pagination" example:"100"`
}

func (*OffsetLimit) Bind added in v1.1.1

func (r *OffsetLimit) Bind(bind *Bind, max uint64)

Bind sets the offset and limit SQL fragment on the bind object.

func (*OffsetLimit) Clamp added in v1.1.1

func (r *OffsetLimit) Clamp(total uint64)

Clamp restricts the limit to the number of rows available after offset.

func (*OffsetLimit) Query added in v1.1.1

func (r *OffsetLimit) Query(params url.Values)

Query sets offset and limit query parameters on the provided map.

type Op added in v1.1.1

type Op uint

Op represents a database operation type.

const (
	None Op = iota
	Get
	Insert
	Update
	Delete
	List
)

Operations

func (Op) String added in v1.1.1

func (o Op) String() string

type Opt added in v1.1.1

type Opt func(*Options) error

Opt is an option of a database, which Open is given

func WithBind added in v1.1.1

func WithBind(k string, v any) Opt

WithBind sets a bind variable for each query.

func WithBroadcaster added in v1.1.1

func WithBroadcaster(b Publisher, tables ...string) Opt

WithBroadcaster publishes the rows which are inserted, updated and deleted, once they're committed, to a broadcaster, such as go-server's broadcaster.Broadcaster, as a change of each row: its action, the database, such as main, its table, and its rowid. Changes of the tables, when there are some, are published, or else of all of them, other than the shadow tables of virtual tables, such as fts5's. A row which is written more than once in a transaction is one change. A transaction of more than MaxChanges rows of a table is one change of the table, without a row. Writes by other processes, and of tables WITHOUT ROWID, aren't published.

Publish is called after the commit, before the writer is released, so it mustn't block, or query the database.

func WithFunction added in v1.1.1

func WithFunction(name string, deterministic bool, fn Fn) Opt

WithFunction creates a function on each connection, which SQL calls by its name, of Func0, Func1, Func2, Func3 or FuncN, such as:

sqlite.WithFunction("double", true, sqlite.Func1(func(n int64) (int64, error) {
	return n * 2, nil
}))

A deterministic function always returns the same result for the same arguments, so it can be used in indexes.

func WithMaxReaders added in v1.1.1

func WithMaxReaders(n int) Opt

WithMaxReaders sets the most connections which read at once, which is DefaultReaders, unless it's set. A database in memory has one connection.

func WithPragma added in v1.1.1

func WithPragma(name, value string) Opt

WithPragma sets a pragma on each connection, such as cache_size, after the defaults: journal_mode WAL, synchronous NORMAL, foreign_keys ON and busy_timeout, which it can change. Its value is a number, a name, or a string in single quotes.

func WithTracer added in v1.1.1

func WithTracer(t trace.Tracer) Opt

WithTracer sets the OpenTelemetry tracer, of a span of each query, which is named by the query's name, of Bind.Query, or sqlite.query, or, of a transaction's statements, sqlite.transaction, sqlite.commit or sqlite.rollback, with its SQL, and its arguments, as arg. and their names, and of opening the database, sqlite.open.

type Options added in v1.1.1

type Options struct {
	// The most connections which read at once
	Readers int

	// The pragmas, which are set on each connection, after the defaults
	Pragmas []Pragma

	// The functions, which are created on each connection
	Functions []Function

	// The bind variables of each query
	Bind *Bind

	// The OpenTelemetry tracer, of a span of each query
	Tracer trace.Tracer

	// The broadcaster, which the rows which are written are published to,
	// once they're committed, and the tables which are, or all of them
	Broadcaster Publisher
	Tables      []string
}

Options are what Open is given, which an implementation, such as package ncruces, reads, with Apply

func Apply added in v1.1.1

func Apply(opts ...Opt) (*Options, error)

Apply returns the options, of their defaults, as they're set

type PoolConn added in v1.1.1

type PoolConn interface {
	Conn

	// Ping the database
	Ping(context.Context) error

	// Close the database
	Close() error
}

PoolConn is a database, opened from a file or in memory, which writes on one connection, and reads on many.

type Pragma added in v1.1.1

type Pragma struct {
	Name  string
	Value string
}

Pragma is a pragma, which is set on each connection, such as cache_size, of -4000.

type Publisher added in v1.1.1

type Publisher interface {
	Publish(schema.Change) int
}

Publisher is what changes are published to, such as go-server's broadcaster.Broadcaster. Publish doesn't block, and returns the watchers which missed the change.

type Queries added in v1.1.1

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

Queries represents a collection of named SQL statements parsed from a reader. SQL statements are separated by comment lines in the format: -- <identifier> or -- <identifier>.<identifier>, with any number of dots between them. Each statement is stored with its key.

func NewQueries added in v1.1.1

func NewQueries(r io.Reader) (*Queries, error)

NewQueries parses SQL statements from a reader and returns a Queries collection. SQL statements must be separated by comment lines with a key: -- <identifier>.<identifier>, with one or more dots, where an identifier consists of letters, digits and underscores, and doesn't start with a digit, so a comment line of one word, such as "-- change", isn't a key. A key is only a key outside of a string, a quoted identifier, or a block comment, so a line of a string which looks like one, such as "-- note", is part of its string. Other comment lines, such as those which describe a statement, or one which ends a sentence with a period, such as "-- form.", and comments at the end of a line, are removed from the statement, except within strings, quoted identifiers and block comments. Returns an error if duplicate keys are found, a key has no statement, or reading fails.

Example input format:

-- user.select
SELECT * FROM users WHERE id = @id;

-- user.insert
INSERT INTO users (name, email) VALUES (@name, @email);

func (*Queries) Keys added in v1.1.1

func (s *Queries) Keys() []string

Keys returns a slice of all SQL statement identifiers in the order they were parsed.

func (*Queries) Query added in v1.1.1

func (s *Queries) Query(key string) string

Query retrieves the SQL statement associated with the given key. Returns an empty string if the key does not exist.

type Reader added in v1.1.1

type Reader interface {
	// Scan row into a result
	Scan(Row) error
}

Reader scans a database row into an object.

type Row added in v1.1.1

type Row interface {
	Scan(...any) error
}

Row is a row of a query's results, which is scanned into values.

type Selector added in v1.1.1

type Selector interface {
	// Set bind parameters for getting, updating or deleting
	Select(*Bind, Op) (string, error)
}

Selector binds parameters for get, update, or delete operations.

type Writer added in v1.1.1

type Writer interface {
	// Set bind parameters for an insert
	Insert(*Bind) (string, error)

	// Set bind parameters for an update
	Update(*Bind) error
}

Writer binds object fields for insert or update operations.

Directories

Path Synopsis
filesearch module
Package ncruces opens SQLite databases with ncruces/go-sqlite3, which is SQLite compiled to WebAssembly, so it's pure Go, without cgo.
Package ncruces opens SQLite databases with ncruces/go-sqlite3, which is SQLite compiled to WebAssembly, so it's pure Go, without cgo.
fts5
Package fts5 adds SQLite's full-text search, of the fts5 virtual table, to each connection, which package ncruces opens, when it's imported:
Package fts5 adds SQLite's full-text search, of the fts5 virtual table, to each connection, which package ncruces opens, when it's imported:
rtree
Package rtree adds SQLite's spatial indexes, of the rtree and geopoly virtual tables, to each connection, which package ncruces opens, when it's imported:
Package rtree adds SQLite's spatial indexes, of the rtree and geopoly virtual tables, to each connection, which package ncruces opens, when it's imported:
vec1
Package vec1 adds SQLite's vector search, of the vec1 virtual table, to each connection, which package ncruces opens, when it's imported:
Package vec1 adds SQLite's vector search, of the vec1 virtual table, to each connection, which package ncruces opens, when it's imported:
Package test is the tests which an implementation, such as package ncruces, passes, so it can be replaced by another, which behaves the same.
Package test is the tests which an implementation, such as package ncruces, passes, so it can be replaced by another, which behaves the same.
Package values converts values between Go and SQLite, of SQLite's five types: integers, floats, text, blobs and NULL.
Package values converts values between Go and SQLite, of SQLite's five types: integers, floats, text, blobs and NULL.

Jump to

Keyboard shortcuts

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