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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.command.dml;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.analysis.DataAnalysisOperation;
import org.h2.expression.analysis.PartitionData;
import org.h2.util.ValueHashMap;
import org.h2.value.Value;
import org.h2.value.ValueArray;
/**
* Grouped data for aggregates.
*
* <p>
* Call sequence:
* </p>
* <ul>
* <li>{@link #reset()}.</li>
* <li>For each source row {@link #nextSource()} should be invoked.</li>
* <li>{@link #done()}.</li>
* <li>{@link #next()} is invoked inside a loop until it returns null.</li>
* </ul>
* <p>
* Call sequence for lazy group sorted result:
* </p>
* <ul>
* <li>{@link #resetLazy()} (not required before the first execution).</li>
* <li>For each source group {@link #nextLazyGroup()} should be invoked.</li>
* <li>For each source row {@link #nextLazyRow()} should be invoked. Each group
* can have one or more rows.</li>
* </ul>
*/
public abstract class SelectGroups {
private static final class Grouped extends SelectGroups {
private final int[] groupIndex;
/**
* Map of group-by key to group-by expression data e.g. AggregateData
*/
private HashMap<ValueArray, Object[]> groupByData;
/**
* Key into groupByData that produces currentGroupByExprData. Not used
* in lazy mode.
*/
private ValueArray currentGroupsKey;
/**
* Cursor for {@link #next()} method.
*/
private Iterator<Entry<ValueArray, Object[]>> cursor;
Grouped(Session session, ArrayList<Expression> expressions, int[] groupIndex) {
super(session, expressions);
this.groupIndex = groupIndex;
}
@Override
public void reset() {
super.reset();
groupByData = new HashMap<>();
currentGroupsKey = null;
cursor = null;
}
@Override
public void nextSource() {
if (groupIndex == null) {
currentGroupsKey = ValueArray.getEmpty();
} else {
Value[] keyValues = new Value[groupIndex.length];
// update group
for (int i = 0; i < groupIndex.length; i++) {
int idx = groupIndex[i];
Expression expr = expressions.get(idx);
keyValues[i] = expr.getValue(session);
}
currentGroupsKey = ValueArray.get(keyValues);
}
Object[] values = groupByData.get(currentGroupsKey);
if (values == null) {
values = createRow();
groupByData.put(currentGroupsKey, values);
}
currentGroupByExprData = values;
currentGroupRowId++;
}
@Override
void updateCurrentGroupExprData() {
// this can be null in lazy mode
if (currentGroupsKey != null) {
// since we changed the size of the array, update the object in
// the groups map
groupByData.put(currentGroupsKey, currentGroupByExprData);
}
}
@Override
public void done() {
super.done();
if (groupIndex == null && groupByData.size() == 0) {
groupByData.put(ValueArray.getEmpty(), createRow());
}
cursor = groupByData.entrySet().iterator();
}
@Override
public ValueArray next() {
if (cursor.hasNext()) {
Map.Entry<ValueArray, Object[]> entry = cursor.next();
currentGroupByExprData = entry.getValue();
currentGroupRowId++;
return entry.getKey();
}
return null;
}
@Override
public void remove() {
cursor.remove();
currentGroupByExprData = null;
currentGroupRowId--;
}
@Override
public void resetLazy() {
super.resetLazy();
currentGroupsKey = null;
}
}
private static final class Plain extends SelectGroups {
private ArrayList<Object[]> rows;
/**
* Cursor for {@link #next()} method.
*/
private Iterator<Object[]> cursor;
Plain(Session session, ArrayList<Expression> expressions) {
super(session, expressions);
}
@Override
public void reset() {
super.reset();
rows = new ArrayList<>();
cursor = null;
}
@Override
public void nextSource() {
Object[] values = createRow();
rows.add(values);
currentGroupByExprData = values;
currentGroupRowId++;
}
@Override
void updateCurrentGroupExprData() {
rows.set(rows.size() - 1, currentGroupByExprData);
}
@Override
public void done() {
super.done();
cursor = rows.iterator();
}
@Override
public ValueArray next() {
if (cursor.hasNext()) {
currentGroupByExprData = cursor.next();
currentGroupRowId++;
return ValueArray.getEmpty();
}
return null;
}
}
/**
* The session.
*/
final Session session;
/**
* The query's column list, including invisible expressions such as order by expressions.
*/
final ArrayList<Expression> expressions;
/**
* The array of current group-by expression data e.g. AggregateData.
*/
Object[] currentGroupByExprData;
/**
* Maps an expression object to an index, to use in accessing the Object[]
* pointed to by groupByData.
*/
private final HashMap<Expression, Integer> exprToIndexInGroupByData = new HashMap<>();
/**
* Maps an window expression object to its data.
*/
private final HashMap<DataAnalysisOperation, PartitionData> windowData = new HashMap<>();
/**
* Maps an partitioned window expression object to its data.
*/
private final HashMap<DataAnalysisOperation, ValueHashMap<PartitionData>> windowPartitionData = new HashMap<>();
/**
* The id of the current group.
*/
int currentGroupRowId;
/**
* Creates new instance of grouped data.
*
* @param session
* the session
* @param expressions
* the expressions
* @param isGroupQuery
* is this query is a group query
* @param groupIndex
* the indexes of group expressions, or null
* @return new instance of the grouped data.
*/
public static SelectGroups getInstance(Session session, ArrayList<Expression> expressions, boolean isGroupQuery,
int[] groupIndex) {
return isGroupQuery ? new Grouped(session, expressions, groupIndex) : new Plain(session, expressions);
}
SelectGroups(Session session, ArrayList<Expression> expressions) {
this.session = session;
this.expressions = expressions;
}
/**
* Is there currently a group-by active.
*
* @return {@code true} if there is currently a group-by active,
* otherwise returns {@code false}.
*/
public boolean isCurrentGroup() {
return currentGroupByExprData != null;
}
/**
* Get the group-by data for the current group and the passed in expression.
*
* @param expr
* expression
* @return expression data or null
*/
public final Object getCurrentGroupExprData(Expression expr) {
Integer index = exprToIndexInGroupByData.get(expr);
if (index == null) {
return null;
}
return currentGroupByExprData[index];
}
/**
* Set the group-by data for the current group and the passed in expression.
*
* @param expr
* expression
* @param obj
* expression data to set
*/
public final void setCurrentGroupExprData(Expression expr, Object obj) {
Integer index = exprToIndexInGroupByData.get(expr);
if (index != null) {
assert currentGroupByExprData[index] == null;
currentGroupByExprData[index] = obj;
return;
}
index = exprToIndexInGroupByData.size();
exprToIndexInGroupByData.put(expr, index);
if (index >= currentGroupByExprData.length) {
currentGroupByExprData = Arrays.copyOf(currentGroupByExprData, currentGroupByExprData.length * 2);
updateCurrentGroupExprData();
}
currentGroupByExprData[index] = obj;
}
/**
* Creates new object arrays to holds group-by data.
*
* @return new object array to holds group-by data.
*/
final Object[] createRow() {
return new Object[Math.max(exprToIndexInGroupByData.size(), expressions.size())];
}
/**
* Get the window data for the specified expression.
*
* @param expr
* expression
* @param partitionKey
* a key of partition
* @return expression data or null
*/
public final PartitionData getWindowExprData(DataAnalysisOperation expr, Value partitionKey) {
if (partitionKey == null) {
return windowData.get(expr);
} else {
ValueHashMap<PartitionData> map = windowPartitionData.get(expr);
return map != null ? map.get(partitionKey) : null;
}
}
/**
* Set the window data for the specified expression.
*
* @param expr
* expression
* @param partitionKey
* a key of partition
* @param obj
* window expression data to set
*/
public final void setWindowExprData(DataAnalysisOperation expr, Value partitionKey, PartitionData obj) {
if (partitionKey == null) {
Object old = windowData.put(expr, obj);
assert old == null;
} else {
ValueHashMap<PartitionData> map = windowPartitionData.get(expr);
if (map == null) {
map = new ValueHashMap<>();
windowPartitionData.put(expr, map);
}
map.put(partitionKey, obj);
}
}
/**
* Update group-by data specified by implementation.
*/
abstract void updateCurrentGroupExprData();
/**
* Returns identity of the current row. Used by aggregates to check whether
* they already processed this row or not.
*
* @return identity of the current row
*/
public int getCurrentGroupRowId() {
return currentGroupRowId;
}
/**
* Resets this group data for reuse.
*/
public void reset() {
currentGroupByExprData = null;
exprToIndexInGroupByData.clear();
windowData.clear();
windowPartitionData.clear();
currentGroupRowId = 0;
}
/**
* Invoked for each source row to evaluate group key and setup all necessary
* data for aggregates.
*/
public abstract void nextSource();
/**
* Invoked after all source rows are evaluated.
*/
public void done() {
currentGroupRowId = 0;
}
/**
* Returns the key of the next group.
*
* @return the key of the next group, or null
*/
public abstract ValueArray next();
/**
* Removes the data for the current key.
*
* @see #next()
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Resets this group data for reuse in lazy mode.
*/
public void resetLazy() {
currentGroupByExprData = null;
currentGroupRowId = 0;
}
/**
* Moves group data to the next group in lazy mode.
*/
public void nextLazyGroup() {
currentGroupByExprData = new Object[Math.max(exprToIndexInGroupByData.size(), expressions.size())];
}
/**
* Moves group data to the next row in lazy mode.
*/
public void nextLazyRow() {
currentGroupRowId++;
}
/**
* @return Expressions.
*/
public ArrayList<Expression> expressions() {
return expressions;
}
}