forked from deepmarker/pqinterval
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
91 lines (78 loc) · 1.68 KB
/
parse.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
package pqinterval
import (
"fmt"
"strconv"
"strings"
)
// ParseErr is returned on a failure to parse a
// postgres result into an Interval or Duration.
type ParseErr struct {
String string
Cause error
}
func Parse(s string) (Interval, error) {
chunks := strings.Split(s, " ")
ival := Interval{}
var negTime bool
if len(chunks)%2 == 1 {
// Parse the time component
t := chunks[len(chunks)-1]
chunks = chunks[:len(chunks)-1]
if t[0] == '-' {
negTime = true
t = t[1:]
} else if t[0] == '+' {
t = t[1:]
}
parts := strings.Split(t, ":")
if len(parts) < 2 || len(parts) > 3 {
return ival, fmt.Errorf("invalid time format")
}
hrs, err := strconv.Atoi(parts[0])
if err != nil {
return ival, err
}
if negTime {
hrs = -hrs
}
mins, err := strconv.Atoi(parts[1])
if err != nil {
return ival, err
}
var secs int
if len(parts) > 2 {
secs, err = strconv.Atoi(parts[2])
if err != nil {
return ival, err
}
}
ival.hrs = int32(hrs)
ival.us = uint32(mins*usPerMin + secs*usPerSec)
}
for len(chunks) > 0 {
quantity, err := strconv.Atoi(chunks[0])
if err != nil {
return Interval{}, err
}
unit := chunks[1]
chunks = chunks[2:]
switch unit {
case "year", "years":
ival.yrs = uint32(quantity)
if negTime {
ival.yrs |= yrSignBit
}
case "mon", "mons":
ival.hrs += int32(24 * daysPerMon * quantity)
case "day", "days":
ival.hrs += int32(24 * quantity)
default:
return Interval{}, fmt.Errorf("invalid unit: %s", unit)
}
}
return ival, nil
}
// Error implements the error interface.
func (pe ParseErr) Error() string {
return fmt.Sprintf("pqinterval: Error parsing %q: %s", pe.String, pe.Cause)
}