Gorm: Can't create uuid primary key in Postgres

Created on 8 May 2018  路  6Comments  路  Source: go-gorm/gorm

Hi! When i am trying to create table with uuid PK, gorm produce table with integer PK.

What version of Go are you using (go version)?

go version go1.9.2 linux/amd64

Which database and its version are you using?

Postgres 9.6

Please provide a complete runnable program to reproduce your issue. IMPORTANT

 package main

 import (
    "fmt"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
 )

 // Organisation -
 type Organisation struct {
    gorm.Model
    id        string `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
    Name      string
    State     int8
    Actual    bool
    Previous  string `gorm:"type:uuid"`
    Next      string `gorm:"type:uuid"`
    Permanent string `gorm:"type:uuid"`
    Inn       string
    Kpp       string
    Www       []string `gorm:"type:text[]"`
    Forms     []string `gorm:"type:text[]"`
 }

 func main() {
    db, err := gorm.Open("postgres", "host=127.0.0.1 port=9920 user=gorm dbname=gorm password=gorm sslmode=disable")

    if err != nil {
        fmt.Printf("Error! %s", err)
    }

    defer db.Close()

    db.AutoMigrate(&Organisation{})
 }


gorm_v1 document

Most helpful comment

  1. Make sure that uuid-ossp extension is added to your schema. You can add it by running the following statement:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
  1. You can set the ID column type in your table as uuid like so:
CREATE TABLE users (
    id uuid DEFAULT uuid_generate_v4() NOT NULL
);

*use an alter statement if table is already defined

  1. Go ahead and define your model
 type User struct {
    id        string `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
}
  1. Set Primary Key field value in a BeforeCreate callback. You can refer to the gorm documentation here
// BeforeCreate set Model's primary key value to uuid
// http://doc.gorm.io/crud.html#setting-primary-key-in-callbacks
func (user *User) BeforeCreate(scope *gorm.Scope) error {
    id, err := uuid.NewV4()

    if err != nil {
        fmt.Printf("Something went wrong: %s", err)
        return err
    }

    scope.SetColumn("ID", id)
    return nil
}

Not sure if am allowed to post this here but if it helps you could skim through the code in this Repo GolangKe API to see how am doing it. The Project is fairly new and the README isn't detailed yet 馃槄

DISCLAIMER Am very new to Go and actively learning.

All 6 comments

Experiencing the same with postgres 10, it just won't migrate at all if a uuid is being used for primary key

First, gorm.Model embedded field already contains a field ID with gorm:"primary_key".
Then, your id field is unexported. Gorm know about it麓s existence, but cant set its value, so it just ignore it. That麓s is imposed by reflection package.
With id as Id, i think that ID from gorm.Model would conflict with Id from your code, cause both will be named "id". If not, your code would create a table with composite primary key int from gorm.Model and uuid from your code.

  1. Make sure that uuid-ossp extension is added to your schema. You can add it by running the following statement:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
  1. You can set the ID column type in your table as uuid like so:
CREATE TABLE users (
    id uuid DEFAULT uuid_generate_v4() NOT NULL
);

*use an alter statement if table is already defined

  1. Go ahead and define your model
 type User struct {
    id        string `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
}
  1. Set Primary Key field value in a BeforeCreate callback. You can refer to the gorm documentation here
// BeforeCreate set Model's primary key value to uuid
// http://doc.gorm.io/crud.html#setting-primary-key-in-callbacks
func (user *User) BeforeCreate(scope *gorm.Scope) error {
    id, err := uuid.NewV4()

    if err != nil {
        fmt.Printf("Something went wrong: %s", err)
        return err
    }

    scope.SetColumn("ID", id)
    return nil
}

Not sure if am allowed to post this here but if it helps you could skim through the code in this Repo GolangKe API to see how am doing it. The Project is fairly new and the README isn't detailed yet 馃槄

DISCLAIMER Am very new to Go and actively learning.

Thanks for this @samuelralak we should add documentation somewhere.

Check out this answer on StackOverflow. I find that approach to be quite useful.

This issue will be automatically closed because it is marked as GORM V1 issue, we have released the public testing GORM V2 release and its documents https://v2.gorm.io/docs/ already, the testing release has been used in some production services for a while, and going to release the final version in following weeks, we are still actively collecting feedback before it, please open a new issue for any suggestion or problem, thank you

Also check out https://github.com/go-gorm/gorm/wiki/GORM-V2-Release-Note-Draft for how to use the public testing version and its changelog

Was this page helpful?
0 / 5 - 0 ratings

Related issues

koalacxr picture koalacxr  路  3Comments

sredxny picture sredxny  路  3Comments

corvinusy picture corvinusy  路  3Comments

leebrooks0 picture leebrooks0  路  3Comments

Quentin-M picture Quentin-M  路  3Comments