From a6e90777e3606e88af26ef2cffd47388eb58c4f0 Mon Sep 17 00:00:00 2001 From: truongns Date: Tue, 7 Mar 2023 18:10:25 +0900 Subject: [PATCH] Fix #4930 workaround for databases that support auto-increment in composite primary key. --- schema/schema.go | 10 ++++++++++ schema/schema_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/schema/schema.go b/schema/schema.go index b34383bd..fab1dcef 100644 --- a/schema/schema.go +++ b/schema/schema.go @@ -225,6 +225,16 @@ func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Nam schema.PrioritizedPrimaryField = schema.PrimaryFields[0] } + // If there are multiple primary keys, the AUTOINCREMENT field is prioritized + if schema.PrioritizedPrimaryField == nil && len(schema.PrimaryFields) > 1 { + for _, field := range schema.PrimaryFields { + if _, ok := field.TagSettings["AUTOINCREMENT"]; ok { + schema.PrioritizedPrimaryField = field + break + } + } + } + for _, field := range schema.PrimaryFields { schema.PrimaryFieldDBNames = append(schema.PrimaryFieldDBNames, field.DBName) } diff --git a/schema/schema_test.go b/schema/schema_test.go index 8a752fb7..b263974d 100644 --- a/schema/schema_test.go +++ b/schema/schema_test.go @@ -293,3 +293,30 @@ func TestEmbeddedStructForCustomizedNamingStrategy(t *testing.T) { }) } } + +func TestCompositePrimaryKeyWithAutoIncrement(t *testing.T) { + type Product struct { + ProductID uint `gorm:"primaryKey;autoIncrement"` + LanguageCode uint `gorm:"primaryKey"` + Code string + Name string + } + + product, err := schema.Parse(&Product{}, &sync.Map{}, schema.NamingStrategy{}) + if err != nil { + t.Fatalf("failed to parse product struct with composite primary key, got error %v", err) + } + + prioritizedPrimaryField := schema.Field{ + Name: "ProductID", DBName: "product_id", BindNames: []string{"ProductID"}, DataType: schema.Uint, PrimaryKey: true, Size: 64, HasDefaultValue: true, AutoIncrement: true, TagSettings: map[string]string{"PRIMARYKEY": "PRIMARYKEY", "AUTOINCREMENT": "AUTOINCREMENT"}, + } + + product.Fields = []*schema.Field{product.PrioritizedPrimaryField} + + checkSchemaField(t, product, &prioritizedPrimaryField, func(f *schema.Field) { + f.Creatable = true + f.Updatable = true + f.Readable = true + }) + +}