Debian Codegraph @

src/main/org/h2/expression/analysis/WindowFrame.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.Collections;
10 import java.util.Iterator;
11 import java.util.NoSuchElementException;
12
13 import org.h2.api.ErrorCode;
14 import org.h2.engine.SessionLocal;
15 import org.h2.expression.BinaryOperation;
16 import org.h2.expression.BinaryOperation.OpType;
17 import org.h2.expression.Expression;
18 import org.h2.expression.ValueExpression;
19 import org.h2.message.DbException;
20 import org.h2.result.SortOrder;
21 import org.h2.table.ColumnResolver;
22 import org.h2.value.Value;
23 import org.h2.value.ValueNull;
24
25 /**
26 * Window frame clause.
27 */
28 public final class WindowFrame {
29
30 private abstract static class Itr implements Iterator<Value[]> {
31
32 final ArrayList<Value[]> orderedRows;
33
34 int cursor;
35
36 Itr(ArrayList<Value[]> orderedRows) {
37 this.orderedRows = orderedRows;
38 }
39
40 }
41
42 private static class PlainItr extends Itr {
43
44 final int endIndex;
45
46 PlainItr(ArrayList<Value[]> orderedRows, int startIndex, int endIndex) {
47 super(orderedRows);
48 this.endIndex = endIndex;
49 cursor = startIndex;
50 }
51
52 @Override
53 public boolean hasNext() {
54 return cursor <= endIndex;
55 }
56
57 @Override
58 public Value[] next() {
59 if (cursor > endIndex) {
60 throw new NoSuchElementException();
61 }
62 return orderedRows.get(cursor++);
63 }
64
65 }
66
67 private static class PlainReverseItr extends Itr {
68
69 final int startIndex;
70
71 PlainReverseItr(ArrayList<Value[]> orderedRows, int startIndex, int endIndex) {
72 super(orderedRows);
73 this.startIndex = startIndex;
74 cursor = endIndex;
75 }
76
77 @Override
78 public boolean hasNext() {
79 return cursor >= startIndex;
80 }
81
82 @Override
83 public Value[] next() {
84 if (cursor < startIndex) {
85 throw new NoSuchElementException();
86 }
87 return orderedRows.get(cursor--);
88 }
89
90 }
91
92 private static class BiItr extends PlainItr {
93
94 final int end1, start1;
95
96 BiItr(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1, int startIndex2, int endIndex2) {
97 super(orderedRows, startIndex1, endIndex2);
98 end1 = endIndex1;
99 start1 = startIndex2;
100 }
101
102 @Override
103 public Value[] next() {
104 if (cursor > endIndex) {
105 throw new NoSuchElementException();
106 }
107 Value[] r = orderedRows.get(cursor);
108 cursor = cursor != end1 ? cursor + 1 : start1;
109 return r;
110 }
111
112 }
113
114 private static class BiReverseItr extends PlainReverseItr {
115
116 final int end1, start1;
117
118 BiReverseItr(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1, int startIndex2, int endIndex2) {
119 super(orderedRows, startIndex1, endIndex2);
120 end1 = endIndex1;
121 start1 = startIndex2;
122 }
123
124 @Override
125 public Value[] next() {
126 if (cursor < startIndex) {
127 throw new NoSuchElementException();
128 }
129 Value[] r = orderedRows.get(cursor);
130 cursor = cursor != start1 ? cursor - 1 : end1;
131 return r;
132 }
133
134 }
135
136 private static final class TriItr extends BiItr {
137
138 private final int end2, start2;
139
140 TriItr(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1, int startIndex2, int endIndex2,
141 int startIndex3, int endIndex3) {
142 super(orderedRows, startIndex1, endIndex1, startIndex2, endIndex3);
143 end2 = endIndex2;
144 start2 = startIndex3;
145 }
146
147 @Override
148 public Value[] next() {
149 if (cursor > endIndex) {
150 throw new NoSuchElementException();
151 }
152 Value[] r = orderedRows.get(cursor);
153 cursor = cursor != end1 ? cursor != end2 ? cursor + 1 : start2 : start1;
154 return r;
155 }
156
157 }
158
159 private static final class TriReverseItr extends BiReverseItr {
160
161 private final int end2, start2;
162
163 TriReverseItr(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1, int startIndex2, int endIndex2,
164 int startIndex3, int endIndex3) {
165 super(orderedRows, startIndex1, endIndex1, startIndex2, endIndex3);
166 end2 = endIndex2;
167 start2 = startIndex3;
168 }
169
170 @Override
171 public Value[] next() {
172 if (cursor < startIndex) {
173 throw new NoSuchElementException();
174 }
175 Value[] r = orderedRows.get(cursor);
176 cursor = cursor != start1 ? cursor != start2 ? cursor - 1 : end2 : end1;
177 return r;
178 }
179
180 }
181
182 private final WindowFrameUnits units;
183
184 private final WindowFrameBound starting;
185
186 private final WindowFrameBound following;
187
188 private final WindowFrameExclusion exclusion;
189
190 /**
191 * Returns iterator for the specified frame, or default iterator if frame is
192 * null.
193 *
194 * @param over
195 * window
196 * @param session
197 * the session
198 * @param orderedRows
199 * ordered rows
200 * @param sortOrder
201 * sort order
202 * @param currentRow
203 * index of the current row
204 * @param reverse
205 * whether iterator should iterate in reverse order
206 * @return iterator
207 */
208 public static Iterator<Value[]> iterator(Window over, SessionLocal session, ArrayList<Value[]> orderedRows,
209 SortOrder sortOrder, int currentRow, boolean reverse) {
210 WindowFrame frame = over.getWindowFrame();
211 if (frame != null) {
212 return frame.iterator(session, orderedRows, sortOrder, currentRow, reverse);
213 }
214 int endIndex = orderedRows.size() - 1;
215 return plainIterator(orderedRows, 0,
216 over.getOrderBy() == null ? endIndex : toGroupEnd(orderedRows, sortOrder, currentRow, endIndex),
217 reverse);
218 }
219
220 /**
221 * Returns end index for the specified frame, or default end index if frame
222 * is null.
223 *
224 * @param over
225 * window
226 * @param session
227 * the session
228 * @param orderedRows
229 * ordered rows
230 * @param sortOrder
231 * sort order
232 * @param currentRow
233 * index of the current row
234 * @return end index
235 * @throws UnsupportedOperationException
236 * if over is not null and its exclusion clause is not EXCLUDE
237 * NO OTHERS
238 */
239 public static int getEndIndex(Window over, SessionLocal session, ArrayList<Value[]> orderedRows,
240 SortOrder sortOrder, int currentRow) {
241 WindowFrame frame = over.getWindowFrame();
242 if (frame != null) {
243 return frame.getEndIndex(session, orderedRows, sortOrder, currentRow);
244 }
245 int endIndex = orderedRows.size() - 1;
246 return over.getOrderBy() == null ? endIndex : toGroupEnd(orderedRows, sortOrder, currentRow, endIndex);
247 }
248
249 private static Iterator<Value[]> plainIterator(ArrayList<Value[]> orderedRows, int startIndex, int endIndex,
250 boolean reverse) {
251 if (endIndex < startIndex) {
252 return Collections.emptyIterator();
253 }
254 return reverse ? new PlainReverseItr(orderedRows, startIndex, endIndex)
255 : new PlainItr(orderedRows, startIndex, endIndex);
256 }
257
258 private static Iterator<Value[]> biIterator(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1,
259 int startIndex2, int endIndex2, boolean reverse) {
260 return reverse ? new BiReverseItr(orderedRows, startIndex1, endIndex1, startIndex2, endIndex2)
261 : new BiItr(orderedRows, startIndex1, endIndex1, startIndex2, endIndex2);
262 }
263
264 private static Iterator<Value[]> triIterator(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1,
265 int startIndex2, int endIndex2, int startIndex3, int endIndex3, boolean reverse) {
266 return reverse ? new TriReverseItr(orderedRows, startIndex1, endIndex1, startIndex2, endIndex2, //
267 startIndex3, endIndex3)
268 : new TriItr(orderedRows, startIndex1, endIndex1, startIndex2, endIndex2, startIndex3, endIndex3);
269 }
270
271 private static int toGroupStart(ArrayList<Value[]> orderedRows, SortOrder sortOrder, int offset, int minOffset) {
272 Value[] row = orderedRows.get(offset);
273 while (offset > minOffset && sortOrder.compare(row, orderedRows.get(offset - 1)) == 0) {
274 offset--;
275 }
276 return offset;
277 }
278
279 private static int toGroupEnd(ArrayList<Value[]> orderedRows, SortOrder sortOrder, int offset, int maxOffset) {
280 Value[] row = orderedRows.get(offset);
281 while (offset < maxOffset && sortOrder.compare(row, orderedRows.get(offset + 1)) == 0) {
282 offset++;
283 }
284 return offset;
285 }
286
287 private static int getIntOffset(WindowFrameBound bound, Value[] values, SessionLocal session) {
288 Value v = bound.isVariable() ? values[bound.getExpressionIndex()] : bound.getValue().getValue(session);
289 int value;
290 if (v == ValueNull.INSTANCE || (value = v.getInt()) < 0) {
291 throw DbException.get(ErrorCode.INVALID_PRECEDING_OR_FOLLOWING_1, v.getTraceSQL());
292 }
293 return value;
294 }
295
296 /**
297 * Appends bound value to the current row and produces row for comparison
298 * operations.
299 *
300 * @param session
301 * the session
302 * @param orderedRows
303 * rows in partition
304 * @param sortOrder
305 * the sort order
306 * @param currentRow
307 * index of the current row
308 * @param bound
309 * window frame bound
310 * @param add
311 * false for PRECEDING, true for FOLLOWING
312 * @return row for comparison operations, or null if result is out of range
313 * and should be treated as UNLIMITED
314 */
315 private static Value[] getCompareRow(SessionLocal session, ArrayList<Value[]> orderedRows, SortOrder sortOrder,
316 int currentRow, WindowFrameBound bound, boolean add) {
317 int sortIndex = sortOrder.getQueryColumnIndexes()[0];
318 Value[] row = orderedRows.get(currentRow);
319 Value currentValue = row[sortIndex];
320 int type = currentValue.getValueType();
321 Value newValue;
322 Value range = getValueOffset(bound, orderedRows.get(currentRow), session);
323 switch (type) {
324 case Value.NULL:
325 newValue = ValueNull.INSTANCE;
326 break;
327 case Value.TINYINT:
328 case Value.SMALLINT:
329 case Value.INTEGER:
330 case Value.BIGINT:
331 case Value.NUMERIC:
332 case Value.REAL:
333 case Value.DOUBLE:
334 case Value.DECFLOAT:
335 case Value.TIME:
336 case Value.TIME_TZ:
337 case Value.DATE:
338 case Value.TIMESTAMP:
339 case Value.TIMESTAMP_TZ:
340 case Value.INTERVAL_YEAR:
341 case Value.INTERVAL_MONTH:
342 case Value.INTERVAL_DAY:
343 case Value.INTERVAL_HOUR:
344 case Value.INTERVAL_MINUTE:
345 case Value.INTERVAL_SECOND:
346 case Value.INTERVAL_YEAR_TO_MONTH:
347 case Value.INTERVAL_DAY_TO_HOUR:
348 case Value.INTERVAL_DAY_TO_MINUTE:
349 case Value.INTERVAL_DAY_TO_SECOND:
350 case Value.INTERVAL_HOUR_TO_MINUTE:
351 case Value.INTERVAL_HOUR_TO_SECOND:
352 case Value.INTERVAL_MINUTE_TO_SECOND:
353 OpType opType = add ^ (sortOrder.getSortTypes()[0] & SortOrder.DESCENDING) != 0 ? OpType.PLUS
354 : OpType.MINUS;
355 try {
356 newValue = new BinaryOperation(opType, ValueExpression.get(currentValue), ValueExpression.get(range))
357 .optimize(session).getValue(session).convertTo(type);
358 } catch (DbException ex) {
359 switch (ex.getErrorCode()) {
360 case ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1:
361 case ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2:
362 return null;
363 }
364 throw ex;
365 }
366 break;
367 default:
368 throw DbException.getInvalidValueException("unsupported type of sort key for RANGE units",
369 currentValue.getTraceSQL());
370 }
371 Value[] newRow = row.clone();
372 newRow[sortIndex] = newValue;
373 return newRow;
374 }
375
376 private static Value getValueOffset(WindowFrameBound bound, Value[] values, SessionLocal session) {
377 Value value = bound.isVariable() ? values[bound.getExpressionIndex()] : bound.getValue().getValue(session);
378 if (value == ValueNull.INSTANCE || value.getSignum() < 0) {
379 throw DbException.get(ErrorCode.INVALID_PRECEDING_OR_FOLLOWING_1, value.getTraceSQL());
380 }
381 return value;
382 }
383
384 /**
385 * Creates new instance of window frame clause.
386 *
387 * @param units
388 * units
389 * @param starting
390 * starting clause
391 * @param following
392 * following clause
393 * @param exclusion
394 * exclusion clause
395 */
396 public WindowFrame(WindowFrameUnits units, WindowFrameBound starting, WindowFrameBound following,
397 WindowFrameExclusion exclusion) {
398 this.units = units;
399 this.starting = starting;
400 if (following != null && following.getType() == WindowFrameBoundType.CURRENT_ROW) {
401 following = null;
402 }
403 this.following = following;
404 this.exclusion = exclusion;
405 }
406
407 /**
408 * Returns the units.
409 *
410 * @return the units
411 */
412 public WindowFrameUnits getUnits() {
413 return units;
414 }
415
416 /**
417 * Returns the starting clause.
418 *
419 * @return the starting clause
420 */
421 public WindowFrameBound getStarting() {
422 return starting;
423 }
424
425 /**
426 * Returns the following clause.
427 *
428 * @return the following clause, or null
429 */
430 public WindowFrameBound getFollowing() {
431 return following;
432 }
433
434 /**
435 * Returns the exclusion clause.
436 *
437 * @return the exclusion clause
438 */
439 public WindowFrameExclusion getExclusion() {
440 return exclusion;
441 }
442
443 /**
444 * Checks validity of this frame.
445 *
446 * @return whether bounds of this frame valid
447 */
448 public boolean isValid() {
449 WindowFrameBoundType s = starting.getType(),
450 f = following != null ? following.getType() : WindowFrameBoundType.CURRENT_ROW;
451 return s != WindowFrameBoundType.UNBOUNDED_FOLLOWING && f != WindowFrameBoundType.UNBOUNDED_PRECEDING
452 && s.compareTo(f) <= 0;
453 }
454
455 /**
456 * Check if bounds of this frame has variable expressions. This method may
457 * be used only after {@link #optimize(SessionLocal)} invocation.
458 *
459 * @return if bounds of this frame has variable expressions
460 */
461 public boolean isVariableBounds() {
462 if (starting.isVariable()) {
463 return true;
464 }
465 if (following != null && following.isVariable()) {
466 return true;
467 }
468 return false;
469 }
470
471 /**
472 * Map the columns of the resolver to expression columns.
473 *
474 * @param resolver
475 * the column resolver
476 * @param level
477 * the subquery nesting level
478 * @param state
479 * current state for nesting checks
480 */
481 void mapColumns(ColumnResolver resolver, int level, int state) {
482 starting.mapColumns(resolver, level, state);
483 if (following != null) {
484 following.mapColumns(resolver, level, state);
485 }
486 }
487
488 /**
489 * Try to optimize bound expressions.
490 *
491 * @param session
492 * the session
493 */
494 void optimize(SessionLocal session) {
495 starting.optimize(session);
496 if (following != null) {
497 following.optimize(session);
498 }
499 }
500
501 /**
502 * Update an aggregate value.
503 *
504 * @param session
505 * the session
506 * @param stage
507 * select stage
508 * @see Expression#updateAggregate(SessionLocal, int)
509 */
510 void updateAggregate(SessionLocal session, int stage) {
511 starting.updateAggregate(session, stage);
512 if (following != null) {
513 following.updateAggregate(session, stage);
514 }
515 }
516
517 /**
518 * Returns iterator.
519 *
520 * @param session
521 * the session
522 * @param orderedRows
523 * ordered rows
524 * @param sortOrder
525 * sort order
526 * @param currentRow
527 * index of the current row
528 * @param reverse
529 * whether iterator should iterate in reverse order
530 * @return iterator
531 */
532 public Iterator<Value[]> iterator(SessionLocal session, ArrayList<Value[]> orderedRows, SortOrder sortOrder,
533 int currentRow, boolean reverse) {
534 int startIndex = getIndex(session, orderedRows, sortOrder, currentRow, starting, false);
535 int endIndex = following != null ? getIndex(session, orderedRows, sortOrder, currentRow, following, true)
536 : units == WindowFrameUnits.ROWS ? currentRow
537 : toGroupEnd(orderedRows, sortOrder, currentRow, orderedRows.size() - 1);
538 if (endIndex < startIndex) {
539 return Collections.emptyIterator();
540 }
541 int size = orderedRows.size();
542 if (startIndex >= size || endIndex < 0) {
543 return Collections.emptyIterator();
544 }
545 if (startIndex < 0) {
546 startIndex = 0;
547 }
548 if (endIndex >= size) {
549 endIndex = size - 1;
550 }
551 return exclusion != WindowFrameExclusion.EXCLUDE_NO_OTHERS
552 ? complexIterator(orderedRows, sortOrder, currentRow, startIndex, endIndex, reverse)
553 : plainIterator(orderedRows, startIndex, endIndex, reverse);
554 }
555
556 /**
557 * Returns start index of this frame,
558 *
559 * @param session
560 * the session
561 * @param orderedRows
562 * ordered rows
563 * @param sortOrder
564 * sort order
565 * @param currentRow
566 * index of the current row
567 * @return start index
568 * @throws UnsupportedOperationException
569 * if exclusion clause is not EXCLUDE NO OTHERS
570 */
571 public int getStartIndex(SessionLocal session, ArrayList<Value[]> orderedRows, SortOrder sortOrder, //
572 int currentRow) {
573 if (exclusion != WindowFrameExclusion.EXCLUDE_NO_OTHERS) {
574 throw new UnsupportedOperationException();
575 }
576 int startIndex = getIndex(session, orderedRows, sortOrder, currentRow, starting, false);
577 if (startIndex < 0) {
578 startIndex = 0;
579 }
580 return startIndex;
581 }
582
583 /**
584 * Returns end index of this frame,
585 *
586 * @param session
587 * the session
588 * @param orderedRows
589 * ordered rows
590 * @param sortOrder
591 * sort order
592 * @param currentRow
593 * index of the current row
594 * @return end index
595 * @throws UnsupportedOperationException
596 * if exclusion clause is not EXCLUDE NO OTHERS
597 */
598 private int getEndIndex(SessionLocal session, ArrayList<Value[]> orderedRows, SortOrder sortOrder, //
599 int currentRow) {
600 if (exclusion != WindowFrameExclusion.EXCLUDE_NO_OTHERS) {
601 throw new UnsupportedOperationException();
602 }
603 int endIndex = following != null ? getIndex(session, orderedRows, sortOrder, currentRow, following, true)
604 : units == WindowFrameUnits.ROWS ? currentRow
605 : toGroupEnd(orderedRows, sortOrder, currentRow, orderedRows.size() - 1);
606 int size = orderedRows.size();
607 if (endIndex >= size) {
608 endIndex = size - 1;
609 }
610 return endIndex;
611 }
612
613 /**
614 * Returns starting or ending index of a window frame.
615 *
616 * @param session
617 * the session
618 * @param orderedRows
619 * rows in partition
620 * @param sortOrder
621 * the sort order
622 * @param currentRow
623 * index of the current row
624 * @param bound
625 * window frame bound
626 * @param forFollowing
627 * false for start index, true for end index
628 * @return starting or ending index of a window frame (inclusive), can be 0
629 * or be equal to the number of rows if frame is not limited from
630 * that side
631 */
632 private int getIndex(SessionLocal session, ArrayList<Value[]> orderedRows, SortOrder sortOrder, int currentRow,
633 WindowFrameBound bound, boolean forFollowing) {
634 int size = orderedRows.size();
635 int last = size - 1;
636 int index;
637 switch (bound.getType()) {
638 case UNBOUNDED_PRECEDING:
639 index = -1;
640 break;
641 case PRECEDING:
642 switch (units) {
643 case ROWS: {
644 int value = getIntOffset(bound, orderedRows.get(currentRow), session);
645 index = value > currentRow ? -1 : currentRow - value;
646 break;
647 }
648 case GROUPS: {
649 int value = getIntOffset(bound, orderedRows.get(currentRow), session);
650 if (!forFollowing) {
651 index = toGroupStart(orderedRows, sortOrder, currentRow, 0);
652 while (value > 0 && index > 0) {
653 value--;
654 index = toGroupStart(orderedRows, sortOrder, index - 1, 0);
655 }
656 if (value > 0) {
657 index = -1;
658 }
659 } else {
660 if (value == 0) {
661 index = toGroupEnd(orderedRows, sortOrder, currentRow, last);
662 } else {
663 index = currentRow;
664 while (value > 0 && index >= 0) {
665 value--;
666 index = toGroupStart(orderedRows, sortOrder, index, 0) - 1;
667 }
668 }
669 }
670 break;
671 }
672 case RANGE: {
673 index = currentRow;
674 Value[] row = getCompareRow(session, orderedRows, sortOrder, index, bound, false);
675 if (row != null) {
676 index = Collections.binarySearch(orderedRows, row, sortOrder);
677 if (index >= 0) {
678 if (!forFollowing) {
679 while (index > 0 && sortOrder.compare(row, orderedRows.get(index - 1)) == 0) {
680 index--;
681 }
682 } else {
683 while (index < last && sortOrder.compare(row, orderedRows.get(index + 1)) == 0) {
684 index++;
685 }
686 }
687 } else {
688 index = ~index;
689 if (!forFollowing) {
690 if (index == 0) {
691 index = -1;
692 }
693 } else {
694 index--;
695 }
696 }
697 } else {
698 index = -1;
699 }
700 break;
701 }
702 default:
703 throw DbException.getUnsupportedException("units=" + units);
704 }
705 break;
706 case CURRENT_ROW:
707 switch (units) {
708 case ROWS:
709 index = currentRow;
710 break;
711 case GROUPS:
712 case RANGE:
713 index = forFollowing ? toGroupEnd(orderedRows, sortOrder, currentRow, last)
714 : toGroupStart(orderedRows, sortOrder, currentRow, 0);
715 break;
716 default:
717 throw DbException.getUnsupportedException("units=" + units);
718 }
719 break;
720 case FOLLOWING:
721 switch (units) {
722 case ROWS: {
723 int value = getIntOffset(bound, orderedRows.get(currentRow), session);
724 int rem = last - currentRow;
725 index = value > rem ? size : currentRow + value;
726 break;
727 }
728 case GROUPS: {
729 int value = getIntOffset(bound, orderedRows.get(currentRow), session);
730 if (forFollowing) {
731 index = toGroupEnd(orderedRows, sortOrder, currentRow, last);
732 while (value > 0 && index < last) {
733 value--;
734 index = toGroupEnd(orderedRows, sortOrder, index + 1, last);
735 }
736 if (value > 0) {
737 index = size;
738 }
739 } else {
740 if (value == 0) {
741 index = toGroupStart(orderedRows, sortOrder, currentRow, 0);
742 } else {
743 index = currentRow;
744 while (value > 0 && index <= last) {
745 value--;
746 index = toGroupEnd(orderedRows, sortOrder, index, last) + 1;
747 }
748 }
749 }
750 break;
751 }
752 case RANGE: {
753 index = currentRow;
754 Value[] row = getCompareRow(session, orderedRows, sortOrder, index, bound, true);
755 if (row != null) {
756 index = Collections.binarySearch(orderedRows, row, sortOrder);
757 if (index >= 0) {
758 if (forFollowing) {
759 while (index < last && sortOrder.compare(row, orderedRows.get(index + 1)) == 0) {
760 index++;
761 }
762 } else {
763 while (index > 0 && sortOrder.compare(row, orderedRows.get(index - 1)) == 0) {
764 index--;
765 }
766 }
767 } else {
768 index = ~index;
769 if (forFollowing) {
770 if (index != size) {
771 index--;
772 }
773 }
774 }
775 } else {
776 index = size;
777 }
778 break;
779 }
780 default:
781 throw DbException.getUnsupportedException("units=" + units);
782 }
783 break;
784 case UNBOUNDED_FOLLOWING:
785 index = size;
786 break;
787 default:
788 throw DbException.getUnsupportedException("window frame bound type=" + bound.getType());
789 }
790 return index;
791 }
792
793 private Iterator<Value[]> complexIterator(ArrayList<Value[]> orderedRows, SortOrder sortOrder, int currentRow,
794 int startIndex, int endIndex, boolean reverse) {
795 if (exclusion == WindowFrameExclusion.EXCLUDE_CURRENT_ROW) {
796 if (currentRow < startIndex || currentRow > endIndex) {
797 // Nothing to exclude
798 } else if (currentRow == startIndex) {
799 startIndex++;
800 } else if (currentRow == endIndex) {
801 endIndex--;
802 } else {
803 return biIterator(orderedRows, startIndex, currentRow - 1, currentRow + 1, endIndex, reverse);
804 }
805 } else {
806 // Do not include previous rows if they are not in the range
807 int exStart = toGroupStart(orderedRows, sortOrder, currentRow, startIndex);
808 // Do not include next rows if they are not in the range
809 int exEnd = toGroupEnd(orderedRows, sortOrder, currentRow, endIndex);
810 boolean includeCurrentRow = exclusion == WindowFrameExclusion.EXCLUDE_TIES;
811 if (includeCurrentRow) {
812 // Simplify exclusion if possible
813 if (currentRow == exStart) {
814 exStart++;
815 includeCurrentRow = false;
816 } else if (currentRow == exEnd) {
817 exEnd--;
818 includeCurrentRow = false;
819 }
820 }
821 if (exStart > exEnd || exEnd < startIndex || exStart > endIndex) {
822 // Empty range or nothing to exclude
823 } else if (includeCurrentRow) {
824 if (startIndex == exStart) {
825 if (endIndex == exEnd) {
826 return Collections.singleton(orderedRows.get(currentRow)).iterator();
827 } else {
828 return biIterator(orderedRows, currentRow, currentRow, exEnd + 1, endIndex, reverse);
829 }
830 } else {
831 if (endIndex == exEnd) {
832 return biIterator(orderedRows, startIndex, exStart - 1, currentRow, currentRow, reverse);
833 } else {
834 return triIterator(orderedRows, startIndex, exStart - 1, currentRow, currentRow, exEnd + 1,
835 endIndex, reverse);
836 }
837 }
838 } else {
839 if (startIndex >= exStart) {
840 startIndex = exEnd + 1;
841 } else if (endIndex <= exEnd) {
842 endIndex = exStart - 1;
843 } else {
844 return biIterator(orderedRows, startIndex, exStart - 1, exEnd + 1, endIndex, reverse);
845 }
846 }
847 }
848 return plainIterator(orderedRows, startIndex, endIndex, reverse);
849 }
850
851 /**
852 * Append SQL representation to the specified builder.
853 *
854 * @param builder
855 * string builder
856 * @param formattingFlags
857 * quote all identifiers
858 * @return the specified string builder
859 * @see org.h2.expression.Expression#getSQL(StringBuilder, int, int)
860 */
861 public StringBuilder getSQL(StringBuilder builder, int formattingFlags) {
862 builder.append(units.getSQL());
863 if (following == null) {
864 builder.append(' ');
865 starting.getSQL(builder, false, formattingFlags);
866 } else {
867 builder.append(" BETWEEN ");
868 starting.getSQL(builder, false, formattingFlags).append(" AND ");
869 following.getSQL(builder, true, formattingFlags);
870 }
871 if (exclusion != WindowFrameExclusion.EXCLUDE_NO_OTHERS) {
872 builder.append(' ').append(exclusion.getSQL());
873 }
874 return builder;
875 }
876
877 }