sql_middleware/sqlite/
prepared.rs

1use std::sync::Arc;
2
3use crate::middleware::{ResultSet, RowValues, SqlMiddlewareDbError};
4
5use super::connection::SqliteConnection;
6use super::params::Params;
7
8/// Handle to a prepared `SQLite` statement tied to a connection.
9pub struct SqlitePreparedStatement<'conn> {
10    connection: &'conn mut SqliteConnection,
11    query: Arc<String>,
12}
13
14impl<'conn> SqlitePreparedStatement<'conn> {
15    pub(crate) fn new(connection: &'conn mut SqliteConnection, query: Arc<String>) -> Self {
16        Self { connection, query }
17    }
18
19    /// Execute the prepared statement as a query and materialise the rows into a [`ResultSet`].
20    ///
21    /// # Errors
22    /// Returns [`SqlMiddlewareDbError`] if execution fails or result conversion encounters an issue.
23    pub async fn query(&mut self, params: &[RowValues]) -> Result<ResultSet, SqlMiddlewareDbError> {
24        let params_owned = Params::convert(params)?.0;
25        self.connection
26            .execute_select(
27                self.query.as_ref(),
28                &params_owned,
29                super::query::build_result_set,
30            )
31            .await
32    }
33
34    /// Execute the prepared statement as a DML (INSERT/UPDATE/DELETE) returning rows affected.
35    ///
36    /// # Errors
37    /// Returns [`SqlMiddlewareDbError`] if execution fails or if the result cannot be converted into the expected row count.
38    pub async fn execute(&mut self, params: &[RowValues]) -> Result<usize, SqlMiddlewareDbError> {
39        let params_owned = Params::convert(params)?.0;
40        self.connection
41            .execute_dml(self.query.as_ref(), &params_owned)
42            .await
43    }
44
45    /// Access the raw SQL string of the prepared statement.
46    #[must_use]
47    pub fn sql(&self) -> &str {
48        self.query.as_str()
49    }
50}