使用标准数据库/sqlRow.Scan()我在行中遇到空值问题。在不考虑连续可能的空值的情况下,我可能会收到类似<nil> -> *string. 这在使用 LEFT JOIN 查询或缺少 NO NULL 列约束的弱定义表时很常见。
有一些sql.NullXXX类型(例如 sql.NullInt64)可用于扫描一行中可能的空值,然后检查该值是否为.Valid。但是,这些类型没有实现 JSON 编组,需要更多的逻辑和编码。
为了解决这个问题,COALESCE()在 SQL 查询中处理列值是更好的方法还是在 golang 代码中做一些额外的编码?
您可以为 sql 包提供的类型使用别名,例如(NullInt64、NullString 等...)。使用它有两个优点,一是可以扫描空值并进入 golang 结构,二是可以在 JSON 中编组该结构。
请看示例代码:
// NullInt64 is an alias for sql.NullInt64 data type
type NullInt64 sql.NullInt64
// Scan implements the Scanner interface for NullInt64
func (ni *NullInt64) Scan(value interface{}) error {
var i sql.NullInt64
if err := i.Scan(value); err != nil {
return err
}
// if nil the make Valid false
if reflect.TypeOf(value) == nil {
*ni = NullInt64{i.Int64, false}
} else {
*ni = NullInt64{i.Int64, true}
}
return nil
}
// MarshalJSON for NullInt64
func (ni *NullInt64) MarshalJSON() ([]byte, error) {
if !ni.Valid {
return []byte("null"), nil
}
return json.Marshal(ni.Int64)
}
Run Code Online (Sandbox Code Playgroud)
请看一下这篇文章,它对在 golang 中处理空值以及如何在 JSON 中使用它非常有帮助。
作为一个选项,您可以实现与JSON Marshaler接口匹配的自定义数据类型。之后,您将能够使用常规标签来编组您的结构。
检查示例:
type UserTitleType sql.NullString
func (s UserTitleType) MarshalJSON() ([]byte, error) {
if s.Valid {
return json.Marshal(s.String)
}
return jsonNull, nil
}
type User struct {
Id int64 `json:"id"`
Title UserTitleType `json:"title"`
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13776 次 |
| 最近记录: |