Composite primary keys
Multi-column primary keys — tuple matching, keyset pagination, and the limits that fail loudly instead of guessing.
A model with several pk fields declares a composite primary key. fusion
builds on the full key tuple everywhere: since v0.4.0, no operation binds,
orders, or paginates by the first key column alone
(CHANGELOG.md, [0.4.0], 2026-11-26).
Declaring a composite key
type cpkRow struct {
A int64 `fusion:"pk"`
B int64 `fusion:"pk"`
Name string `fusion:"notnull"`
}AutoMigrate declares the key at table level — inlining it per column
would emit multiple PRIMARY KEY clauses (migrator/migrator.go:178-181, 226-232):
CREATE TABLE cpk_rows (
a INTEGER NOT NULL,
b INTEGER NOT NULL,
name TEXT NOT NULL,
PRIMARY KEY (a, b)
)Scalar id conditions are rejected
On a single-key model, First(&row, 42) matches by primary key. On a
composite-key model a scalar cannot express a tuple, so it fails with
fusion.ErrInvalidValue instead of matching every row sharing the
first key column. This applies to First, Find, Take, Last, and
Delete with a scalar:
// TestCompositePKScalarCondErrors: a scalar id condition cannot bind a
// composite key — it must error instead of matching every sibling sharing
// PKs[0] (audit D/Q).The failed condition touches nothing — a subsequent Count still returns
all rows (composite_pk_test.go:73-79). Single-key behavior is unchanged
by this rule.
Select by tuple with explicit conditions instead:
var row cpkRow
db.Where("a = ? AND b = ?", 1, 2).First(&row)Save matches the full tuple
Save updates by a = ? AND b = ?, so siblings sharing the first key
column are untouched (composite_pk_test.go:84-107). If any key field
is zero, the row is not persisted — Save inserts instead of issuing a
partial-key update (composite_pk_test.go:111-125). FirstOrCreate
follows the same rule: a row counts as existing only when the whole tuple
is set (composite_pk_test.go:232-262).
First and Last order by the tuple
First/Last order by every key column in declaration order, so results
are deterministic when the first column ties:
var first cpkRow
if err := db.First(&first).Error; err != nil {
t.Fatal(err)
}
if first.A != 1 || first.B != 1 {
t.Errorf("First = (%d,%d), want (1,1)", first.A, first.B)
}FindInBatches paginates with row values
Batch iteration advances a keyset cursor over the whole tuple — rendered as a row-value comparison, not a single-column inequality:
-- the composite cursor renders as a row-value comparison:
(a, b) > (?, ?) ORDER BY a, bRow-value syntax is gated on the feature.RowValues dialect flag,
declared by SQLite and PostgreSQL (dialect/feature/feature.go:31-33,
dialect/sqlite/sqlite.go:53, dialect/postgres/postgres.go:57). A
dialect without the flag gets an error that names the feature and matches
fusion.ErrUnsupportedFeature (finisher_api.go:395-397,
errors.go:42-44) — it never falls back to single-column pagination.
SQLite rowid backfill
SQLite's LastInsertID backfill no longer overwrites client-assigned
composite key fields with the rowid — your set key values survive Create
(CHANGELOG.md, [0.4.0]).
Relation limits
Relations infer a single foreign-key column; a composite key cannot be
guessed, so inference fails loudly at parse with
schema.ErrInvalidRelation instead of preloading by the first key column:
- belongs-to onto a composite-key table requires an explicit single
references:column. Without it, parse fails naming the composite key (composite_pk_test.go:274-293):
// belongs-to onto a composite-key table must name its referenced column
// instead of guessing PKs[0].- has-one / has-many / many2many on a composite-key side are rejected
at parse — one FK column cannot express them (
composite_pk_test.go:347-353, 363-369). - A single-column relation with explicit tags keeps working: a
belongs-to naming
foreignKey:ParentB,references:Bonto the composite table preloads normally (composite_pk_test.go:295-330).
type cpkChildRef struct {
ID int64 `fusion:"pk,autoincrement"`
ParentB int64 `fusion:"notnull"`
Parent *cpkRow `fusion:"rel:belongs-to,foreignKey:ParentB,references:B"`
}A working example
Create rows and read one back by full tuple:
rows := []cpkRow{
{A: 2, B: 1, Name: "b21"},
{A: 1, B: 2, Name: "b12"},
{A: 1, B: 1, Name: "b11"},
}
if err := db.Create(&rows).Error; err != nil {
// handle
}
var got cpkRow
if err := db.Where("a = ? AND b = ?", 1, 2).First(&got).Error; err != nil {
// handle
}
fmt.Println(got.Name) // b12Batch inserts need no special handling — every key column is an
InsertColumns member, since only autoincrement keys are excluded
(schema/table.go:189-200).