You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

sqlc配置无法覆盖PostgreSQL interval为time.Duration,求解决方案

问题

使用sqlc生成PostgreSQL代码时,interval字段被映射为int64类型,导致扫描行时报错:Errorf("cannot convert %v to Interval", value)。手动将字段改为time.Duration可正常运行,但不想手动修改生成代码。尝试通过sqlc.yaml配置类型覆盖,但生成的模型中该字段仍为int64,求正确配置方案。

相关配置与代码

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
}
解决方案

你的配置错误在于go_type中的type字段写法不符合sqlc要求,正确配置只需修改该字段为Go类型名称Duration即可,具体如下:

修正后的sqlc.yaml

version: "2"
overrides:
  go:
    overrides:
      - db_type: "interval"
        engine: "postgresql"
        go_type:
          import: "time"
          type: "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"

验证效果

重新运行sqlc生成命令后,Windowrange结构体中的Duration字段会被正确生成为time.Duration:

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

补充说明

  • sqlc的类型覆盖规则中,go_type.type仅需填写Go语言的类型名,无需链接或完整包路径
  • 由于你使用pgx/v4作为SQL驱动包,它原生支持将PostgreSQL的interval类型扫描为time.Duration,因此修改配置后无需额外编写扫描逻辑即可正常工作

内容的提问来源于stack exchange,提问作者Danila Volkomurov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 11:15:40