//! Additive database evolution. Application-owned feature code receives an exact review note.
use super::{plural_table, reference_model_info, Field, Kind};
use crate::{edit::EditPlan, names::GeneratedNames};
use anyhow::{bail, Context, Result};
use std::path::{Path, PathBuf};
/// Add a composite index or unique constraint to an existing resource table.
pub fn add_index(
root: &Path,
resource: &str,
columns: &str,
unique: bool,
acknowledge_unique: bool,
) -> Result<Vec<PathBuf>> {
if unique && !acknowledge_unique {
bail!("A unique index can fail on duplicate existing data. Review duplicates and pass --acknowledge-unique to generate it. No files changed.");
}
let resource = GeneratedNames::new(resource)?;
let table = plural_table(&resource.module);
let columns = columns.split(',').map(str::to_owned).collect::<Vec<_>>();
if !(2..=4).contains(&columns.len()) {
bail!("Composite indexes require 2..=4 comma-separated columns, such as owner_id,created_at. No files changed.");
}
let mut seen = std::collections::BTreeSet::new();
for column in &columns {
crate::names::validate_name(column, false)?;
if column != &heck::ToSnakeCase::to_snake_case(column.as_str()) || !seen.insert(column) {
bail!("Composite index columns must be distinct lowercase snake_case names. No files changed.");
}
}
let mut plan = EditPlan::new(root)?;
let source = plan.read(&format!("app/models/{}.rs", resource.module))?;
let parsed = syn::parse_file(&source)?;
let model = parsed
.items
.into_iter()
.find_map(|item| match item {
syn::Item::Struct(item) if item.ident == "Model" => Some(item),
_ => None,
})
.context("Resource Model is missing; no files changed")?;
let syn::Fields::Named(fields) = model.fields else {
bail!("Resource Model must have named fields; no files changed.")
};
for column in &columns {
if !fields
.named
.iter()
.any(|field| field.ident.as_ref().is_some_and(|name| name == column))
{
bail!("Model {} has no `{column}` field. Add it to the model or use an application-owned migration. No files changed.", resource.ty);
}
}
let stem = format!("{}_{}", table, columns.join("_"));
let index_name = format!("idx_{stem}");
if index_name.len() > 63 {
bail!("Composite index name exceeds PostgreSQL's 63-byte identifier limit. Use a shorter resource/column name or an application-owned migration. No files changed.");
}
let migration = format!("m_{}_{}", if unique { "unique" } else { "index" }, stem);
let column_chain = columns
.iter()
.map(|column| format!(".col(Alias::new({column:?}))"))
.collect::<Vec<_>>()
.join("");
let source = format!("//! Composite {} for {table}; generated, never applied automatically.\nuse capy::migration::{{self as sea_orm_migration, prelude::*}};\n#[derive(DeriveMigrationName)] pub struct Migration;\n#[async_trait::async_trait] impl MigrationTrait for Migration {{\nasync fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {{ manager.create_index(Index::create().name({index_name:?}).table(Alias::new({table:?})){column_chain}{}.to_owned()).await }}\nasync fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {{ manager.drop_index(Index::drop().name({index_name:?}).table(Alias::new({table:?})).to_owned()).await }}\n}}", if unique { "unique constraint" } else { "index" }, if unique { ".unique()" } else { "" });
plan.create(&format!("database/migrations/{migration}.rs"), source)?;
plan.create(&format!("database/evolution/{migration}.md"), format!("# Composite {} on {}\n\nColumns: `{}`. The migration is generated and registered but not applied. Review it and run `capy db:migrate` when ready. Existing application feature code was not rewritten.{}\n", if unique { "uniqueness" } else { "index" }, resource.ty, columns.join(", "), if unique { "\n\n**Data-dependent risk:** inspect and resolve duplicate existing values before applying this unique index. The database will reject the migration if duplicates remain." } else { "" }))?;
plan.anchor(
"database/migrations/mod.rs",
"// capy:modules",
&format!("mod {migration};"),
)?;
plan.anchor(
"database/migrations/mod.rs",
"// capy:migrations",
&format!("Box::new({migration}::Migration),"),
)?;
plan.commit()
}
/// Generate one additive migration and a review note without rewriting customized feature code.
/// Required columns without a default need an application-specific backfill and are rejected.
pub fn add_field(
root: &Path,
resource: &str,
definition: &str,
acknowledge_unique: bool,
) -> Result<Vec<PathBuf>> {
let resource = GeneratedNames::new(resource)?;
let mut field = Field::parse_all(&[definition.to_owned()])?.remove(0);
if field.kind == Kind::Enum {
field.enum_resource = Some(resource.module.clone());
}
if !field.nullable && field.default.is_none() {
bail!("Adding a required column without a default needs a backfill. Add it nullable first, backfill existing rows in an application-owned migration, then make it required. No files changed.");
}
if field.unique && !acknowledge_unique {
bail!("A unique index can fail on existing data. Review duplicates and pass --acknowledge-unique to generate the migration. No files changed.");
}
let mut plan = EditPlan::new(root)?;
let model_path = format!("app/models/{}.rs", resource.module);
let model = plan.read(&model_path).with_context(|| {
format!(
"Resource {} has no model; generate it first. No files changed.",
resource.ty
)
})?;
let table = plural_table(&resource.module);
let parsed = syn::parse_file(&model)?;
let model_item = parsed
.items
.into_iter()
.find_map(|item| match item {
syn::Item::Struct(item) if item.ident == "Model" => Some(item),
_ => None,
})
.context("Resource model is missing `Model`; no files changed")?;
let mut actual_table = None;
for attribute in &model_item.attrs {
if attribute.path().is_ident("sea_orm") {
attribute.parse_nested_meta(|meta| {
if meta.path.is_ident("table_name") {
let value: syn::LitStr = meta.value()?.parse()?;
actual_table = Some(value.value());
}
Ok(())
})?;
}
}
if actual_table.as_deref() != Some(&table) {
bail!("The resource model has a customized table name. Write an application-owned migration for that table; no files changed.");
}
let syn::Fields::Named(existing) = model_item.fields else {
bail!("Resource Model must have named fields; no files changed.")
};
if existing.named.iter().any(|existing| {
existing
.ident
.as_ref()
.is_some_and(|name| name == &field.name)
}) {
bail!("Model already defines `{}`; no files changed.", field.name);
}
if let Some(reference) = &mut field.reference {
let target_path = format!("app/models/{}.rs", reference.target);
let target = plan.read(&target_path).with_context(|| {
format!(
"Generate the referenced resource {} first; no files changed.",
reference.target
)
})?;
let (kind, _) = reference_model_info(&target)?;
field.kind = kind;
}
let migration = format!("m_add_{}_to_{table}", field.name);
let file = format!("database/migrations/{migration}.rs");
let note = format!("database/evolution/{migration}.md");
plan.create(&file, migration_source(&table, &field))?;
plan.create(
¬e,
review_note(&resource.ty, &resource.module, &table, &field),
)?;
plan.anchor(
"database/migrations/mod.rs",
"// capy:modules",
&format!("mod {migration};"),
)?;
plan.anchor(
"database/migrations/mod.rs",
"// capy:migrations",
&format!("Box::new({migration}::Migration),"),
)?;
plan.commit()
}
fn column_type(field: &Field) -> &'static str {
match field.kind {
Kind::String => "string_len(255)",
Kind::Text => "text()",
Kind::Boolean => "boolean()",
Kind::Integer => "integer()",
Kind::Bigint => "big_integer()",
Kind::Float => "double()",
Kind::Uuid => "uuid()",
Kind::Datetime => "timestamp_with_time_zone()",
Kind::Date => "date()",
Kind::Enum => "string_len(255)",
Kind::Decimal => "string_len(41)",
}
}
fn migration_source(table: &str, field: &Field) -> String {
let name = &field.name;
let index_name = format!("idx_{table}_{name}");
let index = if field.index || field.unique {
format!("manager.create_index(Index::create().name({index_name:?}).table(Alias::new({table:?})).col(Alias::new({name:?})){}.to_owned()).await?;", if field.unique { ".unique()" } else { "" })
} else {
String::new()
};
let addition = if let Some(reference) = &field.reference {
let sql_type = match field.kind {
Kind::Integer => "INTEGER",
Kind::Bigint => "BIGINT",
Kind::Uuid => "UUID",
_ => unreachable!("validated target key type"),
};
let target_table = plural_table(&reference.target);
let delete = match reference.on_delete {
super::field::DeleteBehavior::Restrict => "RESTRICT",
super::field::DeleteBehavior::Cascade => "CASCADE",
super::field::DeleteBehavior::SetNull => "SET NULL",
};
let sql = format!("ALTER TABLE \"{table}\" ADD COLUMN \"{name}\" {sql_type} REFERENCES \"{target_table}\"(\"id\") ON DELETE {delete}");
let sql_expr = if field.kind == Kind::Uuid {
let sqlite = sql.replace(" UUID REFERENCES ", " BLOB REFERENCES ");
format!("if manager.get_database_backend() == capy::sea_orm::DbBackend::Sqlite {{ {sqlite:?} }} else {{ {sql:?} }}")
} else {
format!("{sql:?}")
};
format!("use capy::sea_orm::ConnectionTrait;\nmanager.get_connection().execute_unprepared({sql_expr}).await?;")
} else {
let mut column = format!(
"ColumnDef::new(Alias::new({name:?})).{}",
column_type(field)
);
if !field.nullable {
column.push_str(".not_null()");
}
if let Some(default) = &field.default {
if field.kind == Kind::Enum {
column.push_str(&format!(".default({default:?})"));
} else {
let value = if field.kind == Kind::Uuid {
let bytes = if field.nullable {
"value.map(|id| id.as_bytes().to_vec())"
} else {
"value.as_bytes().to_vec()"
};
format!("if manager.get_database_backend() == capy::sea_orm::DbBackend::Sqlite {{ Expr::value({bytes}) }} else {{ Expr::value(value) }}")
} else {
"value".into()
};
column.push_str(&format!(
".default({{ let value: {} = {}; {value} }})",
field.entity_type(),
field.literal(default, false)
));
}
}
format!("manager.alter_table(Table::alter().table(Alias::new({table:?})).add_column({column}).to_owned()).await?;")
};
format!("//! Additive change. Review database/evolution/m_add_{name}_to_{table}.md before applying.\nuse capy::migration::{{self as sea_orm_migration, prelude::*}};\n#[derive(DeriveMigrationName)] pub struct Migration;\n#[async_trait::async_trait] impl MigrationTrait for Migration {{\nasync fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {{ {addition} {index} Ok(()) }}\nasync fn down(&self, _manager: &SchemaManager) -> Result<(), DbErr> {{ Err(DbErr::Custom(\"Reverting this additive migration would discard application data. Write and review an explicit rollback migration.\".into())) }}\n}}")
}
fn review_note(resource: &str, module: &str, table: &str, field: &Field) -> String {
let mut note = format!("# Add `{}` to {resource}\n\nMigration: `m_add_{}_to_{table}`. Generated automatically and registered; **not applied**. Run `capy db:migrate` only after reviewing it and current data. Rollback intentionally refuses to drop data.\n\nApplication code requires manual review. Capy did not rewrite your model, request/response DTOs, controller, policy, factory, seed, tests, or React pages.\n\n- Add `pub {}: {},` to `app/models/{module}.rs` Model.\n- Decide whether and how `{}` belongs in create/update requests and public responses.\n- Map the new field deliberately in controller create/update and response conversion.\n- Update factory and seed defaults, policy behavior, tests, OpenAPI output, and React forms/pages where appropriate.\n- Run `cargo fmt`, `cargo test`, `capy types --strict`, and the frontend build after code edits.\n\n", field.name, field.name, field.name, field.entity_type(), field.name);
if let Some(reference) = &field.reference {
note.push_str(&format!("Reference target: `{}`. Add SeaORM `belongs_to` metadata and a `Related` implementation to the child model. If reverse traversal is needed, add a separate relation extension module; do not rewrite the parent model blindly. The database foreign key uses `on_delete = {}`. API responses should expose the ID only unless you explicitly design an expanded DTO.\n\n", reference.target, reference.on_delete.sea_orm()));
}
if field.unique {
note.push_str("**Data-dependent uniqueness:** inspect and resolve duplicate existing values before applying this migration. A unique index can fail on existing rows.\n\n");
}
if field.kind == Kind::Enum {
note.push_str("**Enum closure:** the additive column uses string storage. Add a reviewed database CHECK constraint for the declared values in an application-owned migration after backfilling existing rows. The Rust enum type and DTO mapping are manual changes.\n\n");
}
if !field.nullable {
note.push_str("**Backfill:** this required column has a database default. Decide whether to retain that default after existing rows are populated.\n\n");
}
note
}