forked from segmentio/go-athena
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalue.go
91 lines (83 loc) · 2.07 KB
/
value.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 athena
import (
"database/sql/driver"
"encoding/hex"
"fmt"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/service/athena"
)
const (
// TimestampLayout is the Go time layout string for an Athena `timestamp`.
TimestampLayout = "2006-01-02 15:04:05.999"
TimestampWithTimeZoneLayout = "2006-01-02 15:04:05.999 MST"
DateLayout = "2006-01-02"
)
func convertRow(columns []*athena.ColumnInfo, in []*athena.Datum, ret []driver.Value) error {
for i, val := range in {
coerced, err := convertValue(*columns[i].Type, val.VarCharValue)
if err != nil {
return err
}
ret[i] = coerced
}
return nil
}
func convertValue(athenaType string, rawValue *string) (interface{}, error) {
if rawValue == nil {
return nil, nil
}
val := *rawValue
switch athenaType {
case "tinyint":
return strconv.ParseInt(val, 10, 8)
case "smallint":
return strconv.ParseInt(val, 10, 16)
case "integer":
return strconv.ParseInt(val, 10, 32)
case "bigint":
return strconv.ParseInt(val, 10, 64)
case "boolean":
switch val {
case "true":
return true, nil
case "false":
return false, nil
}
return nil, fmt.Errorf("cannot parse '%s' as boolean", val)
case "float":
return strconv.ParseFloat(val, 32)
case "double", "decimal":
return strconv.ParseFloat(val, 64)
case "varchar", "string":
return val, nil
case "varbinary", "binary":
arr := strings.Split(val, " ")
dst := make([]byte, 1)
ret := make([]byte, len(arr))
for i, v := range arr {
src := []byte(v)
if len(src) != 2 {
return nil, fmt.Errorf("unexpected byte length %d", len(src))
}
n, err := hex.Decode(dst, src)
if err != nil {
return nil, err
}
if n != 1 {
return nil, fmt.Errorf("unexpected byte length %d", n)
}
ret[i] = dst[0]
}
return ret, nil
case "timestamp":
return time.Parse(TimestampLayout, val)
case "timestamp with time zone":
return time.Parse(TimestampWithTimeZoneLayout, val)
case "date":
return time.Parse(DateLayout, val)
default:
return nil, fmt.Errorf("unknown type `%s` with value %s", athenaType, val)
}
}