Fix #4930 workaround for databases that support auto-increment in composite primary key.
This commit is contained in:
parent
85eaf9eeda
commit
a6e90777e3
@ -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)
|
||||
}
|
||||
|
@ -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
|
||||
})
|
||||
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user