gpt4 book ai didi

sql - 来自数据库/sql json 列的 json.RawMessage 被覆盖

转载 作者:IT王子 更新时间:2023-10-29 00:59:50 28 4
gpt4 key购买 nike

使用嵌入了 json 的结构会出现奇怪的行为。

package main

import (
"database/sql"
"encoding/json"
"fmt"

_ "github.com/lib/pq"
)

type Article struct {
Id int
Doc *json.RawMessage
}

func main() {
db, err := sql.Open("postgres", "postgres://localhost/json_test?sslmode=disable")
if err != nil {
panic(err)
}

_, err = db.Query(`create table if not exists articles (id serial primary key, doc json)`)
if err != nil {
panic(err)
}
_, err = db.Query(`truncate articles`)
if err != nil {
panic(err)
}
docs := []string{
`{"type":"event1"}`,
`{"type":"event2"}`,
}
for _, doc := range docs {
_, err = db.Query(`insert into articles ("doc") values ($1)`, doc)
if err != nil {
panic(err)
}
}

rows, err := db.Query(`select id, doc from articles`)
if err != nil {
panic(err)
}

articles := make([]Article, 0)

for rows.Next() {
var a Article
err := rows.Scan(
&a.Id,
&a.Doc,
)
if err != nil {
panic(err)
}
articles = append(articles, a)
fmt.Println("scan", string(*a.Doc), len(*a.Doc))
}

fmt.Println()

for _, a := range articles {
fmt.Println("loop", string(*a.Doc), len(*a.Doc))
}
}

输出:

scan {"type":"event1"} 17
scan {"type":"event2"} 17

loop {"type":"event2"} 17
loop {"type":"event2"} 17

因此文章最终指向相同的 json。

我做错了什么吗?

更新

编辑为可运行的示例。我正在使用 Postgres 和 lib/pq

最佳答案

我遇到了同样的问题,看了很长时间后,我阅读了 Scan 上的文档,上面写着

If an argument has type *[]byte, Scan saves in that argument a copy of the corresponding data. The copy is owned by the caller and can be modified and held indefinitely. The copy can be avoided by using an argument of type *RawBytes instead; see the documentation for RawBytes for restrictions on its use.

我认为如果您使用 *json.RawMessage 会发生什么,然后 Scan 不会将其视为 *[] 字节并且不会复制到其中。所以你在下一个循环扫描覆盖时进入内部 slice 。

更改您的 Scan 以将 *json.RawMessage 转换为 *[]byte,以便 Scan 将值复制到它。

    err := rows.Scan(
&a.Id,
(*[]byte)(a.Doc),
)

关于sql - 来自数据库/sql json 列的 json.RawMessage 被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24069459/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com