doutan1905 2015-06-17 11:31
浏览 52
已采纳

如何在Gorp中使用TypeConverter?

I would like to use Gorp to load and save structs from the DB that contain specialised types. Amongst other things, this is useful for enumerated strings such as roles:

type Role string

type Account struct {
    User string
    Role Role
}

This doesn't work "out of the box". An error message is raised such as

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

I suspect I need to use a gorp.TypeConverter to solve this, but there is no documentation on how to do this.

Can you help?

  • 写回答

1条回答 默认 最新

  • duanpai9945 2015-06-17 14:36
    关注

    Valuer and Scanner interfaces will do what you want. Here is a working example :

    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
    ", *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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