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:
@@ -836,6 +836,43 @@ func TestTypeMapper_BuildBunTag(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestTypeMapper_BuildBunTag_MultipleUniqueIndexesDeterministic verifies that
|
||||
// when a column belongs to more than one unique index, the "unique:" tag
|
||||
// fragments always appear in the same order across repeated calls, instead
|
||||
// of following Go's randomized map iteration order over Table.Indexes.
|
||||
func TestTypeMapper_BuildBunTag_MultipleUniqueIndexesDeterministic(t *testing.T) {
|
||||
mapper := NewTypeMapper("", "")
|
||||
table := &models.Table{
|
||||
Name: "accounts",
|
||||
Indexes: map[string]*models.Index{
|
||||
"idx_z_accounts_email_tenant": {
|
||||
Name: "idx_z_accounts_email_tenant",
|
||||
Columns: []string{"email", "tenant_id"},
|
||||
Unique: true,
|
||||
},
|
||||
"idx_a_accounts_email_region": {
|
||||
Name: "idx_a_accounts_email_region",
|
||||
Columns: []string{"email", "region_id"},
|
||||
Unique: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
column := &models.Column{Name: "email", Type: "varchar", Length: 255, NotNull: true}
|
||||
|
||||
first := mapper.BuildBunTag(column, table)
|
||||
for i := 0; i < 50; i++ {
|
||||
got := mapper.BuildBunTag(column, table)
|
||||
if got != first {
|
||||
t.Fatalf("BuildBunTag() is non-deterministic across calls: %q vs %q", first, got)
|
||||
}
|
||||
}
|
||||
|
||||
wantOrder := "unique:idx_a_accounts_email_region,unique:idx_z_accounts_email_tenant,"
|
||||
if !strings.Contains(first, wantOrder) {
|
||||
t.Errorf("BuildBunTag() = %q, want unique tags sorted by index name: %q", first, wantOrder)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTypeMapper_BuildBunTag_ArraysAreNativeInEveryMode verifies that array
|
||||
// columns always use a plain "text[]"-style type and the native Go slice
|
||||
// type plus an explicit "array" tag, regardless of NullableTypes style
|
||||
|
||||
Reference in New Issue
Block a user