use larust_core::AppError;
use sqlx::any::{AnyConnectOptions, AnyPoolOptions};
use sqlx::AnyPool;
use std::future::Future;
use std::str::FromStr;
use std::sync::OnceLock;
static POOL: OnceLock<AnyPool> = OnceLock::new();
static READ_POOL: OnceLock<AnyPool> = OnceLock::new();
static BACKEND: OnceLock<Backend> = OnceLock::new();
const SQLITE_READ_MAX_CONNECTIONS: u32 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend {
Sqlite,
MySql,
Postgres,
}
tokio::task_local! {
static POOL_OVERRIDE: &'static AnyPool;
static BACKEND_OVERRIDE: Backend;
}
pub async fn connect(database_url: &str) -> Result<(), AppError> {
sqlx::any::install_default_drivers();
let backend = ensure_backend(database_url)?;
let normalized;
let database_url = match backend {
Backend::Sqlite => {
normalized = normalize_sqlite_url(database_url);
normalized.as_str()
}
Backend::MySql | Backend::Postgres => database_url,
};
let connect_url = match backend {
Backend::Sqlite => append_sqlite_url_param(database_url, "mode=rwc"),
Backend::MySql | Backend::Postgres => database_url.to_string(),
};
let options =
AnyConnectOptions::from_str(&connect_url).map_err(|e| AppError::Config(Box::new(e)))?;
let max_connections = match backend {
Backend::Sqlite => 1,
Backend::MySql | Backend::Postgres => 10,
};
let pool = AnyPoolOptions::new()
.min_connections(1)
.max_connections(max_connections)
.after_connect(move |conn, _meta| {
Box::pin(async move {
use sqlx::Executor;
match backend {
Backend::Sqlite => {
conn.execute(
"PRAGMA journal_mode = WAL; \
PRAGMA busy_timeout = 5000; \
PRAGMA foreign_keys = ON;",
)
.await?;
}
Backend::MySql => {
conn.execute("SET SESSION sql_mode = CONCAT(@@sql_mode, ',ANSI_QUOTES')")
.await?;
}
Backend::Postgres => {
}
}
Ok(())
})
})
.connect_with(options)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
let read_pool = if backend == Backend::Sqlite {
let read_only_url = append_sqlite_url_param(database_url, "mode=ro");
let read_only_options = AnyConnectOptions::from_str(&read_only_url)
.map_err(|e| AppError::Config(Box::new(e)))?;
Some(
AnyPoolOptions::new()
.min_connections(1)
.max_connections(SQLITE_READ_MAX_CONNECTIONS)
.after_connect(|conn, _meta| {
Box::pin(async move {
use sqlx::Executor;
conn.execute("PRAGMA busy_timeout = 5000;").await?;
Ok(())
})
})
.connect_with(read_only_options)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?,
)
} else {
None
};
POOL.set(pool).map_err(|_| {
AppError::Internal(Box::new(std::io::Error::other(
"connect() called more than once",
)))
})?;
if let Some(read_pool) = read_pool {
READ_POOL.set(read_pool).ok();
}
Ok(())
}
pub fn backend() -> Backend {
if let Ok(overridden) = BACKEND_OVERRIDE.try_with(|backend| *backend) {
return overridden;
}
*BACKEND
.get()
.expect("larust_orm::backend() called before connect()")
}
pub fn ensure_backend(database_url: &str) -> Result<Backend, AppError> {
let backend = parse_backend(database_url)?;
BACKEND.set(backend).ok();
Ok(backend)
}
pub fn normalize_sqlite_url(database_url: &str) -> String {
let forward_slashes = database_url.replace('\\', "/");
let path = forward_slashes
.strip_prefix("sqlite://")
.unwrap_or(&forward_slashes);
let is_windows_drive_absolute = path.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
&& path.as_bytes().get(1) == Some(&b':');
if is_windows_drive_absolute {
format!("sqlite:///{path}")
} else {
forward_slashes
}
}
fn append_sqlite_url_param(database_url: &str, param: &str) -> String {
if database_url.contains('?') {
format!("{database_url}&{param}")
} else {
format!("{database_url}?{param}")
}
}
pub fn placeholder(backend: Backend, n: usize) -> String {
match backend {
Backend::Sqlite | Backend::MySql => "?".to_string(),
Backend::Postgres => format!("${n}"),
}
}
fn parse_backend(database_url: &str) -> Result<Backend, AppError> {
if database_url.starts_with("sqlite:") {
Ok(Backend::Sqlite)
} else if database_url.starts_with("mysql:") {
Ok(Backend::MySql)
} else if database_url.starts_with("postgres:") || database_url.starts_with("postgresql:") {
Ok(Backend::Postgres)
} else {
Err(AppError::Config(Box::new(std::io::Error::other(format!(
"unsupported DATABASE_URL scheme in {database_url:?} - expected \
\"sqlite:\", \"mysql:\", \"postgres:\", or \"postgresql:\""
)))))
}
}
pub fn pool() -> Result<&'static AnyPool, AppError> {
if let Ok(overridden) = POOL_OVERRIDE.try_with(|pool| *pool) {
return Ok(overridden);
}
POOL.get().ok_or_else(|| {
AppError::Internal(Box::new(std::io::Error::other(
"database not connected; call larust_orm::connect() \
(via larust_support::orm::connect) at startup before serving requests",
)))
})
}
pub fn read_pool() -> Result<&'static AnyPool, AppError> {
if let Ok(overridden) = POOL_OVERRIDE.try_with(|pool| *pool) {
return Ok(overridden);
}
match READ_POOL.get() {
Some(read_pool) => Ok(read_pool),
None => pool(),
}
}
pub async fn with_pool_override<F: Future>(
pool: &'static AnyPool,
backend: Backend,
fut: F,
) -> F::Output {
POOL_OVERRIDE
.scope(pool, BACKEND_OVERRIDE.scope(backend, fut))
.await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_backend_recognizes_sqlite() {
assert_eq!(
parse_backend("sqlite://database/database.sqlite").unwrap(),
Backend::Sqlite
);
}
#[test]
fn parse_backend_recognizes_mysql() {
assert_eq!(
parse_backend("mysql://root@127.0.0.1/app").unwrap(),
Backend::MySql
);
}
#[test]
fn parse_backend_recognizes_postgres() {
assert_eq!(
parse_backend("postgres://root@127.0.0.1/app").unwrap(),
Backend::Postgres
);
assert_eq!(
parse_backend("postgresql://root@127.0.0.1/app").unwrap(),
Backend::Postgres
);
}
#[test]
fn normalize_sqlite_url_leaves_a_relative_path_alone() {
assert_eq!(
normalize_sqlite_url("sqlite://database/database.sqlite"),
"sqlite://database/database.sqlite"
);
}
#[test]
fn normalize_sqlite_url_converts_backslashes_in_a_windows_absolute_path() {
assert_eq!(
normalize_sqlite_url(r"sqlite://C:\Users\me\AppData\Local\Temp\abc\test.sqlite"),
"sqlite:///C:/Users/me/AppData/Local/Temp/abc/test.sqlite"
);
}
#[test]
fn normalize_sqlite_url_adds_the_third_slash_for_a_drive_absolute_path_already_using_forward_slashes(
) {
assert_eq!(
normalize_sqlite_url("sqlite://C:/Users/me/test.sqlite"),
"sqlite:///C:/Users/me/test.sqlite"
);
}
#[test]
fn normalize_sqlite_url_leaves_a_unix_style_absolute_path_alone() {
assert_eq!(
normalize_sqlite_url("sqlite:///var/lib/app/database.sqlite"),
"sqlite:///var/lib/app/database.sqlite"
);
}
#[test]
fn parse_backend_rejects_an_unsupported_scheme() {
assert!(parse_backend("mongodb://localhost/app").is_err());
}
#[test]
fn append_sqlite_url_param_adds_the_first_query_param_with_a_question_mark() {
assert_eq!(
append_sqlite_url_param("sqlite://database/database.sqlite", "mode=rwc"),
"sqlite://database/database.sqlite?mode=rwc"
);
}
#[test]
fn append_sqlite_url_param_adds_a_second_query_param_with_an_ampersand() {
assert_eq!(
append_sqlite_url_param("sqlite://database/database.sqlite?cache=shared", "mode=ro"),
"sqlite://database/database.sqlite?cache=shared&mode=ro"
);
}
}