[Golang (Go) GORM] Use UUID as primary key on PostgreSQL

UUID as Primary Key

GORM uses the field with the name ID as the table’s primary key by default. You can set the fields as primary key with UUID through PostgreSQL’s uuid-ossp module.

Enable EXTENSION uuid-ossp

PostgreSQL’s uuid-ossp module provides functions to generate universally unique identifiers (UUIDs) using one of several standard algorithms. There are also functions to produce certain special UUID constants. This module is only necessary for special requirements beyond what is available in core PostgreSQL.

To install the uuid-ossp module, you use the CREATE EXTENSION statement on PostgreSQL as follows:

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

To generate the UUID values based on the combination of computer’s MAC address, current timestamp, and a random value, you use the uuid_generate_v1() function:

The function generated the following a UUID value:

1
2
3
4
5
6
# SELECT uuid_generate_v1();

uuid_generate_v1
--------------------------------------
0e37df36-f698-11e6-8dd4-cb9ced3df976
(1 row)

If you want to generate a UUID value solely based on random numbers, you can use the uuid_generate_v4() function. For example:

1
2
3
4
5
6
# SELECT uuid_generate_v4();

uuid_generate_v4
--------------------------------------
a81bc81b-dead-4e5d-abff-90865d1e13b1
(1 row)

This function generates a version 5 UUID, which works like a version 3 UUID except that SHA-1 is used as a hashing method. Version 5 should be preferred over version 3 because SHA-1 is thought to be more secure than MD5.

1
2
3
4
5
# SELECT uuid_generate_v5(uuid_ns_url(), 'http://www.postgresql.org');
uuid_generate_v5
--------------------------------------
e1ee1ad4-cd4e-5889-962a-4f605a68d94e
(1 row)

Struct Field and Tag

Change struct field ID type to string, and append Go tag gorm:"default:uuid_generate_v4()".

1
2
3
4
type User struct {
ID string `gorm:"default:uuid_generate_v4()"` // field named `ID` will be used as a primary field by default
Name string
}

Run Migrate

Run migrate to make it effective.

1
2
// Migrate the schema
db.AutoMigrate(&Product{})

References

[1] Conventions | GORM - The fantastic ORM library for Golang, aims to be developer friendly. - https://gorm.io/docs/conventions.html

[2] PostgreSQL: Documentation: 13: F.44. uuid-ossp - https://www.postgresql.org/docs/current/uuid-ossp.html

[3] GitHub - go-gorm/gorm: The fantastic ORM library for Golang, aims to be developer friendly - https://github.com/go-gorm/gorm

[4] GORM - The fantastic ORM library for Golang, aims to be developer friendly. - https://gorm.io/