Skip to main content

Connection

Struct Connection 

Source
pub struct Connection {
    pub metrics: RwLock<ConnectionMetrics>,
    /* private fields */
}
Expand description

Database connection handle.

If you add a setting that affects SQL compilation or execution, call bump_prepare_context_generation() in its setter so cached prepared statements know they need to be reprepared.

Fields§

§metrics: RwLock<ConnectionMetrics>

Connection-level metrics aggregation

Implementations§

Source§

impl Connection

Source

pub fn is_nested_stmt(&self) -> bool

check if connection executes nested program (so it must not do any “finalization” work as parent program will handle it)

Source

pub fn start_nested(&self)

starts nested program execution

Source

pub fn end_nested(&self)

ends nested program execution

Source

pub fn trigger_is_compiling(&self, trigger: &Arc<Trigger>) -> bool

Check if a specific trigger is currently compiling (for recursive trigger prevention)

Source

pub fn start_trigger_compilation(&self, trigger: Arc<Trigger>)

Source

pub fn end_trigger_compilation(&self)

Source

pub fn is_trigger_executing(&self, trigger: &Arc<Trigger>) -> bool

Check if a specific trigger is currently executing (for recursive trigger prevention)

Source

pub fn start_trigger_execution(&self, trigger: Arc<Trigger>)

Source

pub fn end_trigger_execution(&self)

Source

pub fn prepare( self: &Arc<Connection>, sql: impl AsRef<str>, ) -> Result<Statement>

Source

pub fn _prepare( self: &Arc<Connection>, sql: impl AsRef<str>, ) -> Result<Statement>

Source

pub fn prepare_stmt(self: &Arc<Connection>, stmt: Stmt) -> Result<Statement>

Prepare a statement from an AST node directly, skipping SQL parsing. This is more efficient when AST is already available or constructed programmatically.

Source

pub fn is_mvcc_bootstrap_connection(&self) -> bool

Whether this is an internal connection used for MVCC bootstrap

Source

pub fn promote_to_regular_connection(&self)

Promote MVCC bootstrap connection to a regular connection so it reads from the MV store again.

Source

pub fn demote_to_mvcc_connection(&self)

Demote regular connection to MVCC bootstrap connection so it does not read from the MV store.

Source

pub fn maybe_reparse_schema(self: &Arc<Connection>) -> Result<()>

Parse schema from scratch if version of schema for the connection differs from the schema cookie in the root page. This function must be called outside of any transaction because internally it will start transaction session by itself. In multi-process mode, this is the only way to discover schema changes made by other processes.

Source

pub fn force_reparse_schema(self: &Arc<Connection>) -> Result<()>

Parse schema from scratch even if the schema cookie did not change.

Sync replace-base can install a page snapshot outside ordinary SQL DDL. The replacement may reuse the same schema cookie while changing root pages, so cookie-based refresh would keep stale btree metadata.

Source

pub fn force_reparse_schema_without_publish( self: &Arc<Connection>, ) -> Result<()>

Like Self::force_reparse_schema, but refreshes only this connection’s own schema snapshot without publishing it to the shared database cache.

Use this when the caller must further mutate the schema before it becomes visible to other connections.

Source

pub fn prepare_execute_batch( self: &Arc<Connection>, sql: impl AsRef<str>, ) -> Result<()>

Source

pub fn query( self: &Arc<Connection>, sql: impl AsRef<str>, ) -> Result<Option<Statement>>

Source

pub fn query_runner<'a>( self: &'a Arc<Connection>, sql: &'a [u8], ) -> QueryRunner<'a>

Source

pub fn execute(self: &Arc<Connection>, sql: impl AsRef<str>) -> Result<()>

Execute will run a query from start to finish taking ownership of I/O because it will run pending I/Os if it didn’t finish. TODO: make this api async

Source

pub fn consume_stmt( self: &Arc<Connection>, sql: impl AsRef<str>, ) -> Result<Option<(Statement, usize)>>

