This repository has been archived by the owner on Jul 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_custom_type_test.go
104 lines (88 loc) · 2.24 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
package pgx_test
import (
"errors"
"fmt"
"github.com/jackc/pgx"
"regexp"
"strconv"
)
var pointRegexp *regexp.Regexp = regexp.MustCompile(`^\((.*),(.*)\)$`)
// NullPoint represents a point that may be null.
//
// If Valid is false then the value is NULL.
type NullPoint struct {
X, Y float64 // Coordinates of point
Valid bool // Valid is true if not NULL
}
func (p *NullPoint) Scan(vr *pgx.ValueReader) error {
if vr.Type().DataTypeName != "point" {
return pgx.SerializationError(fmt.Sprintf("NullPoint.Scan cannot decode %s (OID %d)", vr.Type().DataTypeName, vr.Type().DataType))
}
if vr.Len() == -1 {
p.X, p.Y, p.Valid = 0, 0, false
return nil
}
switch vr.Type().FormatCode {
case pgx.TextFormatCode:
s := vr.ReadString(vr.Len())
match := pointRegexp.FindStringSubmatch(s)
if match == nil {
return pgx.SerializationError(fmt.Sprintf("Received invalid point: %v", s))
}
var err error
p.X, err = strconv.ParseFloat(match[1], 64)
if err != nil {
return pgx.SerializationError(fmt.Sprintf("Received invalid point: %v", s))
}
p.Y, err = strconv.ParseFloat(match[2], 64)
if err != nil {
return pgx.SerializationError(fmt.Sprintf("Received invalid point: %v", s))
}
case pgx.BinaryFormatCode:
return errors.New("binary format not implemented")
default:
return fmt.Errorf("unknown format %v", vr.Type().FormatCode)
}
p.Valid = true
return vr.Err()
}
func (p NullPoint) FormatCode() int16 { return pgx.BinaryFormatCode }
func (p NullPoint) Encode(w *pgx.WriteBuf, oid pgx.Oid) error {
if !p.Valid {
w.WriteInt32(-1)
return nil
}
s := fmt.Sprintf("point(%v,%v)", p.X, p.Y)
w.WriteInt32(int32(len(s)))
w.WriteBytes([]byte(s))
return nil
}
func (p NullPoint) String() string {
if p.Valid {
return fmt.Sprintf("%v, %v", p.X, p.Y)
}
return "null point"
}
func Example_CustomType() {
conn, err := pgx.Connect(*defaultConnConfig)
if err != nil {
fmt.Printf("Unable to establish connection: %v", err)
return
}
var p NullPoint
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
}