PostgreSQL枚举与Golang的pgx

huangapple go评论91阅读模式
英文:

postgres enum with golang pgx

问题

假设我有一个使用golangpgx连接到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中的枚举类型的正确方法是什么?
英文:

Let's say I have a micro-service in golang using pgx to connect to postgres database.

I have a data structure that has a enum type:

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

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

So when I try to insert a record with:

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

it fails with

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

I've found a pgx type enum_array, but I have no idea on how to use it.

  • What is the correct way to work with enum in postgres using pgx in golang ?

答案1

得分: 2

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

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

可以使用。

英文:

I found this answer:
https://github.com/jackc/pgx/issues/338#issuecomment-333399112

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

Works.

huangapple
  • 本文由 发表于 2021年6月16日 05:25:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/67993680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定