Source

pub fn from_uri( uri: &str, db_opts: DatabaseOpts, ) -> Result<(Arc<dyn IO>, Arc<Connection>)>

Source

pub fn set_foreign_keys_enabled(&self, enable: bool)

Source

pub fn foreign_keys_enabled(&self) -> bool

Source

pub fn set_check_constraints_ignored(&self, ignore: bool)

Source

pub fn check_constraints_ignored(&self) -> bool

Source

pub fn maybe_update_schema(&self)

Source

pub fn read_schema_version(&self) -> Result<u32>

Read schema version at current transaction

Source

pub fn write_schema_version(self: &Arc<Connection>, version: u32) -> Result<()>

Update schema version to the new value within opened write transaction

New version of the schema must be strictly greater than previous one - otherwise method will panic Write transaction must be opened in advance - otherwise method will panic

Source

pub fn try_wal_watermark_read_page( &self, page_idx: u32, page: &mut [u8], frame_watermark: Option<u64>, ) -> Result<bool>

Try to read page with given ID with fixed WAL watermark position This method return false if page is not found (so, this is probably new page created after watermark position which wasn’t checkpointed to the DB file yet)

Source

pub fn wal_watermark_read_error_is_absent_page(err: &CompletionError) -> bool

Classify a completion error raised while reading a page at a fixed WAL watermark. On Windows under experimental_win_iocp, an absent / zero-length page read surfaces as UnexpectedEof (see core/io/win_iocp.rs); every watermark-read site must treat that as “page absent” (size 0) rather than a hard error. Centralized here so the platform handling cannot drift across the (now four) call sites.

Source

pub fn try_wal_watermark_read_page_begin( &self, page_idx: u32, frame_watermark: Option<u64>, ) -> Result<Option<(Arc<Page>, Completion)>>

Source

pub fn try_wal_watermark_read_page_end( &self, page: &mut [u8], page_ref: Arc<Page>, ) -> Result<bool>

Source

pub fn wal_changed_pages_after(&self, frame_watermark: u64) -> Result<Vec<u32>>

Return unique set of page numbers changes after WAL watermark position in the current WAL session (so, if concurrent connection wrote something to the WAL - this method will not see this change)

Source

pub fn wal_state(&self) -> Result<WalState>

Source

pub fn wal_get_frame( &self, frame_no: u64, frame: &mut [u8], ) -> Result<WalFrameInfo>

Source

pub fn wal_insert_frame( &self, frame_no: u64, frame: &[u8], ) -> Result<WalFrameInfo>

Insert frame (header included) at the position frame_no in the WAL If WAL already has frame at that position - turso-db will compare content of the page and either report conflict or return OK If attempt to write frame at the position frame_no will create gap in the WAL - method will return error

Source

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

Start WAL session by initiating read+write transaction for this connection

Source

pub fn wal_insert_end(self: &Arc<Connection>, force_commit: bool) -> Result<()>

Finish WAL session by ending read+write transaction taken in the Self::wal_insert_begin method All frames written after last commit frame (db_size > 0) within the session will be rolled back

Source

pub fn cacheflush(&self) -> Result<Vec<Completion>>

Flush dirty pages to disk.

Source

pub fn checkpoint( self: &Arc<Self>, mode: CheckpointMode, ) -> Result<CheckpointResult>

Source

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

Close a connection and checkpoint.

Source

pub fn wal_auto_actions_disable(&self)

Disable every automatic WAL maintenance action for this connection (auto-checkpoint AND WAL header restart). Sync-engine consumers call this so they own all WAL bookkeeping themselves.

Source

pub fn wal_auto_actions(&self) -> WalAutoActions

Returns the set of automatic WAL maintenance actions this connection permits. MVCC connections always return an empty set because the MVCC checkpoint state machine drives WAL maintenance explicitly.

Source

pub fn publish_schema_if_newer(&self)

Publish the connection’s current schema snapshot to the shared database cache after a successful commit so other live connections can refresh.

