Skip to main content

SqliteConnection

Struct SqliteConnection 

pub struct SqliteConnection { /* private fields */ }
Expand description

Connections for the SQLite backend. Unlike other backends, SQLite supported connection URLs are:

  • File paths (test.db)
  • URIs (file://test.db)
  • Special identifiers (:memory:)

§Supported loading model implementations

  • [DefaultLoadingMode]

As SqliteConnection only supports a single loading mode implementation, it is not required to explicitly specify a loading mode when calling RunQueryDsl::load_iter() or [LoadConnection::load]

§DefaultLoadingMode

SqliteConnection only supports a single loading mode, which loads values row by row from the result set.

use diesel::connection::DefaultLoadingMode;
{
    // scope to restrict the lifetime of the iterator
    let iter1 = users::table.load_iter::<(i32, String), DefaultLoadingMode>(connection)?;

    for r in iter1 {
        let (id, name) = r?;
        println!("Id: {} Name: {}", id, name);
    }
}

// works without specifying the loading mode
let iter2 = users::table.load_iter::<(i32, String), _>(connection)?;

for r in iter2 {
    let (id, name) = r?;
    println!("Id: {} Name: {}", id, name);
}

This mode does not support creating multiple iterators using the same connection.

use diesel::connection::DefaultLoadingMode;

let iter1 = users::table.load_iter::<(i32, String), DefaultLoadingMode>(connection)?;
let iter2 = users::table.load_iter::<(i32, String), DefaultLoadingMode>(connection)?;

for r in iter1 {
    let (id, name) = r?;
    println!("Id: {} Name: {}", id, name);
}

for r in iter2 {
    let (id, name) = r?;
    println!("Id: {} Name: {}", id, name);
}

§Concurrency

By default, when running into a database lock, the operation will abort with a Database locked error. However, it’s possible to configure it for greater concurrency, trading latency for not having to deal with retries yourself.

You can use this example as blue-print for which statements to run after establishing a connection. It is important to run each PRAGMA in a single statement to make sure all of them apply correctly. In addition the order of the PRAGMA statements is relevant to prevent timeout issues for the later PRAGMA statements.

use diesel::connection::SimpleConnection;
let conn = &mut establish_connection();
// see https://fractaledmind.github.io/2023/09/07/enhancing-rails-sqlite-fine-tuning/
// sleep if the database is busy, this corresponds to up to 2 seconds sleeping time.
conn.batch_execute("PRAGMA busy_timeout = 2000;")?;
// better write-concurrency
conn.batch_execute("PRAGMA journal_mode = WAL;")?;
// fsync only in critical moments
conn.batch_execute("PRAGMA synchronous = NORMAL;")?;
// write WAL changes back every 1000 pages, for an in average 1MB WAL file.
// May affect readers if number is increased
conn.batch_execute("PRAGMA wal_autocheckpoint = 1000;")?;
// free some space by truncating possibly massive WAL files from the last run
conn.batch_execute("PRAGMA wal_checkpoint(TRUNCATE);")?;

Implementations§

§

impl SqliteConnection

pub fn immediate_transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
where F: FnOnce(&mut SqliteConnection) -> Result<T, E>, E: From<Error>,

Run a transaction with BEGIN IMMEDIATE

This method will return an error if a transaction is already open.

§Example
conn.immediate_transaction(|conn| {
    // Do stuff in a transaction
    Ok(())
})

pub fn exclusive_transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
where F: FnOnce(&mut SqliteConnection) -> Result<T, E>, E: From<Error>,

Run a transaction with BEGIN EXCLUSIVE

This method will return an error if a transaction is already open.

§Example
conn.exclusive_transaction(|conn| {
    // Do stuff in a transaction
    Ok(())
})

pub fn register_collation<F>( &mut self, collation_name: &str, collation: F, ) -> Result<(), Error>
where F: Fn(&str, &str) -> Ordering + Send + 'static + UnwindSafe,

Register a collation function.

collation must always return the same answer given the same inputs. If collation panics and unwinds the stack, the process is aborted, since it is used across a C FFI boundary, which cannot be unwound across and there is no way to signal failures via the SQLite interface in this case..

If the name is already registered it will be overwritten.

This method will return an error if registering the function fails, either due to an out-of-memory situation or because a collation with that name already exists and is currently being used in parallel by a query.

The collation needs to be specified when creating a table: CREATE TABLE my_table ( str TEXT COLLATE MY_COLLATION ), where MY_COLLATION corresponds to name passed as collation_name.

§Example
// sqlite NOCASE only works for ASCII characters,
// this collation allows handling UTF-8 (barring locale differences)
conn.register_collation("RUSTNOCASE", |rhs, lhs| {
    rhs.to_lowercase().cmp(&lhs.to_lowercase())
})

pub fn serialize_database_to_buffer(&mut self) -> SerializedDatabase

Serialize the current SQLite database into a byte buffer.

The serialized data is identical to the data that would be written to disk if the database was saved in a file.

§Returns

This function returns a byte slice representing the serialized database.

pub fn deserialize_readonly_database_from_buffer( &mut self, data: &[u8], ) -> Result<(), Error>

Deserialize an SQLite database from a byte buffer.

This function takes a byte slice and attempts to deserialize it into a SQLite database. If successful, the database is loaded into the connection. If the deserialization fails, an error is returned.

The database is opened in READONLY mode.

§Example
let connection = &mut SqliteConnection::establish(":memory:").unwrap();

sql_query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)")
    .execute(connection).unwrap();
