Home > Net >  Data truncated and incorrect integer value errors
Data truncated and incorrect integer value errors

Time:08-24

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.

CodePudding user response:

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.

CodePudding user response:

describe your table. describe your table. pls. describe your table to get more info.

CodePudding user response:

Yeah describe your table. It seems like the sql table is expecting uid to be integer but string is being passed.

  • Related