postgresqlgopgx

Scanning a range type using pgx


I have column of the type int4range and would like to scan it using pgx. I am defining the type as pgtype.Int4range but I am seeing the error

cannot assign &{{18 2} {86 2} i e 2} to **int64

All I am doing is

for rows.Next() {
....
err = rows.Scan(
... 
&healthRange)

Is there something I am missing?


Solution

  • Scan reads the values from the current row into dest values positionally. It's most likely that the parameters passed to Scan does not match the columns in the row.

    Here is a reproducer of the issue:

    package main
    
    import (
        "fmt"
    
        "github.com/jackc/pgx"
        "github.com/jackc/pgx/pgtype"
    )
    
    func main() {
        conn, err := pgx.Connect(pgx.ConnConfig{
            Host:     "localhost",
            Port:     5432,
            User:     "username",
            Password: "password",
        })
        if err != nil {
            panic(err)
        }
        defer conn.Close()
    
        var (
            healthRange pgtype.Int4range
            anotherVar  *int64
        )
        row := conn.QueryRow(`select '[18,86)'::int4range, 2`)
        err = row.Scan(&anotherVar, &healthRange)
        if err != nil {
            panic(err)
        }
        fmt.Printf("%+v", healthRange)
    }
    

    The error message is:

    panic: can't scan into dest[0]: cannot assign &{{18 2} {86 2} i e 2} to **int64
    

    Apply this change to fix the issue:

    - row.Scan(&anotherVar, &healthRange)
    + row.Scan(&healthRange, &anotherVar)
    

    BTW, pgtype.Int4range is in github.com/jackc/pgx@v3, which was first published in 2017. Consider upgrading to the latest version, github.com/jackc/pgx/v5.