sql_query("INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com'), ('Jane Doe', 'jane.doe@example.com')")
    .execute(connection).unwrap();

// Serialize the database to a byte vector
let serialized_db: SerializedDatabase = connection.serialize_database_to_buffer();

// Create a new in-memory SQLite database
let connection = &mut SqliteConnection::establish(":memory:").unwrap();

// Deserialize the byte vector into the new database
connection.deserialize_readonly_database_from_buffer(serialized_db.as_slice()).unwrap();

pub fn deserialize_database_from_buffer( &mut self, data: &[u8], ) -> Result<(), Error>

Trait Implementations§

§

impl Connection for SqliteConnection

§

fn establish(database_url: &str) -> Result<SqliteConnection, ConnectionError>

Establish a connection to the database specified by database_url.

See SqliteConnection for supported database_url.

If the database does not exist, this method will try to create a new database and then establish a connection to it.

§WASM support

If you plan to use this connection type on the wasm32-unknown-unknown target please make sure to read the following notes:

§

type Backend = Sqlite

The backend this type connects to
§

fn set_instrumentation(&mut self, instrumentation: impl Instrumentation)

Set a specific [Instrumentation] implementation for this connection
§

fn set_prepared_statement_cache_size(&mut self, size: CacheSize)

Set the prepared statement cache size to [CacheSize] for this connection
§

fn transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
where F: FnOnce(&mut Self) -> Result<T, E>, E: From<Error>,

Executes the given function inside of a database transaction Read more
§

fn begin_test_transaction(&mut self) -> Result<(), Error>

Creates a transaction that will never be committed. This is useful for tests. Panics if called while inside of a transaction or if called with a connection containing a broken transaction
§

fn test_transaction<T, E, F>(&mut self, f: F) -> T
where F: FnOnce(&mut Self) -> Result<T, E>, E: Debug,

Executes the given function inside a transaction, but does not commit it. Panics if the given function returns an error. Read more
Source§

impl CustomizeConnection<SqliteConnection, Error> for EncryptedConnection

Source§

fn on_acquire(&self, conn: &mut SqliteConnection) -> Result<(), Error>

Called with connections immediately after they are returned from ManageConnection::connect. Read more
Source§

fn on_release(&self, conn: C)

Called with connections when they are removed from the pool. Read more
Source§

impl CustomizeConnection<SqliteConnection, Error> for NopConnection

Source§

fn on_acquire(&self, c: &mut SqliteConnection) -> Result<(), Error>

Called with connections immediately after they are returned from ManageConnection::connect. Read more
Source§

fn on_release(&self, conn: C)

Called with connections when they are removed from the pool. Read more
Source§

impl CustomizeConnection<SqliteConnection, Error> for UnencryptedConnection

Source§

fn on_acquire(&self, c: &mut SqliteConnection) -> Result<(), Error>

Called with connections immediately after they are returned from ManageConnection::connect. Read more
Source§

fn on_release(&self, conn: C)

Called with connections when they are removed from the pool. Read more
§

impl LoadConnection for SqliteConnection

§

type Cursor<'conn, 'query> = StatementIterator<'conn, 'query>

The cursor type returned by [LoadConnection::load] Read more
§

type Row<'conn, 'query> = SqliteRow<'conn, 'query>

The row type used as Iterator::Item for the iterator implementation of [LoadConnection::Cursor]
§

impl MigrationConnection for SqliteConnection

Available on crate feature sqlite only.
§

fn setup(&mut self) -> Result<usize, Error>

Setup the following table: Read more
§

impl R2D2Connection for SqliteConnection

Available on crate feature r2d2 only.
§

fn ping(&mut self) -> Result<(), Error>

Check if a connection is still valid
§

fn is_broken(&mut self) -> bool

Checks if the connection is broken and should not be reused Read more
§

impl SimpleConnection for SqliteConnection

§

fn batch_execute(&mut self, query: &str) -> Result<(), Error>

Execute multiple SQL statements within the same string. Read more
Source§

impl TransactionalKeyStore for SqliteConnection

Source§

type Store<'a> = SqlKeyStore<MutableTransactionConnection<'a>> where Self: 'a

Source§

fn key_store<'a>(&'a mut self) -> Self::Store<'a>

§

impl<'b, Changes, Output> UpdateAndFetchResults<Changes, Output> for SqliteConnection
where Changes: Copy + Identifiable + AsChangeset<Target = <Changes as HasTable>::Table> + IntoUpdateTarget, <Changes as HasTable>::Table: FindDsl<<Changes as Identifiable>::Id>, UpdateStatement<<Changes as HasTable>::Table, <Changes as IntoUpdateTarget>::WhereClause, <Changes as AsChangeset>::Changeset>: ExecuteDsl<SqliteConnection>, <<Changes as HasTable>::Table as FindDsl<<Changes as Identifiable>::Id>>::Output: LoadQuery<'b, SqliteConnection, Output>, <<Changes as HasTable>::Table as Table>::AllColumns: ValidGrouping<()>, <<<Changes as HasTable>::Table as Table>::AllColumns as ValidGrouping<()>>::IsAggregate: MixedAggregates<No, Output = No>,

Available on crate feature sqlite only.
§

fn update_and_fetch(&mut self, changeset: Changes) -> Result<Output, Error>

See the traits documentation.
§

impl WithMetadataLookup for SqliteConnection

§

fn metadata_lookup(&mut self) -> &mut <Sqlite as TypeMetadata>::MetadataLookup

Retrieves the underlying metadata lookup
§

impl Send for SqliteConnection

Auto Trait Implementations§

Blanket Implementations§

§

impl<T> AggregateExpressionMethods for T

§

fn aggregate_distinct(self) -> Self::Output
where Self: DistinctDsl,

DISTINCT modifier for aggregate functions Read more
§

fn aggregate_all(self) -> Self::Output
where Self: AllDsl,

ALL modifier for aggregate functions Read more
§

fn aggregate_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add an aggregate function filter Read more
§

fn aggregate_order<O>(self, o: O) -> Self::Output
where Self: OrderAggregateDsl<O>,

Add an aggregate function order Read more
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
§

impl<C> BoxableConnection<<C as Connection>::Backend> for C
where C: Connection + Any,

§

