Documentation ¶
Overview ¶
Package sqlite provides a Go interface to SQLite 3.
The semantics of this package are deliberately close to the SQLite3 C API, so it is helpful to be familiar with http://www.sqlite.org/c3ref/intro.html.
An SQLite connection is represented by a *sqlite.Conn. Connections cannot be used concurrently. A typical Go program will create a pool of connections (using Open to create a *sqlitex.Pool) so goroutines can borrow a connection while they need to talk to the database.
This package assumes SQLite will be used concurrently by the process through several connections, so the build options for SQLite enable multi-threading and the shared cache: https://www.sqlite.org/sharedcache.html
The implementation automatically handles shared cache locking, see the documentation on Stmt.Step for details.
The optional SQLite 3 extensions compiled in are: session, FTS5, RTree, JSON1, and GeoPoly.
This is not a database/sql driver. For helper functions that make some kinds of statements easier to write, see the sqlitex package.
Statement Caching ¶
Statements are prepared with the Prepare and PrepareTransient methods. When using Prepare, statements are keyed inside a connection by the original query string used to create them. This means long-running high-performance code paths can write:
stmt, err := conn.Prepare("SELECT ...")
After all the connections in a pool have been warmed up by passing through one of these Prepare calls, subsequent calls are simply a map lookup that returns an existing statement.
Streaming Blobs ¶
The sqlite package supports the SQLite incremental I/O interface for streaming blob data into and out of the the database without loading the entire blob into a single []byte. (This is important when working either with very large blobs, or more commonly, a large number of moderate-sized blobs concurrently.)
Deadlines and Cancellation ¶
Every connection can have a done channel associated with it using the SetInterrupt method. This is typically the channel returned by a context.Context Done method.
As database connections are long-lived, the SetInterrupt method can be called multiple times to reset the associated lifetime.
Transactions ¶
SQLite transactions have to be managed manually with this package by directly calling BEGIN / COMMIT / ROLLBACK or SAVEPOINT / RELEASE/ ROLLBACK. The sqlitex has a Savepoint function that helps automate this.
Example ¶
package main import ( "fmt" "zombiezen.com/go/sqlite" "zombiezen.com/go/sqlite/sqlitex" ) func main() { // Open an in-memory database. conn, err := sqlite.OpenConn(":memory:") if err != nil { // handle error } defer conn.Close() // Execute a query. err = sqlitex.ExecuteTransient(conn, "SELECT 'hello, world';", &sqlitex.ExecOptions{ ResultFunc: func(stmt *sqlite.Stmt) error { fmt.Println(stmt.ColumnText(0)) return nil }, }) if err != nil { // handle error } }
Output: hello, world
Example (Http) ¶
Using a Pool to execute SQL in a concurrent HTTP handler.
package main import ( "fmt" "log" "net/http" "zombiezen.com/go/sqlite/sqlitex" ) var dbpool *sqlitex.Pool // Using a Pool to execute SQL in a concurrent HTTP handler. func main() { var err error dbpool, err = sqlitex.Open("file:memory:?mode=memory", 0, 10) if err != nil { log.Fatal(err) } http.HandleFunc("/", handle) log.Fatal(http.ListenAndServe(":8080", nil)) } func handle(w http.ResponseWriter, r *http.Request) { conn := dbpool.Get(r.Context()) if conn == nil { return } defer dbpool.Put(conn) stmt := conn.Prep("SELECT foo FROM footable WHERE id = $id;") stmt.SetText("$id", "_user_id_") for { if hasRow, err := stmt.Step(); err != nil { // ... handle error } else if !hasRow { break } foo := stmt.GetText("foo") // ... use foo fmt.Fprintln(w, foo) } }
Output:
Example (WithoutX) ¶
This is the same as the main package example, but uses the SQLite statement API instead of sqlitex.
package main import ( "fmt" "zombiezen.com/go/sqlite" ) func main() { // Open an in-memory database. conn, err := sqlite.OpenConn(":memory:") 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 ¶
- Constants
- func ConcatChangesets(w io.Writer, changeset1, changeset2 io.Reader) error
- func InvertChangeset(w io.Writer, r io.Reader) error
- type Action
- func (action Action) Accessor() string
- func (action Action) Column() string
- func (action Action) Database() string
- func (action Action) File() string
- func (action Action) Index() string
- func (action Action) Module() string
- func (action Action) Operation() string
- func (action Action) Pragma() string
- func (action Action) PragmaArg() string
- func (action Action) Savepoint() string
- func (action Action) String() string
- func (action Action) Table() string
- func (action Action) Trigger() string
- func (action Action) Type() OpType
- func (action Action) View() string
- type AggregateFunction
- type AuthResult
- type AuthorizeFunc
- type Authorizer
- type Backup
- type Blob
- func (blob *Blob) Close() error
- func (blob *Blob) Read(p []byte) (int, error)
- func (blob *Blob) ReadFrom(r io.Reader) (n int64, err error)
- func (blob *Blob) Seek(offset int64, whence int) (int64, error)
- func (blob *Blob) Size() int64
- func (blob *Blob) Write(p []byte) (int, error)
- func (blob *Blob) WriteString(s string) (int, error)
- func (blob *Blob) WriteTo(w io.Writer) (n int64, err error)
- type Changegroup
- type ChangesetIterator
- func (iter *ChangesetIterator) Close() error
- func (iter *ChangesetIterator) ConflictValue(col int) (Value, error)
- func (iter *ChangesetIterator) ForeignKeyConflicts() (int, error)
- func (iter *ChangesetIterator) New(col int) (Value, error)
- func (iter *ChangesetIterator) Next() (rowReturned bool, err error)
- func (iter *ChangesetIterator) Old(col int) (Value, error)
- func (iter *ChangesetIterator) Operation() (*ChangesetOperation, error)
- func (iter *ChangesetIterator) PrimaryKey() ([]bool, error)
- type ChangesetOperation
- type ColumnType
- type ConflictAction
- type ConflictHandler
- type ConflictType
- type Conn
- func (c *Conn) ApplyChangeset(r io.Reader, filterFn func(tableName string) bool, conflictFn ConflictHandler) error
- func (c *Conn) ApplyInverseChangeset(r io.Reader, filterFn func(tableName string) bool, conflictFn ConflictHandler) error
- func (c *Conn) AutocommitEnabled() bool
- func (c *Conn) Changes() int
- func (c *Conn) CheckReset() string
- func (c *Conn) Close() error
- func (c *Conn) CreateFunction(name string, impl *FunctionImpl) error
- func (c *Conn) CreateSession(db string) (*Session, error)
- func (c *Conn) LastInsertRowID() int64
- func (c *Conn) Limit(id Limit, value int32) int32
- func (c *Conn) OpenBlob(dbn, table, column string, row int64, write bool) (*Blob, error)
- func (c *Conn) Prep(query string) *Stmt
- func (c *Conn) Prepare(query string) (*Stmt, error)
- func (c *Conn) PrepareTransient(query string) (stmt *Stmt, trailingBytes int, err error)
- func (c *Conn) SetAuthorizer(auth Authorizer) error
- func (c *Conn) SetBlockOnBusy()
- func (c *Conn) SetBusyTimeout(d time.Duration)
- func (c *Conn) SetDefensive(enabled bool) error
- func (c *Conn) SetInterrupt(doneCh <-chan struct{}) (oldDoneCh <-chan struct{})
- type Context
- type FunctionImpl
- type Limit
- type OpType
- type OpenFlags
- type ResultCode
- type Session
- type Stmt
- func (stmt *Stmt) BindBool(param int, value bool)
- func (stmt *Stmt) BindBytes(param int, value []byte)
- func (stmt *Stmt) BindFloat(param int, value float64)
- func (stmt *Stmt) BindInt64(param int, value int64)
- func (stmt *Stmt) BindNull(param int)
- func (stmt *Stmt) BindParamCount() int
- func (stmt *Stmt) BindParamName(i int) string
- func (stmt *Stmt) BindText(param int, value string)
- func (stmt *Stmt) BindZeroBlob(param int, len int64)
- func (stmt *Stmt) ClearBindings() error
- func (stmt *Stmt) ColumnBool(col int) bool
- func (stmt *Stmt) ColumnBytes(col int, buf []byte) int
- func (stmt *Stmt) ColumnCount() int
- func (stmt *Stmt) ColumnDatabaseName(col int) string
- func (stmt *Stmt) ColumnFloat(col int) float64
- func (stmt *Stmt) ColumnIndex(colName string) int
- func (stmt *Stmt) ColumnInt(col int) int
- func (stmt *Stmt) ColumnInt32(col int) int32
- func (stmt *Stmt) ColumnInt64(col int) int64
- func (stmt *Stmt) ColumnLen(col int) int
- func (stmt *Stmt) ColumnName(col int) string
- func (stmt *Stmt) ColumnReader(col int) *bytes.Reader
- func (stmt *Stmt) ColumnTableName(col int) string
- func (stmt *Stmt) ColumnText(col int) string
- func (stmt *Stmt) ColumnType(col int) ColumnType
- func (stmt *Stmt) DataCount() int
- func (stmt *Stmt) Finalize() error
- func (stmt *Stmt) GetBool(colName string) bool
- func (stmt *Stmt) GetBytes(colName string, buf []byte) int
- func (stmt *Stmt) GetFloat(colName string) float64
- func (stmt *Stmt) GetInt64(colName string) int64
- func (stmt *Stmt) GetLen(colName string) int
- func (stmt *Stmt) GetReader(colName string) *bytes.Reader
- func (stmt *Stmt) GetText(colName string) string
- func (stmt *Stmt) Reset() error
- func (stmt *Stmt) SetBool(param string, value bool)
- func (stmt *Stmt) SetBytes(param string, value []byte)
- func (stmt *Stmt) SetFloat(param string, value float64)
- func (stmt *Stmt) SetInt64(param string, value int64)
- func (stmt *Stmt) SetNull(param string)
- func (stmt *Stmt) SetText(param string, value string)
- func (stmt *Stmt) SetZeroBlob(param string, len int64)
- func (stmt *Stmt) Step() (rowReturned bool, err error)
- type Value
Examples ¶
Constants ¶
const ( ChangesetData = ConflictType(lib.SQLITE_CHANGESET_DATA) ChangesetNotFound = ConflictType(lib.SQLITE_CHANGESET_NOTFOUND) ChangesetConflict = ConflictType(lib.SQLITE_CHANGESET_CONFLICT) ChangesetConstraint = ConflictType(lib.SQLITE_CHANGESET_CONSTRAINT) ChangesetForeignKey = ConflictType(lib.SQLITE_CHANGESET_FOREIGN_KEY) )
Conflict types.
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.
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.
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
ConcatChangesets concatenates two changesets into a single changeset.
func InvertChangeset ¶ added in v0.6.0
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.
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
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
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
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
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
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
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
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
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
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
Savepoint returns the name given to the SAVEPOINT statement or the empty string if the action does not represent a SAVEPOINT statement.
func (Action) Table ¶ added in v0.5.0
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
Trigger returns the name of the trigger 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. 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. WindowInverse(ctx Context, rowArgs []Value) error // WindowValue is called to get the current value of an aggregate window function. // This function will not be called when using an aggregate window function // as an ordinary 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
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
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
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
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
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: []interface{}{len(dataToInsert)}, }, ) if err != nil { // handle error } // Open a handle to the "myblob" column on the row we just inserted. blob, err := conn.OpenBlob("", "blobs", "myblob", conn.LastInsertRowID(), true) if err != nil { // handle error } _, writeErr := blob.WriteString(dataToInsert) closeErr := blob.Close() if writeErr != nil { // handle error } if closeErr != nil { // handle error } // Read back the blob. var data []byte err = sqlitex.ExecuteTransient(conn, `SELECT myblob FROM blobs;`, &sqlitex.ExecOptions{ ResultFunc: func(stmt *sqlite.Stmt) error { data = make([]byte, stmt.ColumnLen(0)) stmt.ColumnBytes(0, data) return nil }, }) if err != nil { // handle error } fmt.Printf("%s\n", data) }
Output: Hello, World!
func (*Blob) Close ¶
Close releases any resources associated with the blob handle. https://www.sqlite.org/c3ref/blob_close.html
func (*Blob) Read ¶
Read reads up to len(p) bytes from the blob into p. https://www.sqlite.org/c3ref/blob_read.html
func (*Blob) Seek ¶
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) Write ¶
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
WriteString writes s to the blob. https://www.sqlite.org/c3ref/blob_write.html
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.
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.
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.
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.
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.
func (*ChangesetIterator) Operation ¶ added in v0.6.0
func (iter *ChangesetIterator) Operation() (*ChangesetOperation, error)
Operation obtains the current operation from the iterator.
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.
type ChangesetOperation ¶ added in v0.6.0
type ChangesetOperation struct { // Type is one of OpInsert, OpDelete, or OpUpdate. Type OpType // TableName is the name of the table affected by the change. TableName string // NumColumns is the number of columns in the table affected by the change. NumColumns int // Indirect is true if the session object "indirect" flag was set when the // change was made or the change was made by an SQL trigger or foreign key // action instead of directly as a result of a users SQL statement. Indirect bool }
ChangesetOperation holds information about a change in a changeset.
type ColumnType ¶
type ColumnType int
ColumnType are codes for each of the SQLite fundamental datatypes:
- 64-bit signed integer
- 64-bit IEEE floating point number
- string
- BLOB
- NULL
https://www.sqlite.org/c3ref/c_blob.html
const ( TypeInteger ColumnType = lib.SQLITE_INTEGER TypeFloat ColumnType = lib.SQLITE_FLOAT TypeText ColumnType = lib.SQLITE_TEXT TypeBlob ColumnType = lib.SQLITE_BLOB TypeNull ColumnType = lib.SQLITE_NULL )
Data types.
func (ColumnType) String ¶
func (t ColumnType) String() string
String returns the SQLite constant name of the type.
type ConflictAction ¶ added in v0.6.0
type ConflictAction int32
ConflictAction is an enumeration of actions that can be taken in response to a changeset conflict. The zero value is ChangesetOmit.
https://www.sqlite.org/session/c_changeset_abort.html
func (ConflictAction) String ¶ added in v0.6.0
func (code ConflictAction) String() string
String returns the C constant name of the conflict action.
type ConflictHandler ¶ added in v0.6.0
type ConflictHandler func(ConflictType, *ChangesetIterator) ConflictAction
A ConflictHandler function determines the action to take to resolve a conflict while applying a changeset.
type ConflictType ¶ added in v0.6.0
type ConflictType int32
ConflictType is an enumeration of changeset conflict types.
https://www.sqlite.org/session/c_changeset_conflict.html
func (ConflictType) String ¶ added in v0.6.0
func (code ConflictType) String() string
String returns the C constant name of the conflict type.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is an open connection to an SQLite3 database.
A Conn can only be used by goroutine at a time.
func OpenConn ¶
OpenConn opens a single SQLite database connection with the given flags. No flags or a value of 0 defaults to the following:
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 ¶
AutocommitEnabled reports whether conn is in autocommit mode. https://sqlite.org/c3ref/get_autocommit.html
func (*Conn) CheckReset ¶
CheckReset reports whether any statement on this connection is in the process of returning results.
func (*Conn) Close ¶
Close closes the database connection using sqlite3_close and finalizes persistent prepared statements. https://www.sqlite.org/c3ref/close.html
func (*Conn) CreateFunction ¶
func (c *Conn) CreateFunction(name string, impl *FunctionImpl) error
CreateFunction registers a Go function with SQLite for use in SQL queries.
https://sqlite.org/appfunc.html
Example ¶
package main import ( "fmt" "regexp" "zombiezen.com/go/sqlite" "zombiezen.com/go/sqlite/sqlitex" ) func main() { conn, err := sqlite.OpenConn(":memory:") 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
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.
func (*Conn) LastInsertRowID ¶
LastInsertRowID reports the rowid of the most recently successful INSERT.
func (*Conn) Limit ¶ added in v0.5.0
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.
func (*Conn) Prep ¶
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.
func (*Conn) Prepare ¶
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.
func (*Conn) PrepareTransient ¶
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.
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.
func (*Conn) SetBusyTimeout ¶
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.
func (*Conn) SetDefensive ¶ added in v0.5.0
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:
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
AuxData returns the auxiliary data associated with the given argument, with zero being the leftmost argument, or nil if no such data is present.
Auxiliary data may be used by (non-aggregate) SQL functions to associate metadata with argument values. If the same value is passed to multiple invocations of the same SQL function during query execution, under some circumstances the associated metadata may be preserved. An example of where this might be useful is in a regular-expression matching function. The compiled version of the regular expression can be stored as metadata associated with the pattern string. Then as long as the pattern string remains the same, the compiled regular expression can be reused on multiple invocations of the same function.
For more details, see https://www.sqlite.org/c3ref/get_auxdata.html
Example ¶
This example shows the same regexp function as in the CreateFunction example, but it uses auxiliary data to avoid recompiling the regular expression.
package main import ( "fmt" "regexp" "zombiezen.com/go/sqlite" "zombiezen.com/go/sqlite/sqlitex" ) func main() { conn, err := sqlite.OpenConn(":memory:") 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
Conn returns the database connection that is calling the SQL function.
func (Context) SetAuxData ¶ added in v0.4.0
SetAuxData sets the auxiliary data associated with the given argument, with zero being the leftmost argument. SQLite is free to discard the metadata at any time, including during the call to SetAuxData.
Auxiliary data may be used by (non-aggregate) SQL functions to associate metadata with argument values. If the same value is passed to multiple invocations of the same SQL function during query execution, under some circumstances the associated metadata may be preserved. An example of where this might be useful is in a regular-expression matching function. The compiled version of the regular expression can be stored as metadata associated with the pattern string. Then as long as the pattern string remains the same, the compiled regular expression can be reused on multiple invocations of the same function.
For more details, see https://www.sqlite.org/c3ref/get_auxdata.html
type FunctionImpl ¶ added in v0.2.0
type FunctionImpl struct { // NArgs is the required number of arguments that the function accepts. // If NArgs is negative, then the function is variadic. // // Multiple function implementations may be registered with the same name // with different numbers of required arguments. NArgs int // Scalar is called when a scalar function is invoked in SQL. Scalar func(ctx Context, args []Value) (Value, error) // 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 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.
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
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 // 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.
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 ResultBusyRecovery ResultCode = lib.SQLITE_BUSY_RECOVERY ResultBusySnapshot ResultCode = lib.SQLITE_BUSY_SNAPSHOT ResultCantOpenNoTempDir ResultCode = lib.SQLITE_CANTOPEN_NOTEMPDIR ResultCantOpenIsDir ResultCode = lib.SQLITE_CANTOPEN_ISDIR ResultCantOpenFullPath ResultCode = lib.SQLITE_CANTOPEN_FULLPATH ResultCantOpenConvPath ResultCode = lib.SQLITE_CANTOPEN_CONVPATH ResultCorruptVTab ResultCode = lib.SQLITE_CORRUPT_VTAB ResultReadOnlyRecovery ResultCode = lib.SQLITE_READONLY_RECOVERY ResultReadOnlyCantLock ResultCode = lib.SQLITE_READONLY_CANTLOCK ResultReadOnlyRollback ResultCode = lib.SQLITE_READONLY_ROLLBACK ResultReadOnlyDBMoved ResultCode = lib.SQLITE_READONLY_DBMOVED ResultReadOnlyCantInit ResultCode = lib.SQLITE_READONLY_CANTINIT ResultReadOnlyDirectory ResultCode = lib.SQLITE_READONLY_DIRECTORY ResultAbortRollback ResultCode = lib.SQLITE_ABORT_ROLLBACK ResultConstraintCheck ResultCode = lib.SQLITE_CONSTRAINT_CHECK ResultConstraintCommitHook ResultCode = lib.SQLITE_CONSTRAINT_COMMITHOOK ResultConstraintForeignKey ResultCode = lib.SQLITE_CONSTRAINT_FOREIGNKEY ResultConstraintFunction ResultCode = lib.SQLITE_CONSTRAINT_FUNCTION ResultConstraintNotNull ResultCode = lib.SQLITE_CONSTRAINT_NOTNULL ResultConstraintPrimaryKey ResultCode = lib.SQLITE_CONSTRAINT_PRIMARYKEY ResultConstraintTrigger ResultCode = lib.SQLITE_CONSTRAINT_TRIGGER ResultConstraintUnique ResultCode = lib.SQLITE_CONSTRAINT_UNIQUE ResultConstraintVTab ResultCode = lib.SQLITE_CONSTRAINT_VTAB ResultConstraintRowID ResultCode = lib.SQLITE_CONSTRAINT_ROWID ResultNoticeRecoverWAL ResultCode = lib.SQLITE_NOTICE_RECOVER_WAL ResultNoticeRecoverRollback ResultCode = lib.SQLITE_NOTICE_RECOVER_ROLLBACK ResultWarningAutoIndex ResultCode = lib.SQLITE_WARNING_AUTOINDEX ResultAuthUser ResultCode = lib.SQLITE_AUTH_USER )
Extended result codes.
func ErrCode ¶
func ErrCode(err error) ResultCode
ErrCode returns the error's SQLite error code or ResultError if the error does not represent a SQLite error. ErrorCode returns ResultOK if and only if the error is nil.
func (ResultCode) IsSuccess ¶
func (code ResultCode) IsSuccess() bool
IsSuccess reports whether code indicates success.
func (ResultCode) Message ¶
func (code ResultCode) Message() string
Message returns the English-language text that describes the result code.
func (ResultCode) String ¶
func (code ResultCode) String() string
String returns the C constant name of the result code.
func (ResultCode) ToError ¶ added in v0.9.0
func (code ResultCode) ToError() error
ToError converts an error code into an error for which ErrCode(code.ToError()) == code. If the code indicates success, ToError returns nil.
func (ResultCode) ToPrimary ¶
func (code ResultCode) ToPrimary() ResultCode
ToPrimary returns the primary result code of the given code. https://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes
type Session ¶ added in v0.6.0
type Session struct {
// contains filtered or unexported fields
}
A Session tracks database changes made by a Conn. It is used to build changesets.
For more details: https://www.sqlite.org/sessionintro.html
func (*Session) Attach ¶ added in v0.6.0
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
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.
func (*Session) Disable ¶ added in v0.6.0
func (s *Session) Disable()
Disable disables recording of changes.
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.
func (*Session) WriteChangeset ¶ added in v0.6.0
WriteChangeset generates a changeset from a session.
https://www.sqlite.org/session/sqlite3session_changeset.html
func (*Session) WritePatchset ¶ added in v0.6.0
WritePatchset generates a patchset from a session.
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 ¶
BindBool binds value (as an integer 0 or 1) to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindBytes ¶
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.
func (*Stmt) BindFloat ¶
BindFloat binds value to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindInt64 ¶
BindInt64 binds value to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindNull ¶
BindNull binds an SQL NULL value to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindParamCount ¶
BindParamCount reports the number of parameters in stmt.
func (*Stmt) BindParamName ¶
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.
func (*Stmt) BindText ¶
BindText binds value to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) BindZeroBlob ¶
BindZeroBlob binds a blob of zeros of length len to a numbered stmt parameter.
Parameter indices start at 1.
func (*Stmt) ClearBindings ¶
ClearBindings clears all bound parameter values on a statement.
func (*Stmt) ColumnBool ¶ added in v0.9.0
ColumnBool reports whether a query result value is non-zero.
Column indices start at 0.
func (*Stmt) ColumnBytes ¶
ColumnBytes reads a query result into buf. It reports the number of bytes read.
Column indices start at 0.
func (*Stmt) ColumnCount ¶
ColumnCount returns the number of columns in the result set returned by the prepared statement.
func (*Stmt) ColumnDatabaseName ¶
func (*Stmt) ColumnFloat ¶
ColumnFloat returns a query result as a float64.
Column indices start at 0.
func (*Stmt) ColumnIndex ¶
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 ¶
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.
func (*Stmt) ColumnInt32 ¶
ColumnInt32 returns a query result value as an int32.
Column indices start at 0.
func (*Stmt) ColumnInt64 ¶
ColumnInt64 returns a query result value as an int64.
Column indices start at 0.
func (*Stmt) ColumnLen ¶
ColumnLen returns the number of bytes in a query result.
Column indices start at 0.
func (*Stmt) ColumnName ¶
ColumnName returns the name assigned to a particular column in the result set of a SELECT statement.
func (*Stmt) ColumnReader ¶
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) 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.
func (*Stmt) DataCount ¶
DataCount returns the number of columns in the current row of the result set of prepared statement.
func (*Stmt) Finalize ¶
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.
func (*Stmt) GetBool ¶ added in v0.9.0
GetBool reports whether the query result value for colName is non-zero.
func (*Stmt) GetBytes ¶
GetBytes reads a query result for colName into buf. It reports the number of bytes read.
func (*Stmt) GetReader ¶
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) Reset ¶
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.
func (*Stmt) SetBytes ¶
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 ¶
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) SetNull ¶
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 ¶
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 ¶
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 ¶
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 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
BlobValue returns a new blob Value, copying the bytes from the given byte slice.
func FloatValue ¶ added in v0.2.0
FloatValue returns a new Value representing the given floating-point number.
func IntegerValue ¶ added in v0.2.0
IntegerValue returns a new Value representing the given integer.
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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
zombiezen-sqlite-migrate
Module
|
|
Package fs provides a fallback for the io/fs package in Go 1.16.
|
Package fs provides a fallback for the io/fs package in Go 1.16. |
Package shell provides a minimal SQLite REPL, similar to the built-in one.
|
Package shell provides a minimal SQLite REPL, similar to the built-in one. |
Package sqlitefile provides bytes buffers backed by a temporary SQLite table.
|
Package sqlitefile provides bytes buffers backed by a temporary SQLite table. |
Package sqlitemigration provides a connection pool type that guarantees a series of SQL scripts has been run once successfully before making connections available to the application.
|
Package sqlitemigration provides a connection pool type that guarantees a series of SQL scripts has been run once successfully before making connections available to the application. |
Package sqlitex provides utilities for working with SQLite.
|
Package sqlitex provides utilities for working with SQLite. |