英文:
postgres enum with golang pgx
问题
假设我有一个使用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中的枚举类型的正确方法是什么?
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论