From ca022267dbbfe7a8ba7070557352a5cd08f6cb37 Mon Sep 17 00:00:00 2001 From: "cemre.mengu" Date: Sat, 25 Mar 2023 11:30:11 +0300 Subject: [PATCH] add tests --- pgtype/json_test.go | 5 +++++ pgtype/jsonb_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/pgtype/json_test.go b/pgtype/json_test.go index d72cfb24..f3368a41 100644 --- a/pgtype/json_test.go +++ b/pgtype/json_test.go @@ -83,6 +83,11 @@ func TestJSONCodecUnmarshalSQLNull(t *testing.T) { require.NoError(t, err) require.Nil(t, m) + m = map[string]interface{}{"foo": "bar"} + err = conn.QueryRow(ctx, "select null::json").Scan(&m) + require.NoError(t, err) + require.Nil(t, m) + // Pointer to pointer are nilified n := 42 p := &n diff --git a/pgtype/jsonb_test.go b/pgtype/jsonb_test.go index 7dadc6c5..dfaeb8c4 100644 --- a/pgtype/jsonb_test.go +++ b/pgtype/jsonb_test.go @@ -4,7 +4,9 @@ import ( "context" "testing" + pgx "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxtest" + "github.com/stretchr/testify/require" ) func TestJSONBTranscode(t *testing.T) { @@ -31,3 +33,40 @@ func TestJSONBTranscode(t *testing.T) { {jsonStruct{Name: "Adam", Age: 10}, new(jsonStruct), isExpectedEq(jsonStruct{Name: "Adam", Age: 10})}, }) } + +func TestJSONBCodecUnmarshalSQLNull(t *testing.T) { + defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + // Slices are nilified + slice := []string{"foo", "bar", "baz"} + err := conn.QueryRow(ctx, "select null::jsonb").Scan(&slice) + require.NoError(t, err) + require.Nil(t, slice) + + // Maps are nilified + m := map[string]any{"foo": "bar"} + err = conn.QueryRow(ctx, "select null::jsonb").Scan(&m) + require.NoError(t, err) + require.Nil(t, m) + + m = map[string]interface{}{"foo": "bar"} + err = conn.QueryRow(ctx, "select null::jsonb").Scan(&m) + require.NoError(t, err) + require.Nil(t, m) + + // Pointer to pointer are nilified + n := 42 + p := &n + err = conn.QueryRow(ctx, "select null::jsonb").Scan(&p) + require.NoError(t, err) + require.Nil(t, p) + + // A string cannot scan a NULL. + str := "foobar" + err = conn.QueryRow(ctx, "select null::jsonb").Scan(&str) + require.EqualError(t, err, "can't scan into dest[0]: cannot scan NULL into *string") + + // A non-string cannot scan a NULL. + err = conn.QueryRow(ctx, "select null::jsonb").Scan(&n) + require.EqualError(t, err, "can't scan into dest[0]: cannot scan NULL into *int") + }) +}