1

我正在尝试获取一些旧代码来通过其单元测试。给我带来问题的测试在这里:

func Test1(t *testing.T){
 //Code
        testDevice := Device{
                                 ID: 1,
                                 Guid: "C6",
                                 Name: "test device",
                            }  
                         err := Dbmap.Insert(&testDevice)
                         So(err, ShouldBeNil)
 //More code    
}

当我运行时go test,这会返回:

'sql: Scan error on column index 0: converting driver.Value type <nil> ("<nil>") to a int64: invalid syntax'

这很奇怪,因为我传递的是 1,一个整数。设备结构在这里定义:

type Device struct {
        ID   int64 `db:"id"`
        Guid string
        Name string
}

这是它插入的 Postgres 表的架构:

CREATE TABLE devices(
ID INTEGER,
Guid VARCHAR,
Name VARCHAR
);

我已经尝试使用该sql.NillInt64类型,但这似乎并不能解决问题。感觉好像 gorp、go 或 postgres 以某种方式将整数解释为 nil。作为最终数据点,这一切都在各种 Docker 容器中运行,尽管我认为这个问题与 Docker 无关。有什么见解吗?

4

1 回答 1

0

答案归结为 Go 和 postgres 之间的区分大小写的交互。彼得的评论基本上回答了这个问题,但任何阅读这篇文章的人都可能需要更多解释。Go 只导出大写的对象,而 postgres 默认将列名解释为小写。所以我需要大写映射到小写列的结构(除非我想通过引用每个大写列名)。为此,请在结构中使用标签,本质上是告诉 Go 将其称为一件事,而 postgres 将其称为另一件事。您的新结构应如下所示:

type Device struct {
        ID   int64 `db:"id"`
        Guid string `db:"guid"`
        Name string `db:"name"`
}

现在只需在 postgres 中保留所有小写字母,您就可以设置了!

于 2018-04-13T23:53:21.593 回答