seedkit 2.1.1

Generate realistic, constraint-safe seed data for PostgreSQL, MySQL, and SQLite
use std::path::Path;

use anyhow::{Context, Result};
use seedkit_core::config::{read_config, SeedKitConfig};
use seedkit_core::schema::introspect::{database_type_from_url, SchemaIntrospector};
use seedkit_core::schema::types::{DatabaseSchema, DatabaseType};

use crate::args::{Dialect, SchemaFile};

/// Message for commands that need a live connection.
pub fn needs_database(action: &str) -> anyhow::Error {
    anyhow::anyhow!(
        "{action} writes to or reads from a database, so it can't be used with --schema-file"
    )
}

pub async fn introspect_configured(
    db: Option<&str>,
    namespace: Option<&str>,
    file: &SchemaFile,
) -> Result<DatabaseSchema> {
    let config = read_config(Path::new("."))?;
    Ok(introspect(db, namespace, config.as_ref(), file).await?.1)
}

/// The database URL and schema. With `--schema-file`, the schema comes from
/// the file, no connection is made, and the URL is empty.
pub async fn introspect(
    db: Option<&str>,
    namespace: Option<&str>,
    config: Option<&SeedKitConfig>,
    file: &SchemaFile,
) -> Result<(String, DatabaseSchema)> {
    let namespace = namespace
        .or_else(|| config.and_then(|cfg| cfg.database.schema.as_deref()))
        .unwrap_or("public");
    if let (Some(path), Some(dialect)) = (&file.schema_file, file.dialect) {
        let sql = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read schema file {}", path.display()))?;
        let database_type = match dialect {
            Dialect::Postgres => DatabaseType::PostgreSQL,
            Dialect::Mysql => DatabaseType::MySQL,
            Dialect::Sqlite => DatabaseType::SQLite,
        };
        let name = path
            .file_stem()
            .map(|stem| stem.to_string_lossy().into_owned())
            .unwrap_or_else(|| "schema".into());
        let schema = seedkit_core::schema::ddl::parse_schema(&sql, database_type, &name, namespace)
            .with_context(|| format!("Reading {}", path.display()))?;
        return Ok((String::new(), schema));
    }
    let db_url = resolve_db_url(db, config)?;
    let schema = match database_type_from_url(&db_url)? {
        DatabaseType::PostgreSQL => {
            let pool = sqlx::postgres::PgPoolOptions::new()
                .max_connections(5)
                .connect(&db_url)
                .await
                .context("Failed to connect to PostgreSQL")?;
            let introspector = seedkit_core::schema::postgres::PostgresIntrospector::with_schema(
                pool,
                namespace.to_owned(),
            );
            introspector.introspect().await?
        }
        DatabaseType::MySQL => {
            let pool = sqlx::mysql::MySqlPoolOptions::new()
                .max_connections(5)
                .connect(&db_url)
                .await
                .context("Failed to connect to MySQL")?;
            let db_name = extract_mysql_db_name(&db_url).unwrap_or("mysql".to_string());
            let introspector = seedkit_core::schema::mysql::MySqlIntrospector::new(pool, db_name);
            introspector.introspect().await?
        }
        DatabaseType::SQLite => {
            let pool = sqlx::sqlite::SqlitePoolOptions::new()
                .max_connections(1)
                .connect(&db_url)
                .await
                .context("Failed to connect to SQLite")?;
            let introspector = seedkit_core::schema::sqlite::SqliteIntrospector::new(pool);
            introspector.introspect().await?
        }
    };
    Ok((db_url, schema))
}

fn resolve_db_url(
    explicit: Option<&str>,
    config: Option<&seedkit_core::config::SeedKitConfig>,
) -> Result<String> {
    if let Some(url) = explicit {
        return Ok(url.to_string());
    }

    // Try environment variable
    if let Ok(url) = std::env::var("DATABASE_URL") {
        return Ok(url);
    }

    // Try .env file
    if dotenvy::dotenv().is_ok() {
        if let Ok(url) = std::env::var("DATABASE_URL") {
            return Ok(url);
        }
    }

    // Try seedkit.toml
    if let Some(cfg) = config {
        if let Some(ref url) = cfg.database.url {
            return Ok(url.clone());
        }
    }

    Err(seedkit_core::error::SeedKitError::NoDatabaseUrl.into())
}

fn extract_mysql_db_name(url: &str) -> Option<String> {
    // mysql://user:pass@host:port/database
    url.rsplit('/')
        .next()
        .map(|s| s.split('?').next().unwrap_or(s).to_string())
}