seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
Documentation
use indexmap::IndexMap;
use sqlx::sqlite::SqlitePool;
use sqlx::Row;

use crate::error::{Result, SeedKitError};
use crate::schema::introspect::SchemaIntrospector;
use crate::schema::types::*;

pub struct SqliteIntrospector {
    pool: SqlitePool,
}

/// Whether a table is one SQLite creates for itself, such as `sqlite_sequence`
/// for AUTOINCREMENT or `sqlite_stat1` for ANALYZE. SQLite reserves every name
/// starting with `sqlite_`, in any case, for these.
pub(crate) fn is_internal_table(name: &str) -> bool {
    name.get(..7)
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("sqlite_"))
}

impl SqliteIntrospector {
    pub fn new(pool: SqlitePool) -> Self {
        Self { pool }
    }

    async fn introspect_tables(&self) -> Result<IndexMap<String, Table>> {
        // `_` is a LIKE wildcard, so escape it: only SQLite's reserved
        // `sqlite_` names are internal, not every name starting "sqlite".
        let query = "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name";
        let rows = sqlx::query(query)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| SeedKitError::Introspection {
                query: "fetch tables".to_string(),
                source: e,
            })?;

        let mut tables = IndexMap::new();
        for row in rows {
            let name: String = row.get("name");
            let mut table = Table::new(name.clone());
            if let Some(ddl) = row.get::<Option<String>, _>("sql") {
                table.check_constraints = super::checks::sqlite_lists(&ddl);
            }
            tables.insert(name, table);
        }
        Ok(tables)
    }

    async fn introspect_columns(&self, tables: &mut IndexMap<String, Table>) -> Result<()> {
        let table_names: Vec<String> = tables.keys().cloned().collect();
        for table_name in table_names {
            let query = "SELECT * FROM pragma_table_xinfo(?) WHERE hidden != 1 ORDER BY cid";
            let rows = sqlx::query(query)
                .bind(&table_name)
                .fetch_all(&self.pool)
                .await
                .map_err(|e| SeedKitError::Introspection {
                    query: format!("PRAGMA table_xinfo({})", table_name),
                    source: e,
                })?;

            let mut pk_columns = Vec::new();
            for row in rows {
                let cid: i32 = row.get("cid");
                let name: String = row.get("name");
                let type_str: String = row.get("type");
                let notnull: i32 = row.get("notnull");
                let dflt_value: Option<String> = row.get("dflt_value");
                let pk: i32 = row.get("pk");

                let data_type = DataType::from_raw(&type_str);
                let is_auto = pk > 0 && type_str.eq_ignore_ascii_case("INTEGER");

                let mut column = Column::new(name.clone(), data_type, type_str);
                column.nullable = notnull == 0;
                column.has_default = dflt_value.is_some();
                column.is_auto_increment = is_auto;
                column.is_generated = matches!(row.get::<i32, _>("hidden"), 2 | 3);
                column.ordinal_position = cid as u32;

                if let Some(table) = tables.get_mut(&table_name) {
                    // Set primary key if pk > 0
                    if pk > 0 {
                        pk_columns.push((pk, name.clone()));
                    }
                    table.columns.insert(name, column);
                }
            }
            if !pk_columns.is_empty() {
                pk_columns.sort_by_key(|(position, _)| *position);
                tables[&table_name].primary_key = Some(PrimaryKey {
                    columns: pk_columns.into_iter().map(|(_, name)| name).collect(),
                    name: None,
                });
            }
        }

        Ok(())
    }

    async fn introspect_foreign_keys(&self, tables: &mut IndexMap<String, Table>) -> Result<()> {
        let table_names: Vec<String> = tables.keys().cloned().collect();
        for table_name in table_names {
            let rows = sqlx::query("SELECT * FROM pragma_foreign_key_list(?)")
                .bind(&table_name)
                .fetch_all(&self.pool)
                .await
                .map_err(|e| SeedKitError::Introspection {
                    query: format!("PRAGMA foreign_key_list({})", table_name),
                    source: e,
                })?;

            // Group by id (FK id)
            let mut fk_map: IndexMap<i32, ForeignKey> = IndexMap::new();
            for row in &rows {
                let id: i32 = row.get("id");
                let table: String = row.get("table");
                let from: String = row.get("from");
                let to: Option<String> = row.get("to");
                // REFERENCES parent without a column list targets its primary key.
                let to = to
                    .or_else(|| {
                        let seq: i32 = row.get("seq");
                        tables
                            .get(&table)?
                            .primary_key
                            .as_ref()?
                            .columns
                            .get(seq as usize)
                            .cloned()
                    })
                    .ok_or_else(|| {
                        SeedKitError::Other(format!(
                            "Missing referenced primary key for {table_name}.{from}"
                        ))
                    })?;
                let on_delete: String = row.get("on_delete");
                let on_update: String = row.get("on_update");

                let entry = fk_map.entry(id).or_insert_with(|| ForeignKey {
                    name: None,
                    source_columns: Vec::new(),
                    referenced_schema: None,
                    referenced_table: table,
                    referenced_columns: Vec::new(),
                    on_delete: ForeignKeyAction::parse_action(&on_delete),
                    on_update: ForeignKeyAction::parse_action(&on_update),
                    is_deferrable: false,
                });
                entry.source_columns.push(from);
                entry.referenced_columns.push(to);
            }

            if let Some(table) = tables.get_mut(&table_name) {
                for (_, fk) in fk_map {
                    table.foreign_keys.push(fk);
                }
            }
        }

        Ok(())
    }

    async fn introspect_unique_constraints(
        &self,
        tables: &mut IndexMap<String, Table>,
    ) -> Result<()> {
        let table_names: Vec<String> = tables.keys().cloned().collect();
        for table_name in table_names {
            let indexes = sqlx::query("SELECT * FROM pragma_index_list(?)")
                .bind(&table_name)
                .fetch_all(&self.pool)
                .await
                .map_err(|e| SeedKitError::Introspection {
                    query: format!("PRAGMA index_list({})", table_name),
                    source: e,
                })?;

            for idx_row in &indexes {
                let unique: i32 = idx_row.get("unique");
                let idx_name: String = idx_row.get("name");

                if unique == 1 {
                    let cols = sqlx::query("SELECT * FROM pragma_index_info(?)")
                        .bind(&idx_name)
                        .fetch_all(&self.pool)
                        .await
                        .map_err(|e| SeedKitError::Introspection {
                            query: format!("PRAGMA index_info({})", idx_name),
                            source: e,
                        })?;

                    // Expression keys have no column name. Generation cannot
                    // evaluate them, so skip the index like PostgreSQL does.
                    let Some(columns) = cols
                        .iter()
                        .map(|r| r.get::<Option<String>, _>("name"))
                        .collect::<Option<Vec<String>>>()
                    else {
                        continue;
                    };

                    if let Some(table) = tables.get_mut(&table_name) {
                        // A true INTEGER PRIMARY KEY aliases the rowid and
                        // has no backing PK index (including the DESC exception).
                        if idx_row.get::<String, _>("origin") == "pk" {
                            for name in &columns {
                                if let Some(column) = table.columns.get_mut(name) {
                                    column.is_auto_increment = false;
                                }
                            }
                        }
                        table.unique_constraints.push(UniqueConstraint {
                            name: Some(idx_name),
                            columns,
                        });
                    }
                }
            }
        }

        Ok(())
    }
}

impl SchemaIntrospector for SqliteIntrospector {
    async fn introspect(&self) -> Result<DatabaseSchema> {
        let mut schema = DatabaseSchema::new(DatabaseType::SQLite, "sqlite".to_string());

        schema.tables = self.introspect_tables().await?;
        self.introspect_columns(&mut schema.tables).await?;
        self.introspect_foreign_keys(&mut schema.tables).await?;
        self.introspect_unique_constraints(&mut schema.tables)
            .await?;

        Ok(schema)
    }
}