Hacker News new | past | comments | ask | show | jobs | submit login

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?




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


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.


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.


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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: