dongluzhi5208 2018-04-11 22:59
浏览 91
已采纳

Go和Postgres将整数重新解释为nil类型

I'm trying to get some old code to pass its unit tests. The test that's giving me problems is here:

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

When I run go test, this returns:

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

This is strange because I'm passing it 1, an integer. The device struct is defined here:

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

Here's the schema for the Postgres table it's inserting into:

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

I've tried using the sql.NillInt64 type, but that doesn't seem to fix the problem. It feels like somehow, gorp, go, or postgres is interpreting the integer as a nil there. As a final data point, this is all running in various Docker containers, though I don't think this problem is related to Docker. Any insights?

  • 写回答

1条回答 默认 最新

  • douwen4401 2018-04-13 23:53
    关注

    The answer came down to case sensitivity interaction between Go and postgres. Peter's comment essentially answers the question, but anyone reading this might want more explanation. Go only exports objects that are capitalized, while postgres defaults to interpreting column names as lower case. So I needed structs that were uppercase mapped to lowercase columns (unless I wanted to go through quoting every single uppercase column name). To do this, use tags in your struct, essentially telling Go to call it one thing, while postgres calls it another. Your new structs should looks like this:

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

    Now just keep everything lowercase in postgres and you'll be set!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。