Skip to content

Enforce foreign keys on SQLite connections - #65

Open
nicoloesch wants to merge 1 commit into
mainfrom
54-sqlite-foreign-keys
Open

nicoloesch wants to merge 1 commit into
mainfrom
54-sqlite-foreign-keys

Conversation

@nicoloesch

Copy link
Copy Markdown
Collaborator

Summary

  • Engines that ResolvedConnection.create_engine builds for SQLite now enforce foreign keys on every connection. SQLite ignores declared keys unless PRAGMA foreign_keys is set on each connection, so they were never enforced, unlike PostgreSQL and DuckDB.
  • The pragma is set by a connect listener, enable_sqlite_foreign_keys, because the setting belongs to a single connection and a pool opens new ones over time. SQLite ignores the pragma inside a transaction, and the connect event runs before the first statement.
  • This covers production engines, the CLI and isolated_test_database, since all build the engine through the same method.
  • A listener attached to the returned engine runs afterwards and can turn enforcement off.
  • Tests cover enforcement on every pooled connection, a child inserted before its parent, a later listener turning it off, the isolated test database, and DuckDB engines getting no listener.

Migration

  • Writes to a SQLite database must now insert parents before children, and a row that references a missing parent is refused.
  • To keep the old behaviour, attach a connect listener that runs PRAGMA foreign_keys = OFF.
  • The orm-loader test suite passes unchanged. omop-alchemy has fixtures that insert children without parents, which fail until fixed.

Checklist

  • Applied exactly one label (breaking, feature, fix, dependencies, or chore)
  • Tests pass locally (uv run pytest -q)
  • Lint passes (uv run ruff check .)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking Incompatible API change. MAJOR: x+1.y.z

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQLite connections come up with foreign key enforcement off

1 participant