bottle-sqlite
bottle-sqlite copied to clipboard
Enable foreign keys when opening the database
Currently, the foreign key enforcement in SQLite is disabled by default, would it be possible to add an option that enable it automatically?
$ sqlite3
SQLite version 3.9.2 2015-11-02 18:31:45
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> pragma foreign_keys;
0
If someone else is interested I came up with following workaround. First create function decorator:
from functools import wraps
def pragmaForeignKeys(func):
'''Enable support for foreign keys'''
@wraps(func)
def wrapper(*args, **kwargs):
db = args[0]
db.execute('PRAGMA foreign_keys = ON')
return func(*args, **kwargs)
return wrapper
Then instead of this:
def doSomethingWithSQL(db, param1, param2, param3):
db.execute('PRAGMA foreign_keys = ON')
sql = 'SELECT ?, ?, ? FROM my_table'
db.execute(sql, (param1, param2, param3))
# ...
you can write this:
@pragmaForeignKeys
def doSomethingWithSQL(db, param1, param2, param3):
sql = 'SELECT ?, ?, ? FROM my_table'
db.execute(sql, (param1, param2, param3))
# ...
Each function which is decorated with @pragmaForeignKeys
will run PRAGMA foreign_keys = ON
first. Only requirement is that connection to sqlite (db
) must be first parameter in doSomethingWithSQL
.