use std::time::Duration;
use crate::sql::config::Engine;
pub enum ConnectionPool {
Postgres(sqlx::PgPool),
Mysql(sqlx::MySqlPool),
Sqlite(sqlx::SqlitePool),
}
const ACQUIRE_TIMEOUT: Duration = Duration::from_secs(10);
const STATEMENT_TIMEOUT_MS: u64 = 30_000;
fn mysql_timeout_statements() -> [String; 2] {
[
format!("SET SESSION max_execution_time = {STATEMENT_TIMEOUT_MS}"),
format!(
"SET SESSION max_statement_time = {}",
STATEMENT_TIMEOUT_MS / 1000
),
]
}
async fn apply_mysql_statement_timeout(conn: &mut sqlx::MySqlConnection) {
for statement in mysql_timeout_statements() {
match sqlx::query(&statement).execute(&mut *conn).await {
Ok(_) => return,
Err(err) => {
tracing::debug!(%statement, error = %err, "mysql statement timeout variable not accepted");
}
}
}
tracing::warn!(
"mysql server accepts neither max_execution_time nor max_statement_time; \
no server-side statement timeout is in effect"
);
}
pub async fn build(engine: Engine, dsn: &str, read_only: bool) -> Result<ConnectionPool, String> {
match engine {
Engine::Postgres => sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(ACQUIRE_TIMEOUT)
.after_connect(|conn, _meta| {
Box::pin(async move {
sqlx::query(&format!("SET statement_timeout = {STATEMENT_TIMEOUT_MS}"))
.execute(conn)
.await?;
Ok(())
})
})
.connect(dsn)
.await
.map(ConnectionPool::Postgres)
.map_err(|e| format!("postgres connect: {e}")),
Engine::Mysql => sqlx::mysql::MySqlPoolOptions::new()
.max_connections(5)
.acquire_timeout(ACQUIRE_TIMEOUT)
.after_connect(|conn, _meta| {
Box::pin(async move {
apply_mysql_statement_timeout(conn).await;
Ok(())
})
})
.connect(dsn)
.await
.map(ConnectionPool::Mysql)
.map_err(|e| format!("mysql connect: {e}")),
Engine::Sqlite => {
let opts = dsn
.parse::<sqlx::sqlite::SqliteConnectOptions>()
.map_err(|e| format!("sqlite dsn: {e}"))?
.read_only(read_only)
.pragma("query_only", "ON");
sqlx::sqlite::SqlitePoolOptions::new()
.max_connections(5)
.acquire_timeout(ACQUIRE_TIMEOUT)
.connect_with(opts)
.await
.map(ConnectionPool::Sqlite)
.map_err(|e| format!("sqlite connect: {e}"))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mysql_timeout_covers_mysql_then_mariadb_variables() {
let [mysql, mariadb] = mysql_timeout_statements();
assert_eq!(mysql, "SET SESSION max_execution_time = 30000");
assert_eq!(mariadb, "SET SESSION max_statement_time = 30");
}
#[tokio::test]
async fn builds_sqlite_pool_readonly() {
let dir = std::env::temp_dir();
let path = dir.join(format!("sqlgw_pool_test_{}.db", std::process::id()));
let rw_url = format!("sqlite://{}?mode=rwc", path.display());
{
let rw = sqlx::sqlite::SqlitePool::connect(&rw_url).await.unwrap();
sqlx::query("CREATE TABLE IF NOT EXISTS t (id INTEGER)")
.execute(&rw)
.await
.unwrap();
rw.close().await;
}
let ro_url = format!("sqlite://{}", path.display());
let pool = build(Engine::Sqlite, &ro_url, true).await.unwrap();
assert!(matches!(pool, ConnectionPool::Sqlite(_)));
let _ = std::fs::remove_file(&path);
}
#[tokio::test]
async fn builds_sqlite_pool_in_memory() {
let pool = build(Engine::Sqlite, "sqlite::memory:", false)
.await
.unwrap();
assert!(matches!(pool, ConnectionPool::Sqlite(_)));
}
}