entc/gen: bake Schema into generated code and allow same table names across schemas#4485
entc/gen: bake Schema into generated code and allow same table names across schemas#4485dannyota wants to merge 2 commits into
Conversation
…across schemas When two PostgreSQL schemas have tables with the same name (e.g., global.templates and lead.templates), code generation previously failed because Tables() rejected same table names across schemas and the template generated duplicate Go identifiers. This change: - Uses schema-qualified keys in the tables map to allow same table names in different schemas - Adds computeTableIdents() to generate unique Go identifiers: uses pascal(name) by default, falls back to pascal(schema)+"_"+pascal(name) on collision - Adds TableIdent() method on Graph, used by the schema template - Emits the Schema field in generated migrate/schema.go table structs - Fixes CopyTables to preserve Schema, Comment, View, Pos fields and use schema-qualified keys for FK ref lookups Fixes ent#2330
|
The original logic defaults to 'the first schema in the desired reality is the schema to be migrated'. Should we modify ent/dialect/sql/schema |
|
Thanks, good catch. I updated the inspect-mode migration logic so it no longer defaults to the first schema in the desired realm when multiple schemas are present. The selection now prefers:
I also added TestAtlas_DesiredSchema to cover current-schema matching, configured-schema fallback, single-schema compatibility, and the multi-schema no-match case. |
Fixes #2330
When two PostgreSQL schemas have tables with the same name (e.g.,
global.templatesandlead.templates), code generation fails becauseTables()rejects same table names across schemas and the template generates duplicate Go identifiers.Changes
entc/gen/graph.go"schema.table") in the tables map to allow same table names in different schemasnodeTmap (*Type → *schema.Table) for FK lookups instead of bare table name lookupscomputeTableIdents()to generate unique Go identifiers:pascal(name)by default,pascal(schema) + "_" + pascal(name)on collisionTableIdent(*schema.Table) stringmethod onGraph, used by the schema templateentc/gen/template/migrate/schema.tmplpascal $t.Name/pascal $fk.RefTable.Nameusages with$.TableIdentSchemafield in generated table structs when setdialect/sql/schema/schema.goCopyTablesto preserveSchema,Comment,View,Posfields (previously silently dropped)byNamemap and FK ref lookupBackward Compatibility
Schemafield emitted, identifiers unchanged. Generated code identical to before.UsersTable).Global_TemplatesTable).Table.SchemaoverridesCopyTablesSchemafield (was silently dropped).Testing
TestMultiSchemaSameTableName,TestSingleSchemaTableIdent,TestDuplicateTableNameSameSchema,TestCopyTablesMultiSchemamultischema/ent/migrate/schema.gowith Schema baked in, verified against MySQL 8