A
A
Alexander Wolf2018-11-15 16:45:44
go
Alexander Wolf, 2018-11-15 16:45:44

How to develop null/undefined support for types (DB/JSON)?

Good afternoon, comrades!
I've been struggling with the issue of organizing null/undefined in golang for JSON and DB communication for a long time now.
For example, I have bool type. It can come from the client as true/false/null/undefined.
If it's true/false, then you need to update the value in the database. If null came, then it is necessary to set it as NULL in the database. If undefined came, then you don’t need to touch it in the database at all.
The only solutions I see so far are:
1.Use *ptr instead of type. In conjunction with the fact that Go almost always knows how to convert them, it's simple, convenient and easy. But here I lose one of the states. That is, either I cast undefined to nil, or null to nil. Accordingly, this method is not suitable (but in my opinion this is the most beautiful way, if it can be somehow modified, it will be as cool as possible).
2. Use sql.NullInt etc. instead of regular types. But here the same problem as in paragraph 1. I decided to invent my own types that wrap all standard types. But it's terribly inconvenient. Firstly, to write them into the structure, you have to fence something like nullable.Int{12}, and secondly, to get the value back, you need to do item.count.Value, for example.
I would like some simple solution. It is possible to use pointers and somehow beautifully send queries to the database. Community help needed. Who does what in their projects?
PS: to transform the structure, there is a function that, using reflect, converts the structure to 2 arrays: names (field names) and values ​​(field values ​​in the same order). Then it is fed functions to create a query or update rows. It can be changed/discarded.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question