postgresql - 我应该如何将Postgres日期类型分配给变量

标签 postgresql go

我在具有以下架构的列中将过期日期插入Postgres:exp DATE NOT NULL
我在Golang中创建这些日期的方式是使用使用Time数据类型的“时间”库(不确定其基础类型是否为字符串,go docs并未真正指定see here)。

这是我使用pgx库进行插入的方式

expirationDate := time.Unix(expiresAt, 0)
sql := `
  insert into items 
  (sub, uuid, exp) 
  VALUES ($1, $2, $3)
`
_, err := connection.Exec(
  context.Background(),
  sql,
  subject,
  id,
  expirationDate,
)

我的代码expiresAt中的其他地方是这样制作的:

days := 1 * 24 * time.Hour
expirationTime := time.Now().Add(days)
expirationTime.Unix() // this is what's being passed in my function (expiresAt int64) that does the DB insertion

问题是试图使该日期早于Postgres。
当我在pgAdmin中查看它时,我看到它被存储为yyyy-mm-dd,因此我假设也许可以将其分配给一个字符串变量,所以我尝试了以下操作:

type RevokedRefreshToken struct {
  OldUUID           string
  OldExpirationDate string
}
var revokedRefreshToken RevokedRefreshToken
err := connection.QueryRow(context.Background(), "select uuid, exp from items where sub = $1", subject).
Scan(&revokedRefreshToken.OldUUID, &revokedRefreshToken.OldExpirationDate)

我也尝试过:
-int64类型
-时间类型
-不使用其内存地址传递它(在Scan()中不带&)

我仍然不知道要为此数据库值分配的数据类型。
这是我认为来自pgx的错误:can't scan into dest[1]: unable to assign to *string
我需要使用什么数据类型来分配PostgreSQL的数据库值date type

最佳答案

如果我没记错的话,pgxDATE映射到time.Time。要进行扫描,您要么需要一个指向该指针的指针,要么使用pgxpgtype.Date数据类型(我已经习惯了这些,所以我总是使用它们):

var dt pgtype.Date
err := conn.QueryRow("select exp from items where sub = $1", 1).Scan(&dt)

然后pgtype.Date具有一个称为Time的字段,其类型为time.Time,因此您应该可以正常使用它。参见documentation

关于postgresql - 我应该如何将Postgres日期类型分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61410868/

相关文章:

iterator - 在 Go 中创建迭代器最惯用的方法是什么?

linux - 安装露天社区版时 initdb 出现权限被拒绝错误

postgresql - Postgres : How to sort by string date with timezone?

go - Golang 中的匿名接口(interface)实现

go - 如何在golang中将文本附加到文件中?

go - 去获取github…给GOPATH不能启动〜

postgresql - 生成 Postgres 转储并保存到另一台服务器

java - 将 Java 连接到 PostgreSQL 时强制 TZ?

PostgreSQL WHERE IN 子句变体

go - uint8, int8 的算术运算