postgres: refactor typecasting code

It's starting to feel cleaner because the ugliness is a bit
more centralized per module now.