【问题标题】:postgres throws error: null value in column "id" violates not-null constraint even when value is actually not nullpostgres 抛出错误:“id”列中的空值违反非空约束,即使值实际上不为空
【发布时间】:2020-11-07 01:45:44
【问题描述】:

我正在使用 grpc 构建一个 rest api,但即使我填充了值,我也会收到上述错误。 curl Post 被重定向到 createAlbum 方法

我确实在 postgres 中手动创建了一个数据库和表

我的数据库名称是我使用 psql 登录的专辑(未提供密码)

然后我创建了

create Table PHOTO(id INTEGER PRIMARY KEY, albumId INTEGER NOT NULL, title VARCHAR(255) NOT NULL, url VARCHAR(255) UNIQUE NOT NULL, thubmNailUrl VARCHAR(255) UNIQUE NOT NULL);

这是我的主要代码

func main(){
prosgretConname := fmt.Sprintf("dbname=%v user=%v sslmode=disable", "album", "s")
    log.Infof("conname is %s", prosgretConname)
    db, err := gorm.Open("postgres", prosgretConname)
    if err != nil {
        panic("Failed to connect to database!")
    }// connects correctly to db

    //db.Table("photo")
    defer db.Close()
    go startGRPC(db)
    go startHTTP()
    // Block forever
    var wg sync.WaitGroup
    wg.Add(1)
    wg.Wait()

}
func startGRPC(db *gorm.DB) {
    lis, err := net.Listen("tcp", "localhost:5566")
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    grpcServer := grpc.NewServer()
    srv := svc.NewAlbumServer(db)
    albumgpb.RegisterAlbumServiceServer(grpcServer, srv)
...
}

现在我的 newAlbumServer 返回一个 db 实例

type Album struct {
    title        string `json:"title"`
    albumid      int    `json:"albumid"`
    id           int    `json:"id" gorm:"primary_key;not null"`
    url          string `json:"url"`
    thumbnailurl string `json:"thumbnailurl"`
}
func (a *AlbumServiceServer) CreateAlbum(ctx context.Context, in *albumgpb.Albumreq) (*albumgpb.Albumreq, error) {
    tx := a.db.Begin()

    photo := Album{}
    photo.title = in.Album.Title
    photo.albumid = int(in.Album.AlbumId)
    photo.id = int(in.Album.Id)
    photo.url = in.Album.Url
    photo.thumbnailurl = in.Album.ThumbNailUrl

    log.Infof("%v", photo.id) // this prints 1
    log.Infof("the id is %v", int(in.Album.Id))// this prints 1 on server logs
    log.Infof("%+v\n", in) //this prints the entire request in the POST command
    //tx.Table("photo").

err := tx.Table("public.photo").Create(&photo).Error // fails in this line stating pq: null value in column "id" violates not-null constraint 

if err != nil {
    log.Errorf("could not insert into db")
    tx.Rollback()
    return nil, err
}

tx.Commit()

....

这是我的 curl 请求和响应

curl -X POST "http://localhost:8080/album" -d '{"id":1,"albumId":2,"title":"bleh","url":"sds","thumbNailUrl":"123"}'
2020-07-17 14:34:54.641 IST [16074] ERROR:  null value in column "id" violates not-null constraint
2020-07-17 14:34:54.641 IST [16074] DETAIL:  Failing row contains (null, null, null, null, null).
2020-07-17 14:34:54.641 IST [16074] STATEMENT:  INSERT INTO "public"."photo" DEFAULT VALUES RETURNING "public"."photo".*
{"error":"pq: null value in column \"id\" violates not-null constraint","code":2,"message":"pq: null value in column \"id\" violates not-null constraint"}

任何关于它为什么失败或我做错了什么的建议都会很有帮助

【问题讨论】:

  • 我确信原因与here 描述的相同:所有基于reflection 的包——并且gorm 应该不是例外——只能访问@ 的导出字段987654328@ 类型,而您的不会导出。因此,我推测 ORM 代码不会从您的数据类型的值中读取任何字段,并且 id 最终映射到 NULL。你能验证一下吗?
  • 减轻了该错误,但由于某种原因,现在将导出值更改为下划线错误:关系“照片”的列“album_id”在字符 39 处不存在 2020-07-17 14:59 :36.911 IST [17790] 声明:插入“公共”。“照片”(“标题”,“album_id”,“id”,“url”,“thumb_nail_url”)值(1 美元,2 美元,3 美元,4 美元,5 美元)返回“公共”。“照片”。“id”@kostix
  • 我想通了,因为我正在使用 AlbumId 创建表,出于某种原因,它正在将其映射到 album_id 任何 psql 人都可以回答这是为什么吗?我是 psql 的新手
  • 这不是 postgres 做的,而是 gorm 做的,它会自动将骆驼案例转换为蛇案例,如果您不希望这样做,您可能可以通过某种形式的设置更改默认值,但我不确定由于我不是 gorm 用户,因此您应该访问他们的网页和文档以找出答案。或者,您可以使用结构标签强制列名,就像您对 json 所做的那样,例如`json:"albumid" gorm:"albumid"`,再说一遍,我不确定这是否会有所帮助,但如果你处于绑定状态,你可以尝试一下。
  • 除了 mkopriva 所说的之外,请注意,您的 Album 结构的所有字段上都有 json 标签,但其中只有一个也有 gorm 标签。 gorm 包不太可能考虑json 标签。

标签: postgresql go go-gorm grpc-go


【解决方案1】:

请看this

由于id 字段未导出(以小写字母开头),因此json 包和gorm 均不可见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2012-11-02
    • 2020-03-17
    相关资源
    最近更新 更多