go version)?1.10.1
PostgreSQL 10.5
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
}
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:
ecosystem ENUM type:go
db.Exec("CREATE TYPE ecosystem AS ENUM('production', 'testsystem');")
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
Most helpful comment
Could it be possible to support
enumwith postgres? Or to write in the doc that it's not possible to useenumwith postgres? I spent quite some time trying to have it working but no success ... :(Thanks!