使用pgx扫描范围类型

huangapple go评论102阅读模式
英文:

Scanning a range type using pgx

问题

我有一个 int4range 类型的列,并希望使用 pgx 进行扫描。我将类型定义为 pgtype.Int4range,但是我看到了以下错误:

无法将 &{{18 2} {86 2} i e 2} 分配给 **int64

我所做的只是:

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

我是否漏掉了什么?

英文:

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?

答案1

得分: 2

Scan将当前行的值按位置读入到目标值(dest)中。很可能是Scan的参数与行中的列不匹配。

以下是问题的复现代码:

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)
}

错误信息如下:

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

应用以下更改以修复此问题:

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

顺便提一下,pgtype.Int4range位于github.com/jackc/pgx@v3中,该版本于2017年首次发布。考虑升级到最新版本github.com/jackc/pgx/v5

英文:

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.

huangapple
  • 本文由 发表于 2023年7月22日 05:36:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76741375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定