Source

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

Publish the connection’s current schema snapshot after pages were replaced outside normal SQL commit ordering.

External restore paths can move the schema cookie backwards. In that case the shared schema cache must be replaced rather than updated monotonically, otherwise new connections can re-adopt stale metadata.

Source

pub fn reset_main_mvcc_tx_for_wal_session(&self)

Roll back the main-database MVCC transaction while keeping the surrounding raw WAL-insert session open.

Source

pub fn discard_main_mvcc_tx_after_external_restore(&self)

Discard the main-db MVCC transaction left by a sync raw-WAL session before reparsing state after external file replacement.

Source

pub fn has_main_mvcc_tx_for_wal_session(&self) -> bool

Returns whether the main database currently has a live MVCC transaction.

Source

pub fn commit_main_mvcc_tx_for_wal_session(self: &Arc<Self>) -> Result<()>

Commit the main-database MVCC transaction while keeping the surrounding raw WAL-insert session open.

Source

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

Source

pub fn set_portable_logical_changes_enabled(&self, enabled: bool)

Enable or disable writing portable logical-change metadata into MVCC logical-log frames.

Source

pub fn portable_logical_changes_enabled(&self) -> bool

Source

pub fn set_mvcc_log_meta(&self, key: String, value: Option<String>)

Source

pub fn mvcc_log_meta(&self, key: &str) -> Option<String>

Source

pub fn last_insert_rowid(&self) -> i64

Source

pub fn set_changes(&self, num_changes: i64)

Source

pub fn changes(&self) -> i64

Source

pub fn total_changes(&self) -> i64

Source

pub fn get_cache_size(&self) -> i32

Source

pub fn set_cache_size(&self, size: i32)

Source

pub fn get_capture_data_changes_info( &self, ) -> RwLockReadGuard<'_, Option<CaptureDataChangesInfo>>

Source

pub fn set_capture_data_changes_info( &self, opts: Option<CaptureDataChangesInfo>, )

Source

pub fn get_cdc_transaction_id(&self) -> i64

Source

pub fn set_cdc_transaction_id(&self, id: i64)

Source

pub fn get_page_size(&self) -> PageSize

Source

pub fn is_closed(&self) -> bool

Source

pub fn is_query_only(&self) -> bool

Source

pub fn get_database_canonical_path(&self) -> String

Source

pub fn is_readonly(&self, index: usize) -> bool

Check if a specific attached database is read only or not, by its index

Source

pub fn reset_page_size(&self, size: u32) -> Result<()>

Reset the page size for the current connection.

Specifying a new page size does not change the page size immediately. Instead, the new page size is remembered and is used to set the page size when the database is first created, if it does not already exist when the page_size pragma is issued, or at the next VACUUM command that is run on the same database connection while not in WAL mode.

Source

pub fn open_new( &self, path: &str, vfs: &str, ) -> Result<(Arc<dyn IO>, Arc<Database>)>

Source

pub fn list_vfs(&self) -> Vec<String>

Source

pub fn get_auto_commit(&self) -> bool

Source

pub fn set_load_extension_enabled(&self, enabled: bool)

Source

pub fn reparse_schema_after_extension_load(self: &Arc<Connection>) -> Result<()>

Source

pub fn pragma_query( self: &Arc<Connection>, pragma_name: &str, ) -> Result<Vec<Vec<Value>>>

Query the current rows/values of pragma_name.

Source

pub fn pragma_update<V: Display>( self: &Arc<Connection>, pragma_name: &str, pragma_value: V, ) -> Result<Vec<Vec<Value>>>

Set a new value to pragma_name.

Some pragmas will return the updated value which cannot be retrieved with this method.

Source

pub fn experimental_views_enabled(&self) -> bool

Source

pub fn experimental_index_method_enabled(&self) -> bool

Source

pub fn experimental_custom_types_enabled(&self) -> bool

Source

