Pg: Native UUID type support

Created on 3 Mar 2017  路  5Comments  路  Source: go-pg/pg

Is it possible to add native postgresql UUID type support for creating table over model with CreateTable func?
https://www.postgresql.org/docs/9.6/static/datatype-uuid.html

Most helpful comment

For CreateTable you can add field annotation

type Article struct {
    Id uuid.UUID `sql:",type:uuid"`
}

Later go-pg can be improved to treat [16]byte as uuid (but I am not sure if it should be)...

All 5 comments

I tried https://github.com/satori/go.uuid - it supports UUIDv5.

For CreateTable you can add field annotation

type Article struct {
    Id uuid.UUID `sql:",type:uuid"`
}

Later go-pg can be improved to treat [16]byte as uuid (but I am not sure if it should be)...

Thank you very much!

I am new to go and go pg. Here is what I had learnt the hard way

  1. UUID is not build in support, you need add an _UUID extension_ to a postgres database. this is a contrib. extension that's reason you need to explicitly create it.

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

  1. Extension are per database. if you have create a new database. You need to repeat the above procedure
  2. Use the latest version of go-pg as earlier version had problem
  3. Ensure above imports, please pay attention the package references 'pg' and 'uuid'. We would using them.
import (
    pg "github.com/go-pg/pg/v10"
    "github.com/go-pg/pg/v10/orm"
    uuid "github.com/satori/go.uuid"
)
  1. You need now tell go-pg to correctly map your struct to postgres sql type. if you don't pay attention to this details especially usage of 'pg' and 'type:uuid. most of the information available on net refers 'sql' and using will result into creation of table with type 'bytea' instead of 'uuid'

    you need to use 'pg' as a package reference not _'sql'_

type Story struct {
    Id       uuid.UUID `pg:",pk,type:uuid default uuid_generate_v4()"`
    Title    string
    AuthorId uuid.UUID `pg:",type:uuid DEFAULT uuid_generate_v4()"`
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

rhymes picture rhymes  路  5Comments

owentran picture owentran  路  6Comments

l0gicgate picture l0gicgate  路  5Comments

NinaLeven picture NinaLeven  路  6Comments

jayschwa picture jayschwa  路  4Comments