sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

Postgres JSON `->>` operator generates `string` not `*string`

Open danthegoodman1 opened this issue 9 months ago • 1 comments

Version

1.27.0

What happened?

-- name: ListJobs :many
-- Returns jobs with reduced data, to reduce payload size
select id,
       (data ->> 'PhoneNumber')::text as phone_number,
       (data ->> 'ContactName')::text as contact_name,
       (data ->> 'State')::text       as state
from jobs

In the JSON contact_name output is not always in the JSON, can fails to make a nullable string for the ListJobsRow type.

ContactName in the ListJobsRow will only ever be string or interface{}

COALESCE((data ->> 'ContactName')::text, NULL) as contact_name, makes it an interface{}

CASE WHEN (data ->> 'ContactName') IS NULL THEN NULL ELSE (data ->> 'ContactName')::text END as contact_name, returns a string

Considering the ->> operator can return a NULL if the property doesn't exist in the JSON, it should really be a *string or sql.NullString instead of string.

Relevant log output


Database schema


SQL queries


Configuration


Playground URL

https://play.sqlc.dev/p/e5583c55e36fe049212dd7abbe79d8b560444d58675560b18375ffcb31ef8cd6

What operating system are you using?

macOS

What database engines are you using?

PostgreSQL

What type of code are you generating?

Go

danthegoodman1 avatar Jan 17 '25 19:01 danthegoodman1