mysql_async/connection_like/
mod.rs

1// Copyright (c) 2017 Anatoly Ikorsky
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9use futures_util::FutureExt;
10
11use crate::{BoxFuture, Pool};
12
13/// Inner [`Connection`] representation.
14#[derive(Debug)]
15pub(crate) enum ConnectionInner<'a, 't: 'a> {
16    /// Just a connection.
17    Conn(crate::Conn),
18    /// Mutable reference to a connection.
19    ConnMut(&'a mut crate::Conn),
20    /// Connection wrapped in a transaction.
21    Tx(&'a mut crate::Transaction<'t>),
22}
23
24impl std::ops::Deref for ConnectionInner<'_, '_> {
25    type Target = crate::Conn;
26
27    fn deref(&self) -> &Self::Target {
28        match self {
29            ConnectionInner::Conn(ref conn) => conn,
30            ConnectionInner::ConnMut(conn) => conn,
31            ConnectionInner::Tx(tx) => tx.0.deref(),
32        }
33    }
34}
35
36impl std::ops::DerefMut for ConnectionInner<'_, '_> {
37    fn deref_mut(&mut self) -> &mut Self::Target {
38        match self {
39            ConnectionInner::Conn(conn) => conn,
40            ConnectionInner::ConnMut(conn) => conn,
41            ConnectionInner::Tx(tx) => tx.0.inner.deref_mut(),
42        }
43    }
44}
45
46/// Some connection.
47///
48/// This could at least be queried.
49#[derive(Debug)]
50pub struct Connection<'a, 't: 'a> {
51    pub(crate) inner: ConnectionInner<'a, 't>,
52}
53
54impl Connection<'_, '_> {
55    #[inline]
56    pub(crate) fn as_mut(&mut self) -> &mut crate::Conn {
57        &mut self.inner
58    }
59}
60
61impl<'a, 't: 'a> Connection<'a, 't> {
62    /// Borrows a [`Connection`] rather than consuming it.
63    ///
64    /// This is useful to allow calling [`Query`] methods while still retaining
65    /// ownership of the original connection.
66    ///
67    /// # Examples
68    ///
69    /// ```no_run
70    /// # use mysql_async::Connection;
71    /// # use mysql_async::prelude::Query;
72    /// async fn connection_by_ref(mut connection: Connection<'_, '_>) {
73    ///     // Perform some query
74    ///     "SELECT 1".ignore(connection.by_ref()).await.unwrap();
75    ///     // Perform another query.
76    ///     // We can only do this because we used `by_ref` earlier.
77    ///     "SELECT 2".ignore(connection).await.unwrap();
78    /// }
79    /// ```
80    ///
81    /// [`Query`]: crate::prelude::Query
82    pub fn by_ref(&mut self) -> Connection<'_, '_> {
83        Connection {
84            inner: ConnectionInner::ConnMut(self.as_mut()),
85        }
86    }
87}
88
89impl From<crate::Conn> for Connection<'static, 'static> {
90    fn from(conn: crate::Conn) -> Self {
91        Self {
92            inner: ConnectionInner::Conn(conn),
93        }
94    }
95}
96
97impl<'a> From<&'a mut crate::Conn> for Connection<'a, 'static> {
98    fn from(conn: &'a mut crate::Conn) -> Self {
99        Self {
100            inner: ConnectionInner::ConnMut(conn),
101        }
102    }
103}
104
105impl<'a, 't> From<&'a mut crate::Transaction<'t>> for Connection<'a, 't> {
106    fn from(tx: &'a mut crate::Transaction<'t>) -> Self {
107        Self {
108            inner: ConnectionInner::Tx(tx),
109        }
110    }
111}
112
113impl std::ops::Deref for Connection<'_, '_> {
114    type Target = crate::Conn;
115
116    fn deref(&self) -> &Self::Target {
117        &self.inner
118    }
119}
120
121/// Result of a [`ToConnection::to_connection`] call.
122pub enum ToConnectionResult<'a, 't: 'a> {
123    /// Connection is immediately available.
124    Immediate(Connection<'a, 't>),
125    /// We need some time to get a connection and the operation itself may fail.
126    Mediate(BoxFuture<'a, Connection<'a, 't>>),
127}
128
129impl<'a, 't: 'a> ToConnectionResult<'a, 't> {
130    /// Resolves `self` to a connection.
131    #[inline]
132    pub async fn resolve(self) -> crate::Result<Connection<'a, 't>> {
133        match self {
134            ToConnectionResult::Immediate(immediate) => Ok(immediate),
135            ToConnectionResult::Mediate(mediate) => mediate.await,
136        }
137    }
138}
139
140/// Everything that can be given in exchange to a connection.
141///
142/// Note that you could obtain a `'static` connection by giving away `Conn` or `Pool`.
143pub trait ToConnection<'a, 't: 'a>: Send {
144    /// Converts self to a connection.
145    fn to_connection(self) -> ToConnectionResult<'a, 't>;
146}
147
148impl<'a, 't: 'a, T: Into<Connection<'a, 't>> + Send> ToConnection<'a, 't> for T {
149    fn to_connection(self) -> ToConnectionResult<'a, 't> {
150        ToConnectionResult::Immediate(self.into())
151    }
152}
153
154impl ToConnection<'static, 'static> for Pool {
155    fn to_connection(self) -> ToConnectionResult<'static, 'static> {
156        let fut = async move {
157            let conn = self.get_conn().await?;
158            Ok(conn.into())
159        }
160        .boxed();
161        ToConnectionResult::Mediate(fut)
162    }
163}
164
165impl<'a> ToConnection<'a, 'static> for &'a Pool {
166    fn to_connection(self) -> ToConnectionResult<'a, 'static> {
167        let fut = async move {
168            let conn = self.get_conn().await?;
169            Ok(conn.into())
170        }
171        .boxed();
172        ToConnectionResult::Mediate(fut)
173    }
174}