Skip to main content

sql_middleware/sqlite/
prepared.rs

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