Skip to main content

easy_sql/database_structs/
connection.rs

1use std::{
2    fmt::Debug,
3    ops::{Deref, DerefMut},
4};
5
6use easy_macros::always_context;
7
8use sqlx::{Database, Executor};
9
10use crate::{
11    Driver, EasyExecutor,
12    traits::{DriverConnection, InternalDriver, SetupSql},
13};
14/// Wrapper around [`sqlx::pool::PoolConnection`](https://docs.rs/sqlx/latest/sqlx/pool/struct.PoolConnection.html)
15///
16/// Will contain sql query watch data in the future (gated by a feature)
17#[derive(Debug)]
18pub struct Connection<D: Driver> {
19    internal: sqlx::pool::PoolConnection<InternalDriver<D>>,
20}
21
22#[always_context]
23impl<D: Driver> Connection<D> {
24    pub fn new(conn: sqlx::pool::PoolConnection<InternalDriver<D>>) -> Self {
25        Connection { internal: conn }
26    }
27}
28
29#[always_context]
30impl<D: Driver> EasyExecutor<D> for Connection<D>
31where
32    for<'b> &'b mut DriverConnection<D>: Executor<'b, Database = D::InternalDriver>,
33{
34    type InternalExecutor<'b>
35        = &'b mut DriverConnection<D>
36    where
37        Self: 'b;
38
39    async fn query_setup<O: SetupSql<D> + Send + Sync>(
40        &mut self,
41        sql: O,
42    ) -> anyhow::Result<O::Output>
43    where
44        DriverConnection<D>: Send + Sync,
45    {
46        sql.query(self).await
47    }
48
49    fn executor<'a>(&'a mut self) -> Self::InternalExecutor<'a> {
50        &mut *self.internal
51    }
52}
53
54impl<D: Driver> Deref for Connection<D> {
55    type Target = <InternalDriver<D> as Database>::Connection;
56
57    fn deref(&self) -> &Self::Target {
58        &self.internal
59    }
60}
61
62impl<D: Driver> DerefMut for Connection<D> {
63    fn deref_mut(&mut self) -> &mut Self::Target {
64        &mut self.internal
65    }
66}