我一直在考虑使用GormValuerInterface赚钱:
type Amount struct {
Units int64
Nanos int32
}
我看到以下警告(我的)和错误(GORM):
WARN[0005] updating account ac9112c1-34cc-43c2-9f2d-a433c8310844 balance from 123.210000000 to 111.550000000 by -12.340000000
ERRO[0005] unexpected value type: {SQL:balance + ? Vars:[-12.340000000]}
更新语句定义为:
err := adapter.DB.Model(account).
Where("id = ? and version = ?", account.ID, account.Version).
UpdateColumn("balance", gorm.Expr("balance + ?", amount)).
UpdateColumn("version", gorm.Expr("version + 1")).Error
我写了一个GormValue函数(定义为):
func (i Amount) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
return clause.Expr{
SQL: "?",
Vars: []interface{}{fmt.Sprintf("%d.%d", i.Units, i.Nanos)},
}
}
我认为这很好,因为对于Valuer接口,我有类似的东西可以正常读取/写入数据:
func (i Amount) Value() (driver.Value, error) {
f := fmt.Sprintf("%d.%d", i.Units, i.Nanos)
return driver.Value(f), nil
}
不过,有了这个新界面的实现,我现在看到的是:
panic: value method shared/database/dbtypes.Amount.GormValue called using nil *Amount pointer
goroutine 944 [running]:
shared/database/dbtypes.(*Amount).GormValue(0x0, 0x1f47400, 0xc000044118, 0xc000ce5530, 0x0, 0x0, 0x0, 0x0, 0x0)
<autogenerated>:1 +0x254
gorm.io/gorm.(*Statement).AddVar(0xc000cef380, 0x1f33fc0, 0xc000cef380, 0xc000ce3080, 0x18, 0x18)
/path/to/go/pkg/mod/gorm.io/gorm@v1.20.2/statement.go:166 +0x12e6
gorm.io/gorm/clause.Values.Build(0xc00ce4f600, 0x18, 0x18, 0xc0006c84c0, 0x1, 0x1, 0x1f47c40, 0xc000cef380)
/path/to/go/pkg/mod/gorm.io/gorm@v1.20.2/clause/values.go:33 +0x311
gorm.io/gorm/clause.Clause.Build(0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1f2cd40, 0xc000ce5740, ...)
/path/to/go/pkg/mod/gorm.io/gorm@v1.20.2/clause/clause.go:55 +0xbd
gorm.io/gorm.(*Statement).Build(0xc000cef380, 0xc000d70ae0, 0x3, 0x3)
/path/to/go/pkg/mod/gorm.io/gorm@v1.20.2/statement.go:387 +0x2f1
gorm.io/gorm/callbacks.CreateWithReturning(0xc000ce5530)
/path/to/go/pkg/mod/gorm.io/gorm@v1.20.2/callbacks/create.go:123 +0xe71
gorm.io/gorm.(*processor).Execute(0xc00079c000, 0xc000ce5530)
/path/to/go/pkg/mod/gorm.io/gorm@v1.20.2/callbacks.go:101 +0x23d
gorm.io/gorm.(*DB).Create(0xc0007880c0, 0x1c9b380, 0xc0013b9c20, 0x1bf9fc0)
/path/to/go/pkg/mod/gorm.io/gorm@v1.20.2/finisher_api.go:20 +0xa7
database.(*GormAdapter).Create(0xc0004e41b0, 0x1f47480, 0xc000ce4360, 0xc000ace190, 0x1, 0x1, 0x0, 0x0)
/path/to/my/code/database/adapter.go:268 +0x8f
当我尝试插入列/字段类型为*dbtypes.Amount
的列/字段的新记录时,就会发生这种情况,恰好为空。据我所知,如果v为null,则需要在AddVar函数(第167行)中对statement.go进行更改,以不调用v.GormValue()。
这是预期的行为吗?