### Open method example Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/driver.md Example of using the Open method via database/sql with a SQLite URI that sets foreign keys and busy timeout. The connection is opened with sql.Open and deferred close. ```go import ( "database/sql" _ "modernc.org/sqlite" ) db, err := sql.Open("sqlite", "file:/tmp/mydata.sqlite?_pragma=foreign_keys(1)&_busy_timeout=5000") if err != nil { return err } defer db.Close() ``` -------------------------------- ### Open database with DSN parameters Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/configuration.md Examples of opening a database connection using various DSN query parameters for read-only access, configuration, time handling, and custom VFS. ```go // Read-only open; every write fails with SQLITE_READONLY. db, _ := sql.Open("sqlite", "file:/srv/data/app.db?mode=ro") // Comma-free migration-friendly DSN. db, _ := sql.Open("sqlite", "app.db?_busy_timeout=5000&_journal_mode=WAL&_auto_vacuum=INCREMENTAL&_foreign_keys=on") // Times as Unix-nano integers in UTC. db, _ := sql.Open("sqlite", "app.db?_time_integer_format=unix_nano&_timezone=UTC") // Database shipped read-only inside the binary. name, fsvfs, _ := vfs.New(embedded) db, _ := sql.Open("sqlite", "file:data/app.db?vfs="+name) ``` -------------------------------- ### Observing cache pressure with pool.Stats() Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/pcache.md Example of observing cache pressure: create a pool, register it, run queries, then print stats. The Stats() method returns a snapshot of the pool's lifetime counters. ```go pool := pcache.New() sqlite.MustRegisterPageCache(pool) // ... run queries ... s := pool.Stats() fmt.Printf("hits=%d misses=%d evictions=%d easyRefusals=%d\n", s.Hits, s.Misses, s.Evictions, s.EasyRefusals) ``` -------------------------------- ### Private driver with per-driver function Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/driver.md Example of creating a private driver with no package-level registrations and registering a deterministic scalar function on it. The driver is then registered with database/sql and used to open an in-memory database. ```go import ( "database/sql" "database/sql/driver" "modernc.org/sqlite" ) drv := &sqlite.Driver{} // empty: no package-level registrations drv.MustRegisterDeterministicScalarFunction("version", 0, func(*sqlite.FunctionContext, []driver.Value) (driver.Value, error) { return int64(3), nil }) sql.Register("sqlite-private", drv) db, err := sql.Open("sqlite-private", ":memory:") ``` -------------------------------- ### Ship a database inside the binary with embed.FS Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/vfs.md Complete example of shipping a database inside the binary using embed.FS. The VFS is created from the embedded file system and the database is opened with the vfs DSN parameter. The comment notes that the database keeps the VFS alive, so fsvfs.Close() should be called after db.Close(). ```go import ( "database/sql" "embed" _ "modernc.org/sqlite" "modernc.org/sqlite/vfs" ) //go:embed data var data embed.FS func open() (*sql.DB, error) { name, fsvfs, err := vfs.New(data) if err != nil { return nil, err } db, err := sql.Open("sqlite", "file:data/app.db?vfs="+name) if err != nil { fsvfs.Close() return nil, err } // The db keeps the VFS alive; arrange fsvfs.Close() for after db.Close(). return db, nil } ``` -------------------------------- ### DSN Parameter Configuration (modernc.org/sqlite) Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/configuration.md Describes how to configure the SQLite driver via DSN query parameters, including pragmas, time formatting, transaction locking, and VFS selection, with Go code examples. ```APIDOC ## DSN Query Parameters ### Description DSN query parameters configure the modernc.org/sqlite Go driver. Parameters are passed as query strings in the DSN (e.g., `app.db?_busy_timeout=5000&_journal_mode=WAL`). Keys not interpreted by the driver are silently ignored, except for SQLite URI parameters in `file:` names. All parameters are validated before application, so an invalid DSN leaves no side effects. ### Supported Parameters | Key | Alias | Type / values | Default | Description | | --- | --- | --- | --- | --- | | `_pragma` | — | raw SQL text | — | Each value runs with `PRAGMA` prepended, as SQL text — anything after `;` executes too (a DSN with `_pragma` must come from a trusted source). Applied after `_busy_timeout`/`_auto_vacuum`, in lexicographic order. Under `StrictPragmas(true)` a multi-statement value fails with `ErrMultiStatementPragma`. | | `_busy_timeout` | `_timeout` | integer | — | Sets `PRAGMA busy_timeout`. | | `_auto_vacuum` | `_vacuum` | `0 NONE 1 FULL 2 INCREMENTAL` | — | Sets `PRAGMA auto_vacuum`; applied while the database is still new. | | `_foreign_keys` | `_fk` | bool (`0 1 false true no yes off on`) | — | Sets `PRAGMA foreign_keys`. | | `_journal_mode` | `_journal` | `DELETE TRUNCATE PERSIST MEMORY WAL OFF` | — | Sets `PRAGMA journal_mode`; combined with `_defensive=1`, `OFF` is rejected. | | `_synchronous` | `_sync` | `0 OFF 1 NORMAL 2 FULL 3 EXTRA` | — | Sets `PRAGMA synchronous`. | | `_query_only` | — | bool | — | Sets `PRAGMA query_only`; applied last. | | `_time_format` | — | `sqlite` or `datetime` | Go `time.Time.String()` format | Format for writing time values: `sqlite` = `YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM`, `datetime` = `YYYY-MM-DD HH:MM:SS`. | | `_time_integer_format` | — | `unix`, `unix_milli`, `unix_micro`, `unix_nano` | not set (times stored as strings) | Stores times as integers since the Unix epoch. Overrides `_time_format` when both are set. | | `_inttotime` | — | bool | false | Converts INTEGER values from DATE/DATETIME/TIMESTAMP columns to `time.Time` on read. | | `_texttotime` | — | bool | false | `ColumnTypeScanType` reports `time.Time` for TEXT columns declared DATE/DATETIME/TIME/TIMESTAMP; best-effort upgrade of date-shaped TEXT. | | `_timezone` | — | IANA name (`time.LoadLocation`) | local time | TZ for all time reads and writes. | | `_txlock` | — | `deferred`, `immediate`, `exclusive` (case-insensitive) | `deferred` | Locking behavior for `BEGIN` of driver-initiated transactions. | | `_dqs` | — | bool | true (SQLite default) | `false` disables double-quoted-string-literal fallback. | | `_defensive` | — | bool | false | Sets `SQLITE_DBCONFIG_DEFENSIVE` right after `sqlite3_open_v2`. Must appear at most once. | | `_error_rc` | — | bool | false | Error-string reporting mode for synthesized errors. | | `vfs` | — | VFS name | default VFS | Passed as `sqlite3_open_v2` `zVfs`; works in plain file names too. Selecting `modernc.org/sqlite/vfs.New` output opens a database from an `fs.FS` read-only. Supplying it more than once with differing values is an error. | | `mode`, `cache`, `immutable`, `nolock`, `psow`, `modeof` | — | SQLite URI parameters | — | Interpreted by SQLite only — take effect only in `file:` names. | ### Application Order Apply order is fixed, independent of DSN order: `_busy_timeout` and `_auto_vacuum` first, then `_pragma` values, then `_foreign_keys`, `_journal_mode`, `_synchronous`, and `_query_only` last. Where a shorthand key and `_pragma` set the same PRAGMA, whichever applies later wins; a key and its alias both supplied resolves to the alias. ### Validation All validated parameters are validated before any is applied, so a rejected DSN leaves no side effects on the database file. `_defensive` and `_error_rc` are parsed before `sqlite3_open_v2`. ### Examples ```go // Read-only open; every write fails with SQLITE_READONLY. db, _ := sql.Open("sqlite", "file:/srv/data/app.db?mode=ro") // Comma-free migration-friendly DSN. db, _ := sql.Open("sqlite", "app.db?_busy_timeout=5000&_journal_mode=WAL&_auto_vacuum=INCREMENTAL&_foreign_keys=on") // Times as Unix-nano integers in UTC. db, _ := sql.Open("sqlite", "app.db?_time_integer_format=unix_nano&_timezone=UTC") // Database shipped read-only inside the binary. name, fsvfs, _ := vfs.New(embedded) db, _ := sql.Open("sqlite", "file:data/app.db?vfs="+name) ``` ``` -------------------------------- ### Create a connector with sqlite.NewConnector and open with sql.OpenDB Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/connector.md Creates a connector with a DSN that sets the foreign_keys pragma, then opens a database with sql.OpenDB. Validation of the DSN is limited at construction time; errors from unknown parameters or out-of-range values are deferred to Connect. ```go c, err := sqlite.NewConnector("file:app.db?_pragma=foreign_keys(1)") if err != nil { return err } db := sql.OpenDB(c) defer db.Close() ``` -------------------------------- ### SetRegisterFunc Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/vtab.md Installs the engine's registration hook. Intended for the engine package; external callers should use RegisterModule. ```APIDOC ## SetRegisterFunc ### Description Installs the engine's registration hook. Intended for the engine package; external callers should use `RegisterModule`. ### Function Signature `func SetRegisterFunc(fn func(name string, m Module) error)` ### Parameters - **fn** (func(name string, m Module) error) - Required - The registration hook function. ``` -------------------------------- ### ErrNotImplemented variable declaration Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/vtab.md Error returned by RegisterModule when no registration hook is installed. This occurs when the engine package has not wired the hook. ```go var ErrNotImplemented = errors.New("vtab: RegisterModule not wired into engine") ``` -------------------------------- ### Progress-aware backup with explicit cleanup Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/backup.md Shows a loop that calls Step with a chunk size of 64 pages, prints progress using Remaining and PageCount, and defers Finish to ensure resources are released on every path. ```go conn.Raw(func(driverConn any) error { b, err := driverConn.(backupMaker).NewBackup(dstPath) if err != nil { return err } defer b.Finish() // Ensure resources are released on every path. const chunk = 64 // pages per Step for { more, err := b.Step(chunk) if err != nil { return err } remaining, total := b.Remaining(), b.PageCount() fmt.Printf("backed up %d/%d pages\n", total-remaining, total) if !more { return nil } } }) ``` -------------------------------- ### Error handling: duplicate registration Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/driver.md Example of handling an error from RegisterScalarFunction when a function name is already registered. The error message is shown in a comment. ```go err := drv.RegisterScalarFunction("twice", 1, f) if err != nil { // "a function named \"twice\" is already registered" return err } ``` -------------------------------- ### Querying DBStatusCacheSpill counter Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/introspection.md Example of using DBStatus.Status to retrieve the current and high-water values of the DBStatusCacheSpill counter. The error is non-nil only when SQLite rejects the op as out of range. ```go err := sconn.Raw(func(dc any) error { cur, high, err := dc.(sqlite.DBStatus).Status(sqlite.DBStatusCacheSpill, false) if err != nil { return err } // cur bytes spilled from the cache; high is 0 for running counters return nil }) ``` -------------------------------- ### Using FileControlDataVersion for cache invalidation Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/introspection.md Example of using FileControlDataVersion inside sql.Conn.Raw to obtain a cache invalidation token. The returned version changes when the database file contents change. ```go err := sconn.Raw(func(dc any) error { fc := dc.(sqlite.FileControl) v, err := fc.FileControlDataVersion("main") if err != nil { return err } // use v as a cache invalidation token return nil }) ``` -------------------------------- ### Open a database with vfs.New and the vfs DSN parameter Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/vfs.md Creates a new VFS from a directory file system and opens a database using the generated VFS name in the DSN query parameter. The VFS is read-only and refuses to create a journal. ```go name, fsvfs, err := vfs.New(os.DirFS(dir)) if err != nil { return err } defer fsvfs.Close() db, err := sql.Open("sqlite", "file:test.db?vfs="+name) ``` -------------------------------- ### Driver.Open Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/driver.md Opens a new database connection. Accepts a plain file name or a SQLite URI with optional query parameters. Performs connection initialization including DSN parsing, sqlite3_open_v2, and registration of user-defined functions, collations, hooks, and virtual table modules. ```APIDOC ## Open(name string) (conn driver.Conn, err error) ### Description Opens a new database connection. `name` is either a plain file name (`"/tmp/mydata.sqlite"`) or a SQLite URI (`"file:///tmp/mydata.sqlite"`), either optionally followed by `?` and query parameters. Performs DSN parsing, opens the database with sqlite3_open_v2, enables extended result codes, applies DSN parameters, and registers user-defined functions, collations, connection hooks, and virtual table modules. Returns a `driver.Conn` usable by one goroutine at a time. ### Method Open ### Parameters #### name (string) - Required File path or `file:` URI plus query parameters. ### Return `driver.Conn` - database connection ### Example ```go import ( "database/sql" _ "modernc.org/sqlite" ) db, err := sql.Open("sqlite", "file:/tmp/mydata.sqlite?_pragma=foreign_keys(1)&_busy_timeout=5000") if err != nil { return err } defer db.Close() ``` ``` -------------------------------- ### Build and test commands Source: https://github.com/modernc-org/sqlite/blob/master/CONTRIBUTING.md Quick check: compiles tests and builds everything. Use for a single test, the whole suite, or the suite through the pluggable page cache. Also includes commands for linting and cross-building all supported targets. ```sh make editor # quick check: compiles tests, builds everything ``` ```sh go test -v -run TestFoo # a single test; the suite is long ``` ```sh make test # the whole suite; it is long ``` ```sh make test_pcache # the suite again, through the pluggable page cache ``` ```sh make all # editor plus golint and staticcheck ``` ```sh make build_all_targets # cross-build every supported GOOS/GOARCH ``` -------------------------------- ### Veto a commit with RegisterCommitHook Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/hooks.md Registers a commit hook that returns a non-zero value to abort a COMMIT. The example shows the hook registration and a subsequent transaction that fails because the commit is vetoed. ```go conn.Raw(func(driverConn any) error { hooker := driverConn.(sqlite.HookRegisterer) hooker.RegisterCommitHook(func() int32 { fmt.Println("commit vetoed") return 1 // non-zero aborts the COMMIT }) return nil }) _, err := db.Exec(`BEGIN; INSERT INTO t VALUES (2, 'bob'); COMMIT`) // err != nil: COMMIT was aborted by the hook ``` -------------------------------- ### Handle PageCache registration errors with sqlite.RegisterPageCache Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/pagecache.md Checks errors from RegisterPageCache: ErrPageCacheTooLate means register earlier, ErrPageCacheConflict means another cache is installed, and default handles sticky failures. ```go if err := sqlite.RegisterPageCache(m); err != nil { switch { case errors.Is(err, sqlite.ErrPageCacheTooLate): // Register earlier: before the first sql.Open. case errors.Is(err, sqlite.ErrPageCacheConflict): // Another module is already installed; keep it. default: // sticky first-install failure } } ``` -------------------------------- ### Copy a database across connections using NewBackup Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/backup.md Defines a backupMaker interface to type-assert the driver connection, then copies all pages from a source to a destination database. Uses Step(-1) to copy all remaining pages and Finish to release resources. ```go type backupMaker interface { NewBackup(dstUri string) (*sqlite.Backup, error) } func backup(srcPath, dstPath string) error { src, err := sql.Open("sqlite", srcPath) if err != nil { return err } defer src.Close() conn, err := src.Conn(nil) if err != nil { return err } defer conn.Close() return conn.Raw(func(driverConn any) error { b, err := driverConn.(backupMaker).NewBackup(dstPath) if err != nil { return err } defer b.Finish() // also closes the destination connection for { more, err := b.Step(-1) if err != nil || !more { return err } } }) } ``` -------------------------------- ### Using ColumnInfo via Raw Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/introspection.md Shows how to call ColumnInfo through a database/sql connection using Raw. It type-asserts the driver connection to an interface with ColumnInfo, returns an error if unsupported, and then retrieves metadata for the query "SELECT id, name FROM users". The comment indicates the fields available on each returned ColumnInfo. ```go err := sconn.Raw(func(dc any) error { ci, ok := dc.(interface { ColumnInfo(string) ([]sqlite.ColumnInfo, error) }) if !ok { return fmt.Errorf("driver does not support ColumnInfo") } info, err := ci.ColumnInfo("SELECT id, name FROM users") if err != nil { return err } // info[i].Name, info[i].DeclType, info[i].TableName, ... return nil }) ``` -------------------------------- ### Limit Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/introspection.md Sets or queries a per-connection SQLite limit identified by `id`, mapping to `sqlite3_limit`. The limits are bound to the particular connection instance; getting a new connection just to pass it to `Limit` is not useful beyond querying the configured defaults. ```APIDOC ## [FUNCTION] Limit ### Description Sets or queries a per-connection SQLite limit identified by `id`, mapping to `sqlite3_limit`. The limits are bound to the particular connection instance; getting a new connection just to pass it to `Limit` is not useful beyond querying the configured defaults. ### Function Signature `func Limit(c *sql.Conn, id int, newVal int) (r int, err error)` ### Parameters - **c** (*sql.Conn) - Required - The database connection obtained via the `database/sql` escape hatch (`sql.Conn.Raw`). - **id** (int) - Required - The SQLite limit identifier, one of the `SQLITE_LIMIT_*` constants exported by `modernc.org/sqlite/lib`. - **newVal** (int) - Required - The new limit value. Use `-1` to query the current limit without changing it. ### Supported Limit IDs | Constant | Value | Limit | | --- | --- | --- | | `SQLITE_LIMIT_LENGTH` | 0 | max size of any string or BLOB | | `SQLITE_LIMIT_SQL_LENGTH` | 1 | max length of an SQL statement | | `SQLITE_LIMIT_COLUMN` | 2 | max columns in a table/view/result set | | `SQLITE_LIMIT_EXPR_DEPTH` | 3 | max expression tree depth | | `SQLITE_LIMIT_COMPOUND_SELECT` | 4 | max terms in a compound SELECT | | `SQLITE_LIMIT_VDBE_OP` | 5 | max instructions in a virtual machine | | `SQLITE_LIMIT_FUNCTION_ARG` | 6 | max function arguments | | `SQLITE_LIMIT_ATTACHED` | 7 | max attached databases | | `SQLITE_LIMIT_LIKE_PATTERN_LENGTH` | 8 | max pattern length in LIKE/GLOB | | `SQLITE_LIMIT_VARIABLE_NUMBER` | 9 | max variable number in a statement | | `SQLITE_LIMIT_TRIGGER_DEPTH` | 10 | max trigger recursion depth | | `SQLITE_LIMIT_PARSER_DEPTH` | 12 | max parser stack depth | ### Return Value Returns the **previous** value of the limit and an error only when the raw connection is not of the expected type: `fmt.Errorf("unexpected driverConn type: %T", driverConn)`. ### Example ```go prev, err := sqlite.Limit(sconn, sqlite3.SQLITE_LIMIT_LENGTH, 1<<20) // prev == previous max length; sconn is a *sql.Conn from db.Conn(nil) ``` ``` -------------------------------- ### Register page cache in init() with MustRegisterPageCache Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/pagecache.md Use this in an init() function to register a custom page cache, panicking on any error. Must be called before the first sql.Open or driver.Open. ```go func init() { sqlite.MustRegisterPageCache(mypcache) } ``` -------------------------------- ### MIT License for go-isatty Source: https://github.com/modernc-org/sqlite/blob/master/LICENSE-3RD-PARTY.md MIT license text for github.com/mattn/go-isatty. Copyright (c) Yasuhiro MATSUMOTO . ```text Copyright (c) Yasuhiro MATSUMOTO MIT License (Expat) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` -------------------------------- ### Register scalar function upper_rev with modernc.org/sqlite Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/functions.md Registers a scalar function named 'upper_rev' that takes one argument, converts it to uppercase, and appends '_rev'. Registration must occur before the first connection is opened; the example registers before opening the database. The query returns 'SQLITE_rev' for input 'sqlite'. ```go import ( "database/sql" "database/sql/driver" "strings" "modernc.org/sqlite" ) func main() { if err := sqlite.RegisterScalarFunction("upper_rev", 1, func(ctx *sqlite.FunctionContext, args []driver.Value) (driver.Value, error) { s := args[0].(string) return strings.ToUpper(s) + "_rev", nil }); err != nil { panic(err) } db, err := sql.Open("sqlite", ":memory:") if err != nil { panic(err) } defer db.Close() var out string err = db.QueryRow(`SELECT upper_rev('sqlite')`).Scan(&out) // out == "SQLITE_rev" } ``` -------------------------------- ### Serialize and Deserialize a database using raw connection Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/introspection.md Use this Go snippet to serialize the main database to a byte slice and later restore it in another process. It calls Serialize on the raw connection, ships the blob, then calls Deserialize with the same buffer. Deserialize rejects an empty buffer with "sqlite: empty buffer passed to Deserialize". ```go conn.Raw(func(dc any) error { ser := dc.(interface{ Serialize() ([]byte, error) }) blob, err := ser.Serialize() if err != nil { return err } // ship blob to another process, then: return dc.(interface{ Deserialize([]byte) error }).Deserialize(blob) }) ``` -------------------------------- ### Register aggregate function sum_sq with error propagation Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/functions.md Registers an aggregate function 'sum_sq' that computes the sum of squares of integer values. The Step callback returns an error if a value is not an integer, which aborts the query via sqlite3_result_error with SQLITE_ERROR. The example creates a table and runs a query to demonstrate error propagation. ```go import ( "database/sql" "database/sql/driver" "errors" _ "modernc.org/sqlite" "modernc.org/sqlite" ) type sumSquares struct{ acc int64 } func (a *sumSquares) Step(ctx *sqlite.FunctionContext, args []driver.Value) error { v, ok := args[0].(int64) if !ok { return errors.New("sum_sq: expected an integer") } a.acc += v * v return nil } func (a *sumSquares) WindowInverse(ctx *sqlite.FunctionContext, args []driver.Value) error { v := args[0].(int64) a.acc -= v * v return nil } func (a *sumSquares) WindowValue(ctx *sqlite.FunctionContext) (driver.Value, error) { return a.acc, nil } func (a *sumSquares) Final(ctx *sqlite.FunctionContext) {} func main() { impl := &sqlite.FunctionImpl{ NArgs: 1, MakeAggregate: func(sqlite.FunctionContext) (sqlite.AggregateFunction, error) { return &sumSquares{}, nil }, } sqlite.MustRegisterFunction("sum_sq", impl) db, _ := sql.Open("sqlite", ":memory:") defer db.Close() db.Exec(`CREATE TABLE t(v)`) // An error returned from Step aborts the query via // sqlite3_result_error with SQLITE_ERROR. var r sql.NullInt64 err := db.QueryRow(`SELECT sum_sq(v) FROM t`).Scan(&r) // err is non-nil if any row failed the type check _ = err } ``` -------------------------------- ### Set SQLite limit with sqlite.Limit Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/introspection.md Sets a per-connection SQLite limit using sqlite.Limit, which maps to sqlite3_limit. The newVal parameter sets the limit, or -1 queries the current value. Returns the previous limit value. The example sets SQLITE_LIMIT_LENGTH to 1<<20 (1 MiB) and captures the previous value. Requires a *sql.Conn obtained from db.Conn(nil). ```go prev, err := sqlite.Limit(sconn, sqlite3.SQLITE_LIMIT_LENGTH, 1<<20) // prev == previous max length; sconn is a *sql.Conn from db.Conn(nil) ``` -------------------------------- ### Expand undup vendor output into per-target files Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/lib.md Command to expand the generated `lib/` files into per-target standalone files for reading or stepping through code. After running, use `git checkout -- lib` to restore the original state. ```sh go run modernc.org/undup@v0.0.5 -expand -dir lib # rewrites lib/ git checkout -- lib # restore ``` -------------------------------- ### BSD-3-Clause License for golang-lru simplelru/list.go Source: https://github.com/modernc-org/sqlite/blob/master/LICENSE-3RD-PARTY.md BSD-3-Clause license text for github.com/hashicorp/golang-lru/v2, specifically for simplelru/list.go. Copyright (c) 2009 The Go Authors. All rights reserved. ```text This license applies to simplelru/list.go Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ``` -------------------------------- ### func (c *connector) Connect(ctx context.Context) (driver.Conn, error) Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/connector.md Opens a new connection via the package-level driver's Open. The context is honored only up to the point the open begins; sqlite3_open_v2 is blocking with no cancellation hook. A context already cancelled before the call returns ctx.Err() immediately. ```APIDOC ## func (c *connector) Connect(ctx context.Context) (driver.Conn, error) ### Description Opens a new connection via the package-level driver's Open. The context is honored only up to the point the open begins; sqlite3_open_v2 is blocking with no cancellation hook. A context already cancelled before the call returns ctx.Err() immediately. ### Parameters - **ctx** (context.Context) - Required - The context for the connection open. ### Returns - **driver.Conn** - The opened connection. - **error** - An error if the connection could not be opened. ### Example ```go // This method is typically called by database/sql internally. // See the example in the NewConnector section for usage. ``` ``` -------------------------------- ### func NewConnector(dsn string) (driver.Connector, error) Source: https://github.com/modernc-org/sqlite/blob/master/_autodocs/api-reference/connector.md Creates a new driver.Connector using the given DSN. The DSN uses the same syntax and query parameters as Driver.Open. Validation at construction time is limited to query string parsing and conflicting vfs parameters; other issues are reported on Connect. ```APIDOC ## func NewConnector(dsn string) (driver.Connector, error) ### Description Creates a new driver.Connector using the given DSN. The DSN uses the same syntax and query parameters as Driver.Open. Validation at construction time is limited to query string parsing and conflicting vfs parameters; other issues are reported on Connect. ### Parameters - **dsn** (string) - Required - Same syntax and query parameters as Driver.Open. ### Returns - **driver.Connector** - The connector that opens connections using the driver registered as "sqlite". - **error** - An error if the DSN cannot be parsed or has conflicting vfs parameters. ### Example ```go c, err := sqlite.NewConnector("file:app.db?_pragma=foreign_keys(1)") if err != nil { return err } db := sql.OpenDB(c) defer db.Close() ``` ```