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:
sudo apt install postgresql-contrib-14
Then you need to install the extension in each database you are going to use it:
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.
go get github.com/google/uuid
satori/go.uuidopen in new window works too, but it does not look maintained any more.
Generating UUIDs
In PostgreSQL:
SELECT uuid_generate_v4();
In Go:
import "github.com/google/uuid"
fmt.Println(uuid.New())
Using UUIDs in models
You can use uuid.UUID
type in models like this:
import "github.com/google/uuid"
type Story struct {
ID uuid.UUID `bun:"type:uuid,default:uuid_generate_v4()"`
Title string
AuthorID uuid.UUID `bun:"type:uuid"`
}
UUID
field name also works well:
type Story struct {
UUID uuid.UUID `bun:",pk,type:uuid,default:uuid_generate_v4()"`
Title string
AuthorUUID uuid.UUID `bun:"type:uuid"`
}