mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-09-09 18:14:09 +02:00
Support self-referencing FKs in create (#537)
This commit is contained in:
parent
9662d4ce26
commit
39ef137e67
2 changed files with 30 additions and 0 deletions
|
|
@ -813,6 +813,8 @@ class Database:
|
||||||
pk = hash_id
|
pk = hash_id
|
||||||
# Soundness check foreign_keys point to existing tables
|
# Soundness check foreign_keys point to existing tables
|
||||||
for fk in foreign_keys:
|
for fk in foreign_keys:
|
||||||
|
if fk.other_table == name and columns.get(fk.other_column):
|
||||||
|
continue
|
||||||
if not any(
|
if not any(
|
||||||
c for c in self[fk.other_table].columns if c.name == fk.other_column
|
c for c in self[fk.other_table].columns if c.name == fk.other_column
|
||||||
):
|
):
|
||||||
|
|
|
||||||
|
|
@ -288,6 +288,25 @@ def test_create_table_works_for_m2m_with_only_foreign_keys(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
def test_create_error_if_invalid_foreign_keys(fresh_db):
|
||||||
with pytest.raises(AlterError):
|
with pytest.raises(AlterError):
|
||||||
fresh_db["one"].insert(
|
fresh_db["one"].insert(
|
||||||
|
|
@ -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(
|
@pytest.mark.parametrize(
|
||||||
"col_name,col_type,not_null_default,expected_schema",
|
"col_name,col_type,not_null_default,expected_schema",
|
||||||
(
|
(
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue