fix(codegen): sort map iteration to make generated output deterministic
Table.Columns/Constraints/Indexes/Relationships are Go maps, and every writer, reader, diff, inspector, and merge code path that iterated them directly was subject to Go's randomized map order, so identical input could produce different output (or a different in-report violation/diff order) on every run. Most visibly this showed up as bun/gorm `unique:` struct tags changing order across consecutive `make models` runs with no source change. Fixed by sorting map iteration (by Sequence then Name, or alphabetically for string-keyed maps) everywhere the order affects generated output or first-match tie-break logic, across the bun, gorm, sqlite, dbml, drawdb, pgsql, prisma, graphql, typeorm, drizzle, and dctx writers; the dctx, prisma, and typeorm readers; the shared models.GetPrimaryKey/ GetForeignKeys helpers; pkg/diff, pkg/inspector, and pkg/merge; and the TUI column/relationship pickers in pkg/ui.
This commit is contained in:
@@ -820,17 +820,31 @@ func (r *Reader) createImplicitJoinTable(model1, model2 string, tableMap map[str
|
||||
tableMap[joinTableName] = joinTable
|
||||
}
|
||||
|
||||
// getPrimaryKeyColumn returns the primary key column of a table
|
||||
// getPrimaryKeyColumn returns the primary key column of a table. For tables
|
||||
// with a composite primary key, the column with the lowest Sequence (or,
|
||||
// failing that, the alphabetically first Name) is returned deterministically.
|
||||
func (r *Reader) getPrimaryKeyColumn(table *models.Table) *models.Column {
|
||||
if table == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var pk *models.Column
|
||||
for _, col := range table.Columns {
|
||||
if col.IsPrimaryKey {
|
||||
return col
|
||||
if !col.IsPrimaryKey {
|
||||
continue
|
||||
}
|
||||
if pk == nil {
|
||||
pk = col
|
||||
continue
|
||||
}
|
||||
if col.Sequence > 0 && pk.Sequence > 0 {
|
||||
if col.Sequence < pk.Sequence {
|
||||
pk = col
|
||||
}
|
||||
} else if col.Name < pk.Name {
|
||||
pk = col
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return pk
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user