Skip to content

Instantly share code, notes, and snippets.

@austinjp
Last active December 22, 2021 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save austinjp/06dae04e2705a5a898c072007d4f0fbd to your computer and use it in GitHub Desktop.
Save austinjp/06dae04e2705a5a898c072007d4f0fbd to your computer and use it in GitHub Desktop.
Pony ORM with SQLite uses shorthand foreign key syntax instead of explicit
#!/usr/bin/env python
from pony.orm import Database, Optional, Required, Set
db = Database()
@db.on_connect(provider="sqlite")
def pragmas(db, connection):
cursor = connection.cursor()
cursor.execute('PRAGMA foreign_keys = true')
db.bind({
"provider": "sqlite",
"create_db": "true",
"filename": "/tmp/pony_test.db"
})
class A(db.Entity):
_table_ = "A"
b = Set("B", reverse="a")
class B(db.Entity):
_table_ = "B"
a = Optional("A", reverse="b")
db.generate_mapping(create_tables=True)
-- The above script produces the following schema.
CREATE TABLE IF NOT EXISTS "A" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT
);
CREATE TABLE sqlite_sequence(name,seq);
CREATE TABLE IF NOT EXISTS "B" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"a" INTEGER REFERENCES "A" ("id") ON DELETE SET NULL
-- Here I'd expect to see an explicit FOREIGN KEY (...) clause here.
-- However, see https://sqlite.org/foreignkeys.html
-- 'Attaching a "REFERENCES <parent-table>" clause to a column definition creates a foreign key constraint'
-- This is a 'shorthand form to create the foreign key constraint'.
);
CREATE INDEX "idx_b__a" ON "B" ("a");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment