Search code examples
sqlpostgresqlgopgx

How to present dynamic keys in a type struct?


I have a PostgreSQL table which has a JSONB filed. The table can be created by

create table mytable
(
  id         uuid primary key     default gen_random_uuid(),
  data       jsonb       not null,
);

insert into mytable (data)
values ('{
  "user_roles": {
    "0x101": [
      "admin"
    ],
    "0x102": [
      "employee",
      "customer"
    ]
  }
}
'::json);

In above example, I am using "0x101", "0x102" to present two UIDs. In reality, it has more UIDs.

I am using jackc/pgx to read that JSONB field.

Here is my code

import (
    "context"
    "fmt"
    "github.com/jackc/pgx/v4/pgxpool"
)

type Data struct {
    UserRoles struct {
        UID []string `json:"uid,omitempty"`
        // ^ Above does not work because there is no fixed field called "uid".
        // Instead they are "0x101", "0x102", ...
    } `json:"user_roles,omitempty"`
}
type MyTable struct {
    ID   string
    Data Data
}

pg, err := pgxpool.Connect(context.Background(), databaseURL)
sql := "SELECT data FROM mytable"
myTable := new(MyTable)
err = pg.QueryRow(context.Background(), sql).Scan(&myTable.Data)
fmt.Printf("%v", myTable.Data)

As the comment inside mentions, the above code does not work.

How to present dynamic keys in a type struct or how to return all JSONB field data? Thanks!


Solution

  • edit your Data struct as follows,

    type Data struct {
        UserRoles map[string][]string `json:"user_roles,omitempty"`
    }
    

    you can also use a uuid type as the map's key type if you are using a package like https://github.com/google/uuid for uuids.

    However please note that this way if you have more than one entry in the json object user_roles for a particular user(with the same uuid), only one will be fetched.