Search code examples
postgresqlgo

panic: sql: expected 1 destination arguments in Scan, not <number> golang, pq, sql


I am fetching records from the column data using db.QueryRow from a table in . The Column has the type .

Go code

m := Message{}
err := db.QueryRow("SELECT data FROM message WHERE data->>'id'=$1"
                    , id).Scan(m.Id, m.Type, m.Title)

Result

panic: sql: expected 1 destination arguments in Scan, not 3.

As per row.Scan can pass n number of destination arguments. Whats wrong with this code?


Solution

  • The query returns one field per row. The code is scanning for three. Perhaps you want something like:

    err := db.QueryRow("SELECT data->>'id', 
                        data->>'type', data->>'title' FROM message 
                        WHERE data->>'id'=$1", id).Scan(m.Id, m.Type, m.Title)
    
    // Also, pass pointers to the values:
    err := db.QueryRow("SELECT data->>'id', 
                        data->>'type', data->>'title' FROM message 
                        WHERE data->>'id'=$1", id).Scan(&m.Id, &m.Type, &m.Title)
    

    Another option is to fetch the data as a single field and decode the result with the encoding/json package.

    var p []byte
    err := db.QueryRow("SELECT data FROM message 
                        WHERE data->>'id'=$1", id).Scan(&p)
    if err != nil {
            // handle error
    }
    var m Message
    err := json.Unmarshal(p, &m)
    if err != nil {
            // handle error
    }