2

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?

mistermims
  • 77
  • 4

1 Answers1

2

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.

Zeke Lu
  • 6,349
  • 1
  • 17
  • 23
  • Thanks, I was missing `::int4range` in the Select statement – mistermims Jul 22 '23 at 03:19
  • `::int4range` is not needed if the column has the type `int4range` in a real table. – Zeke Lu Jul 22 '23 at 03:33
  • My table had int4range as the type, I defined it as ALTER TABLE ADD COLUMN healthrange int4range DEFAULT '[18,86]'::int4range NOT NULL. Do you think it could be because of the default? – mistermims Jul 22 '23 at 03:36
  • The definition is correct. `&{{18 2} {86 2} i e 2}` in the error message means that the range value has been parsed correctly. Like I said in the answer, it's most likely that the reason is a mismatch between the columns and the parameters passed to `Scan`. – Zeke Lu Jul 22 '23 at 03:39