Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable foreign keys when opening the database #11

Open
jdesgats opened this issue Dec 12, 2015 · 1 comment
Open

Enable foreign keys when opening the database #11

jdesgats opened this issue Dec 12, 2015 · 1 comment

Comments

@jdesgats
Copy link

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
@kotoko
Copy link

kotoko commented Dec 18, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants