Skip to content

Commit

Permalink
Support self-referencing FKs in create (#537)
Browse files Browse the repository at this point in the history
  • Loading branch information
numist committed May 8, 2023
1 parent 9662d4c commit 39ef137
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
2 changes: 2 additions & 0 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,8 @@ def sort_key(p):
pk = hash_id
# Soundness check foreign_keys point to existing tables
for fk in foreign_keys:
if fk.other_table == name and columns.get(fk.other_column):
continue
if not any(
c for c in self[fk.other_table].columns if c.name == fk.other_column
):
Expand Down
28 changes: 28 additions & 0 deletions tests/test_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,25 @@ def do_it():
)


def test_self_referential_foreign_key(fresh_db):
assert [] == fresh_db.table_names()
table = fresh_db.create_table(
"test_table",
columns={
"id": int,
"ref": int,
},
pk="id",
foreign_keys=(("ref", "test_table", "id"),),
)
assert (
"CREATE TABLE [test_table] (\n"
" [id] INTEGER PRIMARY KEY,\n"
" [ref] INTEGER REFERENCES [test_table]([id])\n"
")"
) == table.schema


def test_create_error_if_invalid_foreign_keys(fresh_db):
with pytest.raises(AlterError):
fresh_db["one"].insert(
Expand All @@ -297,6 +316,15 @@ def test_create_error_if_invalid_foreign_keys(fresh_db):
)


def test_create_error_if_invalid_self_referential_foreign_keys(fresh_db):
with pytest.raises(AlterError):
fresh_db["one"].insert(
{"id": 1, "ref_id": 3},
pk="id",
foreign_keys=(("ref_id", "one", "bad_column"),),
)


@pytest.mark.parametrize(
"col_name,col_type,not_null_default,expected_schema",
(
Expand Down

0 comments on commit 39ef137

Please sign in to comment.