Debian Codegraph @

src/main/org/h2/expression/analysis/DataAnalysisOperation.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.expression.analysis;
7
8 import java.util.ArrayList;
9 import java.util.HashMap;
10
11 import org.h2.api.ErrorCode;
12 import org.h2.command.query.QueryOrderBy;
13 import org.h2.command.query.Select;
14 import org.h2.command.query.SelectGroups;
15 import org.h2.engine.SessionLocal;
16 import org.h2.expression.Expression;
17 import org.h2.expression.ExpressionVisitor;
18 import org.h2.message.DbException;
19 import org.h2.result.SortOrder;
20 import org.h2.table.ColumnResolver;
21 import org.h2.table.TableFilter;
22 import org.h2.value.Value;
23 import org.h2.value.ValueInteger;
24
25 /**
26 * A base class for data analysis operations such as aggregates and window
27 * functions.
28 */
29 public abstract class DataAnalysisOperation extends Expression {
30
31 /**
32 * Reset stage. Used to reset internal data to its initial state.
33 */
34 public static final int STAGE_RESET = 0;
35
36 /**
37 * Group stage, used for explicit or implicit GROUP BY operation.
38 */
39 public static final int STAGE_GROUP = 1;
40
41 /**
42 * Window processing stage.
43 */
44 public static final int STAGE_WINDOW = 2;
45
46 /**
47 * SELECT
48 */
49 protected final Select select;
50
51 /**
52 * OVER clause
53 */
54 protected Window over;
55
56 /**
57 * Sort order for OVER
58 */
59 protected SortOrder overOrderBySort;
60
61 private int numFrameExpressions;
62
63 private int lastGroupRowId;
64
65 /**
66 * Create sort order.
67 *
68 * @param session
69 * database session
70 * @param orderBy
71 * array of order by expressions
72 * @param offset
73 * index offset
74 * @return the SortOrder
75 */
76 protected static SortOrder createOrder(SessionLocal session, ArrayList<QueryOrderBy> orderBy, int offset) {
77 int size = orderBy.size();
78 int[] index = new int[size];
79 int[] sortType = new int[size];
80 for (int i = 0; i < size; i++) {
81 QueryOrderBy o = orderBy.get(i);
82 index[i] = i + offset;
83 sortType[i] = o.sortType;
84 }
85 return new SortOrder(session, index, sortType, null);
86 }
87
88 protected DataAnalysisOperation(Select select) {
89 this.select = select;
90 }
91
92 /**
93 * Returns the OVER condition.
94 *
95 * @return the OVER condition
96 */
97 public Window getOverCondition() {
98 return over;
99 }
100
101 /**
102 * Sets the OVER condition.
103 *
104 * @param over
105 * OVER condition
106 */
107 public void setOverCondition(Window over) {
108 this.over = over;
109 }
110
111 /**
112 * Checks whether this expression is an aggregate function.
113 *
114 * @return true if this is an aggregate function (including aggregates with
115 * OVER clause), false if this is a window function
116 */
117 public abstract boolean isAggregate();
118
119 /**
120 * Returns the sort order for OVER clause.
121 *
122 * @return the sort order for OVER clause
123 */
124 protected SortOrder getOverOrderBySort() {
125 return overOrderBySort;
126 }
127
128 @Override
129 public final void mapColumns(ColumnResolver resolver, int level, int state) {
130 if (over != null) {
131 if (state != MAP_INITIAL) {
132 throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, getTraceSQL());
133 }
134 state = MAP_IN_WINDOW;
135 } else {
136 if (state == MAP_IN_AGGREGATE) {
137 throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, getTraceSQL());
138 }
139 state = MAP_IN_AGGREGATE;
140 }
141 mapColumnsAnalysis(resolver, level, state);
142 }
143
144 /**
145 * Map the columns of the resolver to expression columns.
146 *
147 * @param resolver
148 * the column resolver
149 * @param level
150 * the subquery nesting level
151 * @param innerState
152 * one of the Expression MAP_IN_* values
153 */
154 protected void mapColumnsAnalysis(ColumnResolver resolver, int level, int innerState) {
155 if (over != null) {
156 over.mapColumns(resolver, level);
157 }
158 }
159
160 @Override
161 public Expression optimize(SessionLocal session) {
162 if (over != null) {
163 over.optimize(session);
164 ArrayList<QueryOrderBy> orderBy = over.getOrderBy();
165 if (orderBy != null) {
166 overOrderBySort = createOrder(session, orderBy, getNumExpressions());
167 } else if (!isAggregate()) {
168 overOrderBySort = new SortOrder(session, new int[getNumExpressions()]);
169 }
170 WindowFrame frame = over.getWindowFrame();
171 if (frame != null) {
172 int index = getNumExpressions();
173 int orderBySize = 0;
174 if (orderBy != null) {
175 orderBySize = orderBy.size();
176 index += orderBySize;
177 }
178 int n = 0;
179 WindowFrameBound bound = frame.getStarting();
180 if (bound.isParameterized()) {
181 checkOrderBy(frame.getUnits(), orderBySize);
182 if (bound.isVariable()) {
183 bound.setExpressionIndex(index);
184 n++;
185 }
186 }
187 bound = frame.getFollowing();
188 if (bound != null && bound.isParameterized()) {
189 checkOrderBy(frame.getUnits(), orderBySize);
190 if (bound.isVariable()) {
191 bound.setExpressionIndex(index + n);
192 n++;
193 }
194 }
195 numFrameExpressions = n;
196 }
197 }
198 return this;
199 }
200
201 private void checkOrderBy(WindowFrameUnits units, int orderBySize) {
202 switch (units) {
203 case RANGE:
204 if (orderBySize != 1) {
205 String sql = getTraceSQL();
206 throw DbException.getSyntaxError(sql, sql.length() - 1,
207 "exactly one sort key is required for RANGE units");
208 }
209 break;
210 case GROUPS:
211 if (orderBySize < 1) {
212 String sql = getTraceSQL();
213 throw DbException.getSyntaxError(sql, sql.length() - 1,
214 "a sort key is required for GROUPS units");
215 }
216 break;
217 default:
218 }
219 }
220
221 @Override
222 public void setEvaluatable(TableFilter tableFilter, boolean b) {
223 if (over != null) {
224 over.setEvaluatable(tableFilter, b);
225 }
226 }
227
228 @Override
229 public final void updateAggregate(SessionLocal session, int stage) {
230 if (stage == STAGE_RESET) {
231 updateGroupAggregates(session, STAGE_RESET);
232 lastGroupRowId = 0;
233 return;
234 }
235 boolean window = stage == STAGE_WINDOW;
236 if (window != (over != null)) {
237 if (!window && select.isWindowQuery()) {
238 updateGroupAggregates(session, stage);
239 }
240 return;
241 }
242 SelectGroups groupData = select.getGroupDataIfCurrent(window);
243 if (groupData == null) {
244 // this is a different level (the enclosing query)
245 return;
246 }
247
248 int groupRowId = groupData.getCurrentGroupRowId();
249 if (lastGroupRowId == groupRowId) {
250 // already visited
251 return;
252 }
253 lastGroupRowId = groupRowId;
254
255 if (over != null) {
256 if (!select.isGroupQuery()) {
257 over.updateAggregate(session, stage);
258 }
259 }
260 updateAggregate(session, groupData, groupRowId);
261 }
262
263 /**
264 * Update a row of an aggregate.
265 *
266 * @param session
267 * the database session
268 * @param groupData
269 * data for the aggregate group
270 * @param groupRowId
271 * row id of group
272 */
273 protected abstract void updateAggregate(SessionLocal session, SelectGroups groupData, int groupRowId);
274
275 /**
276 * Invoked when processing group stage of grouped window queries to update
277 * arguments of this aggregate.
278 *
279 * @param session
280 * the session
281 * @param stage
282 * select stage
283 */
284 protected void updateGroupAggregates(SessionLocal session, int stage) {
285 if (over != null) {
286 over.updateAggregate(session, stage);
287 }
288 }
289
290 /**
291 * Returns the number of expressions, excluding OVER clause.
292 *
293 * @return the number of expressions
294 */
295 protected abstract int getNumExpressions();
296
297 /**
298 * Returns the number of window frame expressions.
299 *
300 * @return the number of window frame expressions
301 */
302 private int getNumFrameExpressions() {
303 return numFrameExpressions;
304 }
305
306 /**
307 * Stores current values of expressions into the specified array.
308 *
309 * @param session
310 * the session
311 * @param array
312 * array to store values of expressions
313 */
314 protected abstract void rememberExpressions(SessionLocal session, Value[] array);
315
316 /**
317 * Get the aggregate data for a window clause.
318 *
319 * @param session
320 * database session
321 * @param groupData
322 * aggregate group data
323 * @param forOrderBy
324 * true if this is for ORDER BY
325 * @return the aggregate data object, specific to each kind of aggregate.
326 */
327 protected Object getWindowData(SessionLocal session, SelectGroups groupData, boolean forOrderBy) {
328 Object data;
329 Value key = over.getCurrentKey(session);
330 PartitionData partition = groupData.getWindowExprData(this, key);
331 if (partition == null) {
332 data = forOrderBy ? new ArrayList<>() : createAggregateData();
333 groupData.setWindowExprData(this, key, new PartitionData(data));
334 } else {
335 data = partition.getData();
336 }
337 return data;
338 }
339
340 /**
341 * Get the aggregate group data object from the collector object.
342 *
343 * @param groupData
344 * the collector object
345 * @param ifExists
346 * if true, return null if object not found, if false, return new
347 * object if nothing found
348 * @return group data object
349 */
350 protected Object getGroupData(SelectGroups groupData, boolean ifExists) {
351 Object data;
352 data = groupData.getCurrentGroupExprData(this);
353 if (data == null) {
354 if (ifExists) {
355 return null;
356 }
357 data = createAggregateData();
358 groupData.setCurrentGroupExprData(this, data);
359 }
360 return data;
361 }
362
363 /**
364 * Create aggregate data object specific to the subclass.
365 *
366 * @return aggregate-specific data object.
367 */
368 protected abstract Object createAggregateData();
369
370 @Override
371 public boolean isEverything(ExpressionVisitor visitor) {
372 if (over == null) {
373 return true;
374 }
375 switch (visitor.getType()) {
376 case ExpressionVisitor.QUERY_COMPARABLE:
377 case ExpressionVisitor.OPTIMIZABLE_AGGREGATE:
378 case ExpressionVisitor.DETERMINISTIC:
379 case ExpressionVisitor.INDEPENDENT:
380 case ExpressionVisitor.DECREMENT_QUERY_LEVEL:
381 return false;
382 default:
383 return true;
384 }
385 }
386
387 @Override
388 public Value getValue(SessionLocal session) {
389 SelectGroups groupData = select.getGroupDataIfCurrent(over != null);
390 if (groupData == null) {
391 throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, getTraceSQL());
392 }
393 return over == null ? getAggregatedValue(session, getGroupData(groupData, true))
394 : getWindowResult(session, groupData);
395 }
396
397 /**
398 * Returns result of this window function or window aggregate. This method
399 * is not used for plain aggregates.
400 *
401 * @param session
402 * the session
403 * @param groupData
404 * the group data
405 * @return result of this function
406 */
407 private Value getWindowResult(SessionLocal session, SelectGroups groupData) {
408 PartitionData partition;
409 Object data;
410 boolean isOrdered = over.isOrdered();
411 Value key = over.getCurrentKey(session);
412 partition = groupData.getWindowExprData(this, key);
413 if (partition == null) {
414 // Window aggregates with FILTER clause may have no collected values
415 data = isOrdered ? new ArrayList<>() : createAggregateData();
416 partition = new PartitionData(data);
417 groupData.setWindowExprData(this, key, partition);
418 } else {
419 data = partition.getData();
420 }
421 if (isOrdered || !isAggregate()) {
422 Value result = getOrderedResult(session, groupData, partition, data);
423 if (result == null) {
424 return getAggregatedValue(session, null);
425 }
426 return result;
427 }
428 // Window aggregate without ORDER BY clause in window specification
429 Value result = partition.getResult();
430 if (result == null) {
431 result = getAggregatedValue(session, data);
432 partition.setResult(result);
433 }
434 return result;
435 }
436
437 /***
438 * Returns aggregated value.
439 *
440 * @param session
441 * the session
442 * @param aggregateData
443 * the aggregate data
444 * @return aggregated value.
445 */
446 protected abstract Value getAggregatedValue(SessionLocal session, Object aggregateData);
447
448 /**
449 * Update a row of an ordered aggregate.
450 *
451 * @param session
452 * the database session
453 * @param groupData
454 * data for the aggregate group
455 * @param groupRowId
456 * row id of group
457 * @param orderBy
458 * list of order by expressions
459 */
460 protected void updateOrderedAggregate(SessionLocal session, SelectGroups groupData, int groupRowId,
461 ArrayList<QueryOrderBy> orderBy) {
462 int ne = getNumExpressions();
463 int size = orderBy != null ? orderBy.size() : 0;
464 int frameSize = getNumFrameExpressions();
465 Value[] array = new Value[ne + size + frameSize + 1];
466 rememberExpressions(session, array);
467 for (int i = 0; i < size; i++) {
468 @SuppressWarnings("null")
469 QueryOrderBy o = orderBy.get(i);
470 array[ne++] = o.expression.getValue(session);
471 }
472 if (frameSize > 0) {
473 WindowFrame frame = over.getWindowFrame();
474 WindowFrameBound bound = frame.getStarting();
475 if (bound.isVariable()) {
476 array[ne++] = bound.getValue().getValue(session);
477 }
478 bound = frame.getFollowing();
479 if (bound != null && bound.isVariable()) {
480 array[ne++] = bound.getValue().getValue(session);
481 }
482 }
483 array[ne] = ValueInteger.get(groupRowId);
484 @SuppressWarnings("unchecked")
485 ArrayList<Value[]> data = (ArrayList<Value[]>) getWindowData(session, groupData, true);
486 data.add(array);
487 }
488
489 private Value getOrderedResult(SessionLocal session, SelectGroups groupData, PartitionData partition, //
490 Object data) {
491 HashMap<Integer, Value> result = partition.getOrderedResult();
492 if (result == null) {
493 result = new HashMap<>();
494 @SuppressWarnings("unchecked")
495 ArrayList<Value[]> orderedData = (ArrayList<Value[]>) data;
496 int rowIdColumn = getNumExpressions();
497 ArrayList<QueryOrderBy> orderBy = over.getOrderBy();
498 if (orderBy != null) {
499 rowIdColumn += orderBy.size();
500 orderedData.sort(overOrderBySort);
501 }
502 rowIdColumn += getNumFrameExpressions();
503 getOrderedResultLoop(session, result, orderedData, rowIdColumn);
504 partition.setOrderedResult(result);
505 }
506 return result.get(groupData.getCurrentGroupRowId());
507 }
508
509 /**
510 * Returns result of this window function or window aggregate. This method
511 * may not be called on window aggregate without window order clause.
512 *
513 * @param session
514 * the session
515 * @param result
516 * the map to append result to
517 * @param ordered
518 * ordered data
519 * @param rowIdColumn
520 * the index of row id value
521 */
522 protected abstract void getOrderedResultLoop(SessionLocal session, HashMap<Integer, Value> result,
523 ArrayList<Value[]> ordered, int rowIdColumn);
524
525 /**
526 * Used to create SQL for the OVER and FILTER clauses.
527 *
528 * @param builder
529 * string builder
530 * @param sqlFlags
531 * formatting flags
532 * @param forceOrderBy
533 * whether synthetic ORDER BY clause should be generated when it
534 * is missing
535 * @return the builder object
536 */
537 protected StringBuilder appendTailConditions(StringBuilder builder, int sqlFlags, boolean forceOrderBy) {
538 if (over != null) {
539 builder.append(' ');
540 over.getSQL(builder, sqlFlags, forceOrderBy);
541 }
542 return builder;
543 }
544
545 }