如何在Gorp中使用TypeConverter?

时间:2015-06-17 11:31:27

标签: go gorp

我想使用Gorp从包含特殊类型的DB加载和保存结构。除此之外,这对于枚举字符串很有用,例如角色:

type Role string

type Account struct {
    User string
    Role Role
}

这不是“开箱即用”。出现错误消息,例如

panic: sql: converting Exec argument #0's type: unsupported type user.Role, a string

我怀疑我需要使用gorp.TypeConverter来解决此问题,但没有关于如何执行此操作的文档。

你能帮忙吗?

1 个答案:

答案 0 :(得分:2)

ValuerScanner接口可以满足您的需求。这是一个有效的例子:

package roleGorp

import (
    "gopkg.in/gorp.v1"
    "github.com/DATA-DOG/go-sqlmock"
    "fmt"
    "testing"
    "database/sql/driver"
)

type Role string

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

type Account struct {
    User string `db:"user"`
    Role Role `db:"role"`
}

func TestRoleGorp(t *testing.T) {
    db, err := sqlmock.New()
    if err != nil {
        panic(err)
    }
    dbMap := gorp.DbMap{
        Db: db,
        Dialect: gorp.MySQLDialect{
            Engine: "InnoDB",
        },
    }

    rows := sqlmock.NewRows([]string{"user", "role"}).AddRow("user1", "admin")

    sqlmock.ExpectQuery(`SELECT \* FROM account LIMIT 1`).WillReturnRows(rows)

    dbMap.AddTableWithName(Account{}, "account")

    result := &Account{}
    err = dbMap.SelectOne(result, "SELECT * FROM account LIMIT 1")
    if err != nil {
        panic(err)
    }

    fmt.Printf("%+v\n", *result)

    result2 := &Account{
        User: "user2",
        Role: Role("moderator"),
    }

    sqlmock.ExpectExec("insert into `account` \\(`user`,`role`\\) values \\(\\?,\\?\\);").WithArgs("user2", "moderator").WillReturnResult(sqlmock.NewResult(1, 1))

    err = dbMap.Insert(result2)
    if err != nil {
        panic(err)
    }
}