登录
首页 >  Golang >  Go问答

postgresql 时间间隔不会被 sqlc.yaml 配置覆盖

来源:stackoverflow

时间:2024-02-06 21:42:27 312浏览 收藏

本篇文章向大家介绍《postgresql 时间间隔不会被 sqlc.yaml 配置覆盖》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

我发现 sqlc codegen 应用程序存在问题。万一,当我需要 interval (postgresql) 字段时,sqlc 会生成一个带有 int64 字段的对象。此解决方案看起来已损坏,并在扫描行时产生错误: errorf("cannot conversion %v to interval", value)

sqlc.yaml:

version: "2"
overrides:
  go:
    overrides:
      - db_type: "interval"
        engine: "postgresql"
        go_type:
          import: "time"
          package: "time"
          type: "https://pkg.go.dev/time#duration"
sql:
  - queries: "./sql_queries/raffle.query.sql"
    schema: "./migrations/001-init.sql"
    engine: "postgresql"
    gen:
     go:
        package: "raffle_repo"
        out: "../repo/sql/raffle_repo"
        sql_package: "pgx/v4"

schema.sql:

create table windowrange
(
    id        serial    primary key,
    open      timestamp not null ,
    duration  interval not null,
    created_at timestamp default now(),
    updated_at timestamp default now(),
    raffle_id integer not null
        constraint raffle_id
            references raffle
            on delete cascade
);

生成的模型:

type Windowrange struct {
    ID        int32
    Open      time.Time
    Duration  int64
    CreatedAt sql.NullTime
    UpdatedAt sql.NullTime
    RaffleID  int32
}

通过将此字段设置为 time.duration 类型,问题很快就得到了修复。duration 和代码开始工作,但此代码是代码生成的,看起来是个错误的决定。

在尝试通过 sqlc.yaml 配置覆盖类型时,我什么都没有,对象仍在创建 int64 类型。我哪里错了,如何解决这个问题?


正确答案


支持的类型,您将看到 pg_catalog.interval 也是 postgres 中 interval 支持的值之一。

因此,如果您只想使用 time.duration 而不是 int64,则需要将 overrides 部分更改为:

overrides:
  go:
    overrides:
      - db_type: "pg_catalog.interval"
        engine: "postgresql"
        go_type:
          import: "time"
          type: "Duration"

提示:如果它不适用于最明显的数据类型,您可以尝试另一种。

到这里,我们也就讲完了《postgresql 时间间隔不会被 sqlc.yaml 配置覆盖》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>