1pub(crate) mod auto_migration;
6mod column;
7mod conn;
8pub(crate) mod encrypted;
9mod error;
10mod factory;
11mod from_row;
12mod json;
13mod key;
14mod migrate;
15mod model;
16mod paginate;
17mod query;
18mod query_log;
19pub mod relations;
20pub mod schema;
21#[allow(dead_code)] pub(crate) mod schema_check;
23pub(crate) mod schema_diff;
24pub(crate) mod schema_sql;
25pub mod search;
26mod sequence;
27mod value;
28
29use std::str::FromStr;
30use std::time::Duration;
31
32use anyhow::Context;
33use axum::extract::FromRef;
34use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
35
36pub use column::{Col, Comparable, Condition, IntoColumn};
37pub use conn::Conn;
38#[doc(hidden)]
39pub use conn::bounds;
40pub use conn::{Db, Dialect, Executor, FromDb, Row, RowIndex, Sql, Transaction, sql};
41pub(crate) use conn::{RowInner, SchemaEpoch, script};
42pub use encrypted::{Encrypted, Unsealed};
43pub use error::DbError;
44pub use factory::{Factory, FactoryBuilder};
45pub use from_row::FromRow;
46pub use json::{Json, JsonPath, json_index};
47pub use key::{InvalidUlid, ModelKey, Ulid};
48pub use migrate::{Migration, MigrationStatus};
49pub(crate) use migrate::{Migrator, framework_migration};
50pub use model::{Model, ModelHooks};
51pub use paginate::{CursorPage, Page, Paginated, SimplePage};
52pub use query::{Number, Query};
53pub use query_log::capture_queries;
54pub use schema::{ColumnKind, ColumnType, ModelColumn, ModelIndex};
55pub(crate) use sequence::MIGRATION as SEQUENCE_MIGRATION;
56pub use sequence::{NumberFormat, Period, Sequence, SequenceRow};
57pub use sqlx;
61pub use value::{DbValue, ToDbValue};
62
63use crate::{AppState, Config};
64
65pub type DateTime = chrono::DateTime<chrono::Utc>;
67
68pub(crate) fn from_unix(seconds: i64) -> DateTime {
70 chrono::DateTime::from_timestamp(seconds, 0).unwrap_or_default()
71}
72
73pub fn now() -> DateTime {
76 use chrono::SubsecRound;
77 chrono::DateTime::<chrono::Utc>::from(crate::clock::system_now()).trunc_subsecs(6)
78}
79
80impl FromRef<AppState> for Db {
81 fn from_ref(state: &AppState) -> Self {
82 state.db.clone()
83 }
84}
85
86pub(crate) async fn connect(config: &Config) -> anyhow::Result<Db> {
95 let url = &config.database_url;
96 if config.database_pool_size == 0 {
97 anyhow::bail!("DATABASE_POOL_SIZE must be at least 1");
98 }
99 if is_postgres(url) {
100 return connect_postgres(url, config, false).await;
101 }
102 if !url.starts_with("sqlite:") {
103 anyhow::bail!(
105 "DATABASE_URL `{}` must start with sqlite:, postgres:// or postgresql://",
106 redact(url)
107 );
108 }
109 if is_memory(url)
110 && let Some(test_url) = test_database_url().filter(|u| is_postgres(u))
111 {
112 return connect_postgres(&test_url, config, true).await;
113 }
114 let schema = SchemaEpoch::default();
115 let pool = connect_sqlite(config, schema.clone()).await?;
116 Ok(Db::from_sqlite(pool, schema))
117}
118
119fn test_database_url() -> Option<String> {
122 test_database_url_in(
123 std::env::var("TEST_DATABASE_URL").ok(),
124 std::path::Path::new(".env"),
125 )
126}
127
128fn test_database_url_in(env: Option<String>, dotenv: &std::path::Path) -> Option<String> {
130 env.or_else(|| {
131 dotenvy::from_path_iter(dotenv)
132 .ok()?
133 .flatten()
134 .find(|(key, _)| key == "TEST_DATABASE_URL")
135 .map(|(_, url)| url)
136 })
137}
138
139fn is_postgres(url: &str) -> bool {
140 url.starts_with("postgres://") || url.starts_with("postgresql://")
141}
142
143fn is_memory(url: &str) -> bool {
144 url.contains(":memory:") || url.contains("mode=memory")
145}
146
147pub(crate) async fn connect_scratch(config: &Config) -> anyhow::Result<Db> {
150 if is_postgres(&config.database_url) {
151 return connect_postgres(&config.database_url, config, true).await;
152 }
153 let mut scratch = config.clone();
154 scratch.database_url = "sqlite::memory:".into();
155 connect(&scratch).await
156}
157
158pub(crate) async fn drop_scratch(db: &Db) {
160 if db.dialect() != Dialect::Postgres {
161 return;
162 }
163 let Ok(schema) = sql("SELECT current_schema()").scalar::<String>(db).await else {
164 return;
165 };
166 if schema.starts_with("renox_test_") {
167 let _ = sql(format!("DROP SCHEMA {} CASCADE", quote(&schema)))
168 .execute(db)
169 .await;
170 }
171}
172
173#[cfg(feature = "postgres")]
176async fn connect_postgres(url: &str, config: &Config, fresh_schema: bool) -> anyhow::Result<Db> {
177 use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
178 use sqlx::{ConnectOptions, Connection};
179
180 let failed = || format!("could not connect to the database at `{}`", redact(url));
181 let mut options = PgConnectOptions::from_str(url).with_context(failed)?;
182 if fresh_schema {
183 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
184 let nanos = std::time::SystemTime::now()
185 .duration_since(std::time::UNIX_EPOCH)
186 .unwrap_or_default()
187 .as_nanos();
188 let schema = format!(
189 "renox_test_{}_{}_{nanos}",
190 std::process::id(),
191 COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
192 );
193 let mut conn = options.connect().await.with_context(failed)?;
194 sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
195 "CREATE SCHEMA {}",
196 quote(&schema)
197 )))
198 .execute(&mut conn)
199 .await
200 .context("could not create a schema for the test")?;
201 conn.close().await.ok();
202 options = options.options([("search_path", schema)]);
203 }
204 if let Some(limit) = config.database_statement_timeout {
205 options = options.options([("statement_timeout", format!("{}ms", limit.as_millis()))]);
206 }
207 let pool_size = config.database_pool_size;
208 let pool_size = if fresh_schema {
211 pool_size.min(3)
212 } else {
213 pool_size
214 };
215 let schema = SchemaEpoch::default();
216 let epoch = schema.clone();
217 let pool = PgPoolOptions::new()
218 .max_connections(pool_size)
219 .acquire_timeout(config.database_acquire_timeout)
220 .before_acquire(move |_, meta| {
221 let fresh = !epoch.is_stale(meta.age);
222 Box::pin(async move { Ok(fresh) })
223 })
224 .connect_with(options)
225 .await
226 .with_context(failed)?;
227 Ok(Db::from_postgres(pool, schema))
228}
229
230#[cfg(not(feature = "postgres"))]
231async fn connect_postgres(_url: &str, _config: &Config, _fresh_schema: bool) -> anyhow::Result<Db> {
232 anyhow::bail!(
233 "the database URL points to PostgreSQL, but this build has no PostgreSQL support; \
234 enable the `postgres` feature of `renox`"
235 )
236}
237
238fn redact(url: &str) -> String {
240 let Some((scheme, rest)) = url.split_once("://") else {
241 return url.to_owned();
242 };
243 match rest.split_once('@') {
244 Some((user, host)) => {
245 let user = user.split_once(':').map_or(user, |(name, _)| name);
246 format!("{scheme}://{user}:***@{host}")
247 }
248 None => url.to_owned(),
249 }
250}
251
252const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
254
255async fn connect_sqlite(config: &Config, schema: SchemaEpoch) -> anyhow::Result<sqlx::SqlitePool> {
258 let url = &config.database_url;
259 let in_memory = is_memory(url);
260
261 let mut options = SqliteConnectOptions::from_str(url)
262 .with_context(|| format!("DATABASE_URL `{url}` is not a valid SQLite URL"))?
263 .create_if_missing(true)
264 .foreign_keys(true)
265 .busy_timeout(BUSY_TIMEOUT);
266 let busy_budget = config.database_acquire_timeout + BUSY_TIMEOUT;
270 if !in_memory {
271 options = options
272 .journal_mode(SqliteJournalMode::Wal)
273 .synchronous(SqliteSynchronous::Normal);
274 if let Some(dir) = options
275 .get_filename()
276 .parent()
277 .filter(|d| !d.as_os_str().is_empty())
278 {
279 std::fs::create_dir_all(dir)
280 .with_context(|| format!("could not create {}", dir.display()))?;
281 }
282 prepare_file(&options, busy_budget).await.with_context(|| {
283 format!("could not open the database at `{url}` (switching it to WAL)")
284 })?;
285 }
286
287 let pool = if in_memory {
289 SqlitePoolOptions::new()
290 .max_connections(1)
291 .min_connections(1)
292 .idle_timeout(None)
293 .max_lifetime(None)
294 } else {
295 SqlitePoolOptions::new()
297 .max_connections(config.database_pool_size)
298 .before_acquire(move |_, meta| {
299 let fresh = !schema.is_stale(meta.age);
300 Box::pin(async move { Ok(fresh) })
301 })
302 }
303 .acquire_timeout(if in_memory {
304 config.database_acquire_timeout.min(Duration::from_secs(2))
308 } else {
309 config.database_acquire_timeout
310 });
311 let pool = if in_memory {
312 let budget = config.database_acquire_timeout;
316 retry_while(budget, is_pool_timeout, || {
317 pool.clone().connect_with(options.clone())
318 })
319 .await
320 } else {
321 retry_while(busy_budget, is_busy_or_pool_timeout, || {
325 pool.clone().connect_with(options.clone())
326 })
327 .await
328 };
329 pool.with_context(|| format!("could not open the database at `{url}`"))
330}
331
332async fn prepare_file(options: &SqliteConnectOptions, budget: Duration) -> Result<(), sqlx::Error> {
341 use sqlx::{ConnectOptions, Connection};
342
343 let options = options.clone().busy_timeout(Duration::from_millis(100));
347 let conn = retry_while(budget, is_busy, || options.connect()).await?;
348 conn.close().await
349}
350
351fn is_busy(error: &sqlx::Error) -> bool {
354 let Some(code) = error
355 .as_database_error()
356 .and_then(|e| e.code())
357 .and_then(|code| code.parse::<i32>().ok())
358 else {
359 return false;
360 };
361 matches!(code & 0xff, 5 | 6)
362}
363
364fn is_busy_or_pool_timeout(error: &sqlx::Error) -> bool {
365 is_busy(error) || is_pool_timeout(error)
366}
367
368fn is_pool_timeout(error: &sqlx::Error) -> bool {
369 matches!(error, sqlx::Error::PoolTimedOut)
370}
371
372async fn retry_while<T, F>(
376 budget: Duration,
377 retryable: fn(&sqlx::Error) -> bool,
378 mut open: impl FnMut() -> F,
379) -> Result<T, sqlx::Error>
380where
381 F: std::future::Future<Output = Result<T, sqlx::Error>>,
382{
383 let start = tokio::time::Instant::now();
384 let mut tries = 0;
385 loop {
386 tries += 1;
387 match open().await {
388 Err(e) if retryable(&e) && (start.elapsed() < budget || tries < 3) => {
391 tracing::debug!("opening the database failed ({e}); trying again");
392 let jitter = u64::from(rand::random::<u8>()) * 50 / 255;
394 tokio::time::sleep(Duration::from_millis(25 + jitter)).await;
395 }
396 result => return result,
397 }
398 }
399}
400
401pub(crate) fn quote(ident: &str) -> String {
403 format!("\"{}\"", ident.replace('"', "\"\""))
404}
405
406#[doc(hidden)]
411#[cfg(not(feature = "postgres"))]
412#[macro_export]
413macro_rules! __db_text_type {
414 ($t:ty) => {
415 $crate::__db_text_type_for!($t, $crate::__sqlx::sqlite::Sqlite);
416 };
417}
418
419#[doc(hidden)]
420#[cfg(feature = "postgres")]
421#[macro_export]
422macro_rules! __db_text_type {
423 ($t:ty) => {
424 $crate::__db_text_type_for!($t, $crate::__sqlx::sqlite::Sqlite);
425 $crate::__db_text_type_for!($t, $crate::__sqlx::postgres::Postgres);
426 };
427}
428
429#[doc(hidden)]
430#[macro_export]
431macro_rules! __db_text_type_for {
432 ($t:ty, $db:ty) => {
433 impl $crate::__sqlx::Type<$db> for $t {
434 fn type_info() -> <$db as $crate::__sqlx::Database>::TypeInfo {
435 <::std::string::String as $crate::__sqlx::Type<$db>>::type_info()
436 }
437
438 fn compatible(ty: &<$db as $crate::__sqlx::Database>::TypeInfo) -> bool {
439 <::std::string::String as $crate::__sqlx::Type<$db>>::compatible(ty)
440 }
441 }
442
443 impl<'r> $crate::__sqlx::Decode<'r, $db> for $t {
444 fn decode(
445 value: <$db as $crate::__sqlx::Database>::ValueRef<'r>,
446 ) -> ::std::result::Result<Self, $crate::__sqlx::error::BoxDynError> {
447 let text = <::std::string::String as $crate::__sqlx::Decode<$db>>::decode(value)?;
448 text.parse::<$t>().map_err(::std::convert::Into::into)
449 }
450 }
451 };
452}
453
454#[cfg(test)]
455mod tests {
456 use std::sync::atomic::{AtomicU32, Ordering};
457 use std::time::Duration;
458
459 use super::{
460 is_busy, is_busy_or_pool_timeout, is_pool_timeout, redact, retry_while,
461 test_database_url_in,
462 };
463 use crate::db::error::fake;
464
465 #[test]
466 fn urls_lose_only_their_password() {
467 assert_eq!(
468 redact("postgres://app:secret@db:5432/app"),
469 "postgres://app:***@db:5432/app"
470 );
471 assert_eq!(redact("postgres://app@db/app"), "postgres://app:***@db/app");
474 assert_eq!(redact("postgres://db/app"), "postgres://db/app");
475 assert_eq!(redact("sqlite:app.db"), "sqlite:app.db");
476 }
477
478 #[test]
479 fn busy_errors_and_pool_timeouts() {
480 for code in ["5", "6", "517", "261"] {
481 assert!(is_busy(&fake::coded(Some(code))), "{code}");
482 }
483 assert!(!is_busy(&fake::coded(Some("19"))));
484 assert!(!is_busy(&fake::coded(Some("40001")))); assert!(!is_busy(&fake::coded(None)));
486 assert!(!is_busy(&sqlx::Error::PoolTimedOut));
487 assert!(is_busy_or_pool_timeout(&sqlx::Error::PoolTimedOut));
488 assert!(is_busy_or_pool_timeout(&fake::coded(Some("5"))));
489 assert!(!is_busy_or_pool_timeout(&sqlx::Error::PoolClosed));
490 }
491
492 #[test]
495 fn the_test_database_url_comes_from_the_environment_or_dotenv() {
496 let dir = tempfile::tempdir().unwrap();
497 let dotenv = dir.path().join(".env");
498 assert_eq!(test_database_url_in(None, &dotenv), None);
499 std::fs::write(
500 &dotenv,
501 "APP_NAME=x\nTEST_DATABASE_URL=postgres://t@localhost/t\n",
502 )
503 .unwrap();
504 assert_eq!(
505 test_database_url_in(None, &dotenv).as_deref(),
506 Some("postgres://t@localhost/t")
507 );
508 assert_eq!(
509 test_database_url_in(Some("postgres://env/e".into()), &dotenv).as_deref(),
510 Some("postgres://env/e")
511 );
512 std::fs::write(&dotenv, "APP_NAME=x\n").unwrap();
513 assert_eq!(test_database_url_in(None, &dotenv), None);
514 }
515
516 #[tokio::test]
519 async fn sqlite_makes_directories_and_caps_the_in_memory_wait() {
520 let dir = tempfile::tempdir().unwrap();
521 let config = crate::Config {
522 database_url: format!("sqlite://{}/a/b/app.db", dir.path().display()),
523 ..crate::Config::default()
524 };
525 let pool = super::connect_sqlite(&config, Default::default())
526 .await
527 .unwrap();
528 assert!(dir.path().join("a/b/app.db").exists());
529 pool.close().await;
530
531 let config = crate::Config {
532 database_url: "sqlite::memory:".into(),
533 database_acquire_timeout: Duration::from_secs(30),
534 ..crate::Config::default()
535 };
536 let pool = super::connect_sqlite(&config, Default::default())
537 .await
538 .unwrap();
539 assert_eq!(pool.options().get_acquire_timeout(), Duration::from_secs(2));
540 assert_eq!(pool.options().get_max_connections(), 1);
541 }
542
543 #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
545 async fn pools_opening_a_new_file_together_all_open_it() {
546 for _ in 0..10 {
547 let dir = tempfile::tempdir().unwrap();
548 let config = crate::Config {
549 database_url: format!("sqlite://{}/app.db", dir.path().display()),
550 database_acquire_timeout: Duration::from_secs(5),
551 ..crate::Config::default()
552 };
553 let opening: Vec<_> = (0..8)
554 .map(|_| {
555 let config = config.clone();
556 tokio::spawn(async move {
557 super::connect_sqlite(&config, Default::default())
558 .await
559 .map(|_| ())
560 })
561 })
562 .collect();
563 for task in opening {
564 task.await.unwrap().expect("every pool opens the new file");
565 }
566 }
567 }
568
569 #[tokio::test]
571 async fn opening_retries_pool_timeouts_within_the_budget() {
572 let tries = AtomicU32::new(0);
573 let opened = retry_while(Duration::from_secs(30), is_pool_timeout, || async {
574 match tries.fetch_add(1, Ordering::SeqCst) {
575 0 | 1 => Err(sqlx::Error::PoolTimedOut),
576 _ => Ok("pool"),
577 }
578 })
579 .await;
580 assert_eq!(opened.unwrap(), "pool");
581 assert_eq!(tries.load(Ordering::SeqCst), 3);
582 }
583
584 #[tokio::test]
585 async fn opening_gives_up_after_the_budget_and_on_other_errors() {
586 let tries = AtomicU32::new(0);
587 let opened: Result<(), _> = retry_while(Duration::ZERO, is_pool_timeout, || async {
588 tries.fetch_add(1, Ordering::SeqCst);
589 Err(sqlx::Error::PoolTimedOut)
590 })
591 .await;
592 assert!(matches!(opened, Err(sqlx::Error::PoolTimedOut)));
593 assert_eq!(
596 tries.load(Ordering::SeqCst),
597 3,
598 "three tries, then no retry past the budget"
599 );
600
601 let tries = AtomicU32::new(0);
602 let opened: Result<(), _> =
603 retry_while(Duration::from_secs(30), is_pool_timeout, || async {
604 tries.fetch_add(1, Ordering::SeqCst);
605 Err(sqlx::Error::PoolClosed)
606 })
607 .await;
608 assert!(matches!(opened, Err(sqlx::Error::PoolClosed)));
609 assert_eq!(
610 tries.load(Ordering::SeqCst),
611 1,
612 "other errors aren't retried"
613 );
614 }
615}