pggen
pggen copied to clipboard
Support for JSONB?
Is there support to specify how to convert JSONB data to Go structs? I've searched the documentation but haven't found anything.
Interesting. Do you mean something like:
-- name: FetchJsonExample :one
SELECT 1 as col_one, '{"foo": "bar"}'::jsonb as json_col
Would generate this Go code:
type JsonColType struct {
Foo string
}
type FetchJsonExampleRow struct {
ColOne int
JsonCol JsonColType
}
If that's the case, then no, pggen can't do anything like that. pggen converts Postgres types to Go types. In this example, sonb is the Postgres type and pggen converts it to the Go type pgtype.JSONB (overridable to []byte or string).
My recommendation is to extract the desired fields in the SQL query. Postgres has rich support for manipulating jsonb objects and arrays.
-- name: FetchJsonExample :one
SELECT '{"foo": "bar"}'::jsonb ->> 'foo' as json_col
A more involved alternative is to create a composite type in Postgres create the composite type in the query from the jsonb column.
-- schema.sql
CREATE TYPE json_col_type AS ( foo text );
-- query.sql
-- name: FetchJsonExample :one
SELECT 1 as col_one, ('{"foo": "bar"}'::jsonb ->> 'foo')::json_col_type as json_col
There's more example of composite types in https://github.com/jschaf/pggen/tree/main/example/composite.
It's unlikely I'll add JSON unmarshal support directly into pggen. The reasons are:
- If it can be done in SQL, I'd prefer to keep it there as it keeps pggen relatively simple.
- It would require some way of annotating the output type in addition to the
go-typeflag.
Thanks for the long answer.
I would prefer unmarshalling. Wouldn't adding go-type support in the way of table.field=gotype work? With pgx supporting Jsonb with Valueer and Scanner interfaces out of the box (so no unmarshalling code in pggen needed)?
The other solutions seem to contradict the reasons you would save Json into the database in the first place. I could take a look if I can make it work.