数据截断和不正确的整数值错误

huangapple go评论86阅读模式
英文:

Data truncated and incorrect integer value errors

问题

使用GORM时,我想将uuid作为主键,而不是默认的递增整数。我的模型如下:

type User struct {
	ID       string `gorm:"primaryKey" sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
	Username string `json:"username" gorm:"unique"`
	Password string `json:"password"`
}

// 这是一个 Gorm 钩子函数。
func (u *User) BeforeCreate(tx *gorm.DB) error {
	u.ID = uuid.NewString()
	return nil
}

当我插入 SQLite 数据库时,数据可以成功插入,但是当我插入 MySQL 数据库时,会出现以下错误:

  1. 错误 1265: 列 'id' 的数据被截断,位于第 1 行
  2. 错误 1366: 列 'id' 的值 'e2d63365-6876-4183-bd81-6deb3e3906e6' 不正确,位于第 1 行
  3. 错误 1264: 列 'id' 的值超出范围,位于第 1 行

GORM 生成的 SQL 命令如下:

INSERT INTO `users` (`id`,`username`,`password`) VALUES ('4de44e7e-b658-4225-b654-296d4e60624c','joe_mama','supersecret')

我找到了其他关于这些错误的帖子,但它们都是关于 SQL 的,而我无法对其进行任何更改,因为 Gorm 处理了这部分。

英文:

With GORM I want to use uuid as primary key rather than default incrementing integer. My model:

type User struct {
	ID       string `gorm:"primaryKey" sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
	Username string `json:"username" gorm:"unique"`
	Password string `json:"password"`
}

// This is a Gorm hook.
func (u *User) BeforeCreate(tx *gorm.DB) error {
	u.ID = uuid.NewString()
	return nil
}

When I insert into SQLite the data gets inserted but when I insert into a MySQL database I get errors:

  1. Error 1265: Data truncated for column 'id' at row 1
  2. Error 1366: Incorrect integer value: 'e2d63365-6876-4183-bd81-6deb3e3906e6' for column 'id' at row 1
  3. Error 1264: Out of range value for column 'id' at row 1

The command GORM is creating:

INSERT INTO `users` (`id`,`username`,`password`) VALUES ('4de44e7e-b658-4225-b654-296d4e60624c','joe_mama','supersecret')

I've found other posts about such errors but they're all SQL focused which I really can't do anything about since Gorm handles that.

答案1

得分: 1

根据 @FanoFN 的建议,我运行了以下命令:

SHOW CREATE TABLE users;

这显示了模型的架构,并显示我的表正在使用我之前实施的旧架构。

解决方案是删除 users 表并重新迁移模型。

英文:

As suggested by @FanoFN, I ran the following command:

SHOW CREATE TABLE users;

This showed the schema of the model and it showed that my table was using an older schema which I had implemented previously.

The solution ended up being to just drop the users table and remigrate the model.

huangapple
  • 本文由 发表于 2022年8月24日 09:11:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/73466436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定