Skip to main content

diesel/sqlite/connection/
mod.rs

1#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
2extern crate libsqlite3_sys as ffi;
3
4#[cfg(all(target_family = "wasm", target_os = "unknown"))]
5use sqlite_wasm_rs as ffi;
6
7mod attach;
8pub mod authorizer;
9mod bind_collector;
10pub(super) mod borrowed_connection;
11mod collation_needed;
12mod db_config;
13pub(in crate::sqlite) mod error_information;
14mod functions;
15mod hooks;
16mod limits;
17#[cfg(all(
18    test,
19    feature = "std",
20    not(all(target_family = "wasm", target_os = "unknown")),
21    not(miri)
22))]
23#[allow(unsafe_code)]
24mod oom_test_support;
25mod owned_row;
26mod pragmas;
27mod raw;
28mod row;
29mod serialized_database;
30pub(in crate::sqlite) mod sqlite_blob;
31mod sqlite_value;
32mod statement_iterator;
33mod stmt;
34mod trace;
35mod update_hook;
36
37pub use self::authorizer::{AuthorizerContext, AuthorizerDecision};
38pub use self::bind_collector::SqliteBindCollector;#[diesel_derives::__diesel_public_if(
39    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
40)]
41pub(in crate::sqlite) use self::bind_collector::SqliteBindCollector;
42pub use self::bind_collector::SqliteBindValue;
43#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
44pub use self::bind_collector::{OwnedSqliteBindValue, SqliteBindCollectorData, SqliteBindValueRef};
45pub use self::collation_needed::{CollationNeededContext, SqliteTextRep};
46pub use self::limits::SqliteLimit;
47pub use self::pragmas::{AutoVacuumMode, WalCheckpointMode, WalCheckpointOutcome};
48use self::raw::RawConnection;
49pub use self::serialized_database::SerializedDatabase;
50pub use self::sqlite_value::SqliteValue;
51use self::statement_iterator::*;
52use self::stmt::{Statement, StatementUse};
53pub use self::trace::{SqliteTraceEvent, SqliteTraceFlags};
54pub use self::update_hook::{
55    SqliteChangeEvent, SqliteChangeOp, SqliteChangeOps, SqliteUpdateRouter,
56};
57use super::{BorrowedSqliteConnection, SqliteAggregateFunction};
58use crate::connection::instrumentation::{DynInstrumentation, StrQueryHelper};
59use crate::connection::statement_cache::StatementCache;
60use crate::connection::*;
61use crate::expression::QueryMetadata;
62use crate::query_builder::*;
63use crate::result::*;
64use crate::sql_types::TypeMetadata;
65use crate::sqlite::Sqlite;
66#[cfg(not(miri))]
67use alloc::string::String;
68use core::ffi as libc;
69use core::num::NonZeroI64;
70
71/// Connections for the SQLite backend. Unlike other backends, SQLite supported
72/// connection URLs are:
73///
74/// - File paths (`test.db`)
75/// - [URIs](https://sqlite.org/uri.html) (`file://test.db`)
76/// - Special identifiers (`:memory:`)
77///
78/// SQLite has no SQLSTATE codes, so
79/// [`DatabaseErrorInformation::sqlstate`] always returns `None`.
80///
81/// Errors carry the result code of the failed API call in
82/// [`DatabaseErrorInformation::native_code`], the extended result code where
83/// SQLite reports one, listed at <https://www.sqlite.org/rescode.html>.
84///
85/// # Supported loading model implementations
86///
87/// * [`DefaultLoadingMode`]
88///
89/// As `SqliteConnection` only supports a single loading mode implementation,
90/// it is **not required** to explicitly specify a loading mode
91/// when calling [`RunQueryDsl::load_iter()`] or [`LoadConnection::load`]
92///
93/// [`RunQueryDsl::load_iter()`]: crate::query_dsl::RunQueryDsl::load_iter
94///
95/// ## DefaultLoadingMode
96///
97/// `SqliteConnection` only supports a single loading mode, which loads
98/// values row by row from the result set.
99///
100/// ```rust,dejadoc
101/// # include!("../../doctest_setup.rs");
102/// #
103/// # // Reading the query result requires reading memory allocated by the
104/// # // native sqlite library, which miri cannot track provenance for.
105/// # #[cfg(miri)]
106/// # fn main() {}
107/// # #[cfg(not(miri))]
108/// # fn main() {
109/// #     run_test().unwrap();
110/// # }
111/// #
112/// # fn run_test() -> QueryResult<()> {
113/// #     use schema::users;
114/// #     let connection = &mut establish_connection();
115/// use diesel::connection::DefaultLoadingMode;
116/// {
117///     // scope to restrict the lifetime of the iterator
118///     let iter1 = users::table.load_iter::<(i32, String), DefaultLoadingMode>(connection)?;
119///
120///     for r in iter1 {
121///         let (id, name) = r?;
122///         println!("Id: {} Name: {}", id, name);
123///     }
124/// }
125///
126/// // works without specifying the loading mode
127/// let iter2 = users::table.load_iter::<(i32, String), _>(connection)?;
128///
129/// for r in iter2 {
130///     let (id, name) = r?;
131///     println!("Id: {} Name: {}", id, name);
132/// }
133/// #   Ok(())
134/// # }
135/// ```
136///
137/// This mode does **not support** creating
138/// multiple iterators using the same connection.
139///
140/// ```compile_fail,dejadoc
141/// # include!("../../doctest_setup.rs");
142/// #
143/// # fn main() {
144/// #     run_test().unwrap();
145/// # }
146/// #
147/// # fn run_test() -> QueryResult<()> {
148/// #     use schema::users;
149/// #     let connection = &mut establish_connection();
150/// use diesel::connection::DefaultLoadingMode;
151///
152/// let iter1 = users::table.load_iter::<(i32, String), DefaultLoadingMode>(connection)?;
153/// let iter2 = users::table.load_iter::<(i32, String), DefaultLoadingMode>(connection)?;
154///
155/// for r in iter1 {
156///     let (id, name) = r?;
157///     println!("Id: {} Name: {}", id, name);
158/// }
159///
160/// for r in iter2 {
161///     let (id, name) = r?;
162///     println!("Id: {} Name: {}", id, name);
163/// }
164/// #   Ok(())
165/// # }
166/// ```
167///
168/// # Concurrency
169///
170/// By default, when running into a database lock, the operation will abort with a
171/// `Database locked` error. However, it's possible to configure it for greater concurrency,
172/// trading latency for not having to deal with retries yourself.
173///
174/// You can use this example as blue-print for which statements to run after establishing a connection.
175/// It is **important** to run each `PRAGMA` in a single statement to make sure all of them apply
176/// correctly. In addition the order of the `PRAGMA` statements is relevant to prevent timeout
177/// issues for the later `PRAGMA` statements.
178///
179/// ```rust
180/// # include!("../../doctest_setup.rs");
181/// #
182/// # fn main() {
183/// #     run_test().unwrap();
184/// # }
185/// #
186/// # fn run_test() -> QueryResult<()> {
187/// #     use schema::users;
188/// use diesel::connection::SimpleConnection;
189/// use diesel::sqlite::WalCheckpointMode;
190/// let conn = &mut establish_connection();
191/// // see https://fractaledmind.github.io/2023/09/07/enhancing-rails-sqlite-fine-tuning/
192/// // sleep if the database is busy, this corresponds to up to 2 seconds sleeping time.
193/// conn.batch_execute("PRAGMA busy_timeout = 2000;")?;
194/// // better write-concurrency
195/// conn.batch_execute("PRAGMA journal_mode = WAL;")?;
196/// // fsync only in critical moments
197/// conn.batch_execute("PRAGMA synchronous = NORMAL;")?;
198/// // write WAL changes back every 1000 pages, for an in average 1MB WAL file.
199/// // May affect readers if number is increased
200/// conn.batch_execute("PRAGMA wal_autocheckpoint = 1000;")?;
201/// // free some space by truncating possibly massive WAL files from the last run
202/// conn.wal_checkpoint(None, WalCheckpointMode::Truncate)?;
203/// #   Ok(())
204/// # }
205/// ```
206#[allow(missing_debug_implementations)]
207#[cfg(feature = "__sqlite-shared")]
208pub struct SqliteConnection {
209    // statement_cache needs to be before raw_connection
210    // otherwise we will get errors about open statements before closing the
211    // connection itself
212    statement_cache: StatementCache<Sqlite, Statement>,
213    raw_connection: RawConnection,
214    transaction_state: AnsiTransactionManager,
215    // this exists for the sole purpose of implementing `WithMetadataLookup` trait
216    // and avoiding static mut which will be deprecated in 2024 edition
217    metadata_lookup: (),
218    instrumentation: DynInstrumentation,
219}
220
221// This relies on the invariant that RawConnection or Statement are never
222// leaked. If a reference to one of those was held on a different thread, this
223// would not be thread safe.
224#[allow(unsafe_code)]
225unsafe impl Send for SqliteConnection {}
226
227impl SimpleConnection for SqliteConnection {
228    fn batch_execute(&mut self, query: &str) -> QueryResult<()> {
229        self.instrumentation
230            .on_connection_event(InstrumentationEvent::StartQuery {
231                query: &StrQueryHelper::new(query),
232            });
233        let resp = self.raw_connection.exec(query);
234        self.instrumentation
235            .on_connection_event(InstrumentationEvent::FinishQuery {
236                query: &StrQueryHelper::new(query),
237                error: resp.as_ref().err(),
238            });
239        if resp.is_err() && self.raw_connection.is_autocommit() {
240            // SQLite ends the transaction on some failures, e.g. an aborting commit hook.
241            self.transaction_state.status = TransactionManagerStatus::Valid(Default::default());
242        }
243        resp
244    }
245}
246
247impl ConnectionSealed for SqliteConnection {}
248
249impl Connection for SqliteConnection {
250    type Backend = Sqlite;
251    type TransactionManager = AnsiTransactionManager;
252
253    /// Establish a connection to the database specified by `database_url`.
254    ///
255    /// See [SqliteConnection] for supported `database_url`.
256    ///
257    /// If the database does not exist, this method will try to
258    /// create a new database and then establish a connection to it.
259    ///
260    /// ## WASM support
261    ///
262    /// If you plan to use this connection type on the `wasm32-unknown-unknown` target please
263    /// make sure to read the following notes:
264    ///
265    /// * The database is stored in memory by default.
266    /// * With `sqlite-wasm-rs` 0.6, enable its `wasm-bindgen` feature to use the
267    ///   built-in host functions, or provide your own.
268    /// * Persistent VFS (Virtual File Systems) is optional,
269    ///   see <https://github.com/Spxg/sqlite-wasm-rs> for details
270    fn establish(database_url: &str) -> ConnectionResult<Self> {
271        let mut instrumentation = DynInstrumentation::default_instrumentation();
272        instrumentation.on_connection_event(InstrumentationEvent::StartEstablishConnection {
273            url: database_url,
274        });
275
276        let establish_result = Self::establish_inner(database_url);
277        instrumentation.on_connection_event(InstrumentationEvent::FinishEstablishConnection {
278            url: database_url,
279            error: establish_result.as_ref().err(),
280        });
281        let mut conn = establish_result?;
282        conn.instrumentation = instrumentation;
283        Ok(conn)
284    }
285
286    fn execute_returning_count<T>(&mut self, source: &T) -> QueryResult<usize>
287    where
288        T: QueryFragment<Self::Backend> + QueryId,
289    {
290        let statement_use = self.prepared_query(source)?;
291        statement_use.run().and_then(|_| {
292            self.raw_connection
293                .rows_affected_by_last_query()
294                .map_err(Error::DeserializationError)
295        })
296    }
297
298    fn transaction_state(&mut self) -> &mut AnsiTransactionManager
299    where
300        Self: Sized,
301    {
302        &mut self.transaction_state
303    }
304
305    fn instrumentation(&mut self) -> &mut dyn Instrumentation {
306        &mut *self.instrumentation
307    }
308
309    fn set_instrumentation(&mut self, instrumentation: impl Instrumentation) {
310        self.instrumentation = instrumentation.into();
311    }
312
313    fn set_prepared_statement_cache_size(&mut self, size: CacheSize) {
314        self.statement_cache.set_cache_size(size);
315    }
316}
317
318impl LoadConnection<DefaultLoadingMode> for SqliteConnection {
319    type Cursor<'conn, 'query> = StatementIterator<'conn, 'query>;
320    type Row<'conn, 'query> = self::row::SqliteRow<'conn, 'query>;
321
322    fn load<'conn, 'query, T>(
323        &'conn mut self,
324        source: T,
325    ) -> QueryResult<Self::Cursor<'conn, 'query>>
326    where
327        T: Query + QueryFragment<Self::Backend> + QueryId + 'query,
328        Self::Backend: QueryMetadata<T::SqlType>,
329    {
330        let statement = self.prepared_query(source)?;
331
332        Ok(StatementIterator::new(statement))
333    }
334}
335
336impl WithMetadataLookup for SqliteConnection {
337    fn metadata_lookup(&mut self) -> &mut <Sqlite as TypeMetadata>::MetadataLookup {
338        &mut self.metadata_lookup
339    }
340}
341
342#[cfg(feature = "r2d2")]
343impl crate::r2d2::R2D2Connection for crate::sqlite::SqliteConnection {
344    fn ping(&mut self) -> QueryResult<()> {
345        use crate::RunQueryDsl;
346
347        crate::r2d2::CheckConnectionQuery.execute(self).map(|_| ())
348    }
349
350    fn is_broken(&mut self) -> bool {
351        AnsiTransactionManager::is_broken_transaction_manager(self)
352    }
353}
354
355impl MultiConnectionHelper for SqliteConnection {
356    fn to_any<'a>(
357        lookup: &mut <Self::Backend as crate::sql_types::TypeMetadata>::MetadataLookup,
358    ) -> &mut (dyn core::any::Any + 'a) {
359        lookup
360    }
361
362    fn from_any(
363        lookup: &mut dyn core::any::Any,
364    ) -> Option<&mut <Self::Backend as crate::sql_types::TypeMetadata>::MetadataLookup> {
365        lookup.downcast_mut()
366    }
367}
368
369/// The decision returned by an [`on_commit`](SqliteConnection::on_commit)
370/// callback, controlling whether a pending commit completes.
371#[derive(#[automatically_derived]impl ::core::fmt::Debug for CommitDecision {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                CommitDecision::Proceed => "Proceed",
                CommitDecision::Rollback => "Rollback",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CommitDecision {
}
#[automatically_derived]impl ::core::clone::Clone for CommitDecision {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for CommitDecision { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    CommitDecision {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CommitDecision {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for CommitDecision { }Eq)]
372pub enum CommitDecision {
373    /// Let the commit proceed normally.
374    Proceed,
375    /// Convert the commit into a rollback.
376    Rollback,
377}
378
379/// The decision returned by an [`on_progress`](SqliteConnection::on_progress)
380/// callback, controlling whether a long-running query keeps executing.
381#[derive(#[automatically_derived]impl ::core::fmt::Debug for ProgressDecision {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ProgressDecision::Continue => "Continue",
                ProgressDecision::Interrupt => "Interrupt",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ProgressDecision {
}
#[automatically_derived]impl ::core::clone::Clone for ProgressDecision {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ProgressDecision { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ProgressDecision {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ProgressDecision {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ProgressDecision { }Eq)]
382pub enum ProgressDecision {
383    /// Let the query continue executing.
384    Continue,
385    /// Interrupt the query (causes `SQLITE_INTERRUPT`).
386    Interrupt,
387}
388
389/// The decision returned by an [`on_busy`](SqliteConnection::on_busy)
390/// callback when the database is locked.
391#[derive(#[automatically_derived]impl ::core::fmt::Debug for BusyDecision {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                BusyDecision::Retry => "Retry",
                BusyDecision::GiveUp => "GiveUp",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for BusyDecision {
}
#[automatically_derived]impl ::core::clone::Clone for BusyDecision {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for BusyDecision { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    BusyDecision {
}
#[automatically_derived]impl ::core::cmp::PartialEq for BusyDecision {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for BusyDecision { }Eq)]
392pub enum BusyDecision {
393    /// Retry the locked operation.
394    Retry,
395    /// Give up, returning `SQLITE_BUSY` to the caller.
396    GiveUp,
397}
398
399impl SqliteConnection {
400    /// Returns the version of the SQLite library this connection runs on.
401    ///
402    /// # Example
403    ///
404    /// ```rust
405    /// # include!("../../doctest_setup.rs");
406    /// use diesel::connection::DatabaseVersion;
407    /// #
408    /// # fn main() {
409    /// #     let conn = &mut establish_connection();
410    /// let supports_jsonb = conn.version() >= DatabaseVersion::new(3, 45, 0);
411    /// # }
412    /// ```
413    pub fn version(&self) -> DatabaseVersion {
414        let version = raw::library_version_number();
415        DatabaseVersion::new(
416            version / 1_000_000,
417            version / 1_000 % 1_000,
418            version % 1_000,
419        )
420    }
421
422    /// Run a transaction with `BEGIN IMMEDIATE`
423    ///
424    /// This method will return an error if a transaction is already open.
425    ///
426    /// # Example
427    ///
428    /// ```rust
429    /// # include!("../../doctest_setup.rs");
430    /// #
431    /// # fn main() {
432    /// #     run_test().unwrap();
433    /// # }
434    /// #
435    /// # fn run_test() -> QueryResult<()> {
436    /// #     let mut conn = SqliteConnection::establish(":memory:").unwrap();
437    /// conn.immediate_transaction(|conn| {
438    ///     // Do stuff in a transaction
439    ///     Ok(())
440    /// })
441    /// # }
442    /// ```
443    pub fn immediate_transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
444    where
445        F: FnOnce(&mut Self) -> Result<T, E>,
446        E: From<Error>,
447    {
448        self.transaction_sql(f, "BEGIN IMMEDIATE")
449    }
450
451    /// Run a transaction with `BEGIN EXCLUSIVE`
452    ///
453    /// This method will return an error if a transaction is already open.
454    ///
455    /// # Example
456    ///
457    /// ```rust
458    /// # include!("../../doctest_setup.rs");
459    /// #
460    /// # fn main() {
461    /// #     run_test().unwrap();
462    /// # }
463    /// #
464    /// # fn run_test() -> QueryResult<()> {
465    /// #     let mut conn = SqliteConnection::establish(":memory:").unwrap();
466    /// conn.exclusive_transaction(|conn| {
467    ///     // Do stuff in a transaction
468    ///     Ok(())
469    /// })
470    /// # }
471    /// ```
472    pub fn exclusive_transaction<T, E, F>(&mut self, f: F) -> Result<T, E>
473    where
474        F: FnOnce(&mut Self) -> Result<T, E>,
475        E: From<Error>,
476    {
477        self.transaction_sql(f, "BEGIN EXCLUSIVE")
478    }
479
480    /// Returns the rowid of the most recent successful INSERT on this connection.
481    ///
482    /// Returns `None` if no successful INSERT into a rowid table has been performed
483    /// on this connection, and `Some(rowid)` otherwise.
484    ///
485    /// See [the SQLite documentation](https://www.sqlite.org/c3ref/last_insert_rowid.html)
486    /// for details.
487    ///
488    /// # Caveats
489    /// - Inserts into `WITHOUT ROWID` tables are not recorded
490    /// - Failed `INSERT` (constraint violations) do not change the value
491    /// - `INSERT OR REPLACE` always updates the value
492    /// - Within triggers, returns the rowid of the trigger's INSERT;
493    ///   reverts after the trigger completes
494    ///
495    /// # Example
496    /// ```rust
497    /// # include!("../../doctest_setup.rs");
498    /// # fn main() {
499    /// #     run_test().unwrap();
500    /// # }
501    /// # fn run_test() -> QueryResult<()> {
502    /// use core::num::NonZeroI64;
503    /// use diesel::connection::SimpleConnection;
504    /// let conn = &mut SqliteConnection::establish(":memory:").unwrap();
505    /// conn.batch_execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")?;
506    /// conn.batch_execute("INSERT INTO users (name) VALUES ('Sean')")?;
507    /// let rowid = conn.last_insert_rowid();
508    /// assert_eq!(rowid, NonZeroI64::new(1));
509    /// conn.batch_execute("INSERT INTO users (name) VALUES ('Tess')")?;
510    /// let rowid = conn.last_insert_rowid();
511    /// assert_eq!(rowid, NonZeroI64::new(2));
512    /// # Ok(())
513    /// # }
514    /// ```
515    pub fn last_insert_rowid(&self) -> Option<NonZeroI64> {
516        NonZeroI64::new(self.raw_connection.last_insert_rowid())
517    }
518
519    fn transaction_sql<T, E, F>(&mut self, f: F, sql: &str) -> Result<T, E>
520    where
521        F: FnOnce(&mut Self) -> Result<T, E>,
522        E: From<Error>,
523    {
524        AnsiTransactionManager::begin_transaction_sql(&mut *self, sql)?;
525        match f(&mut *self) {
526            Ok(value) => {
527                AnsiTransactionManager::commit_transaction(&mut *self)?;
528                Ok(value)
529            }
530            Err(e) => {
531                AnsiTransactionManager::rollback_transaction(&mut *self)?;
532                Err(e)
533            }
534        }
535    }
536
537    fn prepared_query<'conn, 'query, T>(
538        &'conn mut self,
539        source: T,
540    ) -> QueryResult<StatementUse<'conn, 'query>>
541    where
542        T: QueryFragment<Sqlite> + QueryId + 'query,
543    {
544        self.instrumentation
545            .on_connection_event(InstrumentationEvent::StartQuery {
546                query: &crate::debug_query(&source),
547            });
548        let raw_connection = &self.raw_connection;
549        let cache = &mut self.statement_cache;
550        let statement = match cache.cached_statement(
551            &source,
552            &Sqlite,
553            &[],
554            raw_connection,
555            Statement::prepare,
556            &mut *self.instrumentation,
557        ) {
558            Ok(statement) => statement,
559            Err(e) => {
560                self.instrumentation
561                    .on_connection_event(InstrumentationEvent::FinishQuery {
562                        query: &crate::debug_query(&source),
563                        error: Some(&e),
564                    });
565
566                return Err(e);
567            }
568        };
569
570        StatementUse::bind(statement, source, &mut *self.instrumentation)
571    }
572
573    /// Serialize the current SQLite database into a byte buffer.
574    ///
575    /// The serialized data is identical to the data that would be written to disk if the database
576    /// was saved in a file.
577    ///
578    /// # Returns
579    ///
580    /// This function returns a [`SerializedDatabase`] wrapping the serialized
581    /// bytes. If SQLite fails to allocate the buffer holding them, the failure
582    /// is reported by [`SerializedDatabase::try_as_slice`].
583    pub fn serialize_database_to_buffer(&mut self) -> SerializedDatabase {
584        self.raw_connection.serialize()
585    }
586
587    /// Deserialize an SQLite database from a byte buffer.
588    ///
589    /// This function takes a byte slice and attempts to deserialize it into a SQLite database.
590    /// If successful, the database is loaded into the connection. If the deserialization fails,
591    /// an error is returned.
592    ///
593    /// The database is opened in READONLY mode.
594    ///
595    /// # Example
596    ///
597    /// ```no_run
598    /// # use diesel::sqlite::SerializedDatabase;
599    /// # use diesel::sqlite::SqliteConnection;
600    /// # use diesel::result::QueryResult;
601    /// # use diesel::sql_query;
602    /// # use diesel::Connection;
603    /// # use diesel::RunQueryDsl;
604    /// # fn main() {
605    /// let connection = &mut SqliteConnection::establish(":memory:").unwrap();
606    ///
607    /// sql_query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)")
608    ///     .execute(connection).unwrap();
609    /// sql_query("INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com'), ('Jane Doe', 'jane.doe@example.com')")
610    ///     .execute(connection).unwrap();
611    ///
612    /// // Serialize the database to a byte vector
613    /// let serialized_db: SerializedDatabase = connection.serialize_database_to_buffer();
614    ///
615    /// // Create a new in-memory SQLite database
616    /// let connection = &mut SqliteConnection::establish(":memory:").unwrap();
617    ///
618    /// // Deserialize the byte vector into the new database
619    /// connection.deserialize_readonly_database_from_buffer(serialized_db.try_as_slice().unwrap()).unwrap();
620    /// #
621    /// # }
622    /// ```
623    // TODO: Diesel 3.0 This signature needs to change, we want to expose more options (schema name, readonly)
624    // and also ensure that this is not as unsafe as the current construct anymore. Maybe just accept a owned buffer or static pointer
625    // only instead? (So `Cow<'static, [u8]>`?)
626    #[allow(unsafe_code)]
627    pub fn deserialize_readonly_database_from_buffer(&mut self, data: &[u8]) -> QueryResult<()> {
628        self.raw_connection.deserialize(data)
629    }
630
631    /// Provides temporary access to the raw SQLite database connection handle.
632    ///
633    /// This method provides a way to access the underlying `sqlite3` pointer,
634    /// enabling direct use of the SQLite C API for advanced features that
635    /// Diesel does not wrap, such as the [session extension](https://www.sqlite.org/sessionintro.html),
636    /// [hooks](https://www.sqlite.org/c3ref/update_hook.html), or other advanced APIs.
637    ///
638    /// # Why Diesel Doesn't Wrap These APIs
639    ///
640    /// Certain SQLite features, such as the session extension, are **optional** and only
641    /// available when SQLite is compiled with specific flags (e.g., `-DSQLITE_ENABLE_SESSION`
642    /// and `-DSQLITE_ENABLE_PREUPDATE_HOOK` for sessions). These compile-time options determine
643    /// whether the corresponding C API functions exist in the SQLite library's ABI.
644    ///
645    /// Because Diesel must work with any SQLite library at runtime—including system-provided
646    /// libraries that may lack these optional features—it **cannot safely provide wrappers**
647    /// for APIs that may or may not exist. Doing so would either:
648    ///
649    /// - Cause **linker errors** at compile time if the user's `libsqlite3-sys` wasn't compiled
650    ///   with the required flags, or
651    /// - Cause **undefined behavior** at runtime if Diesel called functions that don't exist
652    ///   in the linked library.
653    ///
654    /// While feature gates could theoretically solve this problem, Diesel already has an
655    /// extensive API surface with many existing feature combinations. Each new feature gate
656    /// adds a **combinatorial explosion** of test configurations that must be validated,
657    /// making the library increasingly difficult to maintain. Therefore, exposing the raw
658    /// connection is the preferred approach for niche SQLite features.
659    ///
660    /// By exposing the raw connection handle, Diesel allows users who **know** they have
661    /// access to a properly configured SQLite build to use these advanced features directly
662    /// through their own FFI bindings.
663    ///
664    /// # Safety
665    ///
666    /// This method is marked `unsafe` because improper use of the raw connection handle
667    /// can lead to undefined behavior. The caller must ensure that:
668    ///
669    /// - The connection handle is **not closed** during the callback.
670    /// - The connection handle is **not stored** beyond the callback's scope.
671    /// - Concurrent access rules are respected (SQLite connections are not thread-safe
672    ///   unless using serialized threading mode).
673    /// - **Transaction state is not modified** — do not execute `BEGIN`, `COMMIT`,
674    ///   `ROLLBACK`, or `SAVEPOINT` statements via the raw handle. Diesel's
675    ///   [`AnsiTransactionManager`] tracks transaction nesting internally, and
676    ///   bypassing it will cause Diesel's view of the transaction state to diverge
677    ///   from SQLite's actual state.
678    /// - **Diesel's prepared statements are not disturbed** — do not call
679    ///   `sqlite3_finalize()` or `sqlite3_reset()` on statements that belong to
680    ///   Diesel's `StatementCache`. Doing so will cause use-after-free or
681    ///   double-free when Diesel later accesses those statements.
682    ///
683    /// [`AnsiTransactionManager`]: crate::connection::AnsiTransactionManager
684    ///
685    /// # Example
686    ///
687    /// ```rust
688    /// use diesel::sqlite::SqliteConnection;
689    /// use diesel::Connection;
690    ///
691    /// let mut conn = SqliteConnection::establish(":memory:").unwrap();
692    ///
693    /// // SAFETY: We do not close or store the connection handle,
694    /// // and we do not modify Diesel-managed state (transactions, cached statements).
695    /// let is_valid = unsafe {
696    ///     conn.with_raw_connection(|raw_conn| {
697    ///         // The raw connection pointer can be passed to SQLite C API functions
698    ///         // from your own `libsqlite3-sys` (native) or `sqlite-wasm-rs` (WASM)
699    ///         // dependency — for example, `sqlite3_get_autocommit(raw_conn)` or
700    ///         // `sqlite3session_create(raw_conn, ...)`.
701    ///         !raw_conn.is_null()
702    ///     })
703    /// };
704    /// assert!(is_valid);
705    /// ```
706    ///
707    /// # Platform Notes
708    ///
709    /// This method works identically on both native and WASM targets. However,
710    /// you must depend on the appropriate FFI crate for your target:
711    ///
712    /// - **Native**: Add `libsqlite3-sys` as a dependency
713    /// - **WASM** (`wasm32-unknown-unknown`): Add `sqlite-wasm-rs` as a dependency
714    ///
715    /// Both crates expose a compatible `sqlite3` type that can be used with the
716    /// pointer returned by this method.
717    #[allow(unsafe_code)]
718    pub unsafe fn with_raw_connection<R, F>(&mut self, f: F) -> R
719    where
720        F: FnOnce(*mut ffi::sqlite3) -> R,
721    {
722        f(self.raw_connection.internal_connection.as_ptr())
723    }
724
725    /// Runs `f` with a borrowed `SqliteConnection` wrapping `db`, giving SQLite
726    /// callbacks the full connection API. Statements prepared during `f` are
727    /// finalized on return, but `db` is left open, since SQLite owns it.
728    ///
729    /// # Safety
730    ///
731    /// `db` must be a valid `sqlite3` handle that stays open for the duration
732    /// of the call.
733    #[allow(unsafe_code)]
734    pub(crate) unsafe fn with_borrowed_connection<R>(
735        db: core::ptr::NonNull<ffi::sqlite3>,
736        f: impl FnOnce(&'_ mut BorrowedSqliteConnection) -> R,
737    ) -> R {
738        let mut conn = BorrowedSqliteConnection::new(RawConnection::from_ptr(db));
739
740        let result = f(&mut conn);
741
742        unsafe {
743            // SAFETY: We don't move out the connection, we only call a function
744            // that accesses the underlying state
745
746            // The borrowed connection is discarded without committing or rolling
747            // back, so a transaction left open by `f` would leak onto the handle.
748            if !#[allow(non_exhaustive_omitted_patterns)] match AnsiTransactionManager::transaction_manager_status_mut(conn.inner_mut()).transaction_depth()
            {
            Ok(None) => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("callback must not leave an open transaction on the borrowed connection"));
    }
};assert!(
749                matches!(
750                    AnsiTransactionManager::transaction_manager_status_mut(conn.inner_mut())
751                        .transaction_depth(),
752                    Ok(None)
753                ),
754                "callback must not leave an open transaction on the borrowed connection"
755            );
756        }
757
758        result
759    }
760
761    fn register_diesel_sql_functions(&self) -> QueryResult<()> {
762        // When running under miri with a native libsqlite3 (see
763        // `-Zmiri-native-lib`), native code is not allowed to call back into
764        // Rust. Registering `diesel_manage_updated_at` hands a Rust function
765        // pointer to sqlite, whose `xDestroy` callback is invoked by native
766        // code when the connection is closed, which miri rejects. As miri is
767        // only used to run a subset of the test suite, we skip the registration
768        // entirely in that case.
769        #[cfg(miri)]
770        return Ok(());
771
772        #[cfg(not(miri))]
773        {
774            use crate::sql_types::{Integer, Text};
775
776            // This function has side effects (creates triggers), so it should not
777            // be deterministic. We use DIRECTONLY to prevent it from being called
778            // from malicious schema objects in untrusted databases.
779            self.raw_connection
780                .register_sql_function::<_, i32, Integer>(
781                    "diesel_manage_updated_at",
782                    1,
783                    crate::sqlite::SqliteFunctionBehavior::DIRECTONLY,
784                    |conn, args| {
785                        let table_name: String = functions::build_sql_function_args::<Text, _>(
786                            args,
787                            conn.internal_connection,
788                        )?;
789                        // The template wraps every use in `"`, so doubling embedded
790                        // quotes keeps the argument a single identifier.
791                        let sql = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("CREATE TRIGGER \"__diesel_manage_updated_at_{0}\"\nAFTER UPDATE ON \"{0}\"\nFOR EACH ROW WHEN\n  old.updated_at IS NULL AND\n  new.updated_at IS NULL OR\n  old.updated_at == new.updated_at\nBEGIN\n  UPDATE \"{0}\"\n  SET updated_at = CURRENT_TIMESTAMP\n  WHERE ROWID = new.ROWID;\nEND\n",
                table_name.replace('"', "\"\"")))
    })alloc::format!(
792                            include_str!("diesel_manage_updated_at.sql"),
793                            table_name = table_name.replace('"', "\"\"")
794                        );
795                        Statement::prepare(
796                            conn,
797                            &sql,
798                            crate::connection::statement_cache::PrepareForCache::No,
799                            &[],
800                        )?
801                        .run()?;
802                        Ok(0) // have to return *something*
803                    },
804                )
805        }
806    }
807
808    fn establish_inner(database_url: &str) -> Result<SqliteConnection, ConnectionError> {
809        use crate::result::ConnectionError::CouldntSetupConfiguration;
810        let raw_connection = RawConnection::establish(database_url)?;
811        let conn = Self {
812            statement_cache: StatementCache::new(),
813            raw_connection,
814            transaction_state: AnsiTransactionManager::default(),
815            metadata_lookup: (),
816            instrumentation: DynInstrumentation::none(),
817        };
818        conn.register_diesel_sql_functions()
819            .map_err(CouldntSetupConfiguration)?;
820        // Builds with `SQLITE_ENABLE_FTS3_TOKENIZER` let SQL text pass `fts3_tokenizer()` a pointer to call, and SQLite before 3.12 has no switch.
821        let _ = conn
822            .raw_connection
823            .set_db_config_bool(ffi::SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, false);
824        Ok(conn)
825    }
826}
827
828fn error_message(err_code: libc::c_int) -> &'static str {
829    ffi::code_to_str(err_code)
830}
831
832/// Leaves a cached statement unreset after a failed step, so finalizing it fails.
833#[cfg(all(test, not(miri)))]
834#[allow(unsafe_code)]
835pub(in crate::sqlite) fn leak_failed_cursor(conn: &mut SqliteConnection) {
836    use crate::connection::SimpleConnection;
837    use crate::query_builder::{AstPass, QueryFragment, QueryId};
838
839    /// Overflows `abs` on its second row. Zero-sized, so the statement owns no heap memory.
840    struct OverflowQuery;
841
842    impl QueryId for OverflowQuery {
843        type QueryId = Self;
844        const HAS_STATIC_QUERY_ID: bool = true;
845    }
846
847    impl QueryFragment<Sqlite> for OverflowQuery {
848        fn walk_ast<'b>(&'b self, mut pass: AstPass<'_, 'b, Sqlite>) -> QueryResult<()> {
849            pass.push_sql("SELECT abs(n) FROM overflow_numbers ORDER BY id");
850            Ok(())
851        }
852    }
853
854    // `Box::new` doesn't allocate for a zero-sized query, so `mem::forget` below leaks nothing.
855    const _: () = assert!(core::mem::size_of::<OverflowQuery>() == 0);
856
857    conn.batch_execute(
858        "CREATE TEMP TABLE IF NOT EXISTS overflow_numbers (id INTEGER PRIMARY KEY, n BIGINT);
859         INSERT OR IGNORE INTO overflow_numbers VALUES (1, 1), (2, -9223372036854775808);",
860    )
861    .unwrap();
862    let mut stmt = conn.prepared_query(OverflowQuery).unwrap();
863    // SAFETY: `first_step = true` clears the cached column names, so no stale pointer survives.
864    let first = unsafe { stmt.step(true) };
865    assert!(matches!(first, Ok(true)));
866    // A failed first step resets the statement, so the overflow is on the second row.
867    // SAFETY: `first_step = true` clears the cached column names, so no stale pointer survives.
868    let second = unsafe { stmt.step(true) };
869    assert!(second.is_err());
870    // The query is cached (static query id) and binds nothing, so skipping the drop only
871    // skips the reset: the cache keeps the failed statement and no memory is leaked.
872    core::mem::forget(stmt);
873}
874
875#[cfg(test)]
876mod tests {
877    use super::*;
878    use crate::dsl::sql;
879    use crate::prelude::*;
880    use crate::sql_types::{Integer, Text};
881    #[cfg(not(miri))]
882    use crate::test_helpers::format_error;
883
884    fn connection() -> SqliteConnection {
885        SqliteConnection::establish(":memory:").unwrap()
886    }
887
888    #[diesel_test_helper::test]
889    #[allow(unsafe_code)]
890    fn with_raw_connection_can_return_values() {
891        let connection = &mut connection();
892
893        // SAFETY: We only read connection status, which doesn't modify state.
894        let autocommit_status = unsafe {
895            connection.with_raw_connection(|raw_conn| ffi::sqlite3_get_autocommit(raw_conn))
896        };
897
898        // Outside a transaction, autocommit should be enabled (returns non-zero)
899        assert_ne!(autocommit_status, 0, "Expected autocommit to be enabled");
900    }
901
902    #[diesel_test_helper::test]
903    #[allow(unsafe_code)]
904    fn with_raw_connection_works_after_diesel_operations() {
905        let connection = &mut connection();
906
907        // First, do some Diesel operations
908        crate::sql_query("CREATE TABLE test_table (id INTEGER PRIMARY KEY, value TEXT)")
909            .execute(connection)
910            .unwrap();
911        crate::sql_query("INSERT INTO test_table (value) VALUES ('hello')")
912            .execute(connection)
913            .unwrap();
914
915        // SAFETY: We only read the last insert rowid, which is a read-only operation.
916        let last_rowid = unsafe {
917            connection.with_raw_connection(|raw_conn| ffi::sqlite3_last_insert_rowid(raw_conn))
918        };
919
920        assert_eq!(last_rowid, 1, "Last insert rowid should be 1");
921
922        // Verify Diesel still works after using raw connection
923        let count: i64 = sql::<crate::sql_types::BigInt>("SELECT COUNT(*) FROM test_table")
924            .get_result(connection)
925            .unwrap();
926        assert_eq!(count, 1);
927    }
928
929    #[diesel_test_helper::test]
930    // Registers a callback that is invoked by the native library, or reads memory
931    // allocated by it, which is not supported when running under miri with a native
932    // libsqlite3 (`-Zmiri-native-lib`).
933    #[cfg(not(miri))] // ffi call
934    #[allow(unsafe_code)]
935    fn with_raw_connection_can_execute_raw_sql() {
936        let connection = &mut connection();
937
938        // Create a table using Diesel first
939        crate::sql_query("CREATE TABLE raw_test (id INTEGER PRIMARY KEY, name TEXT)")
940            .execute(connection)
941            .unwrap();
942
943        // SAFETY: We execute a simple INSERT via raw SQLite API.
944        // This modifies the database but in a way compatible with Diesel.
945        let result = unsafe {
946            connection.with_raw_connection(|raw_conn| {
947                let sql = c"INSERT INTO raw_test (name) VALUES ('from_raw')";
948                let mut err_msg: *mut libc::c_char = core::ptr::null_mut();
949                let rc = ffi::sqlite3_exec(
950                    raw_conn,
951                    sql.as_ptr(),
952                    None,
953                    core::ptr::null_mut(),
954                    &mut err_msg,
955                );
956                if rc != ffi::SQLITE_OK && !err_msg.is_null() {
957                    ffi::sqlite3_free(err_msg as *mut libc::c_void);
958                }
959                rc
960            })
961        };
962
963        assert_eq!(result, ffi::SQLITE_OK, "Raw SQL execution should succeed");
964
965        // Verify the insert worked using Diesel
966        let count: i64 = sql::<crate::sql_types::BigInt>("SELECT COUNT(*) FROM raw_test")
967            .get_result(connection)
968            .unwrap();
969        assert_eq!(count, 1);
970
971        let name: String = sql::<Text>("SELECT name FROM raw_test WHERE id = 1")
972            .get_result(connection)
973            .unwrap();
974        assert_eq!(name, "from_raw");
975    }
976
977    #[diesel_test_helper::test]
978    #[allow(unsafe_code)]
979    fn with_raw_connection_works_within_transaction() {
980        let connection = &mut connection();
981
982        crate::sql_query("CREATE TABLE txn_test (id INTEGER PRIMARY KEY, value INTEGER)")
983            .execute(connection)
984            .unwrap();
985
986        connection
987            .transaction::<_, crate::result::Error, _>(|conn| {
988                crate::sql_query("INSERT INTO txn_test (value) VALUES (42)")
989                    .execute(conn)
990                    .unwrap();
991
992                // SAFETY: We only read the autocommit status inside a transaction.
993                let autocommit = unsafe {
994                    conn.with_raw_connection(|raw_conn| ffi::sqlite3_get_autocommit(raw_conn))
995                };
996
997                // Inside a transaction, autocommit should be disabled (returns 0)
998                assert_eq!(
999                    autocommit, 0,
1000                    "Autocommit should be disabled inside transaction"
1001                );
1002
1003                Ok(())
1004            })
1005            .unwrap();
1006
1007        // After transaction commits, autocommit should be re-enabled
1008        let autocommit = unsafe {
1009            connection.with_raw_connection(|raw_conn| ffi::sqlite3_get_autocommit(raw_conn))
1010        };
1011        assert_ne!(
1012            autocommit, 0,
1013            "Autocommit should be enabled after transaction"
1014        );
1015    }
1016
1017    #[diesel_test_helper::test]
1018    // Registers a callback that is invoked by the native library, or reads memory
1019    // allocated by it, which is not supported when running under miri with a native
1020    // libsqlite3 (`-Zmiri-native-lib`).
1021    #[cfg(not(miri))] // ffi call
1022    #[allow(unsafe_code)]
1023    fn with_raw_connection_can_read_database_filename() {
1024        let connection = &mut connection();
1025
1026        // SAFETY: We only read the database filename, which is a read-only operation.
1027        let filename = unsafe {
1028            connection.with_raw_connection(|raw_conn| {
1029                let db_name = c"main";
1030                let filename_ptr = ffi::sqlite3_db_filename(raw_conn, db_name.as_ptr());
1031                if filename_ptr.is_null() {
1032                    None
1033                } else {
1034                    // For :memory: databases, this might return empty string or special value
1035                    let cstr = core::ffi::CStr::from_ptr(filename_ptr);
1036                    Some(cstr.to_string_lossy().into_owned())
1037                }
1038            })
1039        };
1040
1041        // For in-memory databases, sqlite3_db_filename returns a non-null pointer
1042        // to an empty string
1043        assert_eq!(
1044            filename,
1045            Some(String::new()),
1046            "In-memory database filename should be an empty string"
1047        );
1048    }
1049
1050    #[diesel_test_helper::test]
1051    #[allow(unsafe_code)]
1052    fn with_raw_connection_changes_count() {
1053        let connection = &mut connection();
1054
1055        crate::sql_query("CREATE TABLE changes_test (id INTEGER PRIMARY KEY, value INTEGER)")
1056            .execute(connection)
1057            .unwrap();
1058
1059        crate::sql_query("INSERT INTO changes_test (value) VALUES (1), (2), (3)")
1060            .execute(connection)
1061            .unwrap();
1062
1063        // Update all rows using raw connection
1064        let changes = unsafe {
1065            connection.with_raw_connection(|raw_conn| {
1066                let sql = c"UPDATE changes_test SET value = value + 10";
1067                let mut err_msg: *mut libc::c_char = core::ptr::null_mut();
1068                let rc = ffi::sqlite3_exec(
1069                    raw_conn,
1070                    sql.as_ptr(),
1071                    None,
1072                    core::ptr::null_mut(),
1073                    &mut err_msg,
1074                );
1075                if rc != ffi::SQLITE_OK && !err_msg.is_null() {
1076                    ffi::sqlite3_free(err_msg as *mut libc::c_void);
1077                    return -1;
1078                }
1079                ffi::sqlite3_changes(raw_conn)
1080            })
1081        };
1082
1083        assert_eq!(changes, 3, "Should have updated 3 rows");
1084
1085        // Verify the updates using Diesel
1086        let values: Vec<i32> = sql::<Integer>("SELECT value FROM changes_test ORDER BY id")
1087            .load(connection)
1088            .unwrap();
1089        assert_eq!(values, vec![11, 12, 13]);
1090    }
1091
1092    // catch_unwind is not available in WASM (panic = "abort")
1093    #[diesel_test_helper::test]
1094    #[allow(unsafe_code)]
1095    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
1096    fn with_raw_connection_recovers_after_panic() {
1097        let connection = &mut connection();
1098
1099        crate::sql_query("CREATE TABLE panic_test (id INTEGER PRIMARY KEY, value TEXT)")
1100            .execute(connection)
1101            .unwrap();
1102
1103        // Panic inside the callback
1104        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe {
1105            connection.with_raw_connection(|_raw_conn| {
1106                panic!("intentional panic inside with_raw_connection");
1107            })
1108        }));
1109        assert!(result.is_err(), "Should have caught the panic");
1110
1111        // Connection should still be usable after the panic
1112        crate::sql_query("INSERT INTO panic_test (value) VALUES ('after_panic')")
1113            .execute(connection)
1114            .unwrap();
1115
1116        let count: i64 = sql::<crate::sql_types::BigInt>("SELECT COUNT(*) FROM panic_test")
1117            .get_result(connection)
1118            .unwrap();
1119        assert_eq!(count, 1, "Connection should work after panic in callback");
1120    }
1121
1122    // Filesystem access is not available in WASM
1123    #[diesel_test_helper::test]
1124    #[allow(unsafe_code)]
1125    // Registers a callback that is invoked by the native library, or reads memory
1126    // allocated by it, which is not supported when running under miri with a native
1127    // libsqlite3 (`-Zmiri-native-lib`).
1128    #[cfg(not(miri))] // ffi call
1129    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
1130    fn with_raw_connection_can_read_file_database_filename() {
1131        let dir = std::env::temp_dir().join("diesel_test_filename.db");
1132        let db_path = dir.to_str().unwrap();
1133
1134        // Clean up from any previous run
1135        let _ = std::fs::remove_file(db_path);
1136
1137        let connection = &mut SqliteConnection::establish(db_path).unwrap();
1138
1139        // SAFETY: We only read the database filename, which is a read-only operation.
1140        let filename = unsafe {
1141            connection.with_raw_connection(|raw_conn| {
1142                let db_name = c"main";
1143                let filename_ptr = ffi::sqlite3_db_filename(raw_conn, db_name.as_ptr());
1144                if filename_ptr.is_null() {
1145                    None
1146                } else {
1147                    let cstr = core::ffi::CStr::from_ptr(filename_ptr);
1148                    Some(cstr.to_string_lossy().into_owned())
1149                }
1150            })
1151        };
1152
1153        let filename = filename.expect("File-based database should have a filename");
1154        assert!(
1155            filename.contains("diesel_test_filename.db"),
1156            "Filename should contain the database name, got: {filename}"
1157        );
1158
1159        // Clean up
1160        let _ = std::fs::remove_file(db_path);
1161    }
1162
1163    // Registers a callback that is invoked by the native library, or reads memory
1164    // allocated by it, which is not supported when running under miri with a native
1165    // libsqlite3 (`-Zmiri-native-lib`).
1166    #[cfg(not(miri))] // ffi call
1167    #[diesel_test_helper::test]
1168    fn database_serializes_and_deserializes_successfully() {
1169        let expected_users = vec![
1170            (
1171                1,
1172                "John Doe".to_string(),
1173                "john.doe@example.com".to_string(),
1174            ),
1175            (
1176                2,
1177                "Jane Doe".to_string(),
1178                "jane.doe@example.com".to_string(),
1179            ),
1180        ];
1181
1182        let conn1 = &mut connection();
1183        let _ =
1184            crate::sql_query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)")
1185                .execute(conn1);
1186        let _ = crate::sql_query("INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com'), ('Jane Doe', 'jane.doe@example.com')")
1187            .execute(conn1);
1188
1189        for _i in 0..2 {
1190            let serialized_database = conn1.serialize_database_to_buffer();
1191            let conn2 = &mut connection();
1192            conn2
1193                .deserialize_readonly_database_from_buffer(
1194                    serialized_database.try_as_slice().unwrap(),
1195                )
1196                .unwrap();
1197
1198            let query =
1199                sql::<(Integer, Text, Text)>("SELECT id, name, email FROM users ORDER BY id");
1200            let actual_users = query.load::<(i32, String, String)>(conn2).unwrap();
1201
1202            assert_eq!(expected_users, actual_users);
1203            // drop the database here
1204            // and requery the database to make sure the database owns
1205            // required data
1206            std::mem::drop(serialized_database);
1207            let query =
1208                sql::<(Integer, Text, Text)>("SELECT id, name, email FROM users ORDER BY id");
1209            let actual_users = query.load::<(i32, String, String)>(conn2).unwrap();
1210
1211            assert_eq!(expected_users, actual_users);
1212        }
1213    }
1214
1215    // Registers a callback that is invoked by the native library, or reads memory
1216    // allocated by it, which is not supported when running under miri with a native
1217    // libsqlite3 (`-Zmiri-native-lib`).
1218    #[cfg(not(miri))] // ffi call
1219    #[diesel_test_helper::test]
1220    fn database_deserialize_random_bytes() {
1221        let buffer = vec![0, 1, 2, 3, 4];
1222        let conn = &mut SqliteConnection::establish(":memory:").unwrap();
1223
1224        conn.deserialize_readonly_database_from_buffer(&buffer)
1225            .unwrap();
1226
1227        let r = sql::<Integer>("SELECT id FROM users").load::<i32>(conn);
1228
1229        assert!(r.is_err());
1230        assert_eq!(format_error(&r.unwrap_err()), "file is not a database");
1231
1232        let conn = &mut SqliteConnection::establish(":memory:").unwrap();
1233
1234        let _ =
1235            crate::sql_query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)")
1236                .execute(conn);
1237        let _ = crate::sql_query("INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com'), ('Jane Doe', 'jane.doe@example.com')")
1238            .execute(conn);
1239
1240        let db = conn.serialize_database_to_buffer();
1241        // only get a valid header, but append garbage
1242        let mut bad_buffer = db[..100].to_vec();
1243        bad_buffer.extend(b"whatever");
1244        conn.deserialize_readonly_database_from_buffer(&bad_buffer)
1245            .unwrap();
1246
1247        let r = sql::<Integer>("SELECT id FROM users").load::<i32>(conn);
1248
1249        assert!(r.is_err());
1250        assert_eq!(
1251            format_error(&r.unwrap_err()),
1252            "database disk image is malformed"
1253        );
1254
1255        // only get a valid header, but append garbage
1256        let mut size_fitting_bad_buffer = db[..100].to_vec();
1257        size_fitting_bad_buffer.extend(
1258            core::iter::repeat(b"abcdefghij")
1259                .flatten()
1260                .take(db.len() - 100),
1261        );
1262        let r = conn.deserialize_readonly_database_from_buffer(&size_fitting_bad_buffer);
1263
1264        assert!(r.is_err());
1265        assert_eq!(
1266            format_error(&r.unwrap_err()),
1267            "database disk image is malformed"
1268        );
1269    }
1270
1271    #[diesel_test_helper::test]
1272    fn database_serializes_empty_deserialized_database() {
1273        let conn = &mut SqliteConnection::establish(":memory:").unwrap();
1274        conn.deserialize_readonly_database_from_buffer(&[]).unwrap();
1275
1276        let serialized = conn.serialize_database_to_buffer();
1277
1278        assert!(serialized.is_empty());
1279        assert!(serialized.try_as_slice().unwrap().is_empty());
1280    }
1281
1282    #[cfg(all(
1283        feature = "std",
1284        not(all(target_family = "wasm", target_os = "unknown")),
1285        // These tests read memory allocated by the native library or rely on
1286        // native code invoking a panic hook, neither of which is supported when
1287        // running under miri with a native libsqlite3 (`-Zmiri-native-lib`).
1288        not(miri)
1289    ))]
1290    #[allow(unsafe_code)]
1291    mod sqlite_serialize_oom {
1292        use super::super::oom_test_support::{panic_message, run_in_child, with_heap_limit};
1293        use super::super::{SerializedDatabase, ffi};
1294        use crate::connection::{Connection, SimpleConnection};
1295        use crate::sqlite::SqliteConnection;
1296        use crate::test_helpers::format_error;
1297
1298        const MIN_DATABASE_BYTES: i64 = 1_048_576;
1299
1300        // 64 KiB covers statement setup but cannot hold the 1 MiB serialization,
1301        // pinning the failure to output allocation after SQLite reports its size.
1302        fn with_failing_serialize<R>(f: impl FnOnce() -> R) -> R {
1303            with_heap_limit(65_536, f)
1304        }
1305
1306        #[test]
1307        fn sqlite_serialize_oom_is_contained() {
1308            run_in_child(|| {
1309                let mut conn = large_database();
1310
1311                let (baseline_size, baseline) = serialize_direct(&conn);
1312                assert!(
1313                    baseline_size >= MIN_DATABASE_BYTES,
1314                    "the serialized database is smaller than 1 MiB"
1315                );
1316                assert!(
1317                    !baseline.is_null(),
1318                    "SQLite refused to serialize a valid database"
1319                );
1320                // SAFETY: `sqlite3_serialize` returned this buffer and no wrapper owns it.
1321                unsafe { ffi::sqlite3_free(baseline as _) };
1322
1323                let (reported_size, data) = with_failing_serialize(|| serialize_direct(&conn));
1324                if !data.is_null() {
1325                    // SAFETY: `sqlite3_serialize` returned this buffer and no wrapper owns it.
1326                    unsafe { ffi::sqlite3_free(data as _) };
1327                }
1328                assert!(
1329                    data.is_null(),
1330                    "SQLite did not fail the output allocation of the serialization"
1331                );
1332                // SQLite reports the required size before attempting output allocation.
1333                assert!(
1334                    reported_size >= MIN_DATABASE_BYTES,
1335                    "SQLite reported a serialization size of {reported_size} with a null buffer"
1336                );
1337
1338                let serialized: SerializedDatabase =
1339                    with_failing_serialize(|| conn.serialize_database_to_buffer());
1340                let error = serialized
1341                    .try_as_slice()
1342                    .expect_err("the failed output allocation must surface as an error");
1343                assert_eq!(format_error(&error), "out of memory");
1344
1345                let payload = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
1346                    core::hint::black_box(serialized[0]);
1347                }))
1348                .expect_err("the serialized database access did not panic");
1349                let message = panic_message(&*payload);
1350                assert!(
1351                    message.contains("Cannot access the serialized database: out of memory"),
1352                    "SQLite serialization allocation failure surfaced as `{message}` instead \
1353                     of a caught allocation panic"
1354                );
1355            });
1356        }
1357
1358        fn large_database() -> SqliteConnection {
1359            let mut conn = SqliteConnection::establish(":memory:").unwrap();
1360            conn.batch_execute(&format!(
1361                "CREATE TABLE blobs (id INTEGER PRIMARY KEY, payload BLOB);
1362                 INSERT INTO blobs (payload) VALUES (zeroblob({MIN_DATABASE_BYTES}));"
1363            ))
1364            .unwrap();
1365            conn
1366        }
1367
1368        fn serialize_direct(conn: &SqliteConnection) -> (ffi::sqlite3_int64, *mut u8) {
1369            // SAFETY: The connection is live, a null schema selects `main`, and `size` is a writable out-parameter.
1370            unsafe {
1371                let mut size: ffi::sqlite3_int64 = 0;
1372                let data = ffi::sqlite3_serialize(
1373                    conn.raw_connection.internal_connection.as_ptr(),
1374                    core::ptr::null(),
1375                    &mut size as *mut _,
1376                    0,
1377                );
1378                (size, data)
1379            }
1380        }
1381    }
1382
1383    #[cfg(all(
1384        feature = "std",
1385        not(all(target_family = "wasm", target_os = "unknown")),
1386        not(miri)
1387    ))]
1388    mod diesel_manage_updated_at_errors {
1389        use super::super::oom_test_support::run_in_child;
1390        use crate::connection::{Connection, SimpleConnection};
1391        use crate::query_dsl::RunQueryDsl;
1392        use crate::sqlite::{AuthorizerContext, AuthorizerDecision, SqliteConnection};
1393        use crate::test_helpers::format_error;
1394
1395        #[track_caller]
1396        fn assert_no_panic_output(stderr: &str, table_name: &str) {
1397            assert!(
1398                !stderr.contains("panicked") && !stderr.contains(table_name),
1399                "diesel_manage_updated_at reached the panic hook\nstderr:\n{stderr}"
1400            );
1401        }
1402
1403        #[test]
1404        fn missing_table_returns_error_without_panicking() {
1405            let stderr = run_in_child(|| {
1406                let mut conn = SqliteConnection::establish(":memory:").unwrap();
1407                let error = conn
1408                    .batch_execute("SELECT diesel_manage_updated_at('synthetic_key_7c91a2')")
1409                    .unwrap_err();
1410                assert_eq!(
1411                    format_error(&error),
1412                    "no such table: main.synthetic_key_7c91a2"
1413                );
1414            });
1415            assert_no_panic_output(&stderr, "synthetic_key_7c91a2");
1416        }
1417
1418        #[test]
1419        fn denied_trigger_returns_error_without_panicking() {
1420            let stderr = run_in_child(|| {
1421                let mut conn = SqliteConnection::establish(":memory:").unwrap();
1422                conn.batch_execute("CREATE TABLE guarded_7c91a2 (id INTEGER, updated_at TEXT)")
1423                    .unwrap();
1424                conn.on_authorize(|ctx| match ctx {
1425                    AuthorizerContext::CreateTrigger(_) => AuthorizerDecision::Deny,
1426                    _ => AuthorizerDecision::Allow,
1427                });
1428                let error = conn
1429                    .batch_execute("SELECT diesel_manage_updated_at('guarded_7c91a2')")
1430                    .unwrap_err();
1431                assert_eq!(format_error(&error), "not authorized");
1432
1433                conn.remove_authorizer();
1434                let triggers: i64 = crate::dsl::sql::<crate::sql_types::BigInt>(
1435                    "SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger'",
1436                )
1437                .get_result(&mut conn)
1438                .unwrap();
1439                assert_eq!(triggers, 0);
1440            });
1441            assert_no_panic_output(&stderr, "guarded_7c91a2");
1442        }
1443
1444        #[test]
1445        fn failed_step_returns_error_without_panicking() {
1446            let stderr = run_in_child(|| {
1447                let mut conn = SqliteConnection::establish(":memory:").unwrap();
1448                conn.batch_execute(
1449                    "CREATE TABLE readonly_7c91a2 (id INTEGER, updated_at TEXT);
1450                     PRAGMA query_only = ON;",
1451                )
1452                .unwrap();
1453                let error = conn
1454                    .batch_execute("SELECT diesel_manage_updated_at('readonly_7c91a2')")
1455                    .unwrap_err();
1456                assert_eq!(format_error(&error), "attempt to write a readonly database");
1457            });
1458            assert_no_panic_output(&stderr, "readonly_7c91a2");
1459        }
1460    }
1461
1462    #[cfg(not(miri))]
1463    #[diesel_test_helper::test]
1464    fn diesel_manage_updated_at_does_not_execute_its_argument() {
1465        let connection = &mut SqliteConnection::establish(":memory:").unwrap();
1466        connection
1467            .batch_execute(
1468                "CREATE TABLE t (id INTEGER PRIMARY KEY, updated_at TEXT);
1469                 CREATE TABLE victims (id INTEGER PRIMARY KEY);",
1470            )
1471            .unwrap();
1472        let payload = "t AFTER UPDATE ON t BEGIN SELECT 1; END; DROP TABLE victims; --";
1473
1474        let result = sql::<Integer>("SELECT diesel_manage_updated_at(")
1475            .bind::<Text, _>(payload)
1476            .sql(")")
1477            .get_result::<i32>(connection);
1478
1479        let schema = sql::<Text>("SELECT group_concat(name, ',') FROM sqlite_master")
1480            .get_result::<String>(connection)
1481            .unwrap();
1482        assert_eq!(schema, "t,victims");
1483        assert_eq!(
1484            result.map_err(|e| format_error(&e)),
1485            Err(format!("no such table: main.{payload}"))
1486        );
1487    }
1488
1489    #[cfg(not(miri))]
1490    #[diesel_test_helper::test]
1491    fn diesel_manage_updated_at_quotes_the_table_name() {
1492        let connection = &mut SqliteConnection::establish(":memory:").unwrap();
1493        let names = ["users", "select", "odd \"name\"", "a b", "a_b"];
1494        for name in names {
1495            let quoted = name.replace('"', "\"\"");
1496            connection
1497                .batch_execute(&format!(
1498                    "CREATE TABLE \"{quoted}\" (id INTEGER PRIMARY KEY, updated_at TEXT);
1499                     INSERT INTO \"{quoted}\" (id) VALUES (1);"
1500                ))
1501                .unwrap();
1502            sql::<Integer>("SELECT diesel_manage_updated_at(")
1503                .bind::<Text, _>(name)
1504                .sql(")")
1505                .get_result::<i32>(connection)
1506                .unwrap();
1507            connection
1508                .batch_execute(&format!("UPDATE \"{quoted}\" SET id = 2"))
1509                .unwrap();
1510            let updated = sql::<Integer>(&format!(
1511                "SELECT COUNT(*) FROM \"{quoted}\" WHERE updated_at IS NOT NULL"
1512            ))
1513            .get_result::<i32>(connection)
1514            .unwrap();
1515            assert_eq!(updated, 1, "table {name}");
1516        }
1517
1518        let triggers =
1519            sql::<Text>("SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY rowid")
1520                .load::<String>(connection)
1521                .unwrap();
1522        let expected = names.map(|name| format!("__diesel_manage_updated_at_{name}"));
1523        assert_eq!(triggers, expected);
1524    }
1525
1526    // regression test for https://github.com/diesel-rs/diesel/issues/3425
1527    #[diesel_test_helper::test]
1528    fn test_correct_serialization_of_owned_strings() {
1529        use crate::prelude::*;
1530
1531        #[derive(Debug, crate::expression::AsExpression)]
1532        #[diesel(sql_type = diesel::sql_types::Text)]
1533        struct CustomWrapper(String);
1534
1535        impl crate::serialize::ToSql<Text, Sqlite> for CustomWrapper {
1536            fn to_sql<'b>(
1537                &'b self,
1538                out: &mut crate::serialize::Output<'b, '_, Sqlite>,
1539            ) -> crate::serialize::Result {
1540                out.set_value(self.0.to_string());
1541                Ok(crate::serialize::IsNull::No)
1542            }
1543        }
1544
1545        let connection = &mut connection();
1546
1547        let res = crate::select(
1548            CustomWrapper("".into())
1549                .into_sql::<crate::sql_types::Text>()
1550                .nullable(),
1551        )
1552        .get_result::<Option<String>>(connection)
1553        .unwrap();
1554        assert_eq!(res, Some(String::new()));
1555    }
1556
1557    #[diesel_test_helper::test]
1558    fn test_correct_serialization_of_owned_bytes() {
1559        use crate::prelude::*;
1560
1561        #[derive(Debug, crate::expression::AsExpression)]
1562        #[diesel(sql_type = diesel::sql_types::Binary)]
1563        struct CustomWrapper(Vec<u8>);
1564
1565        impl crate::serialize::ToSql<crate::sql_types::Binary, Sqlite> for CustomWrapper {
1566            fn to_sql<'b>(
1567                &'b self,
1568                out: &mut crate::serialize::Output<'b, '_, Sqlite>,
1569            ) -> crate::serialize::Result {
1570                out.set_value(self.0.clone());
1571                Ok(crate::serialize::IsNull::No)
1572            }
1573        }
1574
1575        let connection = &mut connection();
1576
1577        let res = crate::select(
1578            CustomWrapper(Vec::new())
1579                .into_sql::<crate::sql_types::Binary>()
1580                .nullable(),
1581        )
1582        .get_result::<Option<Vec<u8>>>(connection)
1583        .unwrap();
1584        assert_eq!(res, Some(Vec::new()));
1585    }
1586
1587    #[diesel_test_helper::test]
1588    fn correctly_handle_empty_query() {
1589        let check_empty_query_error = |r: crate::QueryResult<usize>| {
1590            assert!(r.is_err());
1591            let err = r.unwrap_err();
1592            assert!(
1593                matches!(err, crate::result::Error::QueryBuilderError(ref b) if b.is::<crate::result::EmptyQuery>()),
1594                "Expected a query builder error, but got {err}"
1595            );
1596        };
1597        let connection = &mut SqliteConnection::establish(":memory:").unwrap();
1598        check_empty_query_error(crate::sql_query("").execute(connection));
1599        check_empty_query_error(crate::sql_query("   ").execute(connection));
1600        check_empty_query_error(crate::sql_query("\n\t").execute(connection));
1601        check_empty_query_error(crate::sql_query("-- SELECT 1;").execute(connection));
1602    }
1603
1604    #[diesel_test_helper::test]
1605    fn last_insert_rowid_returns_none_on_fresh_connection() {
1606        let conn = &mut connection();
1607        assert_eq!(conn.last_insert_rowid(), None);
1608    }
1609
1610    #[diesel_test_helper::test]
1611    fn last_insert_rowid_returns_rowid_after_insert() {
1612        let conn = &mut connection();
1613        crate::sql_query("CREATE TABLE li_test (id INTEGER PRIMARY KEY, val TEXT NOT NULL)")
1614            .execute(conn)
1615            .unwrap();
1616
1617        crate::sql_query("INSERT INTO li_test (val) VALUES ('a')")
1618            .execute(conn)
1619            .unwrap();
1620        assert_eq!(conn.last_insert_rowid(), NonZeroI64::new(1));
1621
1622        crate::sql_query("INSERT INTO li_test (val) VALUES ('b')")
1623            .execute(conn)
1624            .unwrap();
1625        assert_eq!(conn.last_insert_rowid(), NonZeroI64::new(2));
1626    }
1627
1628    // Registers a callback that is invoked by the native library, or reads memory
1629    // allocated by it, which is not supported when running under miri with a native
1630    // libsqlite3 (`-Zmiri-native-lib`).
1631    #[cfg(not(miri))] // ffi call
1632    #[diesel_test_helper::test]
1633    fn last_insert_rowid_unchanged_after_failed_insert() {
1634        let conn = &mut connection();
1635        crate::sql_query(
1636            "CREATE TABLE li_test2 (id INTEGER PRIMARY KEY, val TEXT NOT NULL UNIQUE)",
1637        )
1638        .execute(conn)
1639        .unwrap();
1640
1641        crate::sql_query("INSERT INTO li_test2 (val) VALUES ('a')")
1642            .execute(conn)
1643            .unwrap();
1644        let rowid = conn.last_insert_rowid();
1645        assert_eq!(rowid, NonZeroI64::new(1));
1646
1647        // This should fail due to UNIQUE constraint
1648        let result = crate::sql_query("INSERT INTO li_test2 (val) VALUES ('a')").execute(conn);
1649        assert!(result.is_err());
1650
1651        // rowid should be unchanged
1652        assert_eq!(conn.last_insert_rowid(), NonZeroI64::new(1));
1653    }
1654
1655    #[diesel_test_helper::test]
1656    fn last_insert_rowid_with_explicit_rowid() {
1657        let conn = &mut connection();
1658        crate::sql_query("CREATE TABLE li_test3 (id INTEGER PRIMARY KEY, val TEXT NOT NULL)")
1659            .execute(conn)
1660            .unwrap();
1661
1662        crate::sql_query("INSERT INTO li_test3 (id, val) VALUES (42, 'a')")
1663            .execute(conn)
1664            .unwrap();
1665        assert_eq!(conn.last_insert_rowid(), NonZeroI64::new(42));
1666    }
1667
1668    #[diesel_test_helper::test]
1669    fn last_insert_rowid_unchanged_after_delete_and_update() {
1670        let conn = &mut connection();
1671        crate::sql_query("CREATE TABLE li_test4 (id INTEGER PRIMARY KEY, val TEXT NOT NULL)")
1672            .execute(conn)
1673            .unwrap();
1674
1675        crate::sql_query("INSERT INTO li_test4 (val) VALUES ('a')")
1676            .execute(conn)
1677            .unwrap();
1678        let rowid = conn.last_insert_rowid();
1679        assert_eq!(rowid, NonZeroI64::new(1));
1680
1681        crate::sql_query("UPDATE li_test4 SET val = 'b' WHERE id = 1")
1682            .execute(conn)
1683            .unwrap();
1684        assert_eq!(conn.last_insert_rowid(), NonZeroI64::new(1));
1685
1686        crate::sql_query("DELETE FROM li_test4 WHERE id = 1")
1687            .execute(conn)
1688            .unwrap();
1689        assert_eq!(conn.last_insert_rowid(), NonZeroI64::new(1));
1690    }
1691
1692    #[diesel_test_helper::test]
1693    fn test_injection() {
1694        diesel::table! {
1695            #[sql_name = "quote'table"]
1696            quote_table (id) {
1697                id -> Nullable<Integer>,
1698                name -> Nullable<Text>,
1699            }
1700        }
1701
1702        let mut conn = SqliteConnection::establish(":memory:").unwrap();
1703
1704        conn.batch_execute("CREATE TABLE \"quote'table\" (id INTEGER PRIMARY KEY, name TEXT);")
1705            .unwrap();
1706
1707        diesel::insert_into(quote_table::table)
1708            .values((quote_table::id.eq(1), quote_table::name.eq("Jane")))
1709            .execute(&mut conn)
1710            .unwrap();
1711
1712        if cfg!(not(miri)) {
1713            // string access over ffi
1714            let data = quote_table::table
1715                .load::<(Option<i32>, Option<String>)>(&mut conn)
1716                .unwrap();
1717            assert_eq!(data, [(Some(1), Some("Jane".to_owned()))]);
1718        }
1719    }
1720
1721    #[crate::declare_sql_function]
1722    extern "SQL" {
1723        fn sqlite_version() -> Text;
1724    }
1725
1726    #[diesel_test_helper::test]
1727    #[cfg(not(miri))] // string access over ffi
1728    fn version_matches_sqlite_version() {
1729        let conn = &mut connection();
1730        let reported = crate::select(sqlite_version())
1731            .get_result::<String>(conn)
1732            .unwrap();
1733        assert_eq!(conn.version().to_string(), reported);
1734    }
1735
1736    #[cfg(all(
1737        feature = "std",
1738        not(all(target_family = "wasm", target_os = "unknown")),
1739        // runs processes
1740        not(miri)
1741    ))]
1742    #[diesel_test_helper::test]
1743    fn deserialize_in_auto_extension_keeps_buffer_alive() {
1744        use super::oom_test_support::run_in_child;
1745
1746        run_in_child(|| {
1747            use std::sync::OnceLock;
1748            #[allow(unsafe_code, reason = "Test code")]
1749            fn load_image(conn: &mut BorrowedSqliteConnection) -> QueryResult<()> {
1750                // `conn` is a borrowed connection; its `serialized_data` is dropped
1751                // when this callback returns, but SQLite keeps using the buffer.
1752                unsafe {
1753                    conn.inner_mut()
1754                        .deserialize_readonly_database_from_buffer(IMAGE.get().unwrap())
1755                }
1756            }
1757
1758            static IMAGE: OnceLock<Vec<u8>> = OnceLock::new();
1759
1760            let mut src = SqliteConnection::establish(":memory:").unwrap();
1761            src.batch_execute("CREATE TABLE t(x TEXT); INSERT INTO t VALUES ('hello');")
1762                .unwrap();
1763            let image = src
1764                .serialize_database_to_buffer()
1765                .try_as_slice()
1766                .unwrap()
1767                .to_vec();
1768            IMAGE.set(image).unwrap();
1769
1770            crate::sqlite::register_auto_extension(load_image).unwrap();
1771            let mut conn = SqliteConnection::establish(":memory:").unwrap();
1772            crate::sqlite::reset_auto_extension();
1773
1774            let rows: QueryResult<Vec<String>> = sql::<Text>("SELECT x FROM t").load(&mut conn);
1775            assert_eq!(rows.unwrap(), vec!["hello".to_string()]);
1776        });
1777    }
1778}