Gorm: Postgresql: type "enum" does not exist

Created on 17 Oct 2018  路  4Comments  路  Source: go-gorm/gorm

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

1.10.1

Which database and its version are you using?

PostgreSQL 10.5

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

package models

import (
    "github.com/jinzhu/gorm"

    "time"
    "database/sql/driver"
)


type Project struct {
    gorm.Model
    Title    string `gorm:"unique"`
    Archived bool
    Tasks    []Task `gorm:"ForeignKey:ProjectID"`
}

func (p *Project) Archive() {
    p.Archived = true
}

func (p *Project) Restore() {
    p.Archived = false
}

type Ecosystem string

const (
    Production Ecosystem = "production"
    TestSystem Ecosystem = "testsystem"
)

func (e *Ecosystem) Scan(value interface{}) error {
    *e = Ecosystem(value.([]byte))
    return nil
}

func (e Ecosystem) Value() (driver.Value, error) {
    return string(e), nil
}


type Task struct {
    gorm.Model
    Title     string
    Ecosystem        Ecosystem `json:"ecosystem" sql:"type:ENUM('production', 'testsystem')"`
    Deadline  *time.Time `gorm:"default:null"`
    Done      bool
    ProjectID uint
}

func (t *Task) Complete() {
    t.Done = true
}

func (t *Task) Undo() {
    t.Done = false
}

// DBMigrate will create and migrate the tables, and then make the some relationships if necessary
func DBMigrate(db *gorm.DB) *gorm.DB {
    db.AutoMigrate(&Project{}, &Task{})
    db.Model(&Task{}).AddForeignKey("project_id", "projects(id)", "CASCADE", "CASCADE")
    return db
}
document feature

Most helpful comment

Could it be possible to support enum with postgres? Or to write in the doc that it's not possible to use enum with postgres? I spent quite some time trying to have it working but no success ... :(
Thanks!

All 4 comments

Could it be possible to support enum with postgres? Or to write in the doc that it's not possible to use enum with postgres? I spent quite some time trying to have it working but no success ... :(
Thanks!

While playing around with the above code snippet, I found gorm can handle ENUM struct tags if you:

  1. Manually create the ecosystem ENUM type:
    go db.Exec("CREATE TYPE ecosystem AS ENUM('production', 'testsystem');")
  2. Manually create the tasks table:
    go db.Exec("CREATE TABLE tasks (id integer PRIMARY KEY, title text, ecosystem ecosystem, ...);")

Essentially, AutoMigrate appears to be the culprit.

Manually create the ecosystem ENUM type

Yes

Manually create the tasks table

Not necessary, just set column's type to the type you created

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sredxny picture sredxny  路  3Comments

hypertornado picture hypertornado  路  3Comments

pjebs picture pjebs  路  3Comments

Quentin-M picture Quentin-M  路  3Comments

rfyiamcool picture rfyiamcool  路  3Comments