### Checkpoint Start Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Wraps the CheckpointStart call for the underlying file. ```go func (x *xtsFile) CheckpointStart() { vfsutil.WrapCheckpointStart(x.File) // notest } ``` -------------------------------- ### Start Immediate Transaction Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Begins an immediate transaction on the database connection. This type of transaction will return an error if it cannot be immediately started. ```go // BeginImmediate starts an immediate transaction. // // https://sqlite.org/lang_transaction.html func (c *Conn) BeginImmediate() (Txn, error) { err := c.Exec(`BEGIN IMMEDIATE`) if err != nil { return Txn{}, err } return Txn{c}, nil } ``` -------------------------------- ### Wrap CheckpointStart for vfs.FileCheckpoint Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Wraps a vfs.File to signal the start of a checkpoint if it implements vfs.FileCheckpoint. ```go // WrapCheckpointStart helps wrap [vfs.FileCheckpoint]. func WrapCheckpointStart(f vfs.File) { if f, ok := f.(vfs.FileCheckpoint); ok { f.CheckpointStart() } } ``` -------------------------------- ### WAL Checkpoint Example Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Performs a WAL checkpoint operation. This example shows how to call WALCheckpoint with CHECKPOINT_FULL mode. ```Go defer c.arena.Mark()() nLogPtr := c.arena.New(ptrlen) nCkptPtr := c.arena.New(ptrlen) schemaPtr := c.arena.String(schema) rc := res_t(c.wrp.Xsqlite3_wal_checkpoint_v2( int32(c.handle), int32(schemaPtr), int32(mode), int32(nLogPtr), int32(nCkptPtr))) nLog = int(int32(c.wrp.Read32(nLogPtr))) nCkpt = int(int32(c.wrp.Read32(nCkptPtr))) return nLog, nCkpt, c.error(rc) } ``` -------------------------------- ### BeginTx Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Starts a new transaction with configurable isolation levels and read-only settings. ```APIDOC ## BeginTx ### Description Begins a new transaction with the given context and transaction options. Supports different isolation levels and can enforce read-only mode. ### Method `BeginTx` ### Parameters #### Context - `ctx` (context.Context) - The context for the transaction. #### Transaction Options - `opts` (driver.TxOptions) - Options for the transaction, including IsolationLevel and ReadOnly. ### Returns - `driver.Tx` - The transaction object. - `error` - An error if the transaction could not be started. ``` -------------------------------- ### Creating a Shared Memory Database Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Creates a new shared memory database with optional initial contents. The database name must start with '/'. ```go // Create creates a shared memory database, // using data as its initial contents. // The new database takes ownership of data, // and the caller should not use data after this call. func Create(name string, data []byte) { db := &memDB{ efs: 1, name: name, size: int64(len(data)), } // Convert data from WAL/2 to rollback journal. if len(data) >= 20 && (false || data[18] == 2 && data[19] == 2 || data[18] == 3 && data[19] == 3) { data[18] = 1 data[19] = 1 } sectors := divRoundUp(db.size, sectorSize) db.data = make([][]*[sectorSize]byte, sectors) for i := range db.data { sector := data[i*sectorSize:] if len(sector) >= sectorSize { db.data[i] = (*[sectorSize]byte)(sector) } else { db.data[i] = new([sectorSize]byte) copy((*db.data[i])[:], sector) } } memoryMtx.Lock() memoryDBs[name] = db memoryMtx.Unlock() } ``` -------------------------------- ### Get Value as String Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Returns the value as a string by converting its raw text representation. ```go // Text returns the value as a string. // // https://sqlite.org/c3ref/value_blob.html func (v Value) Text() string { return string(v.RawText()) } ``` -------------------------------- ### Get Name of SQL Parameter by Index Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Returns the name of a SQL parameter at the specified index. Parameter indices start from 1. ```go func (s *Stmt) BindName(param int) string { ptr := ptr_t(s.c.wrp.Xsqlite3_bind_parameter_name( int32(s.handle), int32(param))) if ptr == 0 { return "" } return s.c.wrp.ReadString(ptr, _MAX_NAME) } ``` -------------------------------- ### Initialize SQLite Connection Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Sets up the SQLite connection with busy timeout, initialization hooks, query-only pragmas, and trace functions for closing. ```go if !n.pragmas { err = c.Conn.BusyTimeout(time.Minute) if err != nil { return nil, err } } if n.init != nil { err = n.init(c.Conn) if err != nil { return nil, err } } if n.pragmas || n.init != nil { s, _, err := c.Conn.Prepare(`PRAGMA query_only`) if err != nil { return nil, err } defer s.Close() if s.Step() { c.readOnly = s.ColumnBool(0) } err = s.Close() if err != nil { return nil, err } } if n.term != nil { err = c.Conn.Trace(sqlite3.TRACE_CLOSE, func(sqlite3.TraceEvent, any, any) error { return n.term(c.Conn) }) if err != nil { return nil, err } } return c, nil ``` -------------------------------- ### Get Index of SQL Parameter by Name Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Returns the index of a named SQL parameter within the prepared statement. Parameter indices start from 1. ```go func (s *Stmt) BindIndex(name string) int { defer s.c.arena.Mark()() namePtr := s.c.arena.String(name) return int(s.c.wrp.Xsqlite3_bind_parameter_index(int32(s.handle), int32(namePtr))) } ``` -------------------------------- ### Get File Size Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Calls the underlying vfsFileSize function to get the size of a file. ```go //go:linkname vfsFileSize github.com/ncruces/go-sqlite3/vfs.vfsFileSize func vfsFileSize(_ *sqlite3_wrap.Wrapper, v0, v1 int32) int32 func (e *env) Xgo_file_size(v0, v1 int32) int32 { return vfsFileSize(e.Wrapper, v0, v1) } ``` -------------------------------- ### Using the database/sql Driver Source: https://github.com/ncruces/go-sqlite3/blob/main/README.md This snippet demonstrates how to use the database/sql driver to open a SQLite database and query its version. Ensure the driver is imported. ```go import "database/sql" import _ "github.com/ncruces/go-sqlite3/driver" var version string db, _ := sql.Open("sqlite3", "file:demo.db") db.QueryRow(`SELECT sqlite_version()`).Scan(&version) ``` -------------------------------- ### Start Concurrent Transaction Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Begins a concurrent transaction. This is an experimental feature and requires a custom build of SQLite. ```go // BeginConcurrent starts a concurrent transaction. // // Experimental: requires a custom build of SQLite. // // https://sqlite.org/cgi/src/doc/begin-concurrent/doc/begin_concurrent.md func (c *Conn) BeginConcurrent() (Txn, error) { err := c.Exec(`BEGIN CONCURRENT`) if err != nil { return Txn{}, err } return Txn{c}, nil } ``` -------------------------------- ### Get Full Pathname Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Calls the underlying vfsFullPathname function to get the full pathname. ```go //go:linkname vfsFullPathname github.com/ncruces/go-sqlite3/vfs.vfsFullPathname func vfsFullPathname(_ *sqlite3_wrap.Wrapper, v0, v1, v2, v3 int32) int32 func (e *env) Xgo_full_pathname(v0, v1, v2, v3 int32) int32 { return vfsFullPathname(e.Wrapper, v0, v1, v2, v3) } ``` -------------------------------- ### Get Device Characteristics Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Calls the underlying vfsDeviceCharacteristics function to get the characteristics of the storage device. ```go //go:linkname vfsDeviceCharacteristics github.com/ncruces/go-sqlite3/vfs.vfsDeviceCharacteristics func vfsDeviceCharacteristics(_ *sqlite3_wrap.Wrapper, v0 int32) int32 func (e *env) Xgo_device_characteristics(v0 int32) int32 { return vfsDeviceCharacteristics(e.Wrapper, v0) } ``` -------------------------------- ### Conn.BackupInit Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Initializes an incremental backup operation from a source database to a destination URI. ```APIDOC ## Conn.BackupInit ### Description Initializes a backup operation to copy the content of one database into another. It opens the destination SQLite database file (`dstURI`) and then initializes a backup that copies the contents of `srcDB` on the `src` connection to the "main" database in `dstURI`. This is the first step for incremental backups. ### Method `func (src *Conn) BackupInit(srcDB, dstURI string) (*Backup, error)` ### Parameters - `srcDB` (string): The name of the source database to back up. - `dstURI` (string): The URI of the destination SQLite database file. ### Response - `*Backup`: A pointer to a `Backup` object representing the ongoing backup operation. - `error`: Returns an error if the initialization fails, otherwise nil. ``` -------------------------------- ### Begin Virtual Table Transaction Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Implements the xBegin callback for virtual tables. Initiates a new transaction for the virtual table. ```go func (e *env) Xgo_vtab_begin(pVTab int32) int32 { vtab := e.vtabGetHandle(pVTab).(VTabTxn) err := vtab.Begin() return e.vtabError(pVTab, _VTAB_ERROR, err, ERROR) } ``` -------------------------------- ### Get Sector Size Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Calls the underlying vfsSectorSize function to get the sector size of the device. ```go //go:linkname vfsSectorSize github.com/ncruces/go-sqlite3/vfs.vfsSectorSize func vfsSectorSize(_ *sqlite3_wrap.Wrapper, v0 int32) int32 func (e *env) Xgo_sector_size(v0 int32) int32 { return vfsSectorSize(e.Wrapper, v0) } ``` -------------------------------- ### Set File Size Hint Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Allocates space for the file up to the specified size hint. ```go func (f *vfsFile) SizeHint(size int64) error { return osAllocate(f.File, size) } ``` -------------------------------- ### Register Extension Entry Point for Auto-Loading Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Use `AutoExtension` to register an `entryPoint` function that will be automatically invoked for each new database connection. This allows extensions to be loaded on connection creation. ```go package sqlite3 import ( "bytes" "encoding/base64" "sync" "github.com/ncruces/go-sqlite3/internal/errutil" ) var ( // +checklocks:extRegistryMtx extRegistry []func(*Conn) error extRegistryMtx sync.RWMutex ) // AutoExtension causes the entryPoint function to be invoked // for each new database connection that is created. // // https://sqlite.org/c3ref/auto_extension.html func AutoExtension(entryPoint func(*Conn) error) { extRegistryMtx.Lock() extRegistry = append(extRegistry, entryPoint) extRegistryMtx.Unlock() } ``` -------------------------------- ### Regex Instr Function Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Implements the SQL regex_instr function to find the starting or ending position of a regex match. It supports specifying start position, count, and whether to return the end position. ```go func regexInstr(ctx sqlite3.Context, arg ...sqlite3.Value) { re, err := load(ctx, arg, 1) if err != nil { ctx.ResultError(err) return // notest } text := arg[0].RawText() var pos, n, end, subexpr int if len(arg) > 2 { pos = arg[2].Int() } if len(arg) > 3 { n = arg[3].Int() } if len(arg) > 4 && arg[4].Bool() { end = 1 } if len(arg) > 5 { subexpr = arg[5].Int() } loc := regexFind(re, text, pos, n, subexpr) if loc != nil { ctx.ResultInt(loc[end] + 1) } } ``` -------------------------------- ### Setup Statement Bindings Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Binds values to statement parameters, supporting various data types including time, JSON, and pointers. Handles both named and ordinal parameters. ```go func (s *stmt) setupBindings(args []driver.NamedValue) (err error) { var ids [3]int for _, arg := range args { ids := ids[:0] if arg.Name == "" { ids = append(ids, arg.Ordinal) } else { for _, prefix := range [...]string{ ":", "@", "$"} { if id := s.Stmt.BindIndex(prefix + arg.Name); id != 0 { ids = append(ids, id) } } } for _, id := range ids { switch a := arg.Value.(type) { case bool: err = s.Stmt.BindBool(id, a) case int: err = s.Stmt.BindInt(id, a) case int64: err = s.Stmt.BindInt64(id, a) case float64: err = s.Stmt.BindFloat(id, a) case string: err = s.Stmt.BindText(id, a) case []byte: err = s.Stmt.BindBlob(id, a) case sqlite3.ZeroBlob: err = s.Stmt.BindZeroBlob(id, int64(a)) case time.Time: err = s.Stmt.BindTime(id, a, s.tmWrite) case util.JSON: err = s.Stmt.BindJSON(id, a.Value) case util.Pointer: err = s.Stmt.BindPointer(id, a.Value) case nil: err = s.Stmt.BindNull(id) default: panic(errutil.AssertErr()) } if err != nil { return err } } } return nil } ``` -------------------------------- ### GetInterrupt Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Gets the context set with Conn.SetInterrupt. ```APIDOC ## GetInterrupt ### Description Gets the context set with Conn.SetInterrupt. ### Method Go Function ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response - **context.Context**: The current interrupt context. ``` -------------------------------- ### Perform Full Database Backup Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Initiates and completes a full backup of a source database to a destination URI. Blocks until the backup is finished. Use BackupInit for incremental backups. ```go func (src *Conn) Backup(srcDB, dstURI string) error { b, err := src.BackupInit(srcDB, dstURI) if err != nil { return err } defer b.Close() _, err = b.Step(-1) return err } ``` -------------------------------- ### Get Sector Size from VFS File in Go Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html This Go function retrieves the sector size of a VFS file. It uses the provided wrapper and file pointer to get the underlying Go File interface and then calls its SectorSize method. ```Go //go:linkname vfsSectorSize func vfsSectorSize(wrp *sqlite3_wrap.Wrapper, pFile ptr_t) int32 { file := vfsFileGet(wrp, pFile).(File) return int32(file.SectorSize()) } ``` -------------------------------- ### Open SQLite Database Connection Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Opens a SQLite database connection and demonstrates how to perform an online backup. ```go db, err := driver.Open("temp.db") if err != nil { log.Fatal(err) } defer db.Close() conn, err := db.Conn(context.TODO()) if err != nil { log.Fatal(err) } defer conn.Close() err = conn.Raw(func(driverConn any) error { conn := driverConn.(driver.Conn) return conn.Raw().Backup("main", "backup.db") }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Initialize Extensions for a Connection Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html The `initExtensions` function iterates through the registered extension entry points and executes them for a given database connection. It ensures that extensions are properly initialized. ```go func initExtensions(c *Conn) error { c.base64() extRegistryMtx.RLock() defer extRegistryMtx.RUnlock() for _, f := range extRegistry { if err := f(c); err != nil { return err } } return nil } ``` -------------------------------- ### Get Lock State Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Returns the current lock level of the file. ```go func (f *vfsFile) LockState() LockLevel { return f.lock } ``` -------------------------------- ### Initialize Checksum Flags from Header Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Initializes the computeCksm and verifyCksm flags based on the header information of the file. ```go func (c *cksmFile) init(header *[100]byte) { if r := header[20] == 8; r != c.computeCksm { c.computeCksm = r c.verifyCksm = r } } ``` -------------------------------- ### Create Test Database with Snapshot Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Generates a unique, temporary database for testing, initialized with a given snapshot and optional parameters. The database is automatically cleaned up after the test. ```go // TestDB creates a shared database from a snapshot for the test to use. // The database is automatically deleted when the test and all its subtests complete. // Returns a URI filename appropriate to call Open with. // Each subsequent call to TestDB returns a unique database. // // func Test_something(t *testing.T) { // t.Parallel() // dsn := mvcc.TestDB(t, snapshot, url.Values{ // "_pragma": {"busy_timeout(1000)"}, // }) // // db, err := sql.Open("sqlite3", dsn) // if err != nil { // t.Fatal(err) // } // defer db.Close() // // // ... // } func TestDB(tb testing.TB, snapshot Snapshot, params ...url.Values) string { tb.Helper() name := fmt.Sprintf("%s_%s", tb.Name(), rand.Text()) tb.Cleanup(func() { Delete(name) }) Create(name, snapshot) p := url.Values{"vfs": {"mvcc"}} for _, v := range params { for k, v := range v { for _, v := range v { p.Add(k, v) } } } return (&url.URL{ Scheme: "file", OmitHost: true, Path: "/" + name, RawQuery: p.Encode(), }).String() } ``` -------------------------------- ### Get Sector Size Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Returns the default sector size for the VFS. ```go func (f *vfsFile) SectorSize() int { return _DEFAULT_SECTOR_SIZE } ``` -------------------------------- ### Get File Size Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the current size of the file by seeking to the end. ```go func (f *vfsFile) Size() (int64, error) { return f.Seek(0, io.SeekEnd) } ``` -------------------------------- ### Get VTab Row ID Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Returns the current row ID of the cursor. ```go func (c *cursor) RowID() (int64, error) { return c.rowID, nil } ``` -------------------------------- ### Setting Encryption Key with PRAGMA Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Shows how to set the encryption key for a database connection using PRAGMA statements immediately after opening. This is a more secure method than URI parameters. ```sql PRAGMA key='D41d8cD98f00b204e9800998eCf8427e'; ``` ```sql PRAGMA hexkey='e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; ``` ```sql PRAGMA textkey='your-secret-key'; ``` -------------------------------- ### Get ExtendedCode from ErrorCode Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html The `ExtendedCode` method returns the `ExtendedErrorCode` representation of the `ErrorCode`. ```go func (e ErrorCode) ExtendedCode() ExtendedErrorCode { return xErrorCode(e) } ``` -------------------------------- ### Take a Database Snapshot Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Captures a snapshot of an existing database. The snapshot is a copy of the database's current state. ```go // TakeSnapshot takes a snapshot of a database. // Name may be a URI filename. func TakeSnapshot(name string) Snapshot { name = getName(name) memoryMtx.Lock() db := memoryDBs[name] memoryMtx.Unlock() if db == nil { return Snapshot{} } db.mtx.Lock() defer db.mtx.Unlock() return Snapshot{db.data} ``` -------------------------------- ### Get Interrupt Context Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the context used for interrupting long-running queries. ```Go func (c *Conn) GetInterrupt() context.Context { return c.interrupt } ``` -------------------------------- ### Open SQLite Database with Callbacks Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Opens a SQLite database using the provided data source name. Accepts optional initialization and termination callbacks for connection lifecycle management. The initialization callback can be used to set up the connection, and the termination callback for cleanup. ```go func Open(dataSourceName string, fn ...func(*sqlite3.Conn) error) (*sql.DB, error) { if len(fn) > 2 { return nil, sqlite3.MISUSE } var init, term func(*sqlite3.Conn) error if len(fn) > 1 { term = fn[1] } if len(fn) > 0 { init = fn[0] } c, err := newConnector(dataSourceName, init, term) if err != nil { return nil, err } return sql.OpenDB(c), nil } ``` -------------------------------- ### Get Lock State for XTS File Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Wraps and returns the LockState from the underlying file. ```go func (x *xtsFile) LockState() vfs.LockLevel { return vfsutil.WrapLockState(x.File) // notest } ``` -------------------------------- ### Get Next IN Constraint Value Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the next element from the right-hand side of an IN constraint. ```go // InNext returns the next element // on the right-hand side of an IN constraint. // // https://sqlite.org/c3ref/vtab_in_first.html func (v Value) InNext() (Value, error) { return v.c.returnValue(v.c.wrp.Xsqlite3_vtab_in_next, v.handle) } ``` -------------------------------- ### Implement sliceVFS Open Method Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Handles opening the 'serdes.db' file for the sliceVFS. It returns a SliceFile for in-memory access if the correct flags and name are provided. ```go func (sliceVFS) Open(name string, flags vfs.OpenFlag) (vfs.File, vfs.OpenFlag, error) { if flags&vfs.OPEN_MAIN_DB == 0 || name != "serdes.db" { return nil, flags, sqlite3.CANTOPEN } select { case file := <-fileToOpen: return (*vfsutil.SliceFile)(file), flags | vfs.OPEN_MEMORY, nil default: return nil, flags, sqlite3.MISUSE } } ``` -------------------------------- ### Get First IN Constraint Value Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the first element from the right-hand side of an IN constraint. ```go // InFirst returns the first element // on the right-hand side of an IN constraint. // // https://sqlite.org/c3ref/vtab_in_first.html func (v Value) InFirst() (Value, error) { return v.c.returnValue(v.c.wrp.Xsqlite3_vtab_in_first, v.handle) } ``` -------------------------------- ### Create Virtual Table Module Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Implements the xCreate callback for virtual tables. It retrieves the module and constructs the virtual table. ```go func (e *env) Xgo_vtab_create(pMod, nArg, pArg, ppVTab, pzErr int32) int32 { module := e.vtabGetHandle(pMod).(vtabModule) return e.vtabConstruct(module[0], nArg, pArg, ppVTab, pzErr) } ``` -------------------------------- ### Create a Snapshot from Data Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Constructs a database snapshot from a string of data. It handles different data formats, including WAL/2 rollback journals. ```go package mvcc import ( "github.com/ncruces/go-sqlite3/util/wbt" ) // Snapshot represents a database snapshot. type Snapshot struct { *wbt.Tree[int64, string] } // NewSnapshot creates a snapshot from data. func NewSnapshot(data string) Snapshot { var tree *wbt.Tree[int64, string] // Convert data from WAL/2 to rollback journal. if len(data) >= 20 && (false || data[18] == 2 && data[19] == 2 || data[18] == 3 && data[19] == 3) { tree = tree. Put(0, data[:18]). Put(18, "\001\001"). Put(20, data[20:]) } else if len(data) > 0 { tree = tree.Put(0, data) } return Snapshot{tree} } ``` -------------------------------- ### Get Value as Int Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the value as an integer. This method relies on Int64() for conversion. ```go // Int returns the value as an int. // // https://sqlite.org/c3ref/value_blob.html func (v Value) Int() int { return int(v.Int64()) } ``` -------------------------------- ### Prepare SQL Statement (Default Flags) Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html A convenience wrapper for PrepareFlags that calls it with no flags. ```go func (c *Conn) Prepare(sql string) (stmt *Stmt, tail string, err error) { return c.PrepareFlags(sql, 0) } ``` -------------------------------- ### Stmt.Err Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Gets the last error occurred during Stmt.Step. Returns nil after Stmt.Reset is called. ```APIDOC ## Stmt.Err ### Description Gets the last error occurred during Stmt.Step. Returns nil after Stmt.Reset is called. ### Method func (s *Stmt) Err() error ### Returns - error: The last error encountered during statement execution, or nil. ``` -------------------------------- ### Get Database Connection from Statement Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the database connection associated with a prepared statement. ```Go func (s *Stmt) Conn() *Conn { return s.c } ``` -------------------------------- ### Initialize Extension Environment Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Initializes the extEnv struct, which holds environment details including memory and table bases for WASM extensions. ```go type extEnv struct { *env memoryBase int32 tableBase int32 } func (e *extEnv) X__memory_base() *int32 { return &e.memoryBase } func (e *extEnv) X__table_base() *int32 { return &e.tableBase } ``` -------------------------------- ### Internal Backup Initialization Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Internal helper function to initialize the backup process between two connections. Manages arena allocation for string arguments and handles potential errors during initialization. ```go func (c *Conn) backupInit(dst ptr_t, dstName string, src ptr_t, srcName string) (*Backup, error) { defer c.arena.Mark()() dstPtr := c.arena.String(dstName) srcPtr := c.arena.String(srcName) other := dst if c.handle == dst { other = src } ptr := ptr_t(c.wrp.Xsqlite3_backup_init( int32(dst), int32(dstPtr), int32(src), int32(srcPtr))) if ptr == 0 { defer c.closeDB(other) rc := res_t(c.wrp.Xsqlite3_errcode(int32(dst))) return nil, c.errorFor(dst, rc) } return &Backup{ c: c, otherc: other, handle: ptr, }, nil } ``` -------------------------------- ### Get Shared Memory for XTS File Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Wraps and returns the SharedMemory interface from the underlying file. ```go func (x *xtsFile) SharedMemory() vfs.SharedMemory { return vfsutil.WrapSharedMemory(x.File) // notest } ``` -------------------------------- ### Prepare Statement Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Prepares a SQL statement for execution, checking for any unconsumed SQL tail. Returns a driver.Stmt or an error. ```go if old := c.Conn.SetInterrupt(ctx); old != ctx { defer c.Conn.SetInterrupt(old) } s, tail, err := c.Conn.Prepare(query) if err != nil { return nil, err } if notWhitespace(tail) { s.Close() return nil, errutil.TailErr } return &stmt{Stmt: s, tmRead: c.tmRead, tmWrite: c.tmWrite, inputs: -2}, nil ``` -------------------------------- ### Test Environment Logging Utilities Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Provides utilities for logging test output and writing byte slices or strings to the test buffer. It handles line breaks and ensures thread-safe buffer manipulation. ```go package testenv import ( "bytes" "context" "io/fs" "sync" "github.com/ncruces/go-sqlite3/internal/sqlite3_wrap" ) type Context interface { Context() context.Context Logf(format string, args ...any) } var ( FS fs.FS TB Context Exit func(int32) System func(*sqlite3_wrap.Wrapper, int32) int32 buf []byte mtx sync.Mutex ) func WriteByte(c byte) error { mtx.Lock() defer mtx.Unlock() if c == '\n' { TB.Logf("%s", buf) buf = buf[:0] } else { buf = append(buf, c) } return nil } func Write(p []byte) (n int, err error) { mtx.Lock() defer mtx.Unlock() buf = append(buf, p...) for { before, after, found := bytes.Cut(buf, []byte("\n")) if !found { return len(p), nil } TB.Logf("%s", before) buf = after } } func WriteString(s string) (n int, err error) { return Write([]byte(s)) } ``` -------------------------------- ### Get Journal Filename Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the name of the rollback journal file associated with the Filename object. ```go func (n *Filename) Journal() string { if n == nil || n.zPath == 0 { return "" } return n.path(n.wrp.Xsqlite3_filename_journal) } ``` -------------------------------- ### Get Database Filename Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the name of the main database file associated with the Filename object. ```go func (n *Filename) Database() string { if n == nil || n.zPath == 0 { return "" } return n.path(n.wrp.Xsqlite3_filename_database) } ``` -------------------------------- ### Prepare SQL Statement Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Compiles the first SQL statement in the given string. Returns the prepared statement, the remaining uncompiled SQL (tail), and an error if any. Handles empty input or comments by returning nil for statement and error. ```go func (c *Conn) PrepareFlags(sql string, flags PrepareFlag) (stmt *Stmt, tail string, err error) { if len(sql) > _MAX_SQL_LENGTH { return nil, "", TOOBIG } if c.interrupt.Err() != nil { return nil, "", INTERRUPT } defer c.arena.Mark()() stmtPtr := c.arena.New(ptrlen) tailPtr := c.arena.New(ptrlen) textPtr := c.arena.String(sql) rc := res_t(c.wrp.Xsqlite3_prepare_v3(int32(c.handle), int32(textPtr), int32(len(sql)+1), int32(flags), int32(stmtPtr), int32(tailPtr))) stmt = &Stmt{c: c, sql: sql} stmt.handle = ptr_t(c.wrp.Read32(stmtPtr)) if sql := sql[ptr_t(c.wrp.Read32(tailPtr))-textPtr:]; sql != "" { tail = sql } if err := c.error(rc, sql); err != nil { return nil, "", err } if stmt.handle == 0 { return nil, "", nil } c.stmts = append(c.stmts, stmt) return stmt, tail, nil } ``` -------------------------------- ### Begin Atomic Write Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Wraps and executes the BeginAtomicWrite operation on the underlying file. ```go func (x *xtsFile) BeginAtomicWrite() error { return vfsutil.WrapBeginAtomicWrite(x.File) // notest } ``` -------------------------------- ### Get Pointer Value Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves a pointer associated with the value, returning nil if none exists. ```go // Pointer gets the pointer associated with this value, // or nil if it has no associated pointer. func (v Value) Pointer() any { ptr := ptr_t(v.c.wrp.Xsqlite3_value_pointer_go(int32(v.handle))) return v.c.wrp.GetHandle(ptr) } ``` -------------------------------- ### WrapCheckpointStart Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Helps wrap vfs.FileCheckpoint. If the provided file implements the FileCheckpoint interface, its CheckpointStart method is called. ```APIDOC ## WrapCheckpointStart ### Description Wraps the vfs.FileCheckpoint interface, allowing the CheckpointStart method to be called if the file implements it. ### Parameters - **f** (vfs.File) - The file object to wrap. ### Code Example ```go WrapCheckpointStart(file) ``` ``` -------------------------------- ### Get Value as Int64 Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the value as an int64. It calls the underlying SQLite C function. ```go // Int64 returns the value as an int64. // // https://sqlite.org/c3ref/value_blob.html func (v Value) Int64() int64 { return v.c.wrp.Xsqlite3_value_int64(int32(v.handle)) } ``` -------------------------------- ### Initialize Incremental Backup Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Initializes a backup operation, copying the contents of srcDB from the src connection to the 'main' database in dstURI. Opens the destination database file. ```go func (src *Conn) BackupInit(srcDB, dstURI string) (*Backup, error) { dst, err := src.openDB(dstURI, OPEN_READWRITE|OPEN_CREATE|OPEN_URI) if err != nil { return nil, err } return src.backupInit(dst, "main", src.handle, srcDB) } ``` -------------------------------- ### Get Data Count Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Returns the number of columns in the current result set of a prepared statement. ```go func (s *Stmt) DataCount() int { return int(s.c.wrp.Xsqlite3_data_count(int32(s.handle))) } ``` -------------------------------- ### Get Reflect Type Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Returns the reflect.Type of a reflect.Value. If the value is invalid (reflect.Invalid), it returns nil. ```go package util import "reflect" func ReflectType(v reflect.Value) reflect.Type { if v.Kind() != reflect.Invalid { return v.Type() } return nil } ``` -------------------------------- ### New Connector Creation Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Creates a new connector instance, parsing connection string parameters like _txlock and _timefmt. It validates the _txlock parameter and sets appropriate time formats for reading and writing. ```go func newConnector(name string, init, term func(*sqlite3.Conn) error) (*connector, error) { c := connector{name: name, init: init, term: term} var txlock, timefmt string if strings.HasPrefix(name, "file:") { u, err := url.Parse(name) if err != nil { return nil, err } query, err := url.ParseQuery(u.RawQuery) if err != nil { return nil, err } txlock = query.Get("_txlock") timefmt = query.Get("_timefmt") c.pragmas = query.Has("_pragma") } switch txlock { case "", "deferred", "concurrent", "immediate", "exclusive": c.txLock = txlock default: return nil, fmt.Errorf("sqlite3: invalid _txlock: %s", txlock) } switch timefmt { case "": c.tmRead = sqlite3.TimeFormatAuto c.tmWrite = sqlite3.TimeFormatDefault case "sqlite": c.tmRead = sqlite3.TimeFormatAuto c.tmWrite = sqlite3.TimeFormat3 case "rfc3339": c.tmRead = sqlite3.TimeFormatDefault c.tmWrite = sqlite3.TimeFormatDefault default: c.tmRead = sqlite3.TimeFormat(timefmt) c.tmWrite = sqlite3.TimeFormat(timefmt) } return &c, nil } ``` -------------------------------- ### Connect to Virtual Table Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Implements the xConnect callback for virtual tables. It retrieves the module and constructs the virtual table. ```go func (e *env) Xgo_vtab_connect(pMod, nArg, pArg, ppVTab, pzErr int32) int32 { module := e.vtabGetHandle(pMod).(vtabModule) return e.vtabConstruct(module[1], nArg, pArg, ppVTab, pzErr) } ``` -------------------------------- ### Get Primary ErrorCode from ExtendedErrorCode Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html The `Code` method returns the primary `ErrorCode` component of an `ExtendedErrorCode`. ```go func (e ExtendedErrorCode) Code() ErrorCode { return ErrorCode(e) } ``` -------------------------------- ### Get BLOB Size Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Returns the size of the BLOB in bytes. This is the total size of the BLOB data. ```go // Size returns the size of the BLOB in bytes. // // https://sqlite.org/c3ref/blob_bytes.html func (b *Blob) Size() int64 { return b.bytes } ``` -------------------------------- ### Go SQLite3 Wasm Environment Initialization Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Initializes the SQLite3 Wasm environment, setting up memory limits and configuring the soft heap limit based on context. ```Go func createWrapper(ctx context.Context) (*sqlite3_wrap.Wrapper, error) { mem := &sqlite3_wrap.Memory{Max: 4096} // 256MB if bits.UintSize < 64 { mem.Max = 512 // 32MB } mem.Grow(5, mem.Max) // 320KB env := &env{&sqlite3_wrap.Wrapper{Memory: mem}} env.Module = sqlite3_wasm.New(env) env.X_initialize() if cfg, ok := ctx.Value(configKey{}).(int64); ok { mem.Max = max(cfg, int64(len(mem.Buf))/65536) env.Xsqlite3_soft_heap_limit64((mem.Max - 8) * 65536) } return env.Wrapper, nil } ``` -------------------------------- ### Callback Argument Preparation Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Prepares and returns a slice of Value arguments for callbacks, utilizing a sync.Pool for efficiency. ```go func callbackArgs(db *Conn, nArg int32, pArg ptr_t) *[]Value { arg, ok := valueArgsPool.Get().(*[]Value) if !ok || cap(*arg) < int(nArg) { max := valueArgsLen.Or(nArg) | nArg lst := make([]Value, max) arg = &lst } lst := (*arg)[:nArg] for i := range lst { lst[i] = Value{ c: db, handle: ptr_t(db.wrp.Read32(pArg + ptr_t(i)*ptrlen)), } } *arg = lst return arg } ``` -------------------------------- ### BindNull Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Binds a NULL value to the prepared statement. The SQL parameter index starts at 1. ```APIDOC ## BindNull ### Description Binds a NULL value to the prepared statement. The leftmost SQL parameter has an index of 1. ### Method func (s *Stmt) BindNull(param int) error ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Connector Connect Method Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Establishes a new database connection using the connector's configuration. It opens a SQLite connection context and sets up interrupt handling for the context. If connection fails, it ensures the partially opened connection is closed. ```go func (n *connector) Connect(ctx context.Context) (ret driver.Conn, err error) { c := &conn{ txLock: n.txLock, tmRead: n.tmRead, tmWrite: n.tmWrite, } c.Conn, err = sqlite3.OpenContext(ctx, n.name) if err != nil { return nil, err } defer func() { if ret == nil { c.Close() } }() if old := c.Conn.SetInterrupt(ctx); old != ctx { defer c.Conn.SetInterrupt(old) } ``` -------------------------------- ### BindFloat Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Binds a float64 value to a prepared statement. The SQL parameter index starts at 1. ```APIDOC ## BindFloat ### Description Binds a float64 value to the prepared statement. The leftmost SQL parameter has an index of 1. ### Method func (s *Stmt) BindFloat(param int, value float64) error ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Get Reserved Lock (Go) Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Acquires a reserved lock on the file. This is a write lock on a single byte. ```go func osGetReservedLock(file *os.File) error { // Acquire the RESERVED lock. return osWriteLock(file, _RESERVED_BYTE, 1, 0) } ``` -------------------------------- ### Open Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Opens an SQLite database file with default flags (read-write, create, URI). This is a convenience function that uses a background context. ```APIDOC ## Open ### Description Opens an SQLite database file with default flags: OPEN_READWRITE, OPEN_CREATE, and OPEN_URI. This function uses a background context and is suitable for simple use cases. ### Method func Open(filename string) (*Conn, error) ### Parameters #### Path Parameters - **filename** (string) - Required - The path to the SQLite database file. ### Response #### Success Response - **Conn** (*Conn) - A pointer to the opened database connection. - **error** (error) - nil if the connection was opened successfully, otherwise an error object. #### Error Response - **error** (error) - An error object if the connection could not be opened. ``` -------------------------------- ### Get Database File Object Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the main database File object corresponding to a journal filename. ```go func (n *Filename) DatabaseFile() File { if n == nil || n.zPath == 0 { return nil } if n.flags&(OPEN_MAIN_DB|OPEN_MAIN_JOURNAL|OPEN_WAL) == 0 { return nil } pFile := ptr_t(n.wrp.Xsqlite3_database_file_object(int32(n.zPath))) file, _ := vfsFileGet(n.wrp, ptr_t(pFile)).(File) return file } ``` -------------------------------- ### Memory File Size Hint Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Sets a size hint for the in-memory file, truncating if the new size is smaller. ```go func (m *memFile) SizeHint(size int64) error { m.dataMtx.Lock() defer m.dataMtx.Unlock() if size > m.size { return m.truncate(size) } return nil } ``` -------------------------------- ### Get WAL Filename Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the name of the Write-Ahead Log (WAL) file associated with the Filename object. ```go func (n *Filename) WAL() string { if n == nil || n.zPath == 0 { return "" } return n.path(n.wrp.Xsqlite3_filename_wal) } ``` -------------------------------- ### Create Filename Wrapper Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Creates a Filename wrapper from SQLite's internal representation. Users should not call this directly. ```go func GetFilename(wrp *sqlite3_wrap.Wrapper, id ptr_t, flags OpenFlag) *Filename { if id == 0 { return nil } return &Filename{ wrp: wrp, zPath: id, flags: flags, } } ``` -------------------------------- ### Get Value as Float64 Source: https://github.com/ncruces/go-sqlite3/wiki/coverage.html Retrieves the value as a float64. It uses the SQLite C function for double values. ```go // Float returns the value as a float64. // // https://sqlite.org/c3ref/value_blob.html func (v Value) Float() float64 { return v.c.wrp.Xsqlite3_value_double(int32(v.handle)) } ```