fn as_any(&self) -> &(dyn Any + 'static)

§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSend for T
where T: Any + Send,

§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

§

const WITNESS: W = W::MAKE

A constant of the type witness
§

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

§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
§

impl<T> Instrument for T

§

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

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

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
§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<T> IntoSql for T

§

fn into_sql<T>(self) -> Self::Expression
where Self: Sized + AsExpression<T>, T: SqlType + TypedExpressionType,

Convert self to an expression for Diesel’s query builder. Read more
§

fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
where &'a Self: AsExpression<T>, T: SqlType + TypedExpressionType,

Convert &self to an expression for Diesel’s query builder. Read more
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

impl<C, DB> MigrationHarness<DB> for C
where DB: Backend + DieselReserveSpecialization, C: Connection<Backend = DB> + MigrationConnection + 'static, table: BoxedDsl<'static, DB, Output = BoxedSelectStatement<'static, (Text, Timestamp), FromClause<table>, DB>>, BoxedSelectStatement<'static, Text, FromClause<table>, DB>: LoadQuery<'static, C, MigrationVersion<'static>>, DefaultValues: QueryFragment<DB>, str: ToSql<Text, DB>,

§

fn run_migration( &mut self, migration: &dyn Migration<DB>, ) -> Result<MigrationVersion<'static>, Box<dyn Error + Send + Sync>>

Apply a single migration Read more
§

fn revert_migration( &mut self, migration: &dyn Migration<DB>, ) -> Result<MigrationVersion<'static>, Box<dyn Error + Send + Sync>>

Revert a single migration Read more
§

fn applied_migrations( &mut self, ) -> Result<Vec<MigrationVersion<'static>>, Box<dyn Error + Send + Sync>>

Get a list of already applied migration versions
§

fn has_pending_migration<S>( &mut self, source: S, ) -> Result<bool, Box<dyn Error + Send + Sync>>
where S: MigrationSource<DB>,

Checks if the database represented by the current harness has unapplied migrations
§

fn run_pending_migrations<S>( &mut self, source: S, ) -> Result<Vec<MigrationVersion<'_>>, Box<dyn Error + Send + Sync>>
where S: MigrationSource<DB>,

Execute all unapplied migrations for a given migration source
§

fn run_next_migration<S>( &mut self, source: S, ) -> Result<MigrationVersion<'_>, Box<dyn Error + Send + Sync>>
where S: MigrationSource<DB>,

Execute the next migration from the given migration source
§

fn revert_all_migrations<S>( &mut self, source: S, ) -> Result<Vec<MigrationVersion<'_>>, Box<dyn Error + Send + Sync>>
where S: MigrationSource<DB>,

Revert all applied migrations from a given migration source
§

fn revert_last_migration<S>( &mut self, source: S, ) -> Result<MigrationVersion<'static>, Box<dyn Error + Send + Sync>>
where S: MigrationSource<DB>,

Revert the last migration from a given migration source Read more
§

fn pending_migrations<S>( &mut self, source: S, ) -> Result<Vec<Box<dyn Migration<DB>>>, Box<dyn Error + Send + Sync>>
where S: MigrationSource<DB>,

Get a list of non applied migrations for a specific migration source Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. 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<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
§

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

§

fn vzip(self) -> V

§

impl<T> WindowExpressionMethods for T

§

fn over(self) -> Self::Output
where Self: OverDsl,

Turn a function call into a window function call Read more
§

fn window_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add a filter to the current window function Read more
§

fn partition_by<E>(self, expr: E) -> Self::Output
where Self: PartitionByDsl<E>,

Add a partition clause to the current window function Read more
§

fn window_order<E>(self, expr: E) -> Self::Output
where Self: OrderWindowDsl<E>,

Add a order clause to the current window function Read more
§

fn frame_by<E>(self, expr: E) -> Self::Output
where Self: FrameDsl<E>,

Add a frame clause to the current window function Read more
§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

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

§

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

Source§

impl<T> MaybeSend for T
where T: Send + ?Sized,

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,