在 Go 中从 sql 获取 nil 值

Get nil value from sql in Go

假设我有一个结构 Profile 和 sql table profiles.

type Profile struct {
    ID        int       `json:"id"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
    FirstName string    `json:"first_name"`
    LastName  string    `json:"last_name"`
    Age       int       `json:"age"`
}

并且,我从 profiles table 中获取一条记录,分配到 Profile 结构中。

这些字段是allow null,所以我用了sql.NullString,sql.NullInt64, pq.NullTime 在分配给结构之前检查有效值。

// ... DB.Query(...)
// ... rows.Next()
// ... rows.Scan()
// ...
if firstName.Valid {
    p.FirstName = firstName.String
}
if lastName.Valid {
    p.LastName = lastName.String
}
if age.Valid {
    p.Age = age.Int64
}
// ...

如果我有超过 10 个 tables,每个 tables 有超过 30 列,我必须一次又一次地检查所有变量。 这使得代码变得丑陋,有人有什么建议可以让它变得漂亮吗?

你根本不应该那样检查。可空类型旨在直接在结构中使用:

type Profile struct {
    ID        sql.NullInt64  `json:"id"`
    CreatedAt time.Time      `json:"created_at"`
    UpdatedAt time.Time      `json:"updated_at"`
    FirstName sql.NullString `json:"first_name"`
    LastName  sql.NullString `json:"last_name"`
    Age       sql.NullInt64  `json:"age"`
}

然后使用 product.FirstName.String() 等访问这些值。没有理由检查 product.FirstName.Valid 除非你真正关心 nil 和空值之间的区别(在你的问题的例子中,你显然不关心这种区别)。

在某些情况下可能更合适的替代方法是仅使用指针:

type Profile struct {
    ID        *int      `json:"id"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
    FirstName *string   `json:"first_name"`
    LastName  *string   `json:"last_name"`
    Age       *int      `json:"age"`
}

当然,任何使用这些变量的代码都必须取消引用它们,并检查 nil,因此这可能并不总是最理想的,具体取决于您如何使用这些值。

第三种选择,如果您从不关心 NULL 值和空值之间的区别,那就是创建您自己的类型,将它们同等对待。示例:

type myString string

func (s *myString) Scan(src interface{}) error {
    if src == nil {
        return nil
    }
    if value, ok := src.(string); ok {
        *s = value
        return nil
    }
    return fmt.Errorf("Unsupported type for myString: %T", src)
}