From 3acc4f19684ce187589578314a3ba626aa965030 Mon Sep 17 00:00:00 2001 From: Tom Payne Date: Tue, 28 May 2024 22:59:52 +0200 Subject: [PATCH] feat: add support for NULL geometries --- pgxgeos.go | 8 ++++++++ pgxgeos_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/pgxgeos.go b/pgxgeos.go index 51e9afa..69fef88 100644 --- a/pgxgeos.go +++ b/pgxgeos.go @@ -139,6 +139,10 @@ func (p *binaryScanPlan) Scan(src []byte, target any) error { if !ok { return errors.ErrUnsupported } + if len(src) == 0 { + *pgeom = nil + return nil + } geom, err := p.geosContext.NewGeomFromWKB(src) if err != nil { return err @@ -154,6 +158,10 @@ func (p *textScanPlan) Scan(src []byte, target any) error { if !ok { return errors.ErrUnsupported } + if len(src) == 0 { + *pgeom = nil + return nil + } var err error src, err = hex.DecodeString(string(src)) if err != nil { diff --git a/pgxgeos_test.go b/pgxgeos_test.go index a8d85c9..e96295c 100644 --- a/pgxgeos_test.go +++ b/pgxgeos_test.go @@ -54,6 +54,32 @@ func TestCodecDecodeValue(t *testing.T) { } func TestCodecDecodeNullValue(t *testing.T) { + defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, tb testing.TB, conn *pgx.Conn) { + tb.Helper() + + type s struct { + Geom *geos.Geom `db:"geom"` + } + + for _, format := range []int16{ + pgx.BinaryFormatCode, + pgx.TextFormatCode, + } { + tb.(*testing.T).Run(strconv.Itoa(int(format)), func(t *testing.T) { + tb.Helper() + + rows, err := conn.Query(ctx, "select NULL::geometry AS geom", pgx.QueryResultFormats{format}) + assert.NoError(tb, err) + + value, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[s]) + assert.NoError(t, err) + assert.Zero(t, value) + }) + } + }) +} + +func TestCodecDecodeNullGeometry(t *testing.T) { defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, tb testing.TB, conn *pgx.Conn) { tb.Helper() rows, err := conn.Query(ctx, "select $1::geometry", nil)