首页 > 解决方案 > 在 mysql 中使用 gorm 插入键入的 []byte 引发“错误 1241:操作数应包含 1 列”

问题描述

我有一个带有类型[]byte(密码哈希)的模型,我想MySQL:5.7使用gorm:v2.

// this will work
type ModelRaw struct {
    Bytes   []byte
}

type Hash []byte

// this will NOT work
type ModelTyped struct {
    Bytes Hash
}

func main() {
    // Migrate database
    // Both tables will have a column `bytes` of type `longblob default:NULL`
    if err := gormDB.AutoMigrate(&ModelRaw{}, &ModelTyped{}); err != nil {
        panic(err)
    }

    // this works
    mdl1 := &ModelRaw{Bytes: []byte("random-bytes")}
    if err := gormDB.Debug().Create(mdl1).Error; err != nil {
        panic(err)
    }

    // error here
    mdl2 := &ModelTyped{Bytes: Hash("random-bytes")}
    if err := gormDB.Debug().Create(mdl2).Error; err != nil {
        panic(err)
    }
}

上面的代码导致以下gorm调试输出:

2020/11/06 10:31:29 /go/src/app/main.go:47
[7.715ms] [rows:1] INSERT INTO `model_raws` (`bytes`) VALUES ('random-bytes')

2020/11/06 10:31:29 /go/src/app/main.go:53 Error 1241: Operand should contain 1 column(s)
[0.926ms] [rows:0] INSERT INTO `model_typeds` (`bytes`) VALUES ((114,97,110,100,111,109,45,98,121,116,101,115))
panic: Error 1241: Operand should contain 1 column(s)

演示问题的回购:https ://github.com/Iyashi/go-gorm-b​​ytes-test

工作 gorm:v1并闯入gorm:v2

gorm 的 AutoMigrate() 将 mysql 表列创建为longblob NULL.

标签: mysqlgogo-gorm

解决方案


为此,您应该只实现一个 driver.Valuer 接口:

func (h Hash) Value() (driver.Value, error) {
  return []byte(h), nil
}

然后您输入的数据将按预期与 Gorm v2 一起使用。


推荐阅读