forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect.go
299 lines (260 loc) · 7.11 KB
/
select.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
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package postgres
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"strings"
"time"
"cosmossdk.io/schema"
)
// count returns the number of rows in the table.
func (tm *objectIndexer) count(ctx context.Context, conn dbConn) (int, error) {
sqlStr := fmt.Sprintf("SELECT COUNT(*) FROM %q;", tm.tableName())
if tm.options.logger != nil {
tm.options.logger.Debug("Count", "sql", sqlStr)
}
row := conn.QueryRowContext(ctx, sqlStr)
var count int
err := row.Scan(&count)
return count, err
}
// exists checks if a row with the provided key exists in the table.
func (tm *objectIndexer) exists(ctx context.Context, conn dbConn, key interface{}) (bool, error) {
buf := new(strings.Builder)
params, err := tm.existsSqlAndParams(buf, key)
if err != nil {
return false, err
}
return tm.checkExists(ctx, conn, buf.String(), params)
}
// checkExists checks if a row exists in the table.
func (tm *objectIndexer) checkExists(ctx context.Context, conn dbConn, sqlStr string, params []interface{}) (bool, error) {
if tm.options.logger != nil {
tm.options.logger.Debug("Check exists", "sql", sqlStr, "params", params)
}
var res interface{}
err := conn.QueryRowContext(ctx, sqlStr, params...).Scan(&res)
switch err {
case nil:
return true, nil
case sql.ErrNoRows:
return false, nil
default:
return false, err
}
}
// existsSqlAndParams generates a SELECT statement to check if a row with the provided key exists in the table.
func (tm *objectIndexer) existsSqlAndParams(w io.Writer, key interface{}) ([]interface{}, error) {
_, err := fmt.Fprintf(w, "SELECT 1 FROM %q", tm.tableName())
if err != nil {
return nil, err
}
_, keyParams, err := tm.whereSqlAndParams(w, key, 1)
if err != nil {
return nil, err
}
_, err = fmt.Fprintf(w, ";")
return keyParams, err
}
func (tm *objectIndexer) get(ctx context.Context, conn dbConn, key interface{}) (schema.StateObjectUpdate, bool, error) {
buf := new(strings.Builder)
params, err := tm.getSqlAndParams(buf, key)
if err != nil {
return schema.StateObjectUpdate{}, false, err
}
sqlStr := buf.String()
if tm.options.logger != nil {
tm.options.logger.Debug("Get", "sql", sqlStr, "params", params)
}
row := conn.QueryRowContext(ctx, sqlStr, params...)
return tm.readRow(row)
}
func (tm *objectIndexer) selectAllSql(w io.Writer) error {
err := tm.selectAllClause(w)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, ";")
return err
}
func (tm *objectIndexer) getSqlAndParams(w io.Writer, key interface{}) ([]interface{}, error) {
err := tm.selectAllClause(w)
if err != nil {
return nil, err
}
keyParams, keyCols, err := tm.bindKeyParams(key)
if err != nil {
return nil, err
}
_, keyParams, err = tm.whereSql(w, keyParams, keyCols, 1)
if err != nil {
return nil, err
}
_, err = fmt.Fprintf(w, ";")
return keyParams, err
}
func (tm *objectIndexer) selectAllClause(w io.Writer) error {
allFields := make([]string, 0, len(tm.typ.KeyFields)+len(tm.typ.ValueFields))
for _, field := range tm.typ.KeyFields {
colName, err := tm.updatableColumnName(field)
if err != nil {
return err
}
allFields = append(allFields, colName)
}
for _, field := range tm.typ.ValueFields {
colName, err := tm.updatableColumnName(field)
if err != nil {
return err
}
allFields = append(allFields, colName)
}
if !tm.options.disableRetainDeletions && tm.typ.RetainDeletions {
allFields = append(allFields, "_deleted")
}
_, err := fmt.Fprintf(w, "SELECT %s FROM %q", strings.Join(allFields, ", "), tm.tableName())
if err != nil {
return err
}
return nil
}
func (tm *objectIndexer) readRow(row interface{ Scan(...interface{}) error }) (schema.StateObjectUpdate, bool, error) {
var res []interface{}
for _, f := range tm.typ.KeyFields {
res = append(res, tm.colBindValue(f))
}
for _, f := range tm.typ.ValueFields {
res = append(res, tm.colBindValue(f))
}
if !tm.options.disableRetainDeletions && tm.typ.RetainDeletions {
res = append(res, new(bool))
}
err := row.Scan(res...)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return schema.StateObjectUpdate{}, false, err
}
return schema.StateObjectUpdate{}, false, err
}
var keys []interface{}
for _, field := range tm.typ.KeyFields {
x, err := tm.readCol(field, res[0])
if err != nil {
return schema.StateObjectUpdate{}, false, err
}
keys = append(keys, x)
res = res[1:]
}
var key interface{} = keys
if len(keys) == 1 {
key = keys[0]
}
var values []interface{}
for _, field := range tm.typ.ValueFields {
x, err := tm.readCol(field, res[0])
if err != nil {
return schema.StateObjectUpdate{}, false, err
}
values = append(values, x)
res = res[1:]
}
var value interface{} = values
if len(values) == 1 {
value = values[0]
}
update := schema.StateObjectUpdate{
TypeName: tm.typ.Name,
Key: key,
Value: value,
}
if !tm.options.disableRetainDeletions && tm.typ.RetainDeletions {
deleted := res[0].(*bool)
if *deleted {
update.Delete = true
}
}
return update, true, nil
}
func (tm *objectIndexer) colBindValue(field schema.Field) interface{} {
switch field.Kind {
case schema.BytesKind:
return new(interface{})
default:
return new(sql.NullString)
}
}
func (tm *objectIndexer) readCol(field schema.Field, value interface{}) (interface{}, error) {
switch field.Kind {
case schema.BytesKind:
// for bytes types we either get []byte or nil
value = *value.(*interface{})
return value, nil
default:
}
nullStr := *value.(*sql.NullString)
if field.Nullable {
if !nullStr.Valid {
return nil, nil
}
}
str := nullStr.String
switch field.Kind {
case schema.StringKind, schema.EnumKind, schema.IntegerKind, schema.DecimalKind:
return str, nil
case schema.Uint8Kind:
value, err := strconv.ParseUint(str, 10, 8)
return uint8(value), err
case schema.Uint16Kind:
value, err := strconv.ParseUint(str, 10, 16)
return uint16(value), err
case schema.Uint32Kind:
value, err := strconv.ParseUint(str, 10, 32)
return uint32(value), err
case schema.Uint64Kind:
value, err := strconv.ParseUint(str, 10, 64)
return value, err
case schema.Int8Kind:
value, err := strconv.ParseInt(str, 10, 8)
return int8(value), err
case schema.Int16Kind:
value, err := strconv.ParseInt(str, 10, 16)
return int16(value), err
case schema.Int32Kind:
value, err := strconv.ParseInt(str, 10, 32)
return int32(value), err
case schema.Int64Kind:
value, err := strconv.ParseInt(str, 10, 64)
return value, err
case schema.Float32Kind:
value, err := strconv.ParseFloat(str, 32)
return float32(value), err
case schema.Float64Kind:
value, err := strconv.ParseFloat(str, 64)
return value, err
case schema.BoolKind:
value, err := strconv.ParseBool(str)
return value, err
case schema.JSONKind:
return json.RawMessage(str), nil
case schema.TimeKind:
value, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return nil, err
}
return time.Unix(0, value), nil
case schema.DurationKind:
value, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return nil, err
}
return time.Duration(value), nil
case schema.AddressKind:
return tm.options.addressCodec.StringToBytes(str)
default:
return value, nil
}
}