/
sort_iter.go
420 lines (344 loc) · 8.82 KB
/
sort_iter.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//
// Copyright (c) 2019, 2022 Oracle and/or its affiliates. All rights reserved.
//
// Licensed under the Universal Permissive License v 1.0 as shown at
// https://oss.oracle.com/licenses/upl/
//
package nosqldb
import (
"fmt"
"sort"
"strings"
"github.com/oracle/nosql-go-sdk/nosqldb/internal/proto"
"github.com/oracle/nosql-go-sdk/nosqldb/types"
)
var _ planIter = (*sortIter)(nil)
// sortSpec specifies criterias for sorting the values.
//
// The order-by clause, for each sort expression allows for an optional "sort spec",
// which specifies the relative order of NULLs (less than or greater than all other values)
// and whether the values returned by the sort expression should be sorted in ascending or descending order.
type sortSpec struct {
// isDesc specifies if the desired sorting order is in descending order.
isDesc bool
// nullsFirst specifies if NULL values should sort before all other values.
nullsFirst bool
}
func newSortSpec(r proto.Reader) (sp *sortSpec, err error) {
isDesc, err := r.ReadBoolean()
if err != nil {
return
}
nullsFirst, err := r.ReadBoolean()
if err != nil {
return
}
sp = &sortSpec{
isDesc: isDesc,
nullsFirst: nullsFirst,
}
return
}
// sortIterState represents the dynamic state for a sort iterator.
type sortIterState struct {
*iterState
results []*types.MapValue
nextResultPos int
}
func newSortIterState() *sortIterState {
state := &sortIterState{
iterState: newIterState(),
results: make([]*types.MapValue, 0, 100),
}
return state
}
func (st *sortIterState) close() (err error) {
if err = st.iterState.close(); err != nil {
return
}
st.results = nil
st.nextResultPos = 0
return
}
func (st *sortIterState) done() (err error) {
if err = st.iterState.done(); err != nil {
return
}
st.results = nil
st.nextResultPos = 0
return
}
func (st *sortIterState) reset() (err error) {
if err = st.iterState.reset(); err != nil {
return
}
st.results = st.results[:0]
st.nextResultPos = 0
return nil
}
// sortIter represents a plan iterator that sorts query results based on their
// values on a specified set of top-level fields.
//
// This is used to implement the geo_near function, which sorts results by distance.
type sortIter struct {
*planIterDelegate
// The plan iterator for input values.
input planIter
// sortFields specifies the names of top-level fields that contain the
// values on which to sort the received results.
sortFields []string
// sortSpecs represents the corresponding sorting specs of the fields
// specified in sortFields.
sortSpecs []*sortSpec
// countMemory represents whether to count memory consumption for caching results.
countMemory bool
}
func newSortIter(r proto.Reader, kind planIterKind) (iter *sortIter, err error) {
delegate, err := newPlanIterDelegate(r, sorting)
if err != nil {
return
}
input, err := deserializePlanIter(r)
if err != nil {
return
}
sortFields, err := readStringArray(r)
if err != nil {
return
}
sortSpecs, err := readSortSpecs(r)
if err != nil {
return
}
countMemory := true
if kind == sorting2 {
countMemory, err = r.ReadBoolean()
if err != nil {
return
}
}
iter = &sortIter{
planIterDelegate: delegate,
input: input,
sortFields: sortFields,
sortSpecs: sortSpecs,
countMemory: countMemory,
}
return
}
func (iter *sortIter) open(rcb *runtimeControlBlock) (err error) {
state := newSortIterState()
rcb.setState(iter.statePos, state)
return iter.input.open(rcb)
}
func (iter *sortIter) reset(rcb *runtimeControlBlock) (err error) {
if err = iter.input.reset(rcb); err != nil {
return
}
st := rcb.getState(iter.statePos)
state, ok := st.(*sortIterState)
if !ok {
return fmt.Errorf("wrong iterator state type, expect *sortIterState, got %T", st)
}
return state.reset()
}
func (iter *sortIter) close(rcb *runtimeControlBlock) (err error) {
state := rcb.getState(iter.statePos)
if state == nil {
return
}
if err = iter.input.close(rcb); err != nil {
return
}
return state.close()
}
func (iter *sortIter) next(rcb *runtimeControlBlock) (more bool, err error) {
var ok bool
st := rcb.getState(iter.statePos)
state, ok := st.(*sortIterState)
if !ok {
return false, fmt.Errorf("wrong iterator state type, expect *sortIterState, got %T", st)
}
if state.isDone() {
return false, nil
}
var v *types.MapValue
if state.isOpen() {
for {
more, err = iter.input.next(rcb)
if err != nil {
return false, err
}
if !more {
break
}
res := iter.input.getResult(rcb)
v, ok = res.(*types.MapValue)
if !ok {
return false, fmt.Errorf("the value should be a *types.MapValue, got %T", res)
}
for _, name := range iter.sortFields {
value, _ := v.Get(name)
switch value.(type) {
// ARRAY/MAP values are not supported.
case []interface{}, []types.FieldValue, map[string]interface{}, *types.MapValue:
return false, fmt.Errorf("sort expression does not return a single atomic value, "+
"error at location %s", iter.loc)
}
}
state.results = append(state.results, v)
if iter.countMemory {
sz := int64(sizeOf(v))
err = rcb.incMemoryConsumption(sz)
if err != nil {
return false, err
}
}
}
if rcb.reachedLimit {
return false, nil
}
iter.sortResults(state.results)
err = state.setState(running)
if err != nil {
return false, err
}
}
if state.nextResultPos < len(state.results) {
mv := state.results[state.nextResultPos]
convertEmptyToNull(mv)
rcb.setRegValue(iter.resultReg, mv)
state.nextResultPos++
return true, nil
}
state.done()
return false, nil
}
func (iter *sortIter) sortResults(res []*types.MapValue) {
if len(res) < 2 {
return
}
by := &resultsBySortSpec{
sortFields: iter.sortFields,
sortSpecs: iter.sortSpecs,
results: res,
}
sort.Sort(by)
}
func (iter *sortIter) getPlan() string {
return iter.planIterDelegate.getExecPlan(iter)
}
func (iter *sortIter) displayContent(sb *strings.Builder, f *planFormatter) {
iter.planIterDelegate.displayPlan(iter.input, sb, f)
f.printIndent(sb)
sb.WriteString("Sort Fields: ")
for i, fieldName := range iter.sortFields {
sb.WriteString(fieldName)
if i < len(iter.sortFields)-1 {
sb.WriteString(", ")
}
}
sb.WriteString(",\n")
}
// resultsBySortSpec is used to sort query results on the specified fields by the specified sortSpec.
//
// It implements the sort.Interface.
type resultsBySortSpec struct {
results []*types.MapValue
sortFields []string
sortSpecs []*sortSpec
}
// Len returns the number of results.
func (r *resultsBySortSpec) Len() int {
return len(r.results)
}
// Swap swaps the result with index i and j.
func (r *resultsBySortSpec) Swap(i, j int) {
r.results[i], r.results[j] = r.results[j], r.results[i]
}
// Less reports whether the result with index i should sort before the one with index j.
func (r *resultsBySortSpec) Less(i, j int) bool {
var isLess bool
var k int
var fieldName string
for k, fieldName = range r.sortFields {
v1, ok := r.results[i].Get(fieldName)
if !ok {
continue
}
v2, ok := r.results[j].Get(fieldName)
if !ok {
continue
}
sortSpec := r.sortSpecs[k]
// The ordering of special values: EmptyValue, JSONNullValue, NullValue:
//
// If nullsFirst is specified and the direction is ASC/DESC, the special
// values are considered less/greater than all non-special values.
//
// The relative ordering among the 3 special values themselves is fixed:
// if the direction is ASC, the ordering is EmptyValue < JSONNullValue < NullValue
// otherwise the ordering is reversed.
if v1 == types.NullValueInstance {
if v2 == types.NullValueInstance {
continue
}
if v2 == types.EmptyValueInstance || v2 == types.JSONNullValueInstance {
if sortSpec.isDesc {
return true
}
return false
}
return sortSpec.nullsFirst
}
if v2 == types.NullValueInstance {
if v1 == types.EmptyValueInstance || v1 == types.JSONNullValueInstance {
if sortSpec.isDesc {
return false
}
return true
}
return !sortSpec.nullsFirst
}
if v1 == types.EmptyValueInstance {
if v2 == types.EmptyValueInstance {
continue
}
if v2 == types.JSONNullValueInstance {
if sortSpec.isDesc {
return false
}
return true
}
return sortSpec.nullsFirst
}
if v2 == types.EmptyValueInstance {
if v1 == types.JSONNullValueInstance {
if sortSpec.isDesc {
return true
}
return false
}
return !sortSpec.nullsFirst
}
if v1 == types.JSONNullValueInstance {
if v2 == types.JSONNullValueInstance {
continue
}
return sortSpec.nullsFirst
}
if v2 == types.JSONNullValueInstance {
return !sortSpec.nullsFirst
}
compareRes, _ := compareAtomicValues(nil, true, v1, v2)
if compareRes == 0 {
continue
}
isLess = compareRes == -1
if sortSpec.isDesc {
return !isLess
}
return isLess
}
return false
}