-
Notifications
You must be signed in to change notification settings - Fork 923
How do I tell sqlc to omit a field in the json if it's empty #1087
-
Let's say I have a table
create table "todos" ( "id" uuid primary key default uuid_generate_v4(), "title" varchar(255) not null, "description" text default null );
After I run sqlc generate
the following model will be generated:
type Todo struct { ID uuid.UUID `json:"id"` Title string `json:"title"` Description sql.NullString `json:"description"` }
I would like to omit the description if it's empty (as it's a nullable column).
Now, I can use column override and use string
type instead of sql.NullString
. So now the generated type will be
type Todo struct { ID uuid.UUID `json:"id"` Title string `json:"title"` Description string `json:"description"` }
The problem with this is that if Description is nil
, it won't be omitted from the json
response. So the response would be something like this:
{ "id": "c0507d40-de51-451f-b84e-c2f06af7710f", "title": "This is a todo", "description": null }
Is there a way I can tell sqlc
to add omitempty
tag to a particular field? (Description field in this case)
Any other way to solve this issue?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 3 comments 4 replies
-
Is there a way I can tell sqlc to add omitempty tag to a particular field? (Description field in this case)
There is currently not a way a to do this. What you can do is use a custom struct and override the output of the query to return that struct.
Beta Was this translation helpful? Give feedback.
All reactions
-
Can you share an example or documentation for the same?
Beta Was this translation helpful? Give feedback.
All reactions
-
@kyleconroy can you share an example as I can't find any documentation on how to override output of query to return a custom struct.
Beta Was this translation helpful? Give feedback.
All reactions
-
use a custom struct and override the output of the query to return that struct.
@kyleconroy would appreciate if you can give an example or share any links on how to do this? Thank you!
Beta Was this translation helpful? Give feedback.
All reactions
-
I'm going to go ahead, and assume that currently, there is no way to return a custom struct from queries. Will be re-opening this issue till I find a good resolution
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 3
-
In the same vein, could sql add support for golang json struct flag ,string
? JavaScript does not support parsing int64 numbers, so json marshaling as strings is preferred.
type User struct { Id int64 `json:"id,string"` }
Beta Was this translation helpful? Give feedback.
All reactions
-
I have opened a PR for adding support for omitempty
Beta Was this translation helpful? Give feedback.