use sea_orm::{Database, DatabaseConnection, DbBackend, DbErr};
use sea_orm_migration::MigratorTrait;
pub async fn connect(url: &str) -> Result<DatabaseConnection, DbErr> {
Database::connect(url).await.map_err(|e| {
if !e.to_string().contains("no supporting driver") {
return e;
}
let feature = match url.split(':').next().unwrap_or("") {
"postgres" | "postgresql" => "postgres",
"mysql" | "mariadb" => "mysql",
"sqlite" => "sqlite",
_ => {
return DbErr::Custom(
"unsupported DATABASE_URL scheme (use sqlite:, postgres: or mysql:)".into(),
);
}
};
DbErr::Custom(format!(
"DATABASE_URL uses `{feature}` but ryuk was built without the `{feature}` feature"
))
})
}
pub fn backend(db: &DatabaseConnection) -> &'static str {
match db.get_database_backend() {
DbBackend::Sqlite => "sqlite",
DbBackend::Postgres => "postgres",
_ => "mysql",
}
}
#[cfg(feature = "tenancy")]
pub(crate) async fn ensure_index(
db: &DatabaseConnection,
table: &str,
mut index: sea_orm::sea_query::IndexCreateStatement,
) -> Result<(), DbErr> {
use sea_orm::ConnectionTrait;
use sea_orm::sea_query::{Alias, Expr, ExprTrait, Func, Query};
if db.get_database_backend() != DbBackend::MySql {
if let Err(e) = db.execute(index.if_not_exists()).await {
if db.execute(index.if_not_exists()).await.is_err() {
return Err(e);
}
}
return Ok(());
}
let name = index
.get_index_spec()
.get_name()
.unwrap_or_default()
.to_owned();
let has = || async {
let q = Query::select()
.column(Alias::new("index_name"))
.from((Alias::new("information_schema"), Alias::new("statistics")))
.and_where(Expr::col(Alias::new("table_schema")).eq(Func::cust(Alias::new("DATABASE"))))
.and_where(Expr::col(Alias::new("table_name")).eq(table))
.and_where(Expr::col(Alias::new("index_name")).eq(name.as_str()))
.limit(1)
.to_owned();
db.query_all(&q).await.map(|r| !r.is_empty())
};
if !has().await?
&& let Err(e) = db.execute(&index).await
&& !has().await?
{
return Err(e);
}
Ok(())
}
pub async fn migrate<M: MigratorTrait>(db: &DatabaseConnection) -> Result<(), DbErr> {
M::up(db, None).await
}
#[cfg(all(test, feature = "sqlite"))]
mod tests {
#[tokio::test]
async fn backend_and_bad_scheme() {
let db = super::connect("sqlite::memory:").await.unwrap();
assert_eq!(super::backend(&db), "sqlite");
let e = super::connect("oracle://x").await.unwrap_err().to_string();
assert!(e.contains("unsupported"), "{e}");
}
}