[null] 自定义类型为nil时,没有忽略掉该字段 #1372

Closed
opened 2019-07-29 02:18:01 +00:00 by Tang-RoseChild · 3 comments
Tang-RoseChild commented 2019-07-29 02:18:01 +00:00 (Migrated from github.com)

背景

当类型中的某个字段实现了core.Conversion接口,但是值为nil时,还是调用了ToDB()

期望

为nil时,应该忽略掉该字段,使用数据库默认的值,例如NULL等

示例

Addr 为json 类型

type Person struct {
  Addr *Addr
}

type Addr struct {
  Street string
}
func (r *Addr) FromDB(d []byte) error {
	return json.Unmarshal(d, r)
}

func (r *Addr) ToDB() ([]byte, error) {
	return json.Addr(r)
}

var p Person
session.Insert(p)

输出:
数据库中addr的字段值为 json的 "null",而不是期望的数据库中的 NULL

源代码

if fieldConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
 // balabala

if fieldConvert, ok := fieldValue.Interface().(core.Conversion); ok {
// balabala

这里没有判断nil的处理

## 背景 当类型中的某个字段实现了core.Conversion接口,但是值为nil时,还是调用了ToDB() ## 期望 为nil时,应该忽略掉该字段,使用数据库默认的值,例如NULL等 ## 示例 Addr 为json 类型 ``` type Person struct { Addr *Addr } type Addr struct { Street string } func (r *Addr) FromDB(d []byte) error { return json.Unmarshal(d, r) } func (r *Addr) ToDB() ([]byte, error) { return json.Addr(r) } var p Person session.Insert(p) 输出: 数据库中addr的字段值为 json的 "null",而不是期望的数据库中的 NULL ``` ## [源代码](https://github.com/go-xorm/xorm/blob/master/session_convert.go#L549) ``` if fieldConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok { // balabala if fieldConvert, ok := fieldValue.Interface().(core.Conversion); ok { // balabala ``` 这里没有判断nil的处理

@Tang-RoseChild could you send a PR to fix that?

@Tang-RoseChild could you send a PR to fix that?
Tang-RoseChild commented 2019-07-29 15:57:04 +00:00 (Migrated from github.com)

@Tang-RoseChild could you send a PR to fix that?

i'm too busy now, maybe later?

> @Tang-RoseChild could you send a PR to fix that? i'm too busy now, maybe later?

@Tang-RoseChild That's OK.

@Tang-RoseChild That's OK.
lunny added this to the 1.2.0 milestone 2021-06-12 08:22:20 +00:00
lunny added the
kind
bug
label 2021-06-12 09:42:27 +00:00
lunny referenced this issue from a commit 2021-07-11 13:33:01 +00:00
lunny closed this issue 2021-07-11 13:33:01 +00:00
Sign in to join this conversation.
No Milestone
No Assignees
1 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: xorm/xorm#1372
No description provided.