https://github.com/LiveAlone/playground
grom 版本升级 1.21.13 升级到 1.24.6 版本时候, 发现Insert 返回主键Id 不对。
我的model 定义
type User struct {
ID ID `gorm:"primaryKey;column:id" json:"id"`
Name string
}
type ID int64
func (i ID) GormDataType() string {
return "int64"
}
func (i ID) Value() (driver.Value, error) {
return int64(i), nil
}
func (i ID) Int64() int64 {
return int64(i)
}
发现执行Create 以后 int64 id 类型没有返回,debug 发现版本主键类型解析有问题。
老版本没问题
新版本 GORMDataType 竟然解析成 int64 (GormDataType 自定义类型)
翻看代码,/Users/zyb/go/pkg/mod/gorm.io/gorm@v1.21.13/schema/field.go:76 这个方法
老版本解析类型,立即赋值给 GORMDataType
新版本这行被删除了
导致GORMDataType 不对。
后面由于GROM 类型不对, 未识别自增主键, 没有赋值自增id
type GormDataTypeInterface interface {
GormDataType() string
}
type DataType string
const (
Bool DataType = "bool"
Int DataType = "int"
Uint DataType = "uint"
Float DataType = "float"
String DataType = "string"
Time DataType = "time"
Bytes DataType = "bytes"
)
所以这个接口, 约定返回DataType , 是不是定义返回类型 DataType 而不是string 更明确一点。
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 ✨
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 ✨
Comment From: a631807682
GormDataType refers to the database type and should not be int64. Of course, such a type definition may still not conform to DataType (Int/Uint), such as the alias integer of int in mysql, but the behavior here is only used to guess whether the primary key is self-incrementing. You can be specified directly through autoIncrement.
type User struct {
- ID ID `gorm:"primaryKey;column:id" json:"id"`
+ ID ID `gorm:"primaryKey;column:id;autoIncrement" json:"id"`
Name string
}