This repository has been archived by the owner on Apr 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_custom_type_test.go
105 lines (87 loc) · 2.01 KB
/
example_custom_type_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package pgx_test
import (
"fmt"
"regexp"
"strconv"
"github.com/jackc/pgx"
"github.com/jackc/pgx/pgtype"
"github.com/pkg/errors"
)
var pointRegexp *regexp.Regexp = regexp.MustCompile(`^\((.*),(.*)\)$`)
// Point represents a point that may be null.
type Point struct {
X, Y float64 // Coordinates of point
Status pgtype.Status
}
func (dst *Point) Set(src interface{}) error {
return errors.Errorf("cannot convert %v to Point", src)
}
func (dst *Point) Get() interface{} {
switch dst.Status {
case pgtype.Present:
return dst
case pgtype.Null:
return nil
default:
return dst.Status
}
}
func (src *Point) AssignTo(dst interface{}) error {
return errors.Errorf("cannot assign %v to %T", src, dst)
}
func (dst *Point) DecodeText(ci *pgtype.ConnInfo, src []byte) error {
if src == nil {
*dst = Point{Status: pgtype.Null}
return nil
}
s := string(src)
match := pointRegexp.FindStringSubmatch(s)
if match == nil {
return errors.Errorf("Received invalid point: %v", s)
}
x, err := strconv.ParseFloat(match[1], 64)
if err != nil {
return errors.Errorf("Received invalid point: %v", s)
}
y, err := strconv.ParseFloat(match[2], 64)
if err != nil {
return errors.Errorf("Received invalid point: %v", s)
}
*dst = Point{X: x, Y: y, Status: pgtype.Present}
return nil
}
func (src *Point) String() string {
if src.Status == pgtype.Null {
return "null point"
}
return fmt.Sprintf("%.1f, %.1f", src.X, src.Y)
}
func Example_CustomType() {
conn, err := pgx.Connect(*defaultConnConfig)
if err != nil {
fmt.Printf("Unable to establish connection: %v", err)
return
}
// Override registered handler for point
conn.ConnInfo.RegisterDataType(pgtype.DataType{
Value: &Point{},
Name: "point",
OID: 600,
})
p := &Point{}
err = conn.QueryRow("select null::point").Scan(p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(p)
err = conn.QueryRow("select point(1.5,2.5)").Scan(p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(p)
// Output:
// null point
// 1.5, 2.5
}