pub fn experimental_attach_enabled(&self) -> bool

Source

pub fn experimental_vacuum_enabled(&self) -> bool

Source

pub fn experimental_mvcc_passive_checkpoint_enabled(&self) -> bool

Source

pub fn experimental_multiprocess_wal_enabled(&self) -> bool

Source

pub fn experimental_generated_columns_enabled(&self) -> bool

Source

pub fn experimental_without_rowid_enabled(&self) -> bool

Source

pub fn mvcc_enabled(&self) -> bool

Source

pub fn mv_store( &self, ) -> impl Deref<Target = Option<Arc<MvStore<MvccClock, DynAllocator>>>>

Source

pub fn pragma<V: Display>( self: &Arc<Connection>, pragma_name: &str, pragma_value: V, ) -> Result<Vec<Vec<Value>>>

Query the current value(s) of pragma_name associated to pragma_value.

This method can be used with query-only pragmas which need an argument (e.g. table_info('one_tbl')) or pragmas which returns value(s) (e.g. integrity_check).

Source

pub fn with_schema_mut<T>(&self, f: impl FnOnce(&mut Schema) -> T) -> Result<T>

Source

pub fn is_db_initialized(&self) -> bool

Source

pub fn list_attached_databases(&self) -> Vec<String>

List all attached database aliases

Source

pub fn list_all_databases(&self) -> Vec<(usize, String, String)>

List all databases (main + attached) with their sequence numbers, names, and file paths Returns a vector of tuples: (seq_number, name, file_path)

Source

pub fn get_pager(&self) -> Arc<Pager>

Source

pub fn get_query_only(&self) -> bool

Source

pub fn set_query_only(&self, value: bool)

Source

pub fn set_vdbe_trace(&self, value: bool)

Source

pub fn get_vdbe_trace(&self) -> bool

Source

pub fn get_dml_require_where(&self) -> bool

Source

pub fn set_dml_require_where(&self, value: bool)

Source

pub fn get_dqs_dml(&self) -> bool

Source

pub fn set_dqs_dml(&self, value: bool)

Source

pub fn get_full_column_names(&self) -> bool

Source

pub fn set_full_column_names(&self, value: bool)

Source

pub fn get_short_column_names(&self) -> bool

Source

pub fn set_short_column_names(&self, value: bool)

Source

pub fn get_sync_mode(&self) -> SyncMode

Source

pub fn set_sync_mode(&self, mode: SyncMode)

Source

pub fn get_temp_store(&self) -> TempStore

Source

pub fn set_temp_store(&self, value: TempStore)

Source

pub fn find_sequence(&self, name: &str) -> Result<Arc<Sequence>>

Find a sequence by name, supporting optional schema qualification.

  • "my_seq" → searches main database only
  • "aux.my_seq" → searches the attached database named aux
Source

pub fn set_sequence_currval(&self, name: &str, value: i64)

Record that this connection has seen a value from the named sequence (for currval).

Source

pub fn get_sequence_currval(&self, name: &str) -> Option<i64>

Get the last value returned by nextval/setval for the named sequence on this connection.

Source

pub fn clear_sequence_currval(&self, name: &str)

Drop this connection’s currval entry for a sequence. Called on DROP SEQUENCE (and implicit drops via DROP TABLE on AUTOINCREMENT) so that a subsequent CREATE SEQUENCE <same-name> does not silently inherit the stale per-session currval from the prior sequence — currval() on the fresh sequence must error with “not yet defined in this session” until a nextval/setval establishes it.

Source

pub fn sequence_inner_retries(&self) -> u64

Total times this connection’s autonomous sequence inner-tx ran into a transient conflict (WriteWriteConflict / BusySnapshot / Conflict(_)) and was retried by op_sequence_commit_inner_tx. A non-CYCLE nextval on a non-contended seq must keep this at zero — the regression test for “no inline backing-table compaction” asserts the delta is 0 across the concurrent-nextval scenario.

Source

