use crate::generators::field::Field;
pub const MIGRATION_SRC_DIR: &str = "db/migration/src";
pub const MIGRATION_LIB_BASE: &str = include_str!("../../templates/new/db/migration/src/lib.rs");
pub fn render_migration_file(imports: &str, up_body: &str, down_body: &str) -> String {
crate::templates::get("migration/migration.rs.template")
.replace("{migration_imports}", imports)
.replace("{up_body}", up_body)
.replace("{down_body}", down_body)
}
pub fn create_table_imports(fields: &[Field]) -> String {
if fields.iter().any(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()
}
}
pub fn create_table_up(table_name: &str, fields: &[Field]) -> String {
if fields.is_empty() {
return format!(
" // `create_table` adds an auto-incrementing `id` primary key for you.\n\
\x20 // Add columns with the builder, e.g. `t.string(\"name\").not_null();`.\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<&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
}
pub fn drop_table_down(table_name: &str) -> String {
format!(" drop_table(manager, \"{table_name}\").await\n")
}
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"))
{
lines.insert(i, format!("mod {module};"));
}
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();
lines.insert(i, format!("{indent}Box::new({module}::Migration),"));
}
let mut out = lines.join("\n");
out.push('\n');
out
}