ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! SeaORM connection and migrations.
use sea_orm::{Database, DatabaseConnection, DbBackend, DbErr};
use sea_orm_migration::MigratorTrait;

/// Connect: `let db = ryuk::db::connect(&cfg.database_url).await?;`
///
/// The URL scheme (`sqlite:`, `postgres:`, `mysql:`) picks the driver; a scheme whose
/// driver feature is not compiled in gives an error naming the feature to enable.
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"
        ))
    })
}

/// `"sqlite"`, `"postgres"` or `"mysql"` for the connection's backend.
pub fn backend(db: &DatabaseConnection) -> &'static str {
    match db.get_database_backend() {
        DbBackend::Sqlite => "sqlite",
        DbBackend::Postgres => "postgres",
        _ => "mysql",
    }
}

/// Create a (non-unique) index if it is missing, on any backend and safe when two instances start at once.
/// `CREATE INDEX IF NOT EXISTS` does not exist on MySQL, and inline `INDEX` in `CREATE TABLE` exists only there,
/// so MySQL is looked up in `information_schema` first. `table` is the name the index is on.
#[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 {
            // Two instances creating it at once can collide inside the database; the retry is a no-op.
            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(())
}

/// Apply all pending migrations: `ryuk::db::migrate::<Migrator>(&db).await?;`
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}");
    }
}