首页 > 解决方案 > 带有 golang pgx 的 postgres 枚举

问题描述

假设我有一个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,但我不知道如何使用它。

标签: postgresqlgoenumspgx

解决方案


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

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

作品。


推荐阅读