Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Disable foreign keys in sqlite when running migrations (#37572)
Max Brunsfeld23dc1f5ea406
diff --git a/Cargo.lock b/Cargo.lockindex 295c3a83c52..f4c94f8078b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15347,6 +15347,7 @@ dependencies = ["futures 0.3.31","indoc","libsqlite3-sys",+ "log","parking_lot","smol","sqlformat",diff --git a/crates/sqlez/Cargo.toml b/crates/sqlez/Cargo.tomlindex 16a3adebae2..6eb75aa1719 100644--- a/crates/sqlez/Cargo.toml+++ b/crates/sqlez/Cargo.toml@@ -14,6 +14,7 @@ collections.workspace = truefutures.workspace = trueindoc.workspace = truelibsqlite3-sys.workspace = true+log.workspace = trueparking_lot.workspace = truesmol.workspace = truesqlformat.workspace = truediff --git a/crates/sqlez/src/migrations.rs b/crates/sqlez/src/migrations.rsindex 2429ddeb412..567d82f9afe 100644--- a/crates/sqlez/src/migrations.rs+++ b/crates/sqlez/src/migrations.rs@@ -59,6 +59,7 @@ impl Connection {let mut store_completed_migration = self.exec_bound("INSERT INTO migrations (domain, step, migration) VALUES (?, ?, ?)")?;+ let mut did_migrate = false;for (index, migration) in migrations.iter().enumerate() {let migration =sqlformat::format(migration, &sqlformat::QueryParams::None, Default::default());@@ -70,9 +71,7 @@ impl Connection {&sqlformat::QueryParams::None,Default::default(),);- if completed_migration == migration- || migration.trim().starts_with("-- ALLOW_MIGRATION_CHANGE")- {+ if completed_migration == migration {// Migration already run. Continuecontinue;} else if should_allow_migration_change(index, &completed_migration, &migration)@@ -91,12 +90,58 @@ impl Connection {}self.eager_exec(&migration)?;+ did_migrate = true;store_completed_migration((domain, index, migration))?;}+ if did_migrate {+ self.delete_rows_with_orphaned_foreign_key_references()?;+ self.exec("PRAGMA foreign_key_check;")?()?;+ }+Ok(())})}++ /// Delete any rows that were orphaned by a migration. This is needed+ /// because we disable foreign key constraints during migrations, so+ /// that it's possible to re-create a table with the same name, without+ /// deleting all associated data.+ fn delete_rows_with_orphaned_foreign_key_references(&self) -> Result<()> {+ let foreign_key_info: Vec<(String, String, String, String)> = self.select(+ r#"+ SELECT DISTINCT+ schema.name as child_table,+ foreign_keys.[from] as child_key,+ foreign_keys.[table] as parent_table,+ foreign_keys.[to] as parent_key+ FROM sqlite_schema schema+ JOIN pragma_foreign_key_list(schema.name) foreign_keys+ WHERE+ schema.type = 'table' AND+ schema.name NOT LIKE "sqlite_%"+ "#,+ )?()?;++ if !foreign_key_info.is_empty() {+ log::info!(+ "Found {} foreign key relationships to check",+ foreign_key_info.len()+ );+ }++ for (child_table, child_key, parent_table, parent_key) in foreign_key_info {+ self.exec(&format!(+ "+ DELETE FROM {child_table}+ WHERE {child_key} IS NOT NULL and {child_key} NOT IN+ (SELECT {parent_key} FROM {parent_table})+ "+ ))?()?;+ }++ Ok(())+ }}#[cfg(test)]diff --git a/crates/sqlez/src/thread_safe_connection.rs b/crates/sqlez/src/thread_safe_connection.rsindex 58d3afe78fb..482905ac817 100644--- a/crates/sqlez/src/thread_safe_connection.rs+++ b/crates/sqlez/src/thread_safe_connection.rs@@ -95,6 +95,14 @@ impl<M: Migrator> ThreadSafeConnectionBuilder<M> {let mut migration_result =anyhow::Result::<()>::Err(anyhow::anyhow!("Migration never run"));+ let foreign_keys_enabled: bool =+ connection.select_row::<i32>("PRAGMA foreign_keys")?()+ .unwrap_or(None)+ .map(|enabled| enabled != 0)+ .unwrap_or(false);++ connection.exec("PRAGMA foreign_keys = OFF;")?()?;+for _ in 0..MIGRATION_RETRIES {migration_result = connection.with_savepoint("thread_safe_multi_migration", || M::migrate(connection));@@ -104,6 +112,9 @@ impl<M: Migrator> ThreadSafeConnectionBuilder<M> {}}+ if foreign_keys_enabled {+ connection.exec("PRAGMA foreign_keys = ON;")?()?;+ }migration_result}).await?;diff --git a/crates/workspace/src/persistence.rs b/crates/workspace/src/persistence.rsindex d674f6dd4d5..797c4796830 100644--- a/crates/workspace/src/persistence.rs+++ b/crates/workspace/src/persistence.rs@@ -699,6 +699,9 @@ impl Domain for WorkspaceDb {PRIMARY KEY (workspace_id, worktree_id, relative_worktree_path, language_name, name, path, raw_json)) STRICT;),+ sql!(+ DROP TABLE ssh_connections;+ ),];// Allow recovering from bad migration that was initially shipped to nightly