dongpiao8821 2017-04-21 22:17
浏览 70
已采纳

使用sqlx进行结构嵌入不会从数据库返回值

I have a struct with a time field that may be nil:

type Order struct {
    ...
    PickupTime  *time.Time    `json:"-"`
}

I want to save this to DB with sqlx so I figure I need to use pq.NullTime as suggested here.

Instead of updating the Order object (I don't want to leak DB code into the model layer), I figured I could embedd Order in a PgOrder and alter the PickupTime type:

type PgOrder struct {
    Order
    PickupTime pq.NullTime
}

The problem is that when I simply update an Order in DB, then turn around and fetch that order, the returned PickupTime is empty.

// update
func (pg Postgres) UpdateOrderPickupTime(order *Order, pickupTime time.Time) error {
    _, err := pg.Exec(`UPDATE orders SET pickup_time = $1 WHERE id = $2`, pickupTime, order.ID)
    return err
}

// retrieve
func (pg Postgres) GetOrder(orderID DatabaseID) (*Order, error) {
    pgOrder := PgOrder{}
    err := pg.Get(&pgOrder, `SELECT * FROM orders WHERE id = $1`, orderID)
    if err == sql.ErrNoRows {
        return nil, nil
    }
    ... // at this point pgOrder.PickupTime is 0001-01-01 00:00:00 +0000 UTC

}

If I put a breakpoint betwen updating and retrieving, I can inspect the DB and see that a value is being saved as 2017-04-20 12:05:37-04. So the problem must be in the retrieve portion. If I understand right from the docs, sqlx should be able to handle embedded structs.

  • 写回答

2条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 在matlab中如何进行三个参数的离散傅里叶逆变换(idft)
      • ¥15 遇到问题了,求解答!
      • ¥15 请问coppliasim eduUR5视觉抓取怎么实现仿真,
      • ¥30 JavaWeb实验(购物平台)
      • ¥15 八路抢答器倒计时设计时显示器不输出,只能显示0
      • ¥15 用C语言随机生成一个迷宫
      • ¥15 超多因素的正交方案设计
      • ¥15 Scratch~汽车小游戏
      • ¥30 OSGB转换为3dtiles
      • ¥25 用于Audio的芯片中“Audio Interface”和“Mode Control”是什么?