sqlx_sqlite/options/
connect.rs

1use crate::{SqliteConnectOptions, SqliteConnection};
2use futures_core::future::BoxFuture;
3use log::LevelFilter;
4use sqlx_core::connection::ConnectOptions;
5use sqlx_core::error::Error;
6use sqlx_core::executor::Executor;
7use std::fmt::Write;
8use std::str::FromStr;
9use std::time::Duration;
10use url::Url;
11
12impl ConnectOptions for SqliteConnectOptions {
13    type Connection = SqliteConnection;
14
15    fn from_url(url: &Url) -> Result<Self, Error> {
16        // SQLite URL parsing is handled specially;
17        // we want to treat the following URLs as equivalent:
18        //
19        // * sqlite:foo.db
20        // * sqlite://foo.db
21        //
22        // If we used `Url::path()`, the latter would return an empty string
23        // because `foo.db` gets parsed as the hostname.
24        Self::from_str(url.as_str())
25    }
26
27    fn to_url_lossy(&self) -> Url {
28        self.build_url()
29    }
30
31    fn connect(&self) -> BoxFuture<'_, Result<Self::Connection, Error>>
32    where
33        Self::Connection: Sized,
34    {
35        Box::pin(async move {
36            let mut conn = SqliteConnection::establish(self).await?;
37
38            // Execute PRAGMAs
39            conn.execute(&*self.pragma_string()).await?;
40
41            if !self.collations.is_empty() {
42                let mut locked = conn.lock_handle().await?;
43
44                for collation in &self.collations {
45                    collation.create(&mut locked.guard.handle)?;
46                }
47            }
48
49            Ok(conn)
50        })
51    }
52
53    fn log_statements(mut self, level: LevelFilter) -> Self {
54        self.log_settings.log_statements(level);
55        self
56    }
57
58    fn log_slow_statements(mut self, level: LevelFilter, duration: Duration) -> Self {
59        self.log_settings.log_slow_statements(level, duration);
60        self
61    }
62}
63
64impl SqliteConnectOptions {
65    /// Collect all `PRAMGA` commands into a single string
66    pub(crate) fn pragma_string(&self) -> String {
67        let mut string = String::new();
68
69        for (key, opt_value) in &self.pragmas {
70            if let Some(value) = opt_value {
71                write!(string, "PRAGMA {key} = {value}; ").ok();
72            }
73        }
74
75        string
76    }
77}