@@ -33,24 +33,18 @@ def __init__(self, url, **kwargs):
3333 if not os .path .isfile (matches .group (1 )):
3434 raise RuntimeError ("not a file: {}" .format (matches .group (1 )))
3535
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 )
4237
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 )
5040
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 )
5147
52- # Create engine, raising exception if back end's module not installed
53- self .engine = sqlalchemy .create_engine (url , ** kwargs )
5448
5549 # Log statements to standard error
5650 logging .basicConfig (level = logging .DEBUG )
@@ -229,3 +223,16 @@ def process(value):
229223 else :
230224 self .logger .debug (termcolor .colored (log , "green" ))
231225 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