For postgresql
, here is what I did:
go get github.com/google/uuid
- Use
uuid.UUID
(from “github.com/google/uuid”), as type,
e.gID uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4()"`
- Add uuid-ossp extension for postgres database,
e.gCREATE EXTENSION IF NOT EXISTS "uuid-ossp";
- Then, when you call DB’s Create() method, the uuid is generated automatically.
Update: pg14+ gen_random_uuid()
(as mentioned in Doron Segal
‘s comment)
pg 14 has built-in function gen_random_uuid()
to generate uuid v4, e.g:
create table:
create table uuid_test (uid text default gen_random_uuid());
insert a row:
insert into uuid_test(uid) values (DEFAULT);
Then uid
column is generated automatically.
Similiar, in go you can use the function as defaul value I think, e.g:
ID uuid.UUID
gorm:"type:uuid;default:gen_random_uuid()"
BTW, the gen_random_uuid()
function only support uuid v4 now, to use other versions, you still need uuid-ossp
extension.