Skip to content

Commit b9f02db

Browse files
committed
wkb scanner: support hex encoded data from go-pg
1 parent 5af0ae2 commit b9f02db

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

encoding/wkb/scanner.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ package wkb
33
import (
44
"database/sql"
55
"database/sql/driver"
6+
"encoding/hex"
67
"errors"
8+
"fmt"
79

810
"github.com/paulmach/orb"
911
)
@@ -93,6 +95,17 @@ func (s *GeometryScanner) Scan(d interface{}) error {
9395
return nil
9496
}
9597

98+
// go-pg will return ST_AsBinary(*) data as `\xhexencoded` which
99+
// needs to be converted to true binary for further decoding.
100+
// Code detects the \x prefix and then converts the rest from Hex to binary.
101+
if len(data) > 2 && data[0] == byte('\\') && data[1] == byte('x') {
102+
n, err := hex.Decode(data, data[2:])
103+
if err != nil {
104+
return fmt.Errorf("thought the data was hex, but it is not: %v", err)
105+
}
106+
data = data[:n]
107+
}
108+
96109
switch g := s.g.(type) {
97110
case nil:
98111
m, err := Unmarshal(data)

encoding/wkb/scanner_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,38 @@ func TestScanNil(t *testing.T) {
4949
})
5050
}
5151

52+
func TestScanHexData(t *testing.T) {
53+
cases := []struct {
54+
name string
55+
data []byte
56+
expected orb.Point
57+
}{
58+
{
59+
name: "point",
60+
data: []byte(`\x0101000000e0d57267266e4840b22ac24d46b50240`),
61+
expected: orb.Point{48.860547, 2.338513},
62+
},
63+
}
64+
65+
for _, tc := range cases {
66+
t.Run(tc.name, func(t *testing.T) {
67+
p := orb.Point{}
68+
s := Scanner(&p)
69+
70+
err := s.Scan(tc.data)
71+
if err != nil {
72+
t.Fatalf("scan error: %v", err)
73+
}
74+
75+
if !p.Equal(tc.expected) {
76+
t.Errorf("unequal data")
77+
t.Log(p)
78+
t.Log(tc.expected)
79+
}
80+
})
81+
}
82+
}
83+
5284
func TestScanPoint(t *testing.T) {
5385
cases := []struct {
5486
name string

0 commit comments

Comments
 (0)