Skip to content

Commit 976263e

Browse files
simonwSimon Willison
authored andcommitted
Sanity check add_foreign_key() column exists, closes #29
1 parent 364b0fb commit 976263e

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

sqlite_utils/db.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,9 @@ def guess_foreign_column(self, other_table):
466466
return pks[0].name
467467

468468
def add_foreign_key(self, column, other_table=None, other_column=None):
469+
# Ensure column exists
470+
if column not in self.columns_dict:
471+
raise AlterError("No such column: {}".format(column))
469472
# If other_table is not specified, attempt to guess it from the column
470473
if other_table is None:
471474
other_table = self.guess_foreign_table(column)

tests/test_create.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,14 @@ def test_add_foreign_key(fresh_db):
280280

281281

282282
def test_add_foreign_key_error_if_column_does_not_exist(fresh_db):
283+
fresh_db["books"].insert(
284+
{"id": 1, "title": "Hedgehogs of the world", "author_id": 1}
285+
)
286+
with pytest.raises(AlterError):
287+
fresh_db["books"].add_foreign_key("author2_id", "books", "id")
288+
289+
290+
def test_add_foreign_key_error_if_other_table_does_not_exist(fresh_db):
283291
fresh_db["books"].insert({"title": "Hedgehogs of the world", "author_id": 1})
284292
with pytest.raises(AlterError):
285293
fresh_db["books"].add_foreign_key("author_id", "authors", "id")

0 commit comments

Comments
 (0)