@@ -33,24 +33,18 @@ def __init__(self, url, **kwargs):
33
33
if not os .path .isfile (matches .group (1 )):
34
34
raise RuntimeError ("not a file: {}" .format (matches .group (1 )))
35
35
36
- # Optionally enable foreign key constraints
37
- # http://docs.sqlalchemy.org/en/latest/dialects/sqlite.html#foreign-key-support
38
- if kwargs .pop ("pragma_foreign_keys" , False ):
39
- @sqlalchemy .event .listens_for (sqlalchemy .engine .Engine , "connect" )
40
- def _set_sqlite_pragma (dbapi_connection , connection_record ):
41
- """Enables foreign key support."""
36
+ pragma_foreign_keys = kwargs .pop ("pragma_foreign_keys" , False )
42
37
43
- # Ensure backend is sqlite
44
- if type (dbapi_connection ) is sqlite3 .Connection :
45
- cursor = dbapi_connection .cursor ()
46
-
47
- # Respect foreign key constraints by default
48
- cursor .execute ("PRAGMA foreign_keys=ON" )
49
- cursor .close ()
38
+ # Create engine, raising exception if back end's module not installed
39
+ self .engine = sqlalchemy .create_engine (url , ** kwargs )
50
40
41
+ # Whether to enable foreign key constraints
42
+ if pragma_foreign_keys :
43
+ sqlalchemy .event .listen (self .engine , "connect" , _on_connect )
44
+ else :
45
+ # Create engine, raising exception if back end's module not installed
46
+ self .engine = sqlalchemy .create_engine (url , ** kwargs )
51
47
52
- # Create engine, raising exception if back end's module not installed
53
- self .engine = sqlalchemy .create_engine (url , ** kwargs )
54
48
55
49
# Log statements to standard error
56
50
logging .basicConfig (level = logging .DEBUG )
@@ -229,3 +223,16 @@ def process(value):
229
223
else :
230
224
self .logger .debug (termcolor .colored (log , "green" ))
231
225
return ret
226
+
227
+
228
+ # http://docs.sqlalchemy.org/en/latest/dialects/sqlite.html#foreign-key-support
229
+ def _on_connect (dbapi_connection , connection_record ):
230
+ """Enables foreign key support."""
231
+
232
+ # Ensure backend is sqlite
233
+ if type (dbapi_connection ) is sqlite3 .Connection :
234
+ cursor = dbapi_connection .cursor ()
235
+
236
+ # Respect foreign key constraints by default
237
+ cursor .execute ("PRAGMA foreign_keys=ON" )
238
+ cursor .close ()
0 commit comments