sql_middleware/sqlite/connection/
prepared.rs

1use crate::middleware::SqlMiddlewareDbError;
2
3use super::{SqliteConnection, run_blocking};
4
5impl SqliteConnection {
6    /// Prepare a statement for repeated execution (auto-commit mode only).
7    ///
8    /// # Errors
9    /// Returns `SqlMiddlewareDbError` if preparing the statement fails or a transaction is active.
10    pub async fn prepare_statement(
11        &mut self,
12        query: &str,
13    ) -> Result<crate::sqlite::prepared::SqlitePreparedStatement<'_>, SqlMiddlewareDbError> {
14        if self.in_transaction {
15            return Err(SqlMiddlewareDbError::ExecutionError(
16                "SQLite transaction in progress; operation not permitted (prepare statement)"
17                    .into(),
18            ));
19        }
20        let query_arc = std::sync::Arc::new(query.to_owned());
21        // warm the cache so repeated executions don't re-prepare.
22        let query_clone = std::sync::Arc::clone(&query_arc);
23        run_blocking(self.conn_handle(), move |guard| {
24            let _ = guard
25                .prepare_cached(query_clone.as_ref())
26                .map_err(SqlMiddlewareDbError::SqliteError)?;
27            Ok(())
28        })
29        .await?;
30        Ok(crate::sqlite::prepared::SqlitePreparedStatement::new(
31            self, query_arc,
32        ))
33    }
34}