Skip to content

Commit d0419d9

Browse files
committed
Add ForceDisableForeignKeys to ConnectionBuilder
Since the migrations can enable them and we want to apply migrations but doesn't want the foreign keys support in tests, this option allow to force their desactivation.
1 parent 5392eb6 commit d0419d9

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

internal/mithril-persistence/src/sqlite/connection_builder.rs

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ pub enum ConnectionOptions {
2626

2727
/// Enable foreign key support
2828
EnableForeignKeys,
29+
30+
/// Disable foreign key support after the migrations are run
31+
///
32+
/// This option take priority over [ConnectionOptions::EnableForeignKeys] if both are enabled.
33+
ForceDisableForeignKeys,
2934
}
3035

3136
impl ConnectionBuilder {
@@ -110,21 +115,23 @@ impl ConnectionBuilder {
110115
.with_context(|| "Database migration error")?;
111116
}
112117

113-
Ok(connection)
114-
}
118+
if self
119+
.options
120+
.contains(&ConnectionOptions::ForceDisableForeignKeys)
121+
{
122+
connection
123+
.execute("pragma foreign_keys=false")
124+
.with_context(|| "SQLite initialization: could not disable FOREIGN KEY support.")?;
125+
}
115126

116-
/// Shortcut for `ConnectionBuilder::open_memory().with_migrations(migrations).build()`, mostly
117-
/// useful for quick connections for tests.
118-
pub fn build_memory_with_migration(
119-
migrations: Vec<SqlMigration>,
120-
) -> StdResult<ConnectionThreadSafe> {
121-
Self::open_memory().with_migrations(migrations).build()
127+
Ok(connection)
122128
}
123129
}
124130

125131
#[cfg(test)]
126132
mod tests {
127133
use super::*;
134+
use crate::sqlite::ConnectionOptions::ForceDisableForeignKeys;
128135
use mithril_common::test_utils::TempDir;
129136
use sqlite::Value;
130137

@@ -250,4 +257,16 @@ mod tests {
250257
tables_list
251258
);
252259
}
260+
261+
#[test]
262+
fn can_disable_foreign_keys_even_if_a_migration_enable_them() {
263+
let connection = ConnectionBuilder::open_memory()
264+
.with_migrations(vec![SqlMigration::new(1, "pragma foreign_keys=true;")])
265+
.with_options(&[ForceDisableForeignKeys])
266+
.build()
267+
.unwrap();
268+
269+
let foreign_keys = execute_single_cell_query(&connection, "pragma foreign_keys;");
270+
assert_eq!(Value::Integer(false.into()), foreign_keys);
271+
}
253272
}

0 commit comments

Comments
 (0)