forked from transact-rs/sqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.rs
More file actions
74 lines (64 loc) 路 2.02 KB
/
Copy pathconnection.rs
File metadata and controls
74 lines (64 loc) 路 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use std::convert::TryInto;
use futures_core::future::BoxFuture;
use crate::executor::Executor;
use crate::maybe_owned::MaybeOwned;
use crate::pool::{Pool, PoolConnection};
use crate::transaction::Transaction;
use crate::url::Url;
/// Represents a single database connection rather than a pool of database connections.
///
/// Prefer running queries from [Pool] unless there is a specific need for a single, continuous
/// connection.
pub trait Connection
where
Self: Send + 'static,
Self: Executor,
{
/// Starts a transaction.
///
/// Returns [`Transaction`](struct.Transaction.html).
fn begin(self) -> BoxFuture<'static, crate::Result<Transaction<Self>>>
where
Self: Sized,
{
Box::pin(Transaction::new(0, self))
}
/// Close this database connection.
fn close(self) -> BoxFuture<'static, crate::Result<()>>;
/// Verifies a connection to the database is still alive.
fn ping(&mut self) -> BoxFuture<crate::Result<()>>;
}
/// Represents a type that can directly establish a new connection.
pub trait Connect: Connection {
/// Establish a new database connection.
fn connect<T>(url: T) -> BoxFuture<'static, crate::Result<Self>>
where
T: TryInto<Url, Error = crate::Error>,
Self: Sized;
}
pub(crate) enum ConnectionSource<'c, C>
where
C: Connect,
{
Connection(MaybeOwned<PoolConnection<C>, &'c mut C>),
#[allow(dead_code)]
Pool(Pool<C>),
}
impl<'c, C> ConnectionSource<'c, C>
where
C: Connect,
{
#[allow(dead_code)]
pub(crate) async fn resolve(&mut self) -> crate::Result<&'_ mut C> {
if let ConnectionSource::Pool(pool) = self {
*self = ConnectionSource::Connection(MaybeOwned::Owned(pool.acquire().await?));
}
Ok(match self {
ConnectionSource::Connection(conn) => match conn {
MaybeOwned::Borrowed(conn) => &mut *conn,
MaybeOwned::Owned(ref mut conn) => conn,
},
ConnectionSource::Pool(_) => unreachable!(),
})
}
}