Skip to main content

tank_core/
connection.rs

1use crate::{Driver, ErrorContext, Executor, Result, truncate_long};
2use anyhow::anyhow;
3use std::{
4    borrow::Cow,
5    future::{self, Future},
6};
7use url::Url;
8
9/// A live database handle capable of executing queries and spawning transactions.
10///
11/// Extends [`Executor`] with connection and transaction management.
12///
13/// # Lifecycle
14/// - `connect` creates (or fetches) an underlying connection. It may eagerly
15///   establish network I/O; always await it.
16/// - `begin` starts a transaction scope. Commit/rollback MUST be awaited to
17///   guarantee resource release.
18pub trait Connection: Executor {
19    /// Validates and normalizes the connection URL, handling special cases like in-memory databases.
20    fn sanitize_url(_driver: &Self::Driver, mut url: Cow<'static, str>) -> Result<Url>
21    where
22        Self: Sized,
23    {
24        const MEMORY: &str = ":memory:";
25        let mut in_memory = false;
26        if let Some((scheme, host)) = url.split_once("://")
27            && host.starts_with(MEMORY)
28        {
29            url = format!("{scheme}://localhost{}", &host[MEMORY.len()..]).into();
30            in_memory = true;
31        }
32        let make_context = || {
33            format!(
34                r#"While parsing the connection URL "{}""#,
35                truncate_long(&url)
36            )
37        };
38        let mut result = Url::parse(&url)
39            .with_context(make_context)
40            .inspect_err(|e| log::error!("{e:#}"))?;
41        if in_memory {
42            result.query_pairs_mut().append_pair("mode", "memory");
43        }
44        let names = <Self::Driver as Driver>::NAME;
45        if !names
46            .iter()
47            .any(|name| url.starts_with(name) && url[name.len()..].starts_with("://"))
48        {
49            return Err(anyhow!(
50                r#"Must start with {}"#,
51                names
52                    .iter()
53                    .map(|name| format!(r#""{name}://""#))
54                    .collect::<Vec<_>>()
55                    .join(" or ")
56            ))
57            .with_context(make_context)
58            .inspect_err(|e| log::error!("{e:#}"));
59        }
60        Ok(result)
61    }
62
63    /// Establishes a connection (or pool) to the database specified by the URL.
64    ///
65    /// Implementations may perform I/O or validation during `connect`.
66    /// Callers should treat this as a potentially expensive operation.
67    fn connect(
68        driver: &Self::Driver,
69        url: Cow<'static, str>,
70    ) -> impl Future<Output = Result<<Self::Driver as Driver>::Connection>> + Send
71    where
72        Self: Sized;
73
74    /// Starts a new transaction on this connection.
75    ///
76    /// Must await `commit` or `rollback` to finalize the scope and release resources.
77    fn begin(
78        &mut self,
79    ) -> impl Future<Output = Result<<Self::Driver as Driver>::Transaction<'_>>> + Send;
80
81    /// Closes the connection and releases any session resources.
82    fn disconnect(self) -> impl Future<Output = Result<()>> + Send
83    where
84        Self: Sized,
85    {
86        future::ready(Ok(()))
87    }
88}
89
90impl<S: Connection> Connection for &mut S {
91    fn connect(
92        driver: &Self::Driver,
93        url: Cow<'static, str>,
94    ) -> impl Future<Output = Result<<Self::Driver as Driver>::Connection>> + Send
95    where
96        Self: Sized,
97    {
98        S::connect(driver, url)
99    }
100
101    fn begin(
102        &mut self,
103    ) -> impl Future<Output = Result<<Self::Driver as Driver>::Transaction<'_>>> + Send {
104        (**self).begin()
105    }
106
107    fn disconnect(self) -> impl Future<Output = Result<()>> + Send
108    where
109        Self: Sized,
110    {
111        future::ready(Err(anyhow!(
112            "Cannot disconnect using `&mut Connection`, use the actual object.",
113        )))
114    }
115}