Skip to content
This repository was archived by the owner on Nov 6, 2021. It is now read-only.

Working with database nullable fields

B1nj0y edited this page Oct 13, 2017 · 18 revisions

Rails is easy with database nullable fields, it return a nil if the field is NULL. It's idomatic and transparent for developers.

But Go is a typed language, if you set a struct attribute as string, then you can't evaluate it as nil. Here's is a post for the situation: working-with-db-nulls.

Zero values

Go hasn't a nil for its basic types, but it provides zero values for them:

string:     ""
int:        0
bool:       false
float:      0.0
time.Time:  '0001-01-01 00:00:00','+00:00','UTC'

for example, if a string typed field is NULL, we can set it as "".

COALESCE function

I hope go-on-rails can work with the nullable fields like Rails does, so I searched the web and found the COALESCE, a function available in most popular databases, here is the spark of inspiration: https://github.com/go-sql-driver/mysql/issues/34#issuecomment-158391340.

Clone this wiki locally