doujie1908 2014-06-05 20:15
浏览 55
已采纳

来自数据库/ SQL JSON列的json.RawMessage被覆盖

Getting strange behaviour with a struct with embedded 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))
    }
}

Output:

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

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

So the articles end up pointing to the same json.

Am I doing something wrong?

UPDATE

Edited to a runnable example. I'm using Postgres and lib/pq.

  • 写回答

2条回答 默认 最新

  • doujiao3072 2014-06-24 18:31
    关注

    I ran into this same issue and after looking at if for a long time I read the doc on Scan and it says

    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.

    What I think is happening if you use *json.RawMessage then Scan does not see it as a *[]byte and does not copy into it. So you get in internal slice on the next loop Scan overwrites.

    Change your Scan to cast the *json.RawMessage to a *[]byte so Scan will copy the values to it.

        err := rows.Scan(
            &a.Id,
            (*[]byte)(a.Doc),
        )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置