Skip to main content

Connection

Struct Connection 

Source
pub struct Connection { /* private fields */ }
Expand description

A database connection holding schema metadata and execution/cache state.

Supports transactions (BEGIN/COMMIT/ROLLBACK) and savepoints (SAVEPOINT/RELEASE/ROLLBACK TO). The default runtime path uses pager/WAL/B-tree storage, while MemDatabase is retained as an execution image and limited compatibility fallback.

Implementations§

Source§

impl Connection

Source

pub fn open(path: impl Into<String>) -> Result<Self>

Open a connection.

Creates an empty in-memory database. Expression-only SELECT and table-backed DML (CREATE TABLE, INSERT, SELECT FROM, UPDATE, DELETE) are supported.

Source

pub fn open_strict_multi_process(path: impl Into<String>) -> Result<Self>

Open a connection with strict multi-process refusal enabled.

Convenience shortcut for callers (CI harnesses, multi-agent workloads) that want loud failures on ambiguous concurrency states rather than silent corruption. Equivalent to:

let mut env = ConnectionEnv::default();
env.set_strict_multi_process(true);
Connection::open_with_env(path, env)

See frankensqlite#81 and ConnectionEnv::set_strict_multi_process.

Source

pub fn open_with_page_size( path: impl Into<String>, page_size_bytes: u32, ) -> Result<Self>

Open a connection while requesting a specific page size for newly created databases.

Existing database files ignore the requested page size and continue to use the size encoded in their on-disk header.

Source

pub fn import_bytes(bytes: &[u8]) -> Result<Self>

Import a self-contained SQLite database image into a new in-memory connection.

Source

pub fn open_schema_only(path: impl Into<String>) -> Result<Self>

Open a connection that loads only the database schema (table definitions, indexes, triggers, views) without reading any row data into the in-memory MemDatabase.

This is dramatically faster for large databases when the caller only needs schema metadata or will execute queries through pager-backed cursors (the default for file-backed databases).

Row data is still accessible through the pager’s B-tree cursor stack; only the MemDatabase compatibility image is left empty.

§Examples
let conn = Connection::open_schema_only("large.db")?;
// Schema is available, queries work through pager-backed cursors.
let rows = conn.query("SELECT count(*) FROM big_table")?;
Source

pub fn open_schema_only_with_env( path: impl Into<String>, env: ConnectionEnv, ) -> Result<Self>

Open a schema-only connection with an explicit runtime environment.

Behaves like open_schema_only but allows specifying a custom ConnectionEnv.

Source

pub fn open_with_env( path: impl Into<String>, env: ConnectionEnv, ) -> Result<Self>

Open a connection with an explicit runtime environment.

The supplied ConnectionEnv selects the process-global or custom runtime context whose per-database region this connection joins.

Source

pub fn open_with_page_size_and_env( path: impl Into<String>, page_size_bytes: u32, env: ConnectionEnv, ) -> Result<Self>

Open a connection with an explicit runtime environment and requested page size for newly created databases.

Existing database files keep the page size already encoded in their header; the request only affects brand-new databases.

Source

pub fn import_bytes_with_env(bytes: &[u8], env: ConnectionEnv) -> Result<Self>

Import a self-contained SQLite database image into an in-memory connection using the supplied runtime environment.

Source

pub fn path(&self) -> &str

Returns the configured database path.

Source

pub fn export_bytes(&self) -> Result<Vec<u8>>

Export the current database as a self-contained SQLite database image.

Source

pub fn memory_stats(&self) -> Result<ConnectionMemoryStats>

Snapshot current connection memory usage and page-cache state.

Source

pub fn background_status(&self) -> Result<()>

Return the background-runtime health for this connection’s database.

Source

pub fn stmt_microbatch_counters(&self) -> (u64, u64)

Test/observability: return (hits, renewals) since connection open.

Source

pub fn last_insert_rowid(&self) -> i64

Return the most recent successful INSERT rowid on this connection.

Source

pub fn set_reject_mem_fallback(&self, reject: bool)

Enable parity-certification mode (bd-2ttd8.1).

When enabled, all VDBE cursor operations must route through the real Pager+BtreeCursor stack. The MemPageStore fallback is rejected, causing OpenRead/OpenWrite to fail if no pager transaction is available. Use this in tests to verify that the full storage stack is wired correctly.

