Skip to content

Enable foreign keys when opening the database #11

Open

Description

@jdesgats

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

Activity

  1. kotoko commented on Dec 18, 2021

    @kotoko

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions