Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Jsonb column in golang

Tags:

postgresql

go

I am trying to update a Jsonb column value for a particular row. I ran the query

UPDATE instruction.file SET "details" = (jsonb_set("details",'{"UploadBy"}','"[email protected]"'::jsonb, true)) WHERE id=820;

this works fine in the pgAdmin3.

When I tried to do the same in my Go code. Iam getting the error:"pq: invalid input syntax for type json"

My Go code:

func main() {
    uname := "[email protected]"

    err := Init() //Db init
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    result, err1 := Db.Exec("UPDATE instruction.file SET \"details\" = (jsonb_set(\"details\",'{\"UploadBy\"}',$1::jsonb, true)) WHERE id=$2", uname, "820")
    if err1 != nil {
        fmt.Println("Error", err1)
        return
    }
    n, err1 := result.RowsAffected()
    if err1 != nil {
        fmt.Println("Error", err1)
        return
    }

    if n != 1 {
        err1 = errors.New("Unable to update instruction.file")
        fmt.Println("Error", err1)
        return
    }

    fmt.Println("Success")
    return
}
like image 565
Hardy Avatar asked Feb 21 '17 07:02

Hardy


Video Answer


1 Answers

Use to_jsonb:

Db.Exec(`
    UPDATE instruction.file
    SET details = jsonb_set("details", '{"UploadBy"}', to_jsonb($1::text), true)
    WHERE id = $2
    `, uname, "820"
)
like image 160
Clodoaldo Neto Avatar answered Nov 15 '22 04:11

Clodoaldo Neto