@@ -26,6 +26,11 @@ pub enum ConnectionOptions {
26
26
27
27
/// Enable foreign key support
28
28
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 ,
29
34
}
30
35
31
36
impl ConnectionBuilder {
@@ -110,21 +115,23 @@ impl ConnectionBuilder {
110
115
. with_context ( || "Database migration error" ) ?;
111
116
}
112
117
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
+ }
115
126
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)
122
128
}
123
129
}
124
130
125
131
#[ cfg( test) ]
126
132
mod tests {
127
133
use super :: * ;
134
+ use crate :: sqlite:: ConnectionOptions :: ForceDisableForeignKeys ;
128
135
use mithril_common:: test_utils:: TempDir ;
129
136
use sqlite:: Value ;
130
137
@@ -250,4 +257,16 @@ mod tests {
250
257
tables_list
251
258
) ;
252
259
}
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
+ }
253
272
}
0 commit comments