PostgreSQL interval and Go time.Duration don't map cleanly — use integers instead
A developer building a Go application with PostgreSQL discovered a runtime crash after mapping PostgreSQL's interval type directly to Go's time.Duration. The Go driver lib/pq has no built-in conversion between the two, causing it to fail when trying to parse raw interval bytes into an int64 at runtime — a bug that compiles without error. The root cause is a fundamental mismatch: PostgreSQL intervals can represent ambiguous units like months and years, while Go's time.Duration is simply a nanosecond count. The recommended fix is to store durations as plain integer seconds in PostgreSQL and convert them in the application layer. This approach avoids parsing ambiguity, mirrors industry conventions used by companies like Stripe, and follows the broader principle of using primitive types at database boundaries.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in