Description
Just like the title, An exception has occurred when using *gorm.DB.Create() or *gorm.DB.CreateInBatches(), gorm version: v1.24.2, mysql 8 :
Error 1110: Column 'id' specified twice
I have try to trace the source code to there places:
gorm.io/gorm@v1.24.2/schema/schema.go:248
gorm.io/gorm@v1.24.2/callbacks/create.go:256
my table's DDL:
CREATE TABLE `factory_relation_user` (
`id` int unsigned NOT NULL DEFAULT '0' COMMENT 'PK',
`user_id` varchar(64) DEFAULT NULL COMMENT 'User ID',
`factory_id` int NOT NULL DEFAULT '0' COMMENT 'Factory ID'
) ENGINE=InnoDB;
GORMTag for id:
`gorm:"column:id;type:int(10) unsigned;size:10;primaryKey;default:0;comment:PK"`
then i found exception occurs when my gorm model has there config:
1. `int` type `primary key`
2. it is not autoincrement column
3. it has `default value` like 0
4. by the way my pk is named 'id',but the name is not the factor
so when i set the values for fields
id=111
user_id='111'
factory_id=111
the result of gorm's judgement :
//gorm.io/gorm@v1.24.2/schema/schema.go:248
//field.HasDefaultValue == true but field.DefaultValueInterface is not nil, so field were append into schema.FieldsWithDefaultDBValue
if !field.HasDefaultValue || field.DefaultValueInterface != nil {
schema.FieldsWithDefaultDBValue = append(schema.FieldsWithDefaultDBValue, field)
}
//gorm.io/gorm@v1.24.2/callbacks/create.go:243
for _, field := range stmt.Schema.FieldsWithDefaultDBValue {
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) {
if rvOfvalue, isZero := field.ValueOf(stmt.Context, rv); !isZero {
if len(defaultValueFieldsHavingValue[field]) == 0 {
defaultValueFieldsHavingValue[field] = make([]interface{}, rValLen)
}
defaultValueFieldsHavingValue[field][i] = rvOfvalue
}
}
}
//gorm.io/gorm@v1.24.2/callbacks/create.go:255
//i think gorm should checking duplicate before append clause.Column to values.Columns
for field, vs := range defaultValueFieldsHavingValue {
values.Columns = append(values.Columns, clause.Column{Name: field.DBName})
for idx := range values.Values {
if vs[idx] == nil {
values.Values[idx] = append(values.Values[idx], stmt.Dialector.DefaultValueOf(field))
} else {
values.Values[idx] = append(values.Values[idx], vs[idx])
}
}
}
the generated sql:
insert into(id,user_id,factory_id,id) values(111,'111',111,111);
fix: we should not append exists clause.Column to values.Columns
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