1use crate::{Driver, ErrorContext, Executor, Result, log_error, truncate_long};
2use anyhow::anyhow;
3use std::{
4 borrow::Cow,
5 future::{self, Future},
6};
7use url::Url;
8
9pub trait Connection: Executor {
19 fn sanitize_url(_driver: &Self::Driver, mut url: Cow<'static, str>) -> Result<Url>
21 where
22 Self: Sized,
23 {
24 let mut in_memory = false;
25 if let Some((scheme, host)) = url.split_once("://")
26 && host.starts_with(":memory:")
27 {
28 url = format!("{scheme}://localhost{}", &host[8..]).into();
29 in_memory = true;
30 }
31 let make_context = || format!("While parsing the connection URL:\n{}", truncate_long!(url));
32 let mut result = Url::parse(&url).with_context(make_context)?;
33 if in_memory {
34 result.query_pairs_mut().append_pair("mode", "memory");
35 }
36 let names = <Self::Driver as Driver>::NAME;
37 if !names
38 .iter()
39 .any(|name| url.starts_with(name) && url[name.len()..].starts_with("://"))
40 {
41 return Err(anyhow!(
42 "Connection URL must start with: {}",
43 names.join(", ")
44 ))
45 .with_context(make_context)
46 .inspect_err(log_error);
47 }
48 Ok(result)
49 }
50
51 fn connect(
56 driver: &Self::Driver,
57 url: Cow<'static, str>,
58 ) -> impl Future<Output = Result<<Self::Driver as Driver>::Connection>> + Send
59 where
60 Self: Sized;
61
62 fn begin(
66 &mut self,
67 ) -> impl Future<Output = Result<<Self::Driver as Driver>::Transaction<'_>>> + Send;
68
69 fn disconnect(self) -> impl Future<Output = Result<()>> + Send
71 where
72 Self: Sized,
73 {
74 future::ready(Ok(()))
75 }
76}
77
78impl<S: Connection> Connection for &mut S {
79 fn connect(
80 driver: &Self::Driver,
81 url: Cow<'static, str>,
82 ) -> impl Future<Output = Result<<Self::Driver as Driver>::Connection>> + Send
83 where
84 Self: Sized,
85 {
86 S::connect(driver, url)
87 }
88
89 fn begin(
90 &mut self,
91 ) -> impl Future<Output = Result<<Self::Driver as Driver>::Transaction<'_>>> + Send {
92 (**self).begin()
93 }
94
95 fn disconnect(self) -> impl Future<Output = Result<()>> + Send
96 where
97 Self: Sized,
98 {
99 future::ready(Err(anyhow!(
100 "Cannot disconnect using `&mut Connection`, use the actual object.",
101 )))
102 }
103}