sql_middleware/sqlite/
prepared.rs

1use std::sync::Arc;
2
3use crate::middleware::{ResultSet, RowValues, SqlMiddlewareDbError};
4
5use super::params::convert_params;
6use super::worker::SqliteConnection;
7
8/// Handle to a prepared `SQLite` statement owned by a worker connection.
9///
10/// Instances can be cloned and reused across awaited calls. Dropping the handle
11/// simply releases the reference; the underlying connection will keep the
12/// statement cached via `rusqlite`'s internal `prepare_cached` mechanism.
13#[derive(Clone, Debug)]
14pub struct SqlitePreparedStatement {
15    connection: SqliteConnection,
16    query: Arc<String>,
17}
18
19impl SqlitePreparedStatement {
20    pub(crate) fn new(connection: SqliteConnection, query: Arc<String>) -> Self {
21        Self { connection, query }
22    }
23
24    /// Execute the prepared statement as a query and materialise the rows into a [`ResultSet`].
25    ///
26    /// # Errors
27    /// Returns [`SqlMiddlewareDbError`] if the underlying worker fails to execute the statement or
28    /// if result conversion encounters an issue.
29    pub async fn query(&self, params: &[RowValues]) -> Result<ResultSet, SqlMiddlewareDbError> {
30        let params_owned = convert_params(params);
31        self.connection
32            .execute_prepared_select(Arc::clone(&self.query), params_owned)
33            .await
34    }
35
36    /// Execute the prepared statement as a DML (INSERT/UPDATE/DELETE) returning rows affected.
37    ///
38    /// # Errors
39    /// Returns [`SqlMiddlewareDbError`] if the worker cannot execute the statement or if the result
40    /// cannot be converted into the expected row count.
41    pub async fn execute(&self, params: &[RowValues]) -> Result<usize, SqlMiddlewareDbError> {
42        let params_owned = convert_params(params);
43        self.connection
44            .execute_prepared_dml(Arc::clone(&self.query), params_owned)
45            .await
46    }
47
48    /// Access the raw SQL string of the prepared statement.
49    #[must_use]
50    pub fn sql(&self) -> &str {
51        self.query.as_str()
52    }
53}