Last active
December 22, 2021 10:28
-
-
Save austinjp/06dae04e2705a5a898c072007d4f0fbd to your computer and use it in GitHub Desktop.
Pony ORM with SQLite uses shorthand foreign key syntax instead of explicit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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