Better foreign key enablement

This commit is contained in:
John Doty 2024-07-17 17:03:05 -07:00
parent a08257ec76
commit f9b14a7622

View file

@ -90,11 +90,12 @@ class Database:
def __init__(self, path: pathlib.Path | str, origin: str):
if not isinstance(path, str):
path.parent.mkdir(parents=True, exist_ok=True)
db = sqlite3.Connection(str(path), autocommit=False)
# This is WILD that I need to do this because you cannot enable or
# disable foreign keys with a transaction active, and
# `autocommit=False` means that a transaction is *always* active.
db.executescript("COMMIT;PRAGMA foreign_keys = ON;BEGIN;")
# Enable autocommit as a separate step so that I can enable foreign
# keys cleanly. (Can't enable foreign keys in a transaction.)
db = sqlite3.Connection(str(path))
db.execute("PRAGMA foreign_keys = ON")
db.autocommit = False
cursor = db.execute("PRAGMA foreign_keys")
rows = cursor.fetchall()