Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enumerated types issue #302

Closed
bramp opened this issue Nov 26, 2014 · 3 comments
Closed

Enumerated types issue #302

bramp opened this issue Nov 26, 2014 · 3 comments

Comments

@bramp
Copy link
Contributor

bramp commented Nov 26, 2014

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()

@bramp
Copy link
Contributor Author

bramp commented Nov 26, 2014

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.

@bramp bramp closed this as completed Nov 26, 2014
@schickling
Copy link

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

@charneykaye
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants