Better type signatures for compound foreign key columns

New ForeignKeyColumns type alias - a column name or a list/tuple of
column names - used by add_foreign_key(), add_foreign_keys() (via the
ForeignKeyTuple alias, replacing its Any slots) and the
ForeignKeyIndicator union, which it also simplifies. Tuples now
type-check anywhere lists are accepted.

ForeignKey.__post_init__ normalizes tuple columns/other_columns to
lists so direct construction with tuples compares equal to
introspected foreign keys.

Refs https://github.com/simonw/sqlite-utils/pull/770/changes#r3525703477

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Simon Willison 2026-07-05 15:03:23 -07:00
commit c16edb2dc4
2 changed files with 36 additions and 13 deletions

View file

@ -445,3 +445,19 @@ def test_implicit_compound_primary_key_reference_is_resolved():
fk = db["courses"].foreign_keys[0]
assert fk.is_compound is True
assert fk.other_columns == ["campus_name", "dept_code"]
def test_foreign_key_normalizes_tuple_columns_to_lists():
# Compound columns passed as tuples are normalized to lists, so they
# compare equal to introspected ForeignKeys
fk = ForeignKey(
table="courses",
column=None,
other_table="departments",
other_column=None,
columns=("campus_name", "dept_code"),
other_columns=("campus_name", "dept_code"),
is_compound=True,
)
assert fk.columns == ["campus_name", "dept_code"]
assert fk.other_columns == ["campus_name", "dept_code"]