doido-auth 0.0.17

Unified authentication for Doido — AuthUser trait, extractors, strategies, and auth generators.
Documentation
//! Migration file rendering and registration — mirrors `doido-generators` helpers
//! without depending on that crate.

use super::template;

/// Directory holding the SeaORM migration crate's sources.
pub const MIGRATION_SRC_DIR: &str = "db/migration/src";

/// Fallback migration `lib.rs` used when the app doesn't have one on disk yet.
pub const MIGRATION_LIB_BASE: &str = include_str!("../../templates/new/db/migration/src/lib.rs");

/// Renders a full migration file from the imports line and the `up`/`down` bodies.
pub fn render_migration_file(
    migration_name: &str,
    imports: &str,
    up_body: &str,
    down_body: &str,
) -> String {
    template("migration.rs.template")
        .replace("{migration_name}", migration_name)
        .replace("{migration_imports}", imports)
        .replace("{up_body}", up_body)
        .replace("{down_body}", down_body)
}

/// Inserts a `mod <module>;` declaration and a `Box::new(<module>::Migration)`
/// registration into the migration crate's `lib.rs`, just above the generator markers.
pub fn register_migration(lib: &str, module: &str) -> String {
    let mut lines: Vec<String> = lib.lines().map(String::from).collect();

    if let Some(i) = lines
        .iter()
        .position(|l| l.contains("@generated-migrations-mod"))
    {
        let decl = format!("mod {module};");
        if !lines.iter().any(|l| l.trim() == decl) {
            lines.insert(i, decl);
        }
    }

    if let Some(i) = lines
        .iter()
        .position(|l| l.contains("@generated-migrations-list"))
    {
        let indent: String = lines[i].chars().take_while(|c| c.is_whitespace()).collect();
        let entry = format!("{indent}Box::new({module}::Migration),");
        if !lines.iter().any(|l| l.trim() == entry.trim()) {
            lines.insert(i, entry);
        }
    }

    let mut out = lines.join("\n");
    out.push('\n');
    out
}

/// The `doido_model::migration` import line for a `create_table` migration.
pub fn create_table_imports(fields: &[super::Field]) -> String {
    if fields.iter().any(super::Field::wants_index) {
        "use doido::model::migration::{add_index, create_table, drop_table};".to_string()
    } else {
        "use doido::model::migration::{create_table, drop_table};".to_string()
    }
}

/// Builds the `up()` body for a `create_table` migration.
pub fn create_table_up(table_name: &str, fields: &[super::Field]) -> String {
    if fields.is_empty() {
        return format!(
            "        // `create_table` adds an auto-incrementing `id` primary key for you.\n\
             \x20       create_table(manager, \"{table_name}\", |_t| {{}}).await\n"
        );
    }

    let columns: String = fields
        .iter()
        .map(|f| format!("            {}\n", f.migration_line()))
        .collect();

    let indexes: Vec<&super::Field> = fields.iter().filter(|f| f.wants_index()).collect();

    let mut body = String::new();
    body.push_str(
        "        // `create_table` adds an auto-incrementing `id` primary key for you.\n",
    );
    body.push_str(&format!(
        "        create_table(manager, \"{table_name}\", |t| {{\n{columns}        }})\n"
    ));

    if indexes.is_empty() {
        body.push_str("        .await\n");
    } else {
        body.push_str("        .await?;\n");
        for f in indexes {
            body.push_str(&format!(
                "        add_index(manager, \"{table_name}\", &[\"{}\"]).await?;\n",
                f.column_name()
            ));
        }
        body.push_str("        Ok(())\n");
    }

    body
}

/// The `down()` body that drops a table.
pub fn drop_table_down(table_name: &str) -> String {
    format!("        drop_table(manager, \"{table_name}\").await\n")
}