Skip to content

Commit

Permalink
wkb scanner: support hex encoded data from go-pg
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmach committed Sep 24, 2019
1 parent 5af0ae2 commit b9f02db
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
13 changes: 13 additions & 0 deletions encoding/wkb/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package wkb
import (
"database/sql"
"database/sql/driver"
"encoding/hex"
"errors"
"fmt"

"github.com/paulmach/orb"
)
Expand Down Expand Up @@ -93,6 +95,17 @@ func (s *GeometryScanner) Scan(d interface{}) error {
return nil
}

// go-pg will return ST_AsBinary(*) data as `\xhexencoded` which
// needs to be converted to true binary for further decoding.
// Code detects the \x prefix and then converts the rest from Hex to binary.
if len(data) > 2 && data[0] == byte('\\') && data[1] == byte('x') {
n, err := hex.Decode(data, data[2:])
if err != nil {
return fmt.Errorf("thought the data was hex, but it is not: %v", err)
}
data = data[:n]
}

switch g := s.g.(type) {
case nil:
m, err := Unmarshal(data)
Expand Down
32 changes: 32 additions & 0 deletions encoding/wkb/scanner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,38 @@ func TestScanNil(t *testing.T) {
})
}

func TestScanHexData(t *testing.T) {
cases := []struct {
name string
data []byte
expected orb.Point
}{
{
name: "point",
data: []byte(`\x0101000000e0d57267266e4840b22ac24d46b50240`),
expected: orb.Point{48.860547, 2.338513},
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
p := orb.Point{}
s := Scanner(&p)

err := s.Scan(tc.data)
if err != nil {
t.Fatalf("scan error: %v", err)
}

if !p.Equal(tc.expected) {
t.Errorf("unequal data")
t.Log(p)
t.Log(tc.expected)
}
})
}
}

func TestScanPoint(t *testing.T) {
cases := []struct {
name string
Expand Down

0 comments on commit b9f02db

Please sign in to comment.