From 9d04526060ee0ca481058e6e98a06bb8ae5ef09a Mon Sep 17 00:00:00 2001 From: cubatic45 Date: Sun, 28 Apr 2024 18:21:42 +0800 Subject: [PATCH 1/2] generics model support --- orm/table.go | 13 +++++++++---- orm/table_test.go | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/orm/table.go b/orm/table.go index 29c1c0c3..c3a6f7a9 100644 --- a/orm/table.go +++ b/orm/table.go @@ -95,9 +95,14 @@ type Table struct { func newTable(typ reflect.Type) *Table { t := new(Table) t.Type = typ + name := t.Type.Name() + index := strings.Index(name, "[") + if index > 0 { + name = name[:index] + } t.zeroStruct = reflect.New(t.Type).Elem() - t.TypeName = internal.ToExported(t.Type.Name()) - t.ModelName = internal.Underscore(t.Type.Name()) + t.TypeName = internal.ToExported(name) + t.ModelName = internal.Underscore(name) tableName := tableNameInflector(t.ModelName) t.setName(quoteIdent(tableName)) t.Alias = quoteIdent(t.ModelName) @@ -292,7 +297,7 @@ func (t *Table) addFields(typ reflect.Type, baseIndex []int) { } } -//nolint +// nolint func (t *Table) newField(f reflect.StructField, index []int) *Field { pgTag := tagparser.Parse(f.Tag.Get("pg")) @@ -944,7 +949,7 @@ func (t *Table) mustM2MRelation(field *Field, pgTag *tagparser.Tag) bool { return true } -//nolint +// nolint func (t *Table) tryRelationSlice(field *Field, pgTag *tagparser.Tag) bool { if t.tryM2MRelation(field, pgTag) { internal.Deprecated.Printf( diff --git a/orm/table_test.go b/orm/table_test.go index c01fcd49..285ede5a 100644 --- a/orm/table_test.go +++ b/orm/table_test.go @@ -262,6 +262,23 @@ var _ = Describe("embedding with ignored field", func() { }) }) +type P[T any] struct { + Data T +} + +var _ = Describe("generics model", func() { + var table *orm.Table + + BeforeEach(func() { + strct := reflect.ValueOf(P[string]{}) + table = orm.GetTable(strct.Type()) + }) + It("TypeName and ModelName", func() { + Expect(table.TypeName).To(BeEquivalentTo("P")) + Expect(table.ModelName).To(BeEquivalentTo("p")) + }) +}) + type Nameless struct { tableName struct{} `pg:"_"` From 1fe6177696434e6937e6685351991c820a1c94df Mon Sep 17 00:00:00 2001 From: cubatic45 <148538725+cubatic45@users.noreply.github.com> Date: Fri, 19 Jul 2024 10:34:48 +0800 Subject: [PATCH 2/2] Update table.go --- orm/table.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/orm/table.go b/orm/table.go index c3a6f7a9..9e86eaee 100644 --- a/orm/table.go +++ b/orm/table.go @@ -297,7 +297,7 @@ func (t *Table) addFields(typ reflect.Type, baseIndex []int) { } } -// nolint +//nolint func (t *Table) newField(f reflect.StructField, index []int) *Field { pgTag := tagparser.Parse(f.Tag.Get("pg")) @@ -949,7 +949,7 @@ func (t *Table) mustM2MRelation(field *Field, pgTag *tagparser.Tag) bool { return true } -// nolint +//nolint func (t *Table) tryRelationSlice(field *Field, pgTag *tagparser.Tag) bool { if t.tryM2MRelation(field, pgTag) { internal.Deprecated.Printf(