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:
+24
-4
@@ -5,6 +5,7 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -141,15 +142,28 @@ func (d *Table) SQLName() string {
|
||||
|
||||
// GetPrimaryKey returns the primary key column for the table, or nil if none exists.
|
||||
func (m Table) GetPrimaryKey() *Column {
|
||||
var pk *Column
|
||||
for _, column := range m.Columns {
|
||||
if column.IsPrimaryKey {
|
||||
return column
|
||||
if !column.IsPrimaryKey {
|
||||
continue
|
||||
}
|
||||
if pk == nil || columnLess(column, pk) {
|
||||
pk = column
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return pk
|
||||
}
|
||||
|
||||
// GetForeignKeys returns all foreign key constraints for the table.
|
||||
// columnLess reports whether a should sort before b, by Sequence then Name.
|
||||
func columnLess(a, b *Column) bool {
|
||||
if a.Sequence > 0 && b.Sequence > 0 {
|
||||
return a.Sequence < b.Sequence
|
||||
}
|
||||
return a.Name < b.Name
|
||||
}
|
||||
|
||||
// GetForeignKeys returns all foreign key constraints for the table, sorted
|
||||
// deterministically by Sequence then Name.
|
||||
func (m Table) GetForeignKeys() []*Constraint {
|
||||
keys := make([]*Constraint, 0)
|
||||
|
||||
@@ -158,6 +172,12 @@ func (m Table) GetForeignKeys() []*Constraint {
|
||||
keys = append(keys, c)
|
||||
}
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
if keys[i].Sequence > 0 && keys[j].Sequence > 0 {
|
||||
return keys[i].Sequence < keys[j].Sequence
|
||||
}
|
||||
return keys[i].Name < keys[j].Name
|
||||
})
|
||||
return keys
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user