Skip to content

Can persist an entity, but get am error, when reading using sqlx #2508

@hanskarlneuland

Description

@hanskarlneuland

Describe the bug
I am using sqlx and pgx.
I can persist an entity , but when I try to read it, I get an error
sql: Scan error on column index 2, name "db_timeofday": unsupported Scan, storing driver.Value type string into type *time.Time

To Reproduce
Execute the attached main. It will create the db table, insert an entity and receive an error when reading.

package main

import (
	"context"
	"log"
	"os"

	"github.com/jackc/pgx/v5"
)

type Entity struct {
	Uuid      uuid.UUID `db:"db_uuid"`
	Number    int       `db:"db_number"`
	TimeOfDay time.Time `db:"db_timeofday"`
}

func main() {
	dsn := os.Getenv("DATABASE_URL")
	conn, err := sqlx.Connect("pgx", dsn)

	log.SetFlags(log.Lshortfile)
	if err != nil {
		log.Fatal(err)
	}

	dropAndCreateTable(conn)
	persistEntity(conn)
	readEntity(conn)
}

func dropAndCreateTable(db *sqlx.DB) {
	_, err := db.Exec(dropTable)
	_, err = db.Exec(createTable)
	if err != nil {
		log.Fatal(err)
	}
}
func persistEntity(db *sqlx.DB) {
	entities := []Entity{Entity{Uuid: uuid.UUID{}, Number: 4711, TimeOfDay: time.Now()}}

	query := `INSERT INTO csv_table (db_uuid, db_number, db_timeofday) VALUES (:db_uuid, :db_number, :db_timeofday)`
	named, args, err := sqlx.Named(query, entities)
	if err != nil {
		log.Fatal(err)
	}
	rebind := db.Rebind(named)
	_, err = db.Exec(rebind, args...)
	if err != nil {
		log.Fatal(err)
	}
}

func readEntity(db *sqlx.DB) {
	var loaded Entity
	err := db.Get(&loaded, `SELECT db_uuid, db_number,db_timeofday FROM csv_table WHERE db_number = $1 `, 4711)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Loaded:", loaded)
}

Please run the main`.

Expected behavior
I expect to read the persisted entity without an error.

Actual behavior
The db.Get in readEntity returns an error
main.go:72: sql: Scan error on column index 2, name "db_timeofday": unsupported Scan, storing driver.Value type string into type *time.Time

Version

  • go version go1.26.0 linux/amd64
  • PostgreSQL 17.4 (Debian 17.4-1.pgdg120+2) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
  • pgx: github.com/jackc/pgx/v5 v5.8.0

Additional context
My go.mod:
module pgxexample

go 1.26
require (
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.8.0
github.com/jmoiron/sqlx v1.4.0
)
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/text v0.29.0 // indirect
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions