pub struct SqliteConnection { /* private fields */ }
sqlite
only.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
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);
}
Implementations§
Source§impl SqliteConnection
impl SqliteConnection
Sourcepub fn immediate_transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
pub fn immediate_transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
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(())
})
Sourcepub fn exclusive_transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
pub fn exclusive_transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
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(())
})
Sourcepub fn register_collation<F>(
&mut self,
collation_name: &str,
collation: F,
) -> QueryResult<()>
pub fn register_collation<F>( &mut self, collation_name: &str, collation: F, ) -> QueryResult<()>
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())
})
Sourcepub fn serialize_database_to_buffer(&mut self) -> SerializedDatabase
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.
Sourcepub fn deserialize_readonly_database_from_buffer(
&mut self,
data: &[u8],
) -> QueryResult<()>
pub fn deserialize_readonly_database_from_buffer( &mut self, data: &[u8], ) -> QueryResult<()>
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();
Trait Implementations§
Source§impl Connection for SqliteConnection
impl Connection for SqliteConnection
Source§fn establish(database_url: &str) -> ConnectionResult<Self>
fn establish(database_url: &str) -> ConnectionResult<Self>
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.
Source§type TransactionManager = AnsiTransactionManager
type TransactionManager = AnsiTransactionManager
i-implement-a-third-party-backend-and-opt-into-breaking-changes
only.Source§fn execute_returning_count<T>(&mut self, source: &T) -> QueryResult<usize>
fn execute_returning_count<T>(&mut self, source: &T) -> QueryResult<usize>
i-implement-a-third-party-backend-and-opt-into-breaking-changes
only.Source§fn transaction_state(&mut self) -> &mut AnsiTransactionManagerwhere
Self: Sized,
fn transaction_state(&mut self) -> &mut AnsiTransactionManagerwhere
Self: Sized,
i-implement-a-third-party-backend-and-opt-into-breaking-changes
only.Source§fn instrumentation(&mut self) -> &mut dyn Instrumentation
fn instrumentation(&mut self) -> &mut dyn Instrumentation
i-implement-a-third-party-backend-and-opt-into-breaking-changes
only.Source§fn set_instrumentation(&mut self, instrumentation: impl Instrumentation)
fn set_instrumentation(&mut self, instrumentation: impl Instrumentation)
Instrumentation
implementation for this connectionSource§fn set_prepared_statement_cache_size(&mut self, size: CacheSize)
fn set_prepared_statement_cache_size(&mut self, size: CacheSize)
CacheSize
for this connectionSource§fn transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
fn transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
Source§fn begin_test_transaction(&mut self) -> QueryResult<()>
fn begin_test_transaction(&mut self) -> QueryResult<()>
Source§impl LoadConnection for SqliteConnection
impl LoadConnection for SqliteConnection
Source§type Cursor<'conn, 'query> = StatementIterator<'conn, 'query>
type Cursor<'conn, 'query> = StatementIterator<'conn, 'query>
LoadConnection::load
Read moreSource§type Row<'conn, 'query> = SqliteRow<'conn, 'query>
type Row<'conn, 'query> = SqliteRow<'conn, 'query>
Iterator::Item
for the iterator implementation
of LoadConnection::Cursor
Source§fn load<'conn, 'query, T>(
&'conn mut self,
source: T,
) -> QueryResult<Self::Cursor<'conn, 'query>>where
T: Query + QueryFragment<Self::Backend> + QueryId + 'query,
Self::Backend: QueryMetadata<T::SqlType>,
fn load<'conn, 'query, T>(
&'conn mut self,
source: T,
) -> QueryResult<Self::Cursor<'conn, 'query>>where
T: Query + QueryFragment<Self::Backend> + QueryId + 'query,
Self::Backend: QueryMetadata<T::SqlType>,
i-implement-a-third-party-backend-and-opt-into-breaking-changes
only.Source§impl MultiConnectionHelper for SqliteConnection
impl MultiConnectionHelper for SqliteConnection
Source§fn to_any<'a>(
lookup: &mut <Self::Backend as TypeMetadata>::MetadataLookup,
) -> &mut (dyn Any + 'a)
fn to_any<'a>( lookup: &mut <Self::Backend as TypeMetadata>::MetadataLookup, ) -> &mut (dyn Any + 'a)
i-implement-a-third-party-backend-and-opt-into-breaking-changes
only.Source§fn from_any(
lookup: &mut dyn Any,
) -> Option<&mut <Self::Backend as TypeMetadata>::MetadataLookup>
fn from_any( lookup: &mut dyn Any, ) -> Option<&mut <Self::Backend as TypeMetadata>::MetadataLookup>
i-implement-a-third-party-backend-and-opt-into-breaking-changes
only.Source§impl R2D2Connection for SqliteConnection
Available on crate feature r2d2
only.
impl R2D2Connection for SqliteConnection
r2d2
only.Source§impl SimpleConnection for SqliteConnection
impl SimpleConnection for SqliteConnection
Source§fn batch_execute(&mut self, query: &str) -> QueryResult<()>
fn batch_execute(&mut self, query: &str) -> QueryResult<()>
Source§impl<'b, Changes, Output> UpdateAndFetchResults<Changes, Output> for SqliteConnectionwhere
Changes: Copy + Identifiable + AsChangeset<Target = <Changes as HasTable>::Table> + IntoUpdateTarget,
Changes::Table: FindDsl<Changes::Id>,
Update<Changes, Changes>: ExecuteDsl<SqliteConnection>,
Find<Changes::Table, Changes::Id>: LoadQuery<'b, SqliteConnection, Output>,
<Changes::Table as Table>::AllColumns: ValidGrouping<()>,
<<Changes::Table as Table>::AllColumns as ValidGrouping<()>>::IsAggregate: MixedAggregates<No, Output = No>,
impl<'b, Changes, Output> UpdateAndFetchResults<Changes, Output> for SqliteConnectionwhere
Changes: Copy + Identifiable + AsChangeset<Target = <Changes as HasTable>::Table> + IntoUpdateTarget,
Changes::Table: FindDsl<Changes::Id>,
Update<Changes, Changes>: ExecuteDsl<SqliteConnection>,
Find<Changes::Table, Changes::Id>: LoadQuery<'b, SqliteConnection, Output>,
<Changes::Table as Table>::AllColumns: ValidGrouping<()>,
<<Changes::Table as Table>::AllColumns as ValidGrouping<()>>::IsAggregate: MixedAggregates<No, Output = No>,
Source§fn update_and_fetch(&mut self, changeset: Changes) -> QueryResult<Output>
fn update_and_fetch(&mut self, changeset: Changes) -> QueryResult<Output>
Source§impl WithMetadataLookup for SqliteConnection
impl WithMetadataLookup for SqliteConnection
Source§fn metadata_lookup(&mut self) -> &mut <Sqlite as TypeMetadata>::MetadataLookup
fn metadata_lookup(&mut self) -> &mut <Sqlite as TypeMetadata>::MetadataLookup
i-implement-a-third-party-backend-and-opt-into-breaking-changes
only.impl ConnectionSealed for SqliteConnection
impl Send for SqliteConnection
Auto Trait Implementations§
impl Freeze for SqliteConnection
impl !RefUnwindSafe for SqliteConnection
impl !Sync for SqliteConnection
impl Unpin for SqliteConnection
impl !UnwindSafe for SqliteConnection
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<C> BoxableConnection<<C as Connection>::Backend> for Cwhere
C: Connection + Any,
impl<C> BoxableConnection<<C as Connection>::Backend> for Cwhere
C: Connection + Any,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.