pub fn get_data_sync_retry(&self) -> bool

Source

pub fn set_data_sync_retry(&self, value: bool)

Source

pub fn get_sync_type(&self) -> FileSyncType

Get the sync type setting.

Source

pub fn set_sync_type(&self, value: FileSyncType)

Set the sync type (for PRAGMA fullfsync).

Source

pub fn get_syms_vtab_mods(&self) -> HashSet<String>

Creates a HashSet of modules that have been loaded

Source

pub fn get_syms_functions(&self) -> Vec<(String, bool, i32, bool)>

Returns external (extension) functions: (name, is_aggregate, argc, deterministic)

Source

pub fn register_external_collation( &self, name: String, context: usize, callback: ContextCollationFunction, context_destructor: Option<ContextDestructor>, )

Source

pub fn unregister_external_collation(&self, name: &str)

Source

pub fn set_encryption_key(&self, key: EncryptionKey) -> Result<()>

Source

pub fn set_encryption_cipher(&self, cipher_mode: CipherMode) -> Result<()>

Source

pub fn set_reserved_bytes(&self, reserved_bytes: u8) -> Result<()>

Source

pub fn get_reserved_bytes(&self) -> Option<u8>

Get the reserved bytes value from the pager cache. Returns None if not yet set (database not initialized).

Source

pub fn get_encryption_cipher_mode(&self) -> Option<CipherMode>

Source

pub fn set_busy_handler(&self, handler: Option<BusyHandlerCallback>)

Sets a custom busy handler callback.

Source

pub fn set_busy_timeout(&self, duration: Duration)

Sets maximum total accumulated timeout. If the duration is Zero, we unset the busy handler.

Source

pub fn get_busy_timeout(&self) -> Duration

Get the busy timeout duration.

Source

pub fn set_query_timeout(&self, duration: Duration)

Sets the maximum duration a statement is allowed to run. Duration::ZERO disables query timeout.

Source

pub fn get_query_timeout(&self) -> Duration

Get the query timeout duration.

Source

pub fn get_busy_handler(&self) -> RwLockReadGuard<'_, BusyHandler>

Get a reference to the busy handler.

Source

pub fn set_progress_handler( &self, ops: u64, handler: Option<Box<dyn Fn() -> bool + Send + Sync>>, )

Sets a progress handler invoked approximately every ops VM steps. Passing ops == 0 or None disables the progress handler.

Source

pub fn should_interrupt_for_progress(&self, vm_steps: u64) -> bool

Returns true when the step-based progress handler requests interruption.

Source

pub fn interrupt(&self)

Request interruption of currently running root statements on this connection. If no root statement is active, the request is ignored to match SQLite semantics.

Source

pub fn is_interrupted(&self) -> bool

Returns true if an interrupt is currently pending for this connection.

Source

pub fn is_in_write_tx(&self) -> bool

Returns true if the connection is currently in a write transaction. Used by index methods to determine if it’s safe to flush writes.

Source§

impl Connection

Source

pub fn load_extension<P: AsRef<OsStr>>( self: &Arc<Connection>, path: P, ) -> Result<()>

Source§

impl Connection

Source

pub unsafe fn _build_turso_ext(&self) -> ExtensionApi

Build the connection’s extension api context for manually registering an extension. you probably want to use Connection::load_extension(path).

§Safety

Only to be used when registering a staticly linked extension manually. You should only ever call this method on your applications startup, The caller is responsible for calling _free_extension_ctx after registering the extension.

usage:

let ext_api = conn._build_turso_ext();
unsafe {
    my_extension::register_extension(&mut ext_api);
    conn._free_extension_ctx(ext_api);
}
Source

pub unsafe fn _free_extension_ctx(&self, api: ExtensionApi)

Free the connection’s extension libary context after registering an extension manually.

§Safety

Only to be used if you have previously called Connection::build_turso_ext

Trait Implementations§

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

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, 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = !

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

fn try_from(value: U) -> Result<T, !>

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