From cf1482ecb7fc022779992effde710044c869e771 Mon Sep 17 00:00:00 2001 From: Samuel Dufel Date: Mon, 10 Nov 2025 09:12:08 -0800 Subject: [PATCH] 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> --- entc/gen/type.go | 9 ++++++++- entc/gen/type_test.go | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/entc/gen/type.go b/entc/gen/type.go index 76603c08d..252f0a629 100644 --- a/entc/gen/type.go +++ b/entc/gen/type.go @@ -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 } diff --git a/entc/gen/type_test.go b/entc/gen/type_test.go index 4455b195d..64f716e27 100644 --- a/entc/gen/type_test.go +++ b/entc/gen/type_test.go @@ -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{