Skip to main content

sql_middleware/executor/
connection.rs

1use crate::error::SqlMiddlewareDbError;
2use crate::pool::MiddlewarePoolConnection;
3use crate::query_builder::QueryBuilder;
4
5#[cfg(feature = "mssql")]
6use crate::mssql;
7#[cfg(feature = "postgres")]
8use crate::postgres;
9#[cfg(feature = "sqlite")]
10use crate::sqlite;
11#[cfg(feature = "turso")]
12use crate::turso;
13
14impl MiddlewarePoolConnection {
15    /// Executes a batch of SQL queries within a transaction by delegating to the specific database module.
16    ///
17    /// # Errors
18    /// Returns an error if the selected backend cannot execute the batch or the database responds with an error.
19    pub async fn execute_batch(&mut self, query: &str) -> Result<(), SqlMiddlewareDbError> {
20        match self {
21            #[cfg(feature = "postgres")]
22            MiddlewarePoolConnection::Postgres {
23                client: pg_client, ..
24            } => postgres::execute_batch(pg_client, query).await,
25            #[cfg(feature = "sqlite")]
26            MiddlewarePoolConnection::Sqlite { .. } => {
27                let sqlite_client = self.sqlite_conn_mut()?;
28                sqlite::execute_batch(sqlite_client, query).await
29            }
30            #[cfg(feature = "mssql")]
31            MiddlewarePoolConnection::Mssql {
32                conn: mssql_client, ..
33            } => mssql::execute_batch(mssql_client, query).await,
34            #[cfg(feature = "turso")]
35            MiddlewarePoolConnection::Turso {
36                conn: turso_conn, ..
37            } => turso::execute_batch(turso_conn, query).await,
38            #[allow(unreachable_patterns)]
39            _ => Err(SqlMiddlewareDbError::Unimplemented(
40                "This database type is not enabled in the current build".to_string(),
41            )),
42        }
43    }
44
45    /// Start a fluent query builder that can translate placeholders before executing.
46    ///
47    /// # Examples
48    /// ```rust,no_run
49    /// use sql_middleware::prelude::*;
50    ///
51    /// # async fn demo() -> Result<(), SqlMiddlewareDbError> {
52    /// let cap = ConfigAndPool::new_sqlite("file::memory:?cache=shared".into()).await?;
53    /// let mut conn = cap.get_connection().await?;
54    /// conn.execute_batch("CREATE TABLE t (id INTEGER)").await?;
55    ///
56    /// let rows = conn
57    ///     .query("SELECT id FROM t WHERE id = ?1")
58    ///     .params(&[RowValues::Int(1)])
59    ///     .select()
60    ///     .await?;
61    /// assert!(rows.results.is_empty());
62    /// # Ok(()) }
63    /// ```
64    pub fn query<'a>(&'a mut self, query: &'a str) -> QueryBuilder<'a, 'a> {
65        QueryBuilder::new(self, query)
66    }
67}