From 279c3c0a20e0dbee3c4b644f58e5e3b3de8e051f Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Tue, 6 Dec 2022 19:41:25 -0600 Subject: [PATCH] Fix: json values work with sql.Scanner https://github.com/jackc/pgx/issues/1418 --- pgtype/json.go | 8 ++++++++ pgtype/json_test.go | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/pgtype/json.go b/pgtype/json.go index d0d98fc9..63338bac 100644 --- a/pgtype/json.go +++ b/pgtype/json.go @@ -1,6 +1,7 @@ package pgtype import ( + "database/sql" "database/sql/driver" "encoding/json" "fmt" @@ -82,6 +83,13 @@ func (JSONCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan return scanPlanJSONToByteSlice{} case BytesScanner: return scanPlanBinaryBytesToBytesScanner{} + + // Cannot rely on sql.Scanner being handled later because scanPlanJSONToJSONUnmarshal will take precedence. + // + // https://github.com/jackc/pgx/issues/1418 + case sql.Scanner: + return &scanPlanSQLScanner{formatCode: format} + default: return scanPlanJSONToJSONUnmarshal{} } diff --git a/pgtype/json_test.go b/pgtype/json_test.go index db20e576..00dbbc5c 100644 --- a/pgtype/json_test.go +++ b/pgtype/json_test.go @@ -2,6 +2,7 @@ package pgtype_test import ( "context" + "database/sql" "testing" pgx "github.com/jackc/pgx/v5" @@ -48,6 +49,9 @@ func TestJSONCodec(t *testing.T) { {map[string]any(nil), new([]byte), isExpectedEqBytes([]byte(nil))}, {[]byte(nil), new([]byte), isExpectedEqBytes([]byte(nil))}, {nil, new([]byte), isExpectedEqBytes([]byte(nil))}, + + // Test sql.Scanner. (https://github.com/jackc/pgx/issues/1418) + {"42", new(sql.NullInt64), isExpectedEq(sql.NullInt64{Int64: 42, Valid: true})}, }) pgxtest.RunValueRoundTripTests(context.Background(), t, defaultConnTestRunner, pgxtest.KnownOIDQueryExecModes, "json", []pgxtest.ValueRoundTripTest{