Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgres enum with golang pgx

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 ?
like image 565
ton Avatar asked Jul 17 '26 00:07

ton


1 Answers

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.

like image 169
ton Avatar answered Jul 21 '26 07:07

ton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!