Source

pub fn set_strict_mem_fallback_rejection(&self, strict: bool)

Enable strict non-VDBE fallback rejection for certifying runs.

When enabled together with reject_mem_fallback, dispatching to interpreted in-memory fallback paths (for example JOIN/GROUP BY materialization fallbacks) returns an error instead of silently continuing.

Source

pub fn pager_backend_kind(&self) -> &'static str

Returns the kind of pager backend in use (e.g. “memory”, “iouring”, or “unix”).

Source

pub fn validate_parity_cert_backend(&self) -> Result<(), String>

Validate that the pager backend is suitable for parity-certification.

When reject_mem_fallback is enabled, the pager SHOULD be file-backed (not :memory:) for meaningful parity testing. This method returns Err if parity-cert mode is active but the pager is memory-only.

Note: This is a diagnostic check, not an enforcement gate. In-memory pagers can still be used in parity-cert mode (they have a real SimplePager behind them), but file-backed pagers provide stronger guarantees about I/O path coverage.

Source

pub fn last_local_commit_seq(&self) -> Option<u64>

Returns the most recent commit sequence assigned to a successful COMMIT on this connection.

Returns None when this connection has not committed yet.

Source

pub fn current_concurrent_snapshot_seq(&self) -> Option<u64>

Returns the active concurrent transaction snapshot sequence observed at BEGIN CONCURRENT time for this connection.

Returns None when no concurrent transaction is active.

Source

pub fn root_cx(&self) -> &Cx

Returns a reference to the root capability context for this connection.

Source

pub fn trace_v2(&self, mask: TraceMask, callback: Option<TraceCallback>)

Register or clear sqlite3_trace_v2-compatible callbacks.

Passing Some(callback) enables callback delivery for the requested mask. Passing None clears any existing registration.

Source

pub fn close(self) -> Result<()>

Close the connection and perform pager/WAL shutdown steps.

On close:

  1. Roll back any active transaction.
  2. Run a passive checkpoint (WAL -> DB).
  3. Mark the connection as closed so Drop doesn’t repeat cleanup.
Source

pub fn close_without_checkpoint(self) -> Result<()>

Close the connection without forcing a final WAL checkpoint.

This preserves already-committed state in the WAL and is appropriate when the process is about to exit or when a caller explicitly wants to avoid paying close-time checkpoint latency. Subsequent opens will recover and publish the WAL contents normally.

Source

pub fn close_in_place(&mut self) -> Result<()>

Close the connection in place while retaining the Connection value on error so callers can inspect or retry the handle.

Source

pub fn close_without_checkpoint_in_place(&mut self) -> Result<()>

Close the connection in place without forcing a final WAL checkpoint.

This still rolls back or flushes transaction state and tears down runtime regions; it only skips the passive checkpoint that close() normally performs in WAL mode.

Source

pub fn close_best_effort_in_place(&mut self)

Close the connection using the same no-checkpoint best-effort shutdown path used by Drop, but mark it closed so dropping the handle is not reported as an API misuse.

Source

pub fn register_scalar_function<F>(&self, function: F)
where F: ScalarFunction + 'static,

Register a custom scalar function.

The function becomes available immediately for subsequent queries. Existing prepared statements invalidate and subsequently fail with FrankenError::SchemaChanged so stale cached function bindings cannot execute against the redefined registry.

Overwrites any existing function with the same (name, num_args) key.

Source

pub fn register_aggregate_function<F>(&self, function: F)
where F: AggregateFunction + 'static, F::State: 'static,

Register a custom aggregate function.

The function becomes available immediately for subsequent queries. Existing prepared statements invalidate and subsequently fail with FrankenError::SchemaChanged so stale cached function bindings cannot execute against the redefined registry.

Overwrites any existing function with the same (name, num_args) key.

Source

pub fn register_window_function<F>(&self, function: F)
where F: WindowFunction + 'static, F::State: 'static,

Register a custom window function.

The function becomes available immediately for subsequent queries. Existing prepared statements invalidate and subsequently fail with FrankenError::SchemaChanged so stale cached function bindings cannot execute against the redefined registry.

Overwrites any existing function with the same (name, num_args) key.

Source

pub fn register_module(&self, name: &str, factory: Box<dyn VtabModuleFactory>)

Register a virtual-table module factory under the given name.

