entc/gen: add support for custom collations on ID fields (#4453)

* Add support for custom collations on ID fields

In cases with a string PK / importing existing schema to use ent, it's helpful to be
able to control the collation.

* Update entc/gen/type.go

Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com>

---------

Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com>
This commit is contained in:
Samuel Dufel
2025-11-10 09:12:08 -08:00
committed by GitHub
parent a777c08cdd
commit cf1482ecb7
2 changed files with 20 additions and 1 deletions

View File

@@ -1643,7 +1643,8 @@ func (f Field) PK() *schema.Column {
}
// Override the default-value defined in the
// schema if it was provided by an annotation.
switch ant := f.EntSQL(); {
ant := f.EntSQL()
switch {
case ant == nil:
case ant.Default != "":
c.Default = ant.Default
@@ -1656,6 +1657,12 @@ func (f Field) PK() *schema.Column {
}
c.Default = x
}
// Override collation with annotation value
if ant != nil && ant.Collation != "" {
c.Collation = ant.Collation
}
if f.def != nil {
c.SchemaType = f.def.SchemaType
}

View File

@@ -37,6 +37,18 @@ func TestType(t *testing.T) {
})
require.EqualError(err, "sensitive field \"foo\" cannot have struct tags", "sensitive field cannot have tags")
typ, err = NewType(&Config{Package: "entc/gen"}, &load.Schema{
Fields: []*load.Field{
{Name: "id", Info: &field.TypeInfo{Type: field.TypeString}, Annotations: dict("EntSQL", dict("collation", "utf8_ci_bin"))},
},
})
require.NoError(err)
require.NotNil(typ)
require.NotNil(t, typ.ID)
pkCol := typ.ID.PK()
require.NotNil(pkCol)
require.Equal("utf8_ci_bin", pkCol.Collation)
_, err = NewType(&Config{Package: "entc/gen"}, &load.Schema{
Name: "T",
Fields: []*load.Field{