duanhegn231318 2019-03-29 07:27
浏览 1116
已采纳

如何在Postgres中将元素添加到JSON字段数组

I'm trying to append data to an array that belongs to a json field in postgres. While using pgAdmin I know the following query works. ~

UPDATE lesson SET data =
    jsonb_set (data, '{pages, 999999}', '{"pageNum": 2, "pageType": "voc"}', True)
WHERE id = 2;

I am simply trying to get the above query to work via my rest api written in go. I am getting an error that reads "pq: invalid input syntax for type json".

my code is as follows~

_, err := db.Exec(`
    UPDATE lessons SET data =
        jsonb_set (data, '{pages, 999999}','{"pageNum": $1, "pageType": $2}', True) 
    WHERE id = $3`,
    pageNum, pageType, id) // variable types are int string int

I suspect that the postgres driver isn't interpolating the the $ parameters. It will work if I use fmt.Sprinf() for the whole query but I am trying to avoid SQL injection attacks, and would like to take advantage of the built in security measures of the go sql library.

For reference my data is structured as follows~ Lessons Table

Lessons
   id    int
   data  jsonb

Go structs:

type Lesson struct {
    ID    int    `json:"id"`
    Name  string  `json:"name"`
    Pages []Page  `json:"pages"`
}

type Page struct {
    PageNum    int  `json:"pageNum"`
    PageType   string `json:"pageType"`
  • 写回答

1条回答 默认 最新

  • doulao1934 2019-03-29 07:36
    关注

    You cannot use query parameters within a string in Postgres. Either pass the entire string to Postgres as single parameter:

    str := fmt.Sprintf('{"pageNum": %d, "pageType": %q}', pageNum, pageType)
    _, err := db.Exec(`
        UPDATE lessons SET data =
            jsonb_set (data, '{pages, 999999}', $1, True) 
        WHERE id = $2`,
        str, id) // variable types are int string int
    

    or use string concatenation to do it on the server side:

    _, err := db.Exec(`
        UPDATE lessons SET data =
            jsonb_set (data, '{pages, 999999}','{"pageNum": ' || $1 || ', "pageType": ' || $2 || '}', True) 
        WHERE id = $3`,
        pageNum, pageType, id) // variable types are int string int
    

    The best/safest, is probably the first approach, with full JSON marshaling in your client, rather than a simple fmt.Sprintf. I leave that as an exercise for the reader.

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

报告相同问题?