PostgreSQL: Generating UUID primary keys

What is UUID?

A universally unique identifier (UUID) is a 128-bit number that is generated in a way that makes it very unlikely that the same identifier will be generated by anyone else in the known universe (globally unique).

When to use UUIDs?

You can use UUIDs when you need to generate a globally unique indentifier without using an id generation service, for example, OpenTelemetry uses 16 bytes identifiers as a trace id.

Usually, UUIDs are generated by taking 16 random bytes and the uniqueness is based on the sheer quantity, not the generation algorithm. Such identifiers are unique, but are larger and slightly slower than 64-bit sequential numbers.

TIP

UUIDs are slightly slower than 64-bit sequential identifiers. Use them only when you don’t have an easy way to generate a smaller sequential identifier.

UUID in PostgreSQL

PostgreSQL requires an extension to support UUID column type. The extenstion comes with postgresql-contrib-* package:

  1. sudo apt install postgresql-contrib-14

Then you need to install the extension in each database you are going to use it:

  1. CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

UUID in Go

For working with UUIDs in Go you need to install google/uuidUUIDs - 图1open in new window package.

  1. go get github.com/google/uuid

satori/go.uuidUUIDs - 图2open in new window works too, but it does not look maintained any more.

Generating UUIDs

In PostgreSQL:

  1. SELECT uuid_generate_v4();

In Go:

  1. import "github.com/google/uuid"
  2. fmt.Println(uuid.New())

Using UUIDs in models

You can use uuid.UUID type in models like this:

  1. import "github.com/google/uuid"
  2. type Story struct {
  3. ID uuid.UUID `bun:"type:uuid,default:uuid_generate_v4()"`
  4. Title string
  5. AuthorID uuid.UUID `bun:"type:uuid"`
  6. }

UUID field name also works well:

  1. type Story struct {
  2. UUID uuid.UUID `bun:",pk,type:uuid,default:uuid_generate_v4()"`
  3. Title string
  4. AuthorUUID uuid.UUID `bun:"type:uuid"`
  5. }