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

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

SQLC 覆盖 Bool 类型 PostgreSQL

sqlc 覆盖 bool 类型 postgresql

php小编西瓜为您带来关于SQLC覆盖Bool类型PostgreSQL的介绍。SQLC是一个强大的SQL查询构建器,它可以方便地与各种数据库进行交互。在使用PostgreSQL时,SQLC提供了对Bool类型的覆盖支持,使得我们可以更灵活地处理和查询布尔值。通过SQLC,我们可以轻松地在PostgreSQL中进行布尔值的增删改查操作,提高开发效率并简化代码编写过程。无论是初学者还是有经验的开发者,都可以通过SQLC轻松地操作PostgreSQL中的布尔类型数据。

问题内容

我正在使用 sqlc,并且我的 yaml 配置文件包含 postgresql 的以下类型覆盖:

gen:
  go:
    emit_json_tags: true
    package: "hmdb"
    out: "hmdb"
    overrides:
    - db_type: "hstore"
      nullable: true
      go_type: "github.com/jackc/pgtype.hstore"
    - db_type: "text"
      nullable: true
      go_type:
        import: "gopkg.in/guregu/null.v4"
        package: "null"
        type: "string"
    - db_type: "timestamptz"
      nullable: true
      go_type:
        import: "gopkg.in/guregu/null.v4"
        package: "null"
        type: "time"

这里的一切都有效,但如果我添加:

- db_type: "bool"
      nullable: true
      go_type:
        import: "gopkg.in/guregu/null.v4"
        package: "null"
        type: "bool"

我没有得到预期的结果。我也尝试过 booleanbit 无论有没有 nullable 都无济于事。

我在这里定义了一个更新查询:

-- name: setuser :one
update users set 
    username = coalesce(sqlc.narg(username), username),
    email = coalesce(sqlc.narg('email'), email),
    phone = coalesce(sqlc.narg('phone'), phone),
    password = coalesce(sqlc.narg('password'), password),
    mfatoken = coalesce(sqlc.narg('mfatoken'), mfatoken),
    active = coalesce(sqlc.narg('active'), active)
    where id = $1 returning *;

但生成的结构如下所示:

type SetUserParams struct {
    ID       uuid.UUID    `json:"id"`
    Username null.String  `json:"username"`
    Email    null.String  `json:"email"`
    Phone    null.String  `json:"phone"`
    Password null.String  `json:"password"`
    MFAToken null.String  `json:"mfatoken"`
    Active   sql.NullBool `json:"active"`
}

我想使用 null.bool 而不是 sql.nullbool,这可能吗?

解决方法

像这样创建 schema.yaml

create table users (
    ...
    active pg_catalog.bool
)

sqlc.yaml 中,条目应如下所示:

- db_type: "pg_catalog.bool"
     nullable: true
     go_type:
       import: "gopkg.in/guregu/null.v4"
       package: "null"
       type: "bool"

然后在 sqlcgenerate 之后它看起来像这样:

type SetUserParams struct {
    ...
    Active   null.Bool   `json:"active"`
}

因此它使用 null.bool 而不是 sql.nullbool

卓越飞翔博客
上一篇: Terraform Provider Development:即使更新失败,tfstate 也会更新
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