卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35048本站已运行393

sqlc.yaml 配置不会覆盖 postgresql 时间间隔到 time.Duration

sqlc.yaml 配置不会覆盖 postgresql 时间间隔到 time.duration

php小编柚子在这里为大家介绍一个关于sqlc.yaml配置的问题。在使用postgresql时,我们经常需要使用时间间隔(time.Duration)来表示一段时间。然而,有时候我们会发现在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"

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

卓越飞翔博客
上一篇: 在yocto中编译golang包
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