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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?