Once registered, CREATE VIRTUAL TABLE t USING name(args) will invoke the factory’s create method to instantiate the vtab.

Source

pub fn register_rtree_geometry( &self, table_name: &str, geometry_name: &str, geometry: Box<dyn RtreeGeometry>, ) -> Result<()>

Register a custom geometry callback on a live SQL-created R-tree table.

Source

pub fn prepare(&self, sql: &str) -> Result<PreparedStatement<'_>>

Prepare SQL into a statement.

Source

pub fn query(&self, sql: &str) -> Result<Vec<Row>>

Prepare and execute SQL as a query.

When sql contains multiple statements, only the result rows from the last statement are returned. Intermediate statement results are discarded. This matches common SQL driver semantics (last statement wins).

Source

pub fn query_with_params( &self, sql: &str, params: &[SqliteValue], ) -> Result<Vec<Row>>

Prepare and execute SQL as a query with bound SQL parameters.

Source

pub fn query_with_params_for_each<F>( &self, sql: &str, params: &[SqliteValue], f: F, ) -> Result<()>
where F: FnMut(&Row) -> Result<()>,

Prepare and execute SQL as a query with bound SQL parameters, invoking f for each row as it is produced.

Source

pub fn query_row(&self, sql: &str) -> Result<Row>

Prepare and execute SQL as a query, returning exactly one row.

Source

pub fn query_row_with_params( &self, sql: &str, params: &[SqliteValue], ) -> Result<Row>

Prepare and execute SQL as a query with bound SQL parameters, returning exactly one row.

Source

pub fn execute(&self, sql: &str) -> Result<usize>

Prepare and execute SQL, returning output/affected row count.

For DML (INSERT/UPDATE/DELETE) this returns the number of affected rows. For SELECT and other statement types it returns the number of result rows.

Source

pub fn execute_batch(&self, sql: &str) -> Result<()>

Execute zero or more SQL statements separated by semicolons.

Empty batches and batches containing only whitespace, semicolons, or SQL comments are treated as a no-op, matching SQLite batch semantics.

Source

pub fn begin_transaction(&self) -> Result<()>

Begin a transaction without going through SQL parsing/dispatch.

This follows the same mode selection as plain BEGIN: explicit mode is absent, so concurrent_mode_default still controls whether the transaction auto-promotes to concurrent mode.

Source

pub fn commit_transaction(&self) -> Result<()>

Commit the active transaction without reparsing a COMMIT statement.

Source

pub fn rollback_transaction(&self) -> Result<()>

Roll back the active transaction without reparsing a ROLLBACK statement.

Source

pub fn execute_with_params( &self, sql: &str, params: &[SqliteValue], ) -> Result<usize>

Prepare and execute SQL with bound SQL parameters.

Source

pub fn execute_with_params_skip_statement_savepoint_in_explicit_txn( &self, sql: &str, params: &[SqliteValue], ) -> Result<usize>

Prepare and execute SQL with bound SQL parameters, skipping the internal statement savepoint when the call runs inside an explicit transaction.

This is a narrow performance escape hatch for callers that prevalidate statement inputs and treat the enclosing transaction as the rollback boundary. If execution fails inside an explicit transaction, callers must roll back that transaction to discard any partial effects. Outside an explicit transaction this behaves like execute_with_params.

Source

