Skip to content

PGX seems not calling the Scanner interface with JSONB column #2146

@ludusrusso

Description

@ludusrusso

Describe the bug
When implementing scanner and valuer interface of a type used with pgx, it seems that scanner interface is not used to read data in case of JSONB columns.

It is called when the column is not JSONB, I've tried with a bytea/varchar columns and it works perfectly.

To Reproduce

I've created the following repo to reproduce the issue: https://github.com/ludusrusso/pgx-protobuf

As you can see if you run go run main.go, the program panics with

INFO[0000] calling valuer                               
FATA[0000] can't get tests: can't scan into dest[1]: json: cannot unmarshal string into Go struct field Test.timestamp of type timestamppb.Timestamp 
exit status 1

The problem is due to the fact that pgx is tring to unmarshal test with the json packages, while the struct has been marshalled with protojson.

As you can see from logs, the Scan method is never called.

func (t *Test) Scan(value interface{}) error {
	logrus.Info("calling scanner")

	bytes, ok := value.([]byte)
	if !ok {
		return errors.New("type assertion to []byte failed")
	}

	return protojson.Unmarshal(bytes, t)
}

func (t *Test) Value() (driver.Value, error) {
	logrus.Info("calling valuer")

	return protojson.Marshal(t)
}

Expected behavior
Scan method should be called.

Actual behavior
Scan method is not called.

Version

  • Go: $ go version -> go version go1.23.1 darwin/arm64
  • PostgreSQL: $ psql --no-psqlrc --tuples-only -c 'select version()' -> PostgreSQL 15.8 (Homebrew) on aarch64-apple-darwin23.4.0, compiled by Apple clang version 15.0.0 (clang-1500.3.9.4), 64-bit
  • pgx: $ grep 'github.com/jackc/pgx/v[0-9]' go.mod -> v5.7.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions