News for hackers. Stuff that matters.
Re:Null Values in SQL Queries by marcus_holmes on Tuesday February 04, 2020 @01:29AM (#22232970)
I also am a fan of nulls. But I also make very sure that I have defaults set up on every column for which a null value would make no sense. Which means pretty much every column that isn't an optional foreign key.

I'm writing in Go, so my structs all have empty values unless specifically initialised. This does sometimes mean that I get null uuid's (0000-000000-00000-0000) inserted into tables, which Postgres doesn't understand as null and cheerfully returns as a valid uuid. This has been my only real pain with using nulls.

I've contemplated modding the database driver to interpret nil-value uuid's as null, but that seems a little drastic. Anyone got any better ideas?

Re:Null Values in SQL Queries by gnosek on Tuesday February 04, 2020 @02:22AM (#22233217)
Not sure how this integrates with Go's database drivers but from the Postgres side:

1. NULLIF(the_uuid, '0000-000000-00000-0000')

https://www.postgresql.org/docs/current/functions-conditiona...

2. on insert/update rules to rewrite the uuid (probably using NULLIF)

https://www.postgresql.org/docs/current/sql-createrule.html

Re:Null Values in SQL Queries by kaslai on Tuesday February 04, 2020 @01:58AM (#22233107)
My typical pattern is to use pointer types as a pseudo-optional type. There is the additional cost of dealing with a pointer on the Go side though, which can get cumbersome at times.

`database/sql` does have an interface which lets you define your own marshaling code though. Using it is very simple and would let you marshal an all-zero UUID into NULL easily enough.

Re:Null Values in SQL Queries by uncanny on Tuesday February 04, 2020 @08:18PM (#22243093)
You can use a type that marshals the Go zero value to database null and vice versa. https://godoc.org/github.com/jackc/pgtype/zeronull provides a UUID type with that behavior.
Re:Null Values in SQL Queries by dx034 on Tuesday February 04, 2020 @02:49AM (#22233314)
pgx allows to pass pointers to indicate which values are null. That works with any arbitrary types and prevents from accidentially storing an empty values as null.