multidb
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
use sqlx::{any::AnyPoolOptions, AnyPool};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DatabaseKind {
|
||||
Sqlite,
|
||||
Postgres,
|
||||
MySql,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Database {
|
||||
pool: AnyPool,
|
||||
kind: DatabaseKind,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
pub async fn connect(url: &str, max_connections: u32) -> Result<Self, sqlx::Error> {
|
||||
sqlx::any::install_default_drivers();
|
||||
let kind = DatabaseKind::from_url(url)?;
|
||||
let pool = AnyPoolOptions::new()
|
||||
.max_connections(max_connections)
|
||||
.connect(url)
|
||||
.await?;
|
||||
if kind == DatabaseKind::Sqlite {
|
||||
sqlx::query("PRAGMA foreign_keys = ON").execute(&pool).await?;
|
||||
sqlx::query("PRAGMA journal_mode = WAL").execute(&pool).await?;
|
||||
sqlx::query("PRAGMA busy_timeout = 5000").execute(&pool).await?;
|
||||
}
|
||||
Ok(Self { pool, kind })
|
||||
}
|
||||
|
||||
pub fn pool(&self) -> &AnyPool { &self.pool }
|
||||
pub fn kind(&self) -> DatabaseKind { self.kind }
|
||||
}
|
||||
|
||||
impl DatabaseKind {
|
||||
fn from_url(url: &str) -> Result<Self, sqlx::Error> {
|
||||
if url.starts_with("sqlite:") { Ok(Self::Sqlite) }
|
||||
else if url.starts_with("postgres:") || url.starts_with("postgresql:") { Ok(Self::Postgres) }
|
||||
else if url.starts_with("mysql:") { Ok(Self::MySql) }
|
||||
else { Err(sqlx::Error::Configuration("DATABASE_URL must use sqlite://, postgres:// or mysql://".into())) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user