【问题标题】:postgres enum with golang pgx带有 golang pgx 的 postgres 枚举
【发布时间】:2021-08-31 17:49:36
【问题描述】:

假设我在golang 中有一个微服务,使用pgx 连接到postgres 数据库。

我有一个枚举类型的数据结构:

CREATE TYPE "direction_type" AS ENUM (
  'LEFT',
  'RIGHT',
  'UP',
  'DOWN'
);

CREATE TABLE "move_log" (
    ID uuid PRIMARY KEY,
    direction direction_type,
    steps int4
)

所以当我尝试插入一条记录时:

insertMove := "INSERT INTO move_log (id, direction, steps) values ($1, $2, $3)"
_, err := d.db.ExecContext(ctx, insertMove, uid, "LEFT", steps)

失败了

2 UNKNOWN: ERROR: invalid input value for enum direction_type: "LEFT" (SQLSTATE 22P02)

我找到了一个 pgx 类型 enum_array,但我不知道如何使用它。

  • 在 golang 中使用 pgx 在 postgres 中使用枚举的正确方法是什么?

【问题讨论】:

    标签: postgresql go enums pgx


    【解决方案1】:

    我找到了这个答案: https://github.com/jackc/pgx/issues/338#issuecomment-333399112

    insertMove := "INSERT INTO move_log (id, direction, steps) values ($1, $2::text[]::direction_type[], $3)"
    

    工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-11
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      相关资源
      最近更新 更多