Debian Codegraph @

src/main/org/h2/expression/analysis/WindowFunction.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 import java.util.Iterator;
11
12 import org.h2.command.query.Select;
13 import org.h2.command.query.SelectGroups;
14 import org.h2.engine.SessionLocal;
15 import org.h2.expression.Expression;
16 import org.h2.expression.ValueExpression;
17 import org.h2.message.DbException;
18 import org.h2.table.ColumnResolver;
19 import org.h2.table.TableFilter;
20 import org.h2.value.TypeInfo;
21 import org.h2.value.Value;
22 import org.h2.value.ValueBigint;
23 import org.h2.value.ValueDouble;
24 import org.h2.value.ValueNull;
25
26 /**
27 * A window function.
28 */
29 public class WindowFunction extends DataAnalysisOperation {
30
31 private final WindowFunctionType type;
32
33 private final Expression[] args;
34
35 private boolean fromLast;
36
37 private boolean ignoreNulls;
38
39 /**
40 * Returns minimal number of arguments for the specified type.
41 *
42 * @param type
43 * the type of a window function
44 * @return minimal number of arguments
45 */
46 public static int getMinArgumentCount(WindowFunctionType type) {
47 switch (type) {
48 case NTILE:
49 case LEAD:
50 case LAG:
51 case FIRST_VALUE:
52 case LAST_VALUE:
53 case RATIO_TO_REPORT:
54 return 1;
55 case NTH_VALUE:
56 return 2;
57 default:
58 return 0;
59 }
60 }
61
62 /**
63 * Returns maximal number of arguments for the specified type.
64 *
65 * @param type
66 * the type of a window function
67 * @return maximal number of arguments
68 */
69 public static int getMaxArgumentCount(WindowFunctionType type) {
70 switch (type) {
71 case NTILE:
72 case FIRST_VALUE:
73 case LAST_VALUE:
74 case RATIO_TO_REPORT:
75 return 1;
76 case LEAD:
77 case LAG:
78 return 3;
79 case NTH_VALUE:
80 return 2;
81 default:
82 return 0;
83 }
84 }
85
86 private static Value getNthValue(Iterator<Value[]> iterator, int number, boolean ignoreNulls) {
87 Value v = ValueNull.INSTANCE;
88 int cnt = 0;
89 while (iterator.hasNext()) {
90 Value t = iterator.next()[0];
91 if (!ignoreNulls || t != ValueNull.INSTANCE) {
92 if (cnt++ == number) {
93 v = t;
94 break;
95 }
96 }
97 }
98 return v;
99 }
100
101 /**
102 * Creates new instance of a window function.
103 *
104 * @param type
105 * the type
106 * @param select
107 * the select statement
108 * @param args
109 * arguments, or null
110 */
111 public WindowFunction(WindowFunctionType type, Select select, Expression[] args) {
112 super(select);
113 this.type = type;
114 this.args = args;
115 }
116
117 /**
118 * Returns the type of this function.
119 *
120 * @return the type of this function
121 */
122 public WindowFunctionType getFunctionType() {
123 return type;
124 }
125
126 /**
127 * Sets FROM FIRST or FROM LAST clause value.
128 *
129 * @param fromLast
130 * whether FROM LAST clause was specified.
131 */
132 public void setFromLast(boolean fromLast) {
133 this.fromLast = fromLast;
134 }
135
136 /**
137 * Sets RESPECT NULLS or IGNORE NULLS clause value.
138 *
139 * @param ignoreNulls
140 * whether IGNORE NULLS clause was specified
141 */
142 public void setIgnoreNulls(boolean ignoreNulls) {
143 this.ignoreNulls = ignoreNulls;
144 }
145
146 @Override
147 public boolean isAggregate() {
148 return false;
149 }
150
151 @Override
152 protected void updateAggregate(SessionLocal session, SelectGroups groupData, int groupRowId) {
153 updateOrderedAggregate(session, groupData, groupRowId, over.getOrderBy());
154 }
155
156 @Override
157 protected void updateGroupAggregates(SessionLocal session, int stage) {
158 super.updateGroupAggregates(session, stage);
159 if (args != null) {
160 for (Expression expr : args) {
161 expr.updateAggregate(session, stage);
162 }
163 }
164 }
165
166 @Override
167 protected int getNumExpressions() {
168 return args != null ? args.length : 0;
169 }
170
171 @Override
172 protected void rememberExpressions(SessionLocal session, Value[] array) {
173 if (args != null) {
174 for (int i = 0, cnt = args.length; i < cnt; i++) {
175 array[i] = args[i].getValue(session);
176 }
177 }
178 }
179
180 @Override
181 protected Object createAggregateData() {
182 throw DbException.getUnsupportedException("Window function");
183 }
184
185 @Override
186 protected void getOrderedResultLoop(SessionLocal session, HashMap<Integer, Value> result,
187 ArrayList<Value[]> ordered, int rowIdColumn) {
188 switch (type) {
189 case ROW_NUMBER:
190 for (int i = 0, size = ordered.size(); i < size;) {
191 result.put(ordered.get(i)[rowIdColumn].getInt(), ValueBigint.get(++i));
192 }
193 break;
194 case RANK:
195 case DENSE_RANK:
196 case PERCENT_RANK:
197 getRank(result, ordered, rowIdColumn);
198 break;
199 case CUME_DIST:
200 getCumeDist(result, ordered, rowIdColumn);
201 break;
202 case NTILE:
203 getNtile(result, ordered, rowIdColumn);
204 break;
205 case LEAD:
206 case LAG:
207 getLeadLag(result, ordered, rowIdColumn, session);
208 break;
209 case FIRST_VALUE:
210 case LAST_VALUE:
211 case NTH_VALUE:
212 getNth(session, result, ordered, rowIdColumn);
213 break;
214 case RATIO_TO_REPORT:
215 getRatioToReport(result, ordered, rowIdColumn);
216 break;
217 default:
218 throw DbException.getInternalError("type=" + type);
219 }
220 }
221
222 private void getRank(HashMap<Integer, Value> result, ArrayList<Value[]> ordered, int rowIdColumn) {
223 int size = ordered.size();
224 int number = 0;
225 for (int i = 0; i < size; i++) {
226 Value[] row = ordered.get(i);
227 if (i == 0) {
228 number = 1;
229 } else if (getOverOrderBySort().compare(ordered.get(i - 1), row) != 0) {
230 if (type == WindowFunctionType.DENSE_RANK) {
231 number++;
232 } else {
233 number = i + 1;
234 }
235 }
236 Value v;
237 if (type == WindowFunctionType.PERCENT_RANK) {
238 int nm = number - 1;
239 v = nm == 0 ? ValueDouble.ZERO : ValueDouble.get((double) nm / (size - 1));
240 } else {
241 v = ValueBigint.get(number);
242 }
243 result.put(row[rowIdColumn].getInt(), v);
244 }
245 }
246
247 private void getCumeDist(HashMap<Integer, Value> result, ArrayList<Value[]> orderedData, int rowIdColumn) {
248 int size = orderedData.size();
249 for (int start = 0; start < size;) {
250 Value[] array = orderedData.get(start);
251 int end = start + 1;
252 while (end < size && overOrderBySort.compare(array, orderedData.get(end)) == 0) {
253 end++;
254 }
255 ValueDouble v = ValueDouble.get((double) end / size);
256 for (int i = start; i < end; i++) {
257 int rowId = orderedData.get(i)[rowIdColumn].getInt();
258 result.put(rowId, v);
259 }
260 start = end;
261 }
262 }
263
264 private static void getNtile(HashMap<Integer, Value> result, ArrayList<Value[]> orderedData, int rowIdColumn) {
265 int size = orderedData.size();
266 for (int i = 0; i < size; i++) {
267 Value[] array = orderedData.get(i);
268 long buckets = array[0].getLong();
269 if (buckets <= 0) {
270 throw DbException.getInvalidValueException("number of tiles", buckets);
271 }
272 long perTile = size / buckets;
273 long numLarger = size - perTile * buckets;
274 long largerGroup = numLarger * (perTile + 1);
275 long v;
276 if (i >= largerGroup) {
277 v = (i - largerGroup) / perTile + numLarger + 1;
278 } else {
279 v = i / (perTile + 1) + 1;
280 }
281 result.put(orderedData.get(i)[rowIdColumn].getInt(), ValueBigint.get(v));
282 }
283 }
284
285 private void getLeadLag(HashMap<Integer, Value> result, ArrayList<Value[]> ordered, int rowIdColumn,
286 SessionLocal session) {
287 int size = ordered.size();
288 int numExpressions = getNumExpressions();
289 TypeInfo dataType = args[0].getType();
290 for (int i = 0; i < size; i++) {
291 Value[] row = ordered.get(i);
292 int rowId = row[rowIdColumn].getInt();
293 int n;
294 if (numExpressions >= 2) {
295 n = row[1].getInt();
296 // 0 is valid here
297 if (n < 0) {
298 throw DbException.getInvalidValueException("nth row", n);
299 }
300 } else {
301 n = 1;
302 }
303 Value v = null;
304 if (n == 0) {
305 v = ordered.get(i)[0];
306 } else if (type == WindowFunctionType.LEAD) {
307 if (ignoreNulls) {
308 for (int j = i + 1; n > 0 && j < size; j++) {
309 v = ordered.get(j)[0];
310 if (v != ValueNull.INSTANCE) {
311 n--;
312 }
313 }
314 if (n > 0) {
315 v = null;
316 }
317 } else {
318 if (n <= size - i - 1) {
319 v = ordered.get(i + n)[0];
320 }
321 }
322 } else /* LAG */ {
323 if (ignoreNulls) {
324 for (int j = i - 1; n > 0 && j >= 0; j--) {
325 v = ordered.get(j)[0];
326 if (v != ValueNull.INSTANCE) {
327 n--;
328 }
329 }
330 if (n > 0) {
331 v = null;
332 }
333 } else {
334 if (n <= i) {
335 v = ordered.get(i - n)[0];
336 }
337 }
338 }
339 if (v == null) {
340 if (numExpressions >= 3) {
341 v = row[2].convertTo(dataType, session);
342 } else {
343 v = ValueNull.INSTANCE;
344 }
345 }
346 result.put(rowId, v);
347 }
348 }
349
350 private void getNth(SessionLocal session, HashMap<Integer, Value> result, ArrayList<Value[]> ordered,
351 int rowIdColumn) {
352 int size = ordered.size();
353 for (int i = 0; i < size; i++) {
354 Value[] row = ordered.get(i);
355 int rowId = row[rowIdColumn].getInt();
356 Value v;
357 switch (type) {
358 case FIRST_VALUE:
359 v = getNthValue(WindowFrame.iterator(over, session, ordered, getOverOrderBySort(), i, false), 0,
360 ignoreNulls);
361 break;
362 case LAST_VALUE:
363 v = getNthValue(WindowFrame.iterator(over, session, ordered, getOverOrderBySort(), i, true), 0,
364 ignoreNulls);
365 break;
366 case NTH_VALUE: {
367 int n = row[1].getInt();
368 if (n <= 0) {
369 throw DbException.getInvalidValueException("nth row", n);
370 }
371 n--;
372 Iterator<Value[]> iter = WindowFrame.iterator(over, session, ordered, getOverOrderBySort(), i,
373 fromLast);
374 v = getNthValue(iter, n, ignoreNulls);
375 break;
376 }
377 default:
378 throw DbException.getInternalError("type=" + type);
379 }
380 result.put(rowId, v);
381 }
382 }
383
384 private static void getRatioToReport(HashMap<Integer, Value> result, ArrayList<Value[]> ordered, int rowIdColumn) {
385 int size = ordered.size();
386 Value value = null;
387 for (int i = 0; i < size; i++) {
388 Value v = ordered.get(i)[0];
389 if (v != ValueNull.INSTANCE) {
390 if (value == null) {
391 value = v.convertToDouble();
392 } else {
393 value = value.add(v.convertToDouble());
394 }
395 }
396 }
397 if (value != null && value.getSignum() == 0) {
398 value = null;
399 }
400 for (int i = 0; i < size; i++) {
401 Value[] row = ordered.get(i);
402 Value v;
403 if (value == null) {
404 v = ValueNull.INSTANCE;
405 } else {
406 v = row[0];
407 if (v != ValueNull.INSTANCE) {
408 v = v.convertToDouble().divide(value, TypeInfo.TYPE_DOUBLE);
409 }
410 }
411 result.put(row[rowIdColumn].getInt(), v);
412 }
413 }
414
415 @Override
416 protected Value getAggregatedValue(SessionLocal session, Object aggregateData) {
417 throw DbException.getUnsupportedException("Window function");
418 }
419
420 @Override
421 public void mapColumnsAnalysis(ColumnResolver resolver, int level, int innerState) {
422 if (args != null) {
423 for (Expression arg : args) {
424 arg.mapColumns(resolver, level, innerState);
425 }
426 }
427 super.mapColumnsAnalysis(resolver, level, innerState);
428 }
429
430 @Override
431 public Expression optimize(SessionLocal session) {
432 if (over.getWindowFrame() != null) {
433 switch (type) {
434 case FIRST_VALUE:
435 case LAST_VALUE:
436 case NTH_VALUE:
437 break;
438 default:
439 String sql = getTraceSQL();
440 throw DbException.getSyntaxError(sql, sql.length() - 1);
441 }
442 }
443 if (over.getOrderBy() == null) {
444 if (type.requiresWindowOrdering()) {
445 String sql = getTraceSQL();
446 throw DbException.getSyntaxError(sql, sql.length() - 1, "ORDER BY");
447 }
448 } else if (type == WindowFunctionType.RATIO_TO_REPORT) {
449 String sql = getTraceSQL();
450 throw DbException.getSyntaxError(sql, sql.length() - 1);
451 }
452 super.optimize(session);
453 // Need to re-test, because optimization may remove the window ordering
454 // clause.
455 if (over.getOrderBy() == null) {
456 switch (type) {
457 case RANK:
458 case DENSE_RANK:
459 return ValueExpression.get(ValueBigint.get(1L));
460 case PERCENT_RANK:
461 return ValueExpression.get(ValueDouble.ZERO);
462 case CUME_DIST:
463 return ValueExpression.get(ValueDouble.ONE);
464 default:
465 }
466 }
467 if (args != null) {
468 for (int i = 0; i < args.length; i++) {
469 args[i] = args[i].optimize(session);
470 }
471 }
472 return this;
473 }
474
475 @Override
476 public void setEvaluatable(TableFilter tableFilter, boolean b) {
477 if (args != null) {
478 for (Expression e : args) {
479 e.setEvaluatable(tableFilter, b);
480 }
481 }
482 super.setEvaluatable(tableFilter, b);
483 }
484
485 @Override
486 public TypeInfo getType() {
487 switch (type) {
488 case ROW_NUMBER:
489 case RANK:
490 case DENSE_RANK:
491 case NTILE:
492 return TypeInfo.TYPE_BIGINT;
493 case PERCENT_RANK:
494 case CUME_DIST:
495 case RATIO_TO_REPORT:
496 return TypeInfo.TYPE_DOUBLE;
497 case LEAD:
498 case LAG:
499 case FIRST_VALUE:
500 case LAST_VALUE:
501 case NTH_VALUE:
502 return args[0].getType();
503 default:
504 throw DbException.getInternalError("type=" + type);
505 }
506 }
507
508 @Override
509 public StringBuilder getUnenclosedSQL(StringBuilder builder, int sqlFlags) {
510 builder.append(type.getSQL()).append('(');
511 if (args != null) {
512 writeExpressions(builder, args, sqlFlags);
513 }
514 builder.append(')');
515 if (fromLast && type == WindowFunctionType.NTH_VALUE) {
516 builder.append(" FROM LAST");
517 }
518 if (ignoreNulls) {
519 switch (type) {
520 case LEAD:
521 case LAG:
522 case FIRST_VALUE:
523 case LAST_VALUE:
524 case NTH_VALUE:
525 builder.append(" IGNORE NULLS");
526 //$FALL-THROUGH$
527 default:
528 }
529 }
530 return appendTailConditions(builder, sqlFlags, type.requiresWindowOrdering());
531 }
532
533 @Override
534 public int getCost() {
535 int cost = 1;
536 if (args != null) {
537 for (Expression expr : args) {
538 cost += expr.getCost();
539 }
540 }
541 return cost;
542 }
543
544 }