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
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 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 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 fn begin(
78 &mut self,
79 ) -> impl Future<Output = Result<<Self::Driver as Driver>::Transaction<'_>>> + Send;
80
81 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}