Gorm: Enumerated types issue

Created on 26 Nov 2014  ·  3Comments  ·  Source: go-gorm/gorm

I have the following:

type BufferType string
const (
    Console BufferType = "console"
    Channel BufferType = "channel"
    Conversation BufferType = "conversation"
)

type Buffer struct {
    Bid  int64  `gorm:"primary_key:yes"`
    Type BufferType `sql:"not null;type:ENUM('console', 'channel', 'conversation')"`
    Name string `sql:"size:255;not null"`
}

When I try db.Save(buffer), I get the following error:
sql: converting Exec argument #1's type: unsupported type BufferType, a string)

Would it be possible to resolve that BufferType is really just a string, and save? I get similar errors if I try and load this struct with db.Find()

Most helpful comment

I had the same issue. The solution of @bramp still gave me an error. The following worked for me:

func (u *BufferType) Scan(value interface{}) error { *u = BufferType(value.([]byte)); return nil }
func (u BufferType) Value() (driver.Value, error)  { return string(u), nil }

The difference is using []byte instead of string. This stackoverflow thread helped me: http://stackoverflow.com/a/20582504/2418739

All 3 comments

After some more debugging, this error seems to be coming out of the golang database/sql code, and I found a solution here. I just needed to add:

func (u *BufferType) Scan(value interface{}) error { *u = BufferType(value.(string)); return nil }
func (u BufferType) Value() (driver.Value, error)  { return string(u), nil }

It's a bit clunky, but it helps the database know how to map correctly. I could also add error checking in here if I needed it.

I had the same issue. The solution of @bramp still gave me an error. The following worked for me:

func (u *BufferType) Scan(value interface{}) error { *u = BufferType(value.([]byte)); return nil }
func (u BufferType) Value() (driver.Value, error)  { return string(u), nil }

The difference is using []byte instead of string. This stackoverflow thread helped me: http://stackoverflow.com/a/20582504/2418739

+1 great solution. I wish this was in the GORM docs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

leebrooks0 picture leebrooks0  ·  3Comments

Ganitzsh picture Ganitzsh  ·  3Comments

fieryorc picture fieryorc  ·  3Comments

sredxny picture sredxny  ·  3Comments

littletwolee picture littletwolee  ·  3Comments