sea_orm/database/
mod.rs

1use std::{sync::Arc, time::Duration};
2
3use futures_util::future::BoxFuture;
4#[cfg(feature = "sqlx-mysql")]
5use sqlx::mysql::MySqlConnectOptions;
6#[cfg(feature = "sqlx-postgres")]
7use sqlx::postgres::PgConnectOptions;
8#[cfg(feature = "sqlx-sqlite")]
9use sqlx::sqlite::SqliteConnectOptions;
10
11mod connection;
12mod db_connection;
13#[cfg(feature = "mock")]
14#[cfg_attr(docsrs, doc(cfg(feature = "mock")))]
15mod mock;
16#[cfg(feature = "proxy")]
17#[cfg_attr(docsrs, doc(cfg(feature = "proxy")))]
18mod proxy;
19#[cfg(feature = "rbac")]
20mod restricted_connection;
21#[cfg(all(feature = "schema-sync", feature = "sqlx-dep"))]
22mod sea_schema_shim;
23mod statement;
24mod stream;
25mod transaction;
26
27pub use connection::*;
28pub use db_connection::*;
29#[cfg(feature = "mock")]
30#[cfg_attr(docsrs, doc(cfg(feature = "mock")))]
31pub use mock::*;
32#[cfg(feature = "proxy")]
33#[cfg_attr(docsrs, doc(cfg(feature = "proxy")))]
34pub use proxy::*;
35#[cfg(feature = "rbac")]
36pub use restricted_connection::*;
37pub use statement::*;
38use std::borrow::Cow;
39pub use stream::*;
40use tracing::instrument;
41pub use transaction::*;
42
43use crate::error::*;
44
45/// Defines a database
46#[derive(Debug, Default)]
47pub struct Database;
48
49type AfterConnectCallback = Option<
50    Arc<
51        dyn Fn(DatabaseConnection) -> BoxFuture<'static, Result<(), DbErr>> + Send + Sync + 'static,
52    >,
53>;
54
55/// Defines the configuration options of a database
56#[derive(derive_more::Debug, Clone)]
57pub struct ConnectOptions {
58    /// The URI of the database
59    pub(crate) url: String,
60    /// Maximum number of connections for a pool
61    pub(crate) max_connections: Option<u32>,
62    /// Minimum number of connections for a pool
63    pub(crate) min_connections: Option<u32>,
64    /// The connection timeout for a packet connection
65    pub(crate) connect_timeout: Option<Duration>,
66    /// Maximum idle time for a particular connection to prevent
67    /// network resource exhaustion
68    pub(crate) idle_timeout: Option<Duration>,
69    /// Set the maximum amount of time to spend waiting for acquiring a connection
70    pub(crate) acquire_timeout: Option<Duration>,
71    /// Set the maximum lifetime of individual connections
72    pub(crate) max_lifetime: Option<Duration>,
73    /// Enable SQLx statement logging
74    pub(crate) sqlx_logging: bool,
75    /// SQLx statement logging level (ignored if `sqlx_logging` is false)
76    pub(crate) sqlx_logging_level: log::LevelFilter,
77    /// SQLx slow statements logging level (ignored if `sqlx_logging` is false)
78    pub(crate) sqlx_slow_statements_logging_level: log::LevelFilter,
79    /// SQLx slow statements duration threshold (ignored if `sqlx_logging` is false)
80    pub(crate) sqlx_slow_statements_logging_threshold: Duration,
81    /// set sqlcipher key
82    pub(crate) sqlcipher_key: Option<Cow<'static, str>>,
83    /// Schema search path (PostgreSQL only)
84    pub(crate) schema_search_path: Option<String>,
85    pub(crate) test_before_acquire: bool,
86    /// Only establish connections to the DB as needed. If set to `true`, the db connection will
87    /// be created using SQLx's [connect_lazy](https://docs.rs/sqlx/latest/sqlx/struct.Pool.html#method.connect_lazy)
88    /// method.
89    pub(crate) connect_lazy: bool,
90
91    #[debug(skip)]
92    pub(crate) after_connect: AfterConnectCallback,
93
94    #[cfg(feature = "sqlx-mysql")]
95    #[debug(skip)]
96    pub(crate) mysql_opts_fn:
97        Option<Arc<dyn Fn(MySqlConnectOptions) -> MySqlConnectOptions + Send + Sync>>,
98    #[cfg(feature = "sqlx-postgres")]
99    #[debug(skip)]
100    pub(crate) pg_opts_fn: Option<Arc<dyn Fn(PgConnectOptions) -> PgConnectOptions + Send + Sync>>,
101    #[cfg(feature = "sqlx-sqlite")]
102    #[debug(skip)]
103    pub(crate) sqlite_opts_fn:
104        Option<Arc<dyn Fn(SqliteConnectOptions) -> SqliteConnectOptions + Send + Sync>>,
105}
106
107impl Database {
108    /// Method to create a [DatabaseConnection] on a database. This method will return an error
109    /// if the database is not available.
110    #[instrument(level = "trace", skip(opt))]
111    pub async fn connect<C>(opt: C) -> Result<DatabaseConnection, DbErr>
112    where
113        C: Into<ConnectOptions>,
114    {
115        let opt: ConnectOptions = opt.into();
116
117        if url::Url::parse(&opt.url).is_err() {
118            return Err(conn_err(format!(
119                "The connection string '{}' cannot be parsed.",
120                opt.url
121            )));
122        }
123
124        #[cfg(feature = "sqlx-mysql")]
125        if DbBackend::MySql.is_prefix_of(&opt.url) {
126            return crate::SqlxMySqlConnector::connect(opt).await;
127        }
128        #[cfg(feature = "sqlx-postgres")]
129        if DbBackend::Postgres.is_prefix_of(&opt.url) {
130            return crate::SqlxPostgresConnector::connect(opt).await;
131        }
132        #[cfg(feature = "sqlx-sqlite")]
133        if DbBackend::Sqlite.is_prefix_of(&opt.url) {
134            return crate::SqlxSqliteConnector::connect(opt).await;
135        }
136        #[cfg(feature = "mock")]
137        if crate::MockDatabaseConnector::accepts(&opt.url) {
138            return crate::MockDatabaseConnector::connect(&opt.url).await;
139        }
140
141        Err(conn_err(format!(
142            "The connection string '{}' has no supporting driver.",
143            opt.url
144        )))
145    }
146
147    /// Method to create a [DatabaseConnection] on a proxy database
148    #[cfg(feature = "proxy")]
149    #[instrument(level = "trace", skip(proxy_func_arc))]
150    pub async fn connect_proxy(
151        db_type: DbBackend,
152        proxy_func_arc: std::sync::Arc<Box<dyn ProxyDatabaseTrait>>,
153    ) -> Result<DatabaseConnection, DbErr> {
154        match db_type {
155            DbBackend::MySql => {
156                return crate::ProxyDatabaseConnector::connect(
157                    DbBackend::MySql,
158                    proxy_func_arc.to_owned(),
159                );
160            }
161            DbBackend::Postgres => {
162                return crate::ProxyDatabaseConnector::connect(
163                    DbBackend::Postgres,
164                    proxy_func_arc.to_owned(),
165                );
166            }
167            DbBackend::Sqlite => {
168                return crate::ProxyDatabaseConnector::connect(
169                    DbBackend::Sqlite,
170                    proxy_func_arc.to_owned(),
171                );
172            }
173        }
174    }
175}
176
177impl<T> From<T> for ConnectOptions
178where
179    T: Into<String>,
180{
181    fn from(s: T) -> ConnectOptions {
182        ConnectOptions::new(s.into())
183    }
184}
185
186impl ConnectOptions {
187    /// Create new [ConnectOptions] for a [Database] by passing in a URI string
188    pub fn new<T>(url: T) -> Self
189    where
190        T: Into<String>,
191    {
192        Self {
193            url: url.into(),
194            max_connections: None,
195            min_connections: None,
196            connect_timeout: None,
197            idle_timeout: None,
198            acquire_timeout: None,
199            max_lifetime: None,
200            sqlx_logging: true,
201            sqlx_logging_level: log::LevelFilter::Info,
202            sqlx_slow_statements_logging_level: log::LevelFilter::Off,
203            sqlx_slow_statements_logging_threshold: Duration::from_secs(1),
204            sqlcipher_key: None,
205            schema_search_path: None,
206            test_before_acquire: true,
207            connect_lazy: false,
208            after_connect: None,
209            #[cfg(feature = "sqlx-mysql")]
210            mysql_opts_fn: None,
211            #[cfg(feature = "sqlx-postgres")]
212            pg_opts_fn: None,
213            #[cfg(feature = "sqlx-sqlite")]
214            sqlite_opts_fn: None,
215        }
216    }
217
218    /// Get the database URL of the pool
219    pub fn get_url(&self) -> &str {
220        &self.url
221    }
222
223    /// Set the maximum number of connections of the pool
224    pub fn max_connections(&mut self, value: u32) -> &mut Self {
225        self.max_connections = Some(value);
226        self
227    }
228
229    /// Get the maximum number of connections of the pool, if set
230    pub fn get_max_connections(&self) -> Option<u32> {
231        self.max_connections
232    }
233
234    /// Set the minimum number of connections of the pool
235    pub fn min_connections(&mut self, value: u32) -> &mut Self {
236        self.min_connections = Some(value);
237        self
238    }
239
240    /// Get the minimum number of connections of the pool, if set
241    pub fn get_min_connections(&self) -> Option<u32> {
242        self.min_connections
243    }
244
245    /// Set the timeout duration when acquiring a connection
246    pub fn connect_timeout(&mut self, value: Duration) -> &mut Self {
247        self.connect_timeout = Some(value);
248        self
249    }
250
251    /// Get the timeout duration when acquiring a connection, if set
252    pub fn get_connect_timeout(&self) -> Option<Duration> {
253        self.connect_timeout
254    }
255
256    /// Set the idle duration before closing a connection
257    pub fn idle_timeout(&mut self, value: Duration) -> &mut Self {
258        self.idle_timeout = Some(value);
259        self
260    }
261
262    /// Get the idle duration before closing a connection, if set
263    pub fn get_idle_timeout(&self) -> Option<Duration> {
264        self.idle_timeout
265    }
266
267    /// Set the maximum amount of time to spend waiting for acquiring a connection
268    pub fn acquire_timeout(&mut self, value: Duration) -> &mut Self {
269        self.acquire_timeout = Some(value);
270        self
271    }
272
273    /// Get the maximum amount of time to spend waiting for acquiring a connection
274    pub fn get_acquire_timeout(&self) -> Option<Duration> {
275        self.acquire_timeout
276    }
277
278    /// Set the maximum lifetime of individual connections
279    pub fn max_lifetime(&mut self, lifetime: Duration) -> &mut Self {
280        self.max_lifetime = Some(lifetime);
281        self
282    }
283
284    /// Get the maximum lifetime of individual connections, if set
285    pub fn get_max_lifetime(&self) -> Option<Duration> {
286        self.max_lifetime
287    }
288
289    /// Enable SQLx statement logging (default true)
290    pub fn sqlx_logging(&mut self, value: bool) -> &mut Self {
291        self.sqlx_logging = value;
292        self
293    }
294
295    /// Get whether SQLx statement logging is enabled
296    pub fn get_sqlx_logging(&self) -> bool {
297        self.sqlx_logging
298    }
299
300    /// Set SQLx statement logging level (default INFO).
301    /// (ignored if `sqlx_logging` is `false`)
302    pub fn sqlx_logging_level(&mut self, level: log::LevelFilter) -> &mut Self {
303        self.sqlx_logging_level = level;
304        self
305    }
306
307    /// Set SQLx slow statements logging level and duration threshold (default `LevelFilter::Off`).
308    /// (ignored if `sqlx_logging` is `false`)
309    pub fn sqlx_slow_statements_logging_settings(
310        &mut self,
311        level: log::LevelFilter,
312        duration: Duration,
313    ) -> &mut Self {
314        self.sqlx_slow_statements_logging_level = level;
315        self.sqlx_slow_statements_logging_threshold = duration;
316        self
317    }
318
319    /// Get the level of SQLx statement logging
320    pub fn get_sqlx_logging_level(&self) -> log::LevelFilter {
321        self.sqlx_logging_level
322    }
323
324    /// Get the SQLx slow statements logging settings
325    pub fn get_sqlx_slow_statements_logging_settings(&self) -> (log::LevelFilter, Duration) {
326        (
327            self.sqlx_slow_statements_logging_level,
328            self.sqlx_slow_statements_logging_threshold,
329        )
330    }
331
332    /// set key for sqlcipher
333    pub fn sqlcipher_key<T>(&mut self, value: T) -> &mut Self
334    where
335        T: Into<Cow<'static, str>>,
336    {
337        self.sqlcipher_key = Some(value.into());
338        self
339    }
340
341    /// Set schema search path (PostgreSQL only)
342    pub fn set_schema_search_path<T>(&mut self, schema_search_path: T) -> &mut Self
343    where
344        T: Into<String>,
345    {
346        self.schema_search_path = Some(schema_search_path.into());
347        self
348    }
349
350    /// If true, the connection will be pinged upon acquiring from the pool (default true).
351    pub fn test_before_acquire(&mut self, value: bool) -> &mut Self {
352        self.test_before_acquire = value;
353        self
354    }
355
356    /// If set to `true`, the db connection pool will be created using SQLx's
357    /// [connect_lazy](https://docs.rs/sqlx/latest/sqlx/struct.Pool.html#method.connect_lazy) method.
358    pub fn connect_lazy(&mut self, value: bool) -> &mut Self {
359        self.connect_lazy = value;
360        self
361    }
362
363    /// Get whether DB connections will be established when the pool is created or only as needed.
364    pub fn get_connect_lazy(&self) -> bool {
365        self.connect_lazy
366    }
367
368    /// Set a callback function that will be called after a new connection is established.
369    pub fn after_connect<F>(&mut self, f: F) -> &mut Self
370    where
371        F: Fn(DatabaseConnection) -> BoxFuture<'static, Result<(), DbErr>> + Send + Sync + 'static,
372    {
373        self.after_connect = Some(Arc::new(f));
374
375        self
376    }
377
378    #[cfg(feature = "sqlx-mysql")]
379    #[cfg_attr(docsrs, doc(cfg(feature = "sqlx-mysql")))]
380    /// Apply a function to modify the underlying [`MySqlConnectOptions`] before
381    /// creating the connection pool.
382    pub fn map_sqlx_mysql_opts<F>(&mut self, f: F) -> &mut Self
383    where
384        F: Fn(MySqlConnectOptions) -> MySqlConnectOptions + Send + Sync + 'static,
385    {
386        self.mysql_opts_fn = Some(Arc::new(f));
387        self
388    }
389
390    #[cfg(feature = "sqlx-postgres")]
391    #[cfg_attr(docsrs, doc(cfg(feature = "sqlx-postgres")))]
392    /// Apply a function to modify the underlying [`PgConnectOptions`] before
393    /// creating the connection pool.
394    pub fn map_sqlx_postgres_opts<F>(&mut self, f: F) -> &mut Self
395    where
396        F: Fn(PgConnectOptions) -> PgConnectOptions + Send + Sync + 'static,
397    {
398        self.pg_opts_fn = Some(Arc::new(f));
399        self
400    }
401
402    #[cfg(feature = "sqlx-sqlite")]
403    #[cfg_attr(docsrs, doc(cfg(feature = "sqlx-sqlite")))]
404    /// Apply a function to modify the underlying [`SqliteConnectOptions`] before
405    /// creating the connection pool.
406    pub fn map_sqlx_sqlite_opts<F>(&mut self, f: F) -> &mut Self
407    where
408        F: Fn(SqliteConnectOptions) -> SqliteConnectOptions + Send + Sync + 'static,
409    {
410        self.sqlite_opts_fn = Some(Arc::new(f));
411        self
412    }
413}