Skip to content

Commit

Permalink
fix(schema-engine): combine foreign_keys + defer_foreign_keys PRAGMAs…
Browse files Browse the repository at this point in the history
  • Loading branch information
jkomyno committed May 16, 2024
1 parent 49d5547 commit 93d2882
Showing 1 changed file with 14 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,21 @@ impl SqlRenderer for SqliteFlavour {
}

fn render_redefine_tables(&self, tables: &[RedefineTable], schemas: MigrationPair<&SqlSchema>) -> Vec<String> {
// Based on 'Making Other Kinds Of Table Schema Changes' from https://www.sqlite.org/lang_altertable.html
let mut result = vec!["PRAGMA foreign_keys=OFF".to_string()];
// Based on 'Making Other Kinds Of Table Schema Changes' from https://www.sqlite.org/lang_altertable.html,
// and on https://developers.cloudflare.com/d1/reference/database-commands/#pragma-defer_foreign_keys--onoff.
let mut result: Vec<String> = vec![];

// disables foreign key constraint enforcement
result.push("PRAGMA defer_foreign_keys=ON".to_string());
result.push("PRAGMA foreign_keys=OFF".to_string());

let mut foreign_key_checks = vec![];

for redefine_table in tables {
let tables = schemas.walk(redefine_table.table_ids);
let temporary_table_name = format!("new_{}", &tables.next.name());

// maybe use render_create_table_for_migration?
result.push(self.render_create_table_as(
tables.next,
QuotedWithPrefix(None, Quoted::sqlite_ident(&temporary_table_name)),
Expand Down Expand Up @@ -218,9 +225,13 @@ impl SqlRenderer for SqliteFlavour {
));
}

result.extend(foreign_key_checks);
// Checks the database for foreign key constraint violations.
// Note: this code is probably useless, pending foreign constraint violations are checked fine even without it.
// result.extend(foreign_key_checks);

// resumes immediate enforcement of foreign key constraints.
result.push("PRAGMA foreign_keys=ON".to_string());
result.push("PRAGMA defer_foreign_keys=OFF".to_string());

result
}
Expand Down

0 comments on commit 93d2882

Please sign in to comment.