~nilium/sql

ref: 0eb4a8bb965fb3eb0d99f7cd138e665aa322c3c0 sql/vdb/value.go -rw-r--r-- 5.6 KiB
0eb4a8bbNoel Cower Move drivers to top-level package 11 months ago
                                                                                
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// sql - A tool for querying databases.
// Copyright (C) 2021 Noel Cower
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package vdb

import (
	"database/sql"
	"database/sql/driver"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"math/big"
	"strconv"
	"strings"
	"time"
)

type Value struct {
	Options *QueryOptions
	Type    *sql.ColumnType
	Dest    interface{}
}

const numericBytes = "+-0123456789"

func (v *Value) Value() (driver.Value, error) {
	// Implemented in case someone passes this data back into a query.
	switch d := v.Dest.(type) {
	case *big.Float:
		return d.Text('f', -1), nil
	case *big.Int:
		return d.String(), nil
	case time.Time:
		switch v.Options.TimeFormat {
		case TimeString:
			return d.Format(time.RFC3339Nano), nil
		case TimeFloat:
			t := d.Truncate(time.Second)
			sub := d.Sub(t)
			f := new(big.Float).SetPrec(0).SetFloat64(float64(sub))
			f = f.Quo(f, big.NewFloat(float64(time.Second)))
			f = f.Add(f, big.NewFloat(float64(t.Unix())))
			return f.Text('f', -1), nil
		case TimeUnix:
			return d.Unix(), nil
		case TimeUnixNano, TimeUnixMicro, TimeUnixMilli:
			t := d.Truncate(time.Second)
			sub := d.Sub(t)
			b := big.NewInt(t.Unix())
			b = b.Mul(b, big.NewInt(int64(time.Second)))
			b = b.Add(b, big.NewInt(int64(sub)))
			switch v.Options.TimeFormat {
			case TimeUnixMicro:
				b = b.Quo(b, big.NewInt(int64(time.Microsecond)))
			case TimeUnixMilli:
				b = b.Quo(b, big.NewInt(int64(time.Millisecond)))
			}
			return b.String(), nil
		case TimeCustom:
			return d.Format(v.Options.TimeLayout), nil
		}
	case map[string]interface{}, []interface{}:
		p, err := json.Marshal(v.Dest)
		return string(p), err
	}
	return v.Dest, nil
}

func (v *Value) parseFloat(src string) bool {
	b, ok := new(big.Int).SetString(src, 0)
	if ok {
		v.Dest = b
	}
	return ok
}

func (v *Value) parseInt(src string) bool {
	f, ok := new(big.Float).SetPrec(0).SetString(src)
	if ok {
		v.Dest = f
	}
	return ok
}

func (v *Value) Scan(src interface{}) error {
	tryJSON := v.Options.TryJSON && !v.Options.SkipJSON
	if !tryJSON && !v.Options.SkipJSON && v.Type != nil {
		name := strings.ToLower(v.Type.Name())
		tryJSON = strings.HasSuffix(name, "_json") ||
			name == "json" ||
			strings.HasPrefix(strings.ToLower(v.Type.DatabaseTypeName()), "json")
	}

	switch conc := src.(type) {
	case nil:
		v.Dest = nil
		return nil

	case int64, float64, time.Time, bool:
		v.Dest = conc
		return nil

	case string:
		v.Dest = conc
		src = []byte(conc)
	}

	p, ok := src.([]byte)
	if !ok {
		return fmt.Errorf("unexpected scan type %T", src)
	}

	var text func() string
	text = func() string {
		t, ok := src.(string)
		if !ok {
			t = string(p)
		}
		text = func() string { return t }
		return t
	}

	if tryJSON && len(p) > 0 {
		if strings.IndexByte(numericBytes, p[0]) > -1 && (v.parseInt(text()) || v.parseFloat(text())) {
			return nil
		}
		if json.Unmarshal(p, &v.Dest) == nil {
			return nil
		}
	}

	t := strings.ToLower(v.Type.DatabaseTypeName())
	// TODO: Support Postgres array types?
	switch t {
	case "tinyint",
		"smallint",
		"mediumint",
		"bigint",
		"integer",
		"smallserial",
		"serial",
		"bigserial":
		if v.parseInt(text()) {
			return nil
		}

	case "decimal",
		"numeric",
		"float",
		"double",
		"fixed",
		"dec",
		"double precision",
		"real",
		"money":
		if v.parseFloat(text()) {
			return nil
		}

	case "text",
		"char",
		"character",
		"varchar",
		"character varying",
		"tinytext",
		"mediumtext",
		"longtext",
		"enum",
		"set":
		v.Dest = string(p)
		return nil

	case "blob",
		"bytea",
		"tinyblob",
		"mediumblob",
		"longblob",
		"binary",
		"varbinary":
		v.Dest = append([]byte(nil), p...)
		return nil

	case "json", "jsonb":
		if v.Options.SkipJSON {
			break
		}
		return json.Unmarshal(p, &v.Dest)
	}

	// Fallback:
	v.Dest = string(p)

	return nil
}

func (v *Value) MarshalJSON() ([]byte, error) {
	switch d := v.Dest.(type) {
	case *big.Float:
		return []byte(d.Text('f', -1)), nil
	case *big.Int:
		return []byte(d.String()), nil
	case time.Time:
		switch v.Options.TimeFormat {
		case TimeString:
			return json.Marshal(d.Format(time.RFC3339Nano))
		case TimeFloat:
			t := d.Truncate(time.Second)
			sub := d.Sub(t)
			f := new(big.Float).SetPrec(0).SetFloat64(float64(sub))
			f = f.Quo(f, big.NewFloat(float64(time.Second)))
			f = f.Add(f, big.NewFloat(float64(t.Unix())))
			return []byte(f.Text('f', -1)), nil
		case TimeUnix:
			return []byte(strconv.FormatInt(d.Unix(), 10)), nil
		case TimeUnixNano, TimeUnixMicro, TimeUnixMilli:
			t := d.Truncate(time.Second)
			sub := d.Sub(t)
			b := big.NewInt(t.Unix())
			b = b.Mul(b, big.NewInt(int64(time.Second)))
			b = b.Add(b, big.NewInt(int64(sub)))
			switch v.Options.TimeFormat {
			case TimeUnixMicro:
				b = b.Quo(b, big.NewInt(int64(time.Microsecond)))
			case TimeUnixMilli:
				b = b.Quo(b, big.NewInt(int64(time.Millisecond)))
			}
			return []byte(b.String()), nil
		case TimeCustom:
			return json.Marshal(d.Format(v.Options.TimeLayout))
		}
	case []byte:
		return json.Marshal(base64.StdEncoding.EncodeToString(d))
	}
	return json.Marshal(v.Dest)
}