PostgreSQL data types

timestamptz vs timestamp

TLDR You should prefer using timestamptz over timestamp. None of the types store the provided timezone, but timestamptz at least properly parses the time with a timezone. To save user timezone, create a separate column for it.


Let’s use the following table as an example:

  1. CREATE TABLE test (
  2. t1 timestamptz,
  3. t2 timestamp
  4. );

The first difference between timestamptz and timestamp is that timestamp discards/ignores the provided timezone:

  1. INSERT INTO test VALUES ('2021-01-01 02:00:00+02', '2021-01-01 02:00:00+02') RETURNING *;
  2. t1 | t2
  3. ------------------------+---------------------
  4. 2021-01-01 00:00:00+00 | 2021-01-01 02:00:00

timestamp also ignores the server/session timezone:

  1. SET timezone = 'America/Los_Angeles';

The result:

  1. SELECT * FROM test;
  2. t1 | t2
  3. ------------------------+---------------------
  4. 2020-12-31 16:00:00-08 | 2021-01-01 02:00:00

JSONB

Bun uses JSONB data type to store maps and slices. To change the default type, use type struct tag option:

  1. type Model struct {
  2. Data map[string]interface{} `bun:"type:jsonb"`
  3. }

To enable json.Decoder.UseNumber option:

  1. type Model struct {
  2. Data map[string]interface{} `bun:",json_use_number"`
  3. }

You can also use json.RawMessage to work with raw bytes:

  1. type Model struct {
  2. Data json.RawMessage `bun:"type:jsonb"`
  3. }

Arrays

See Working with PostgreSQL arrays.

UUID

See Generating UUIDs in PostgreSQL.

See also

See Don’t do thisSupported data types - 图1open in new window for more tips.