postgresql - 如何在 Go 中表示 PostgreSQL 区间

标签 postgresql go

如何在 Go 中表示 PostgreSQL 区间?

我的结构看起来像这样:

type Product struct {
    Id              int
    Name            string
    Type            int
    Price           float64
    Execution_time  ????
}

我的数据库中的 execution_time 字段是 interval

最佳答案

我的最佳答案come across是在您的架构中使用 bigint,并在 time.Duration 的包装器类型上实现 ValueScan

// Duration lets us convert between a bigint in Postgres and time.Duration
// in Go
type Duration time.Duration

// Value converts Duration to a primitive value ready to written to a database.
func (d Duration) Value() (driver.Value, error) {
    return driver.Value(int64(d)), nil
}

// Scan reads a Duration value from database driver type.
func (d *Duration) Scan(raw interface{}) error {
    switch v := raw.(type) {
    case int64:
        *d = Duration(v)
    case nil:
        *d = Duration(0)
    default:
        return fmt.Errorf("cannot sql.Scan() strfmt.Duration from: %#v", v)
    }
    return nil
}

不幸的是,您将牺牲在查询中执行区间运算的能力 - 除非一些聪明的家伙想要发布 bigint => interval 的类型转换。

关于postgresql - 如何在 Go 中表示 PostgreSQL 区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32746858/

相关文章:

Go - 测试 - 无输出

postgresql - RoR/Postgres 查询所有父对象的第一个或最后一个子对象

sql - 如何选择多列,但只显示唯一/非重复的结果(基于一个特定列)?

postgresql - 如果我需要等待连接,我应该做主异步吗?

python - 在 Postgres 中存储 JSON 时保留 Python None/NULL

go - Go中的N叉树

javascript - 如何在 Sequelize (Node js) 中关联对象?

node.js - golang base64 编码 vs nodejs 缓冲区 base64 编码

go - 时间包go golang中的IST时区错误

xml - 使用 Go bleve 文本索引库索引 XML