
解决 gorm (postgres) 自增主键自定义类型的问题
在使用 gorm 与 postgres 时,如果将主键设置为自定义类型(例如 bigint),表自动迁移时无法创建自增。这是因为 gorm 无法识别自定义类型的自增属性。
通过调试 gorm 和 postgres 驱动器的代码,找到了解决办法:
在 bigint 类型中添加 gormdbdatatype 方法,用于指定表字段的数据类型:
func (bigint) gormdbdatatype(db *gorm.db, field *schema.field) string {
switch db.dialector.name() {
case "mysql", "sqlite":
return "bigint"
case "postgres":
if field.autoincrement {
return "bigserial"
}
return "bigint"
}
return "bigint"
}gormdbdatatype 方法根据数据库类型返回适当的数据类型。对于 postgres,如果字段是自增的,则返回 "bigserial",否则返回 "bigint"。
修复后的代码:
type GVA_MODEL struct {
ID BigInt `gorm:"primaryKey;autoIncrement;type:bigint;size:64;-youjiankuohaophpcn" form:"id" json:"id" query:"id"` // 主键ID
// ...
}
type BigInt json.Number
// ... (Scan、Value 方法与原代码相同)
func (BigInt) GormDBDataType(db *gorm.DB, field *schema.Field) string {
switch db.Dialector.Name() {
case "mysql", "sqlite":
return "bigint"
case "postgres":
if field.AutoIncrement {
return "bigserial"
}
return "bigint"
}
return "bigint"
}通过这个修复,在自动迁移时,postgres 将正确地创建自定义类型 bigint 的主键并将其设置为自增。










