forked from mailru/go-clickhouse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.go
More file actions
109 lines (99 loc) · 2.33 KB
/
encoder.go
File metadata and controls
109 lines (99 loc) · 2.33 KB
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
106
107
108
109
package clickhouse
import (
"database/sql/driver"
"fmt"
"reflect"
"strconv"
"time"
)
var (
textEncode encoder = new(textEncoder)
)
type encoder interface {
Encode(value driver.Value) ([]byte, error)
}
type textEncoder struct {
}
// Encode encodes driver value into string
// Note: there is 2 convention:
// type string will be quoted
// type []byte will be encoded as is (raw string)
func (e *textEncoder) Encode(value driver.Value) ([]byte, error) {
switch v := value.(type) {
case array:
return e.encodeArray(reflect.ValueOf(v.v))
case []byte:
return v, nil
}
vv := reflect.ValueOf(value)
switch vv.Kind() {
case reflect.Interface, reflect.Ptr:
if vv.IsNil() {
return []byte("NULL"), nil
}
return e.Encode(vv.Elem().Interface())
case reflect.Slice, reflect.Array:
return e.encodeArray(vv)
}
return []byte(e.encode(value)), nil
}
func (e *textEncoder) encode(value driver.Value) string {
if value == nil {
return "NULL"
}
switch v := value.(type) {
case bool:
if v {
return "1"
}
return "0"
case int:
return strconv.FormatInt(int64(v), 10)
case int8:
return strconv.FormatInt(int64(v), 10)
case int16:
return strconv.FormatInt(int64(v), 10)
case int32:
return strconv.FormatInt(int64(v), 10)
case int64:
return strconv.FormatInt(v, 10)
case uint:
return strconv.FormatUint(uint64(v), 10)
case uint8:
return strconv.FormatUint(uint64(v), 10)
case uint16:
return strconv.FormatUint(uint64(v), 10)
case uint32:
return strconv.FormatUint(uint64(v), 10)
case uint64:
return strconv.FormatUint(v, 10)
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32)
case float64:
return strconv.FormatFloat(v, 'f', -1, 64)
case string:
return quote(escape(v))
case time.Time:
return formatTime(v)
}
return fmt.Sprint(value)
}
// EncodeArray encodes a go slice or array as Clickhouse Array
func (e *textEncoder) encodeArray(value reflect.Value) ([]byte, error) {
if value.Kind() != reflect.Slice && value.Kind() != reflect.Array {
return nil, fmt.Errorf("expected array or slice, got %s", value.Kind())
}
res := make([]byte, 0)
res = append(res, '[')
for i := 0; i < value.Len(); i++ {
if i > 0 {
res = append(res, ',')
}
tmp, err := e.Encode(value.Index(i).Interface())
if err != nil {
return nil, err
}
res = append(res, tmp...)
}
return append(res, ']'), nil
}