如何在Go中表示PostgreSQL间隔

fon*_*ini 5 postgresql go

如何在Go中表示PostgreSQL间隔?

我的结构看起来像这样:

type Product struct {
    Id              int
    Name            string
    Type            int
    Price           float64
    Execution_time  ????
}
Run Code Online (Sandbox Code Playgroud)

我的数据库上的execute_time字段为interval

AMa*_*nce 7

我遇到的最好的答案是在您的架构中使用bigint,并在 的包装类型上实现Value& 。Scantime.Duration

// 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
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,您将牺牲在查询内进行区间算术的能力 - 除非一些聪明的人想要发布bigint=>的类型转换interval


Jan*_*zak 4

如果您同意遵守限制time.Duration并且只需要秒精度,您可以:

  • 创建具有第二精度的表 ... someInterval INTERVAL SECOND(0), ...
  • 将 INTERVAL 转换为秒: SELECT EXTRACT(EPOCH FROM someInterval) FROM someTable;

  • 使用time.Duration::Seconds将数据插入到准备好的语句中