PostgreSQL: Generating UUID primary keys

    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

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

    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/uuidopen in new window package.

    In PostgreSQL:

    1. SELECT uuid_generate_v4();

    In Go:

    Using UUIDs in models

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

    1. type Story struct {
    2. ID uuid.UUID `bun:"type:uuid,default:uuid_generate_v4()"`
    3. AuthorID uuid.UUID `bun:"type:uuid"`