use std::io::Write;
use indexmap::IndexMap;
use super::WriteResultExt;
use crate::error::Result;
use crate::generate::engine::GeneratedData;
use crate::generate::value::Value;
use crate::schema::types::{DatabaseSchema, DatabaseType};
pub fn write_sql<W: Write>(
writer: &mut W,
data: &GeneratedData,
schema: &DatabaseSchema,
) -> Result<()> {
let db_type = &schema.database_type;
writeln!(writer, "-- Generated by SeedKit").context("writing header")?;
writeln!(writer, "-- Database: {}", schema.database_name).context("writing header")?;
writeln!(writer).context("writing newline")?;
if matches!(db_type, DatabaseType::MySQL) {
writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;").context("writing FK disable")?;
writeln!(writer).context("writing newline")?;
}
let begin = match db_type {
DatabaseType::PostgreSQL => "BEGIN;",
DatabaseType::MySQL => "START TRANSACTION;",
DatabaseType::SQLite => "BEGIN TRANSACTION;",
};
writeln!(writer, "{begin}").context("writing BEGIN")?;
writeln!(writer).context("writing newline")?;
for (table_name, rows) in &data.tables {
if rows.is_empty() {
continue;
}
writeln!(writer, "-- Table: {}", table_name)
.with_context(|| format!("writing table header for {}", table_name))?;
for group in rows.chunk_by(same_columns) {
write_insert_group(writer, schema, table_name, group)?;
}
}
write_deferred_updates(writer, data, schema)?;
writeln!(writer, "COMMIT;").context("writing COMMIT")?;
if matches!(db_type, DatabaseType::MySQL) {
writeln!(writer, "SET FOREIGN_KEY_CHECKS = 1;").context("writing FK enable")?;
}
Ok(())
}
pub fn write_postgres_copy<W: Write>(
writer: &mut W,
data: &GeneratedData,
schema: &DatabaseSchema,
) -> Result<()> {
writeln!(writer, "-- Generated by SeedKit (PostgreSQL COPY format)")
.context("writing header")?;
writeln!(writer).context("writing newline")?;
writeln!(writer, "BEGIN;").context("writing BEGIN")?;
writeln!(writer).context("writing newline")?;
for (table_name, rows) in &data.tables {
if rows.is_empty() {
continue;
}
for group in rows.chunk_by(same_columns) {
write_copy_group(writer, schema, table_name, group)?;
}
}
write_deferred_updates(writer, data, schema)?;
writeln!(writer, "COMMIT;").context("writing COMMIT")
}
fn write_deferred_updates<W: Write>(
writer: &mut W,
data: &GeneratedData,
schema: &DatabaseSchema,
) -> Result<()> {
if data.deferred_updates.is_empty() {
return Ok(());
}
writeln!(writer, "-- Deferred foreign key updates (cycle resolution)")
.context("writing deferred header")?;
for group in data
.deferred_updates
.chunk_by(|a, b| a.table_name == b.table_name && a.row_index == b.row_index)
{
if let Some(sql) = build_deferred_update_sql(group, data, schema) {
writeln!(writer, "{sql};").context("writing deferred update")?;
}
}
writeln!(writer).context("writing newline")
}
type Row = IndexMap<String, Value>;
fn same_columns(left: &Row, right: &Row) -> bool {
left.keys().eq(right.keys())
}
fn write_default_rows<W: Write>(
writer: &mut W,
schema: &DatabaseSchema,
table: &str,
count: usize,
) -> Result<()> {
let defaults = match schema.database_type {
DatabaseType::MySQL => "() VALUES ()",
DatabaseType::PostgreSQL | DatabaseType::SQLite => "DEFAULT VALUES",
};
let statement = format!("INSERT INTO {} {defaults};", schema.quoted_table(table));
for _ in 0..count {
writeln!(writer, "{statement}")
.with_context(|| format!("writing default row for {table}"))?;
}
Ok(())
}
fn write_insert_group<W: Write>(
writer: &mut W,
schema: &DatabaseSchema,
table_name: &str,
rows: &[Row],
) -> Result<()> {
let columns: Vec<_> = rows[0].keys().collect();
if columns.is_empty() {
return write_default_rows(writer, schema, table_name, rows.len());
}
let db_type = &schema.database_type;
let batch_size = 100;
for chunk in rows.chunks(batch_size) {
let quoted_columns: Vec<String> = columns
.iter()
.map(|c| quote_identifier(c, db_type))
.collect();
writeln!(
writer,
"INSERT INTO {} ({}) VALUES",
schema.quoted_table(table_name),
quoted_columns.join(", ")
)
.with_context(|| format!("writing INSERT for {}", table_name))?;
for (i, row) in chunk.iter().enumerate() {
let values: Vec<String> = columns
.iter()
.map(|col| {
row.get(*col)
.map(|v| v.to_sql_literal(db_type))
.unwrap_or_else(|| "NULL".to_string())
})
.collect();
let separator = if i == chunk.len() - 1 { ";" } else { "," };
writeln!(writer, " ({}){}", values.join(", "), separator)
.with_context(|| format!("writing row for {}", table_name))?;
}
writeln!(writer).context("writing newline")?;
}
Ok(())
}
fn write_copy_group<W: Write>(
writer: &mut W,
schema: &DatabaseSchema,
table_name: &str,
rows: &[Row],
) -> Result<()> {
let columns: Vec<_> = rows[0].keys().collect();
if columns.is_empty() {
return write_default_rows(writer, schema, table_name, rows.len());
}
let db_type = &schema.database_type;
let quoted_columns: Vec<String> = columns
.iter()
.map(|c| quote_identifier(c, db_type))
.collect();
writeln!(
writer,
"COPY {} ({}) FROM stdin;",
schema.quoted_table(table_name),
quoted_columns.join(", ")
)
.with_context(|| format!("writing COPY for {}", table_name))?;
for row in rows {
let values: Vec<String> = columns
.iter()
.map(|col| {
row.get(*col)
.map(value_to_copy_format)
.unwrap_or_else(|| "\\N".to_string())
})
.collect();
writeln!(writer, "{}", values.join("\t"))
.with_context(|| format!("writing COPY data for {}", table_name))?;
}
writeln!(writer, "\\.")
.with_context(|| format!("writing COPY terminator for {}", table_name))?;
writeln!(writer).context("writing newline")?;
Ok(())
}
fn value_to_copy_format(value: &Value) -> String {
match value {
Value::Null => "\\N".to_string(),
Value::Bool(b) => {
if *b {
"t".to_string()
} else {
"f".to_string()
}
}
Value::Int(i) => i.to_string(),
Value::Float(f) => f.to_string(),
Value::String(s) => s
.replace('\\', "\\\\")
.replace('\t', "\\t")
.replace('\n', "\\n")
.replace('\r', "\\r"),
Value::Timestamp(ts) => ts.format("%Y-%m-%d %H:%M:%S").to_string(),
Value::Date(d) => d.format("%Y-%m-%d").to_string(),
Value::Time(t) => t.format("%H:%M:%S").to_string(),
Value::Uuid(u) => u.to_string(),
Value::Json(j) => j.to_string().replace('\\', "\\\\").replace('\t', "\\t"),
Value::Array(items) => value_to_copy_format(&Value::String(
crate::generate::value::pg_array_text(items).into(),
)),
Value::Bytes(b) => format!(
"\\\\x{}",
b.iter()
.map(|byte| format!("{:02x}", byte))
.collect::<String>()
),
}
}
fn build_deferred_update_sql(
updates: &[crate::generate::engine::DeferredUpdate],
data: &GeneratedData,
schema: &DatabaseSchema,
) -> Option<String> {
let db_type = &schema.database_type;
let update = updates.first()?;
let table = schema.tables.get(&update.table_name)?;
let pk = table.primary_key.as_ref()?;
let rows = data.tables.get(&update.table_name)?;
let row = rows.get(update.row_index)?;
let mut where_parts = Vec::new();
for pk_col in &pk.columns {
if let Some(pk_val) = row.get(pk_col) {
where_parts.push(format!(
"{} = {}",
quote_identifier(pk_col, db_type),
pk_val.to_sql_literal(db_type),
));
} else {
let id = update.row_index as i64 + 1;
where_parts.push(format!("{} = {}", quote_identifier(pk_col, db_type), id,));
}
}
if where_parts.is_empty() {
return None;
}
let assignments = updates
.iter()
.map(|u| {
format!(
"{} = {}",
quote_identifier(&u.column_name, db_type),
u.value.to_sql_literal(db_type)
)
})
.collect::<Vec<_>>();
Some(format!(
"UPDATE {} SET {} WHERE {}",
schema.quoted_table(&update.table_name),
assignments.join(", "),
where_parts.join(" AND "),
))
}
fn quote_identifier(name: &str, db_type: &DatabaseType) -> String {
db_type.quote_identifier(name)
}
#[cfg(test)]
mod tests {
use super::*;
use indexmap::IndexMap;
use std::borrow::Cow;
#[test]
fn test_write_sql_basic() {
let mut tables = IndexMap::new();
let mut row = IndexMap::new();
row.insert(
"name".to_string(),
Value::String(Cow::Owned("Alice".to_string())),
);
row.insert("age".to_string(), Value::Int(30));
tables.insert("users".to_string(), vec![row]);
let data = GeneratedData {
tables,
deferred_updates: Vec::new(),
};
let schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut output = Vec::new();
write_sql(&mut output, &data, &schema).unwrap();
let sql = String::from_utf8(output).unwrap();
assert!(sql.contains("INSERT INTO"));
assert!(sql.contains("'Alice'"));
assert!(sql.contains("30"));
}
fn export(db: DatabaseType, copy: bool) -> Vec<String> {
use crate::generate::engine::DeferredUpdate;
use crate::schema::types::{PrimaryKey, Table};
let row = IndexMap::from([("name".to_string(), Value::String("Ada".into()))]);
let data = GeneratedData {
tables: IndexMap::from([("users".to_string(), vec![row])]),
deferred_updates: vec![DeferredUpdate {
table_name: "users".to_string(),
row_index: 0,
column_name: "manager_id".to_string(),
value: Value::Int(1),
}],
};
let mut schema = DatabaseSchema::new(db, "test".to_string());
let mut users = Table::new("users".to_string());
users.primary_key = Some(PrimaryKey {
columns: vec!["id".to_string()],
name: None,
});
schema.tables.insert("users".to_string(), users);
let mut output = Vec::new();
if copy {
write_postgres_copy(&mut output, &data, &schema).unwrap();
} else {
write_sql(&mut output, &data, &schema).unwrap();
}
String::from_utf8(output)
.unwrap()
.lines()
.filter(|l| !l.is_empty() && !l.starts_with("--"))
.map(str::to_owned)
.collect()
}
#[test]
fn exports_run_in_one_transaction() {
for (db, copy, begin) in [
(DatabaseType::PostgreSQL, false, "BEGIN;"),
(DatabaseType::PostgreSQL, true, "BEGIN;"),
(DatabaseType::SQLite, false, "BEGIN TRANSACTION;"),
] {
let statements = export(db, copy);
assert_eq!(
statements.first().map(String::as_str),
Some(begin),
"{db:?}"
);
assert_eq!(
statements.last().map(String::as_str),
Some("COMMIT;"),
"{db:?}"
);
let update = statements.iter().position(|s| s.starts_with("UPDATE"));
assert!(
update < Some(statements.len() - 1),
"{db:?}: {statements:?}"
);
}
}
#[test]
fn mysql_exports_commit_before_restoring_foreign_key_checks() {
let statements = export(DatabaseType::MySQL, false);
assert_eq!(
statements[..2],
["SET FOREIGN_KEY_CHECKS = 0;", "START TRANSACTION;"]
);
assert_eq!(
statements[statements.len() - 2..],
["COMMIT;", "SET FOREIGN_KEY_CHECKS = 1;"]
);
}
#[test]
fn test_quote_identifier() {
assert_eq!(
quote_identifier("users", &DatabaseType::PostgreSQL),
"\"users\""
);
assert_eq!(quote_identifier("users", &DatabaseType::MySQL), "`users`");
}
#[test]
fn test_deferred_updates_produce_real_sql() {
use crate::generate::engine::DeferredUpdate;
use crate::schema::types::*;
let mut tables = IndexMap::new();
let mut row = IndexMap::new();
row.insert("id".to_string(), Value::Int(1));
row.insert(
"name".to_string(),
Value::String(Cow::Owned("Alice".to_string())),
);
row.insert("invited_by_id".to_string(), Value::Null);
tables.insert("users".to_string(), vec![row]);
let data = GeneratedData {
tables,
deferred_updates: vec![DeferredUpdate {
table_name: "users".to_string(),
row_index: 0,
column_name: "invited_by_id".to_string(),
value: Value::Int(1),
}],
};
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut users = Table::new("users".to_string());
users.primary_key = Some(PrimaryKey {
columns: vec!["id".to_string()],
name: None,
});
schema.tables.insert("users".to_string(), users);
let mut output = Vec::new();
write_sql(&mut output, &data, &schema).unwrap();
let sql = String::from_utf8(output).unwrap();
assert!(
sql.contains("UPDATE \"users\" SET \"invited_by_id\" = 1 WHERE \"id\" = 1;"),
"Deferred updates must produce real UPDATE SQL, got:\n{}",
sql
);
assert!(
!sql.contains("-- UPDATE"),
"Deferred updates should not be comments anymore"
);
}
#[test]
fn test_deferred_updates_auto_increment_pk() {
use crate::generate::engine::DeferredUpdate;
use crate::schema::types::*;
let mut tables = IndexMap::new();
let mut row = IndexMap::new();
row.insert(
"name".to_string(),
Value::String(Cow::Owned("Bob".to_string())),
);
row.insert("parent_id".to_string(), Value::Null);
tables.insert("categories".to_string(), vec![row]);
let data = GeneratedData {
tables,
deferred_updates: vec![DeferredUpdate {
table_name: "categories".to_string(),
row_index: 0,
column_name: "parent_id".to_string(),
value: Value::Int(1),
}],
};
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut table = Table::new("categories".to_string());
table.primary_key = Some(PrimaryKey {
columns: vec!["id".to_string()],
name: None,
});
schema.tables.insert("categories".to_string(), table);
let mut output = Vec::new();
write_sql(&mut output, &data, &schema).unwrap();
let sql = String::from_utf8(output).unwrap();
assert!(
sql.contains("UPDATE \"categories\" SET \"parent_id\" = 1 WHERE \"id\" = 1;"),
"Should use synthesized auto-increment PK, got:\n{}",
sql
);
}
#[test]
fn copy_rows_escape_every_line_and_field_separator() {
let row = IndexMap::from([(
"note".to_string(),
Value::String(Cow::Borrowed("one\r\ntwo\tthree\\")),
)]);
let data = GeneratedData {
tables: IndexMap::from([("notes".to_string(), vec![row])]),
deferred_updates: Vec::new(),
};
let schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut output = Vec::new();
write_postgres_copy(&mut output, &data, &schema).unwrap();
let copy = String::from_utf8(output).unwrap();
assert!(!copy.contains('\r'), "{copy:?}");
assert!(
copy.contains("\none\\r\\ntwo\\tthree\\\\\n\\.\n"),
"{copy:?}"
);
}
}