pub fn execute_prepared(&self, stmt: &PreparedStatement<'_>) -> Result<usize>

Execute a prepared DML statement (INSERT/UPDATE/DELETE) with no parameters.

Source

pub fn execute_prepared_with_params( &self, stmt: &PreparedStatement<'_>, params: &[SqliteValue], ) -> Result<usize>

Execute a prepared DML statement (INSERT/UPDATE/DELETE) with bound parameters.

Source

pub fn clear_compilation_reuse_caches(&self)

Clear all prepared-statement / compiled-program / planner-directive caches on this connection and reset statement lookaside scratch buffers.

Intended to be called whenever cached plans may have become stale with respect to the schema, planner inputs, function registry, or committed row image. Write commits clear these caches because prepared execution templates may capture storage visibility assumptions, not just schema.

Historical context: before post-write execution invalidation was added, downstream callers (notably beads_rust) had to wrap re-read paths in CTEs to force dispatch through the uncached slow path. See issue #72.

Source

pub fn in_transaction(&self) -> bool

Returns true if an explicit transaction is active.

Source

pub fn is_concurrent_transaction(&self) -> bool

Returns true if the current transaction was started with BEGIN CONCURRENT (or was promoted to concurrent mode via the fsqlite.concurrent_mode PRAGMA).

Source

pub fn is_concurrent_mode_default(&self) -> bool

Returns true if the connection-level concurrent-mode default is enabled (i.e. PRAGMA fsqlite.concurrent_mode = ON).

Source

pub fn write_merge_mode(&self) -> WriteMergeMode

Returns the current commit-path safety regime (PRAGMA fsqlite.write_merge).

Source

pub fn should_skip_ssi_validation(&self, force_audit_hash: u64) -> bool

Consults the anytime-valid e-process gate to decide whether the caller may skip full SSI validation for one commit.

Returns false unconditionally when write_merge_mode is Safe — the production-safe default. Returns the gate’s current decision otherwise. force_audit_hash should be any uniformly- distributed integer (e.g. the low bits of the commit sequence) so the gate can deterministically audit-sample a subset of commits.

See fsqlite_mvcc::SsiEProcessGate::should_skip_ssi for the mathematical details.

Source

pub fn observe_ssi_outcome(&self, conflict_detected: bool)

Feeds one SSI outcome observation into the e-process. conflict_detected must be the real return of a ssi_validate_and_publish call (true iff it returned Err). Always safe to call regardless of write_merge_mode; the gate is simply unconsulted under Safe.

Source

pub fn ssi_e_process_snapshot(&self) -> SsiEProcessSnapshot

Returns a diagnostic snapshot of the SSI e-process gate.

Source

pub fn reset_ssi_e_process_gate(&self)

Resets the SSI e-process gate state on this connection. Useful when the caller detects a workload regime change (bulk DDL, schema change, long idle period).

Source

pub fn has_concurrent_session(&self) -> bool

Returns true if there is an active MVCC concurrent session for this connection (bd-14zc / 5E.1).

Source

pub fn concurrent_writer_count(&self) -> usize

Returns the number of active concurrent writers across all connections sharing this registry (bd-14zc / 5E.1).

Source

pub fn ssi_decisions_snapshot(&self) -> Vec<SsiDecisionCard>

Returns a snapshot of retained SSI decision cards.

Source

pub fn query_ssi_decisions( &self, query: &SsiDecisionQuery, ) -> Vec<SsiDecisionCard>

Query SSI decision cards by transaction id, decision type, and/or time range.

Source

pub fn raptorq_repair_evidence_snapshot(&self) -> Vec<WalFecRepairEvidenceCard>

Returns a snapshot of retained RaptorQ repair evidence cards.

Source

pub fn query_raptorq_repair_evidence_cards( &self, query: &WalFecRepairEvidenceQuery, ) -> Vec<WalFecRepairEvidenceCard>

Query RaptorQ repair evidence cards by page/frame, severity bucket, and/or time range.

Source

pub fn pragma_state(&self) -> Ref<'_, ConnectionPragmaState>

Returns a reference to the connection-scoped PRAGMA state.

The harness uses this to verify that both engines received identical configuration (journal_mode, synchronous, cache_size, page_size, busy_timeout).

Source

pub fn register_differential_view_subscriber( &self, view_name: &str, sender: Sender<DifferentialEvent>, ) -> Result<u64>

Registers a connection-local differential subscriber for an existing view.

The subscriber receives a snapshot payload at the current committed CommitSeq(N) and will subsequently receive invalidation events beginning at N + 1 until table-level differential routing lands.

Source

pub fn unregister_differential_subscriber(&self, subscriber_id: u64) -> bool

Removes a previously registered differential subscriber.

Source

pub fn differential_subscribers(&self) -> Vec<DifferentialSubscriberStatus>

Returns a stable status snapshot of active differential subscribers.

Source

pub fn differential_subscriber_count(&self) -> usize

Returns the number of active differential subscribers.

Read the current schema cookie value.

Source

pub fn schema_generation(&self) -> u64

Source

pub fn compiled_cache_len(&self) -> usize

Number of entries in the compiled bytecode cache (bd-1dp9.6.7.2.2).

Source

pub fn change_counter(&self) -> u32

Read the current file change counter value.

Trait Implementations§

Source§

impl Debug for Connection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Connection

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more