pgtype icon indicating copy to clipboard operation
pgtype copied to clipboard

json Marshaller interface for Inet

Open atz opened this issue 5 years ago • 4 comments

Note that this does allow the serialization/deserialization between empty string and a Null struct. It does NOT permit invalid addresses or masks.

If this is workable, then I would pursue similar approach for Cidr and Macaddr types.

See #79

atz avatar Dec 02 '20 00:12 atz

Nowhere else in pgtype is an empty string conflated with null. null is a valid JSON value -- we should use it. Also undefined should be handled.

See Bool MarshalJSON and UnmarshalJSON for examples of existing precedent.

jackc avatar Dec 02 '20 00:12 jackc

null is expressible in JSON, but it is not valid under any json-schema that would specify a document with this type, therefore should not be produced as output. Either the JSON representation is a string or it isn't, but it cannot be sometimes a string and sometimes a null (and still work under json-schema).

Outside of the psql DB, I'm not sure what perspective would suggest that there is any difference between two different states where there is no address. Attempting to insert an empty string will fail with:

ERROR:  invalid input syntax for type inet: ""

Whereas attempting to insert a null will succeed (if the field allows null values, obviously).

AFAICT, the options for incoming json empty string are:

  • treat as null
  • return error

atz avatar Dec 02 '20 16:12 atz

I don't know about anything about "json-schema" but if I have a SQL NULL and I marshal it to JSON I certainly expect it to be null not "".

An incoming JSON empty string should be an error.

jackc avatar Dec 02 '20 17:12 jackc

I'm OK w/ returning error. I think having two different serialization types in JSON (a string type and a null type) is fundamentally incorrect, but as long as omitempty still works, my applications could work around it (i.e. never see a null serialization).

atz avatar Dec 02 '20 18:12 atz