WindowFrame.java 21.8 KB
Newer Older
1 2 3 4 5
/*
 * 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
 */
6
package org.h2.expression.analysis;
7 8

import java.util.ArrayList;
9
import java.util.Collections;
10 11 12
import java.util.Iterator;
import java.util.NoSuchElementException;

13 14 15 16
import org.h2.engine.Session;
import org.h2.expression.BinaryOperation;
import org.h2.expression.BinaryOperation.OpType;
import org.h2.expression.ValueExpression;
17
import org.h2.message.DbException;
18
import org.h2.result.SortOrder;
19 20 21 22 23 24 25
import org.h2.value.Value;

/**
 * Window frame clause.
 */
public final class WindowFrame {

26
    private static abstract class Itr implements Iterator<Value[]> {
27 28 29

        final ArrayList<Value[]> orderedRows;

30 31
        int cursor;

32 33 34 35 36 37 38 39 40 41 42
        Itr(ArrayList<Value[]> orderedRows) {
            this.orderedRows = orderedRows;
        }

        @Override
        public final void remove() {
            throw new UnsupportedOperationException();
        }

    }

43
    private static class PlainItr extends Itr {
44

45
        final int endIndex;
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

        PlainItr(ArrayList<Value[]> orderedRows, int startIndex, int endIndex) {
            super(orderedRows);
            this.endIndex = endIndex;
            cursor = startIndex;
        }

        @Override
        public boolean hasNext() {
            return cursor <= endIndex;
        }

        @Override
        public Value[] next() {
            if (cursor > endIndex) {
                throw new NoSuchElementException();
            }
            return orderedRows.get(cursor++);
        }

    }

68
    private static class PlainReverseItr extends Itr {
69

70
        final int startIndex;
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

        PlainReverseItr(ArrayList<Value[]> orderedRows, int startIndex, int endIndex) {
            super(orderedRows);
            this.startIndex = startIndex;
            cursor = endIndex;
        }

        @Override
        public boolean hasNext() {
            return cursor >= startIndex;
        }

        @Override
        public Value[] next() {
            if (cursor < startIndex) {
                throw new NoSuchElementException();
            }
            return orderedRows.get(cursor--);
        }

    }

93
    private static class BiItr extends PlainItr {
94

95
        final int end1, start1;
96 97 98

        BiItr(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1, int startIndex2, int endIndex2) {
            super(orderedRows, startIndex1, endIndex2);
99 100
            end1 = endIndex1;
            start1 = startIndex2;
101 102 103 104 105 106 107 108
        }

        @Override
        public Value[] next() {
            if (cursor > endIndex) {
                throw new NoSuchElementException();
            }
            Value[] r = orderedRows.get(cursor);
109
            cursor = cursor != end1 ? cursor + 1 : start1;
110 111 112 113 114
            return r;
        }

    }

115
    private static class BiReverseItr extends PlainReverseItr {
116

117
        final int end1, start1;
118 119 120

        BiReverseItr(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1, int startIndex2, int endIndex2) {
            super(orderedRows, startIndex1, endIndex2);
121 122
            end1 = endIndex1;
            start1 = startIndex2;
123 124 125 126 127 128 129 130
        }

        @Override
        public Value[] next() {
            if (cursor < startIndex) {
                throw new NoSuchElementException();
            }
            Value[] r = orderedRows.get(cursor);
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
            cursor = cursor != start1 ? cursor - 1 : end1;
            return r;
        }

    }

    private static final class TriItr extends BiItr {

        private final int end2, start2;

        TriItr(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1, int startIndex2, int endIndex2,
                int startIndex3, int endIndex3) {
            super(orderedRows, startIndex1, endIndex1, startIndex2, endIndex3);
            end2 = endIndex2;
            start2 = startIndex3;
        }

        @Override
        public Value[] next() {
            if (cursor > endIndex) {
                throw new NoSuchElementException();
            }
            Value[] r = orderedRows.get(cursor);
            cursor = cursor != end1 ? cursor != end2 ? cursor + 1 : start2 : start1;
            return r;
        }

    }

    private static final class TriReverseItr extends BiReverseItr {

        private final int end2, start2;

        TriReverseItr(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1, int startIndex2, int endIndex2,
                int startIndex3, int endIndex3) {
            super(orderedRows, startIndex1, endIndex1, startIndex2, endIndex3);
            end2 = endIndex2;
            start2 = startIndex3;
        }

        @Override
        public Value[] next() {
            if (cursor < startIndex) {
                throw new NoSuchElementException();
            }
            Value[] r = orderedRows.get(cursor);
            cursor = cursor != start1 ? cursor != start2 ? cursor - 1 : end2 : end1;
178 179 180 181 182
            return r;
        }

    }

183 184 185 186 187
    private final WindowFrameUnits units;

    private final WindowFrameBound starting;

    private final WindowFrameBound following;
188

189 190
    private final WindowFrameExclusion exclusion;

191 192 193 194
    /**
     * Returns iterator for the specified frame, or default iterator if frame is
     * null.
     *
195 196
     * @param over
     *            window
197 198 199 200 201 202 203 204 205 206 207 208 209
     * @param session
     *            the session
     * @param orderedRows
     *            ordered rows
     * @param sortOrder
     *            sort order
     * @param currentRow
     *            index of the current row
     * @param reverse
     *            whether iterator should iterate in reverse order
     *
     * @return iterator
     */
210
    public static Iterator<Value[]> iterator(Window over, Session session, ArrayList<Value[]> orderedRows,
211
            SortOrder sortOrder, int currentRow, boolean reverse) {
212 213 214 215 216 217 218 219
        WindowFrame frame = over.getWindowFrame();
        if (frame != null) {
            return frame.iterator(session, orderedRows, sortOrder, currentRow, reverse);
        }
        int endIndex = orderedRows.size() - 1;
        return plainIterator(orderedRows, 0,
                over.getOrderBy() == null ? endIndex : toGroupEnd(orderedRows, sortOrder, currentRow, endIndex),
                reverse);
220 221
    }

222 223 224 225 226
    private static Iterator<Value[]> plainIterator(ArrayList<Value[]> orderedRows, int startIndex, int endIndex,
            boolean reverse) {
        if (endIndex < startIndex) {
            return Collections.emptyIterator();
        }
227 228
        return reverse ? new PlainReverseItr(orderedRows, startIndex, endIndex)
                : new PlainItr(orderedRows, startIndex, endIndex);
229 230
    }

231 232 233 234 235 236
    private static Iterator<Value[]> biIterator(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1,
            int startIndex2, int endIndex2, boolean reverse) {
        return reverse ? new BiReverseItr(orderedRows, startIndex1, endIndex1, startIndex2, endIndex2)
                : new BiItr(orderedRows, startIndex1, endIndex1, startIndex2, endIndex2);
    }

237 238 239 240 241 242 243
    private static Iterator<Value[]> triIterator(ArrayList<Value[]> orderedRows, int startIndex1, int endIndex1,
            int startIndex2, int endIndex2, int startIndex3, int endIndex3, boolean reverse) {
        return reverse ? new TriReverseItr(orderedRows, startIndex1, endIndex1, startIndex2, endIndex2, //
                startIndex3, endIndex3)
                : new TriItr(orderedRows, startIndex1, endIndex1, startIndex2, endIndex2, startIndex3, endIndex3);
    }

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    private static int toGroupStart(ArrayList<Value[]> orderedRows, SortOrder sortOrder, int offset, int minOffset) {
        Value[] row = orderedRows.get(offset);
        while (offset > minOffset && sortOrder.compare(row, orderedRows.get(offset - 1)) == 0) {
            offset--;
        }
        return offset;
    }

    private static int toGroupEnd(ArrayList<Value[]> orderedRows, SortOrder sortOrder, int offset, int maxOffset) {
        Value[] row = orderedRows.get(offset);
        while (offset < maxOffset && sortOrder.compare(row, orderedRows.get(offset + 1)) == 0) {
            offset++;
        }
        return offset;
    }

    private static int getIntOffset(WindowFrameBound bound, Session session) {
        int value = bound.getValue().getValue(session).getInt();
        if (value < 0) {
            throw DbException.getInvalidValueException("unsigned", value);
        }
        return value;
    }

268 269 270 271 272 273 274 275
    private static Value[] getCompareRow(Session session, ArrayList<Value[]> orderedRows, SortOrder sortOrder,
            int currentRow, WindowFrameBound bound, boolean add) {
        int sortIndex = sortOrder.getQueryColumnIndexes()[0];
        OpType opType = add ^ (sortOrder.getSortTypes()[0] & SortOrder.DESCENDING) != 0 ? OpType.PLUS : OpType.MINUS;
        Value[] row = orderedRows.get(currentRow);
        Value[] newRow = row.clone();
        newRow[sortIndex] = new BinaryOperation(opType, //
                ValueExpression.get(row[sortIndex]), ValueExpression.get(getValueOffset(bound, session))) //
276
                        .optimize(session).getValue(session);
277
        return newRow;
278 279 280 281 282 283 284 285 286 287
    }

    private static Value getValueOffset(WindowFrameBound bound, Session session) {
        Value value = bound.getValue().getValue(session);
        if (value.getSignum() < 0) {
            throw DbException.getInvalidValueException("unsigned", value.getTraceSQL());
        }
        return value;
    }

288 289 290
    /**
     * Creates new instance of window frame clause.
     *
291 292 293 294 295 296
     * @param units
     *            units
     * @param starting
     *            starting clause
     * @param following
     *            following clause
297
     * @param exclusion
298
     *            exclusion clause
299
     */
300 301 302 303 304 305 306 307
    public WindowFrame(WindowFrameUnits units, WindowFrameBound starting, WindowFrameBound following,
            WindowFrameExclusion exclusion) {
        this.units = units;
        this.starting = starting;
        if (following != null && following.getType() == WindowFrameBoundType.CURRENT_ROW) {
            following = null;
        }
        this.following = following;
308
        this.exclusion = exclusion;
309 310
    }

311 312 313 314 315 316 317 318 319 320 321 322
    /**
     * Checks validity of this frame.
     *
     * @return whether bounds of this frame valid
     */
    public boolean isValid() {
        WindowFrameBoundType s = starting.getType(),
                f = following != null ? following.getType() : WindowFrameBoundType.CURRENT_ROW;
        return s != WindowFrameBoundType.UNBOUNDED_FOLLOWING && f != WindowFrameBoundType.UNBOUNDED_PRECEDING
                && s.compareTo(f) <= 0;
    }

323 324 325 326 327 328 329
    /**
     * Returns whether window frame specification contains all rows in
     * partition.
     *
     * @return whether window frame specification contains all rows in partition
     */
    public boolean isFullPartition() {
330 331
        return starting.getType() == WindowFrameBoundType.UNBOUNDED_PRECEDING && following != null
                && following.getType() == WindowFrameBoundType.UNBOUNDED_FOLLOWING
332
                && exclusion == WindowFrameExclusion.EXCLUDE_NO_OTHERS;
333 334 335 336 337
    }

    /**
     * Returns iterator.
     *
338 339
     * @param session
     *            the session
340 341
     * @param orderedRows
     *            ordered rows
342 343
     * @param sortOrder
     *            sort order
344 345
     * @param currentRow
     *            index of the current row
346 347
     * @param reverse
     *            whether iterator should iterate in reverse order
348
     *
349 350
     * @return iterator
     */
351 352
    public Iterator<Value[]> iterator(Session session, ArrayList<Value[]> orderedRows, SortOrder sortOrder,
            int currentRow, boolean reverse) {
353 354
        int startIndex = getIndex(session, orderedRows, sortOrder, currentRow, starting, false);
        int endIndex = following != null ? getIndex(session, orderedRows, sortOrder, currentRow, following, true)
355 356
                : units == WindowFrameUnits.ROWS ? currentRow
                        : toGroupEnd(orderedRows, sortOrder, currentRow, orderedRows.size() - 1);
357
        if (endIndex < startIndex) {
358
            return Collections.emptyIterator();
359
        }
360
        int size = orderedRows.size();
361 362 363 364
        if (startIndex >= size || endIndex < 0) {
            return Collections.emptyIterator();
        }
        if (startIndex < 0) {
365
            startIndex = 0;
366 367 368 369
        }
        if (endIndex >= size) {
            endIndex = size - 1;
        }
370 371 372
        return exclusion != WindowFrameExclusion.EXCLUDE_NO_OTHERS
                ? complexIterator(orderedRows, sortOrder, currentRow, startIndex, endIndex, reverse)
                : plainIterator(orderedRows, startIndex, endIndex, reverse);
373 374 375
    }

    private int getIndex(Session session, ArrayList<Value[]> orderedRows, SortOrder sortOrder, int currentRow,
376
            WindowFrameBound bound, boolean forFollowing) {
377 378 379 380 381
        int size = orderedRows.size();
        int last = size - 1;
        int index;
        switch (bound.getType()) {
        case UNBOUNDED_PRECEDING:
382
            index = -1;
383
            break;
384
        case PRECEDING:
385 386
            switch (units) {
            case ROWS: {
387
                int value = getIntOffset(bound, session);
388
                index = value > currentRow ? -1 : currentRow - value;
389 390
                break;
            }
391 392
            case GROUPS: {
                int value = getIntOffset(bound, session);
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
                if (!forFollowing) {
                    index = toGroupStart(orderedRows, sortOrder, currentRow, 0);
                    while (value > 0 && index > 0) {
                        value--;
                        index = toGroupStart(orderedRows, sortOrder, index - 1, 0);
                    }
                    if (value > 0) {
                        index = -1;
                    }
                } else {
                    if (value == 0) {
                        index = toGroupEnd(orderedRows, sortOrder, currentRow, last);
                    } else {
                        index = currentRow;
                        while (value > 0 && index >= 0) {
                            value--;
                            index = toGroupStart(orderedRows, sortOrder, index, 0) - 1;
                        }
                    }
412 413 414 415
                }
                break;
            }
            case RANGE: {
416
                index = currentRow;
417 418 419 420 421 422 423 424 425 426 427
                Value[] row = getCompareRow(session, orderedRows, sortOrder, index, bound, false);
                index = Collections.binarySearch(orderedRows, row, sortOrder);
                if (index >= 0) {
                    if (!forFollowing) {
                        while (index > 0 && sortOrder.compare(row, orderedRows.get(index - 1)) == 0) {
                            index--;
                        }
                    } else {
                        while (index < last && sortOrder.compare(row, orderedRows.get(index + 1)) == 0) {
                            index++;
                        }
428 429
                    }
                } else {
430 431 432 433 434 435
                    index = ~index;
                    if (!forFollowing) {
                        if (index == 0) {
                            index = -1;
                        }
                    } else {
436
                        index--;
437 438 439 440
                    }
                }
                break;
            }
441 442 443
            default:
                throw DbException.getUnsupportedException("units=" + units);
            }
444
            break;
445
        case CURRENT_ROW:
446 447 448 449 450 451 452 453 454 455 456 457
            switch (units) {
            case ROWS:
                index = currentRow;
                break;
            case GROUPS:
            case RANGE:
                index = forFollowing ? toGroupEnd(orderedRows, sortOrder, currentRow, last)
                        : toGroupStart(orderedRows, sortOrder, currentRow, 0);
                break;
            default:
                throw DbException.getUnsupportedException("units=" + units);
            }
458 459 460 461 462 463 464
            break;
        case FOLLOWING:
            switch (units) {
            case ROWS: {
                int value = getIntOffset(bound, session);
                int rem = last - currentRow;
                index = value > rem ? size : currentRow + value;
465
                break;
466 467 468
            }
            case GROUPS: {
                int value = getIntOffset(bound, session);
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
                if (forFollowing) {
                    index = toGroupEnd(orderedRows, sortOrder, currentRow, last);
                    while (value > 0 && index < last) {
                        value--;
                        index = toGroupEnd(orderedRows, sortOrder, index + 1, last);
                    }
                    if (value > 0) {
                        index = size;
                    }
                } else {
                    if (value == 0) {
                        index = toGroupStart(orderedRows, sortOrder, currentRow, 0);
                    } else {
                        index = currentRow;
                        while (value > 0 && index <= last) {
                            value--;
                            index = toGroupEnd(orderedRows, sortOrder, index, last) + 1;
                        }
                    }
488
                }
489 490 491 492
                break;
            }
            case RANGE: {
                index = currentRow;
493 494 495 496 497 498 499 500 501 502 503
                Value[] row = getCompareRow(session, orderedRows, sortOrder, index, bound, true);
                index = Collections.binarySearch(orderedRows, row, sortOrder);
                if (index >= 0) {
                    if (forFollowing) {
                        while (index < last && sortOrder.compare(row, orderedRows.get(index + 1)) == 0) {
                            index++;
                        }
                    } else {
                        while (index > 0 && sortOrder.compare(row, orderedRows.get(index - 1)) == 0) {
                            index--;
                        }
504 505
                    }
                } else {
506 507 508 509 510
                    index = ~index;
                    if (forFollowing) {
                        if (index != size) {
                            index--;
                        }
511
                    }
512 513
                }
                break;
514
            }
515
            default:
516
                throw DbException.getUnsupportedException("units=" + units);
517
            }
518 519
            break;
        case UNBOUNDED_FOLLOWING:
520
            index = size;
521 522 523
            break;
        default:
            throw DbException.getUnsupportedException("window frame bound type=" + bound.getType());
524
        }
525
        return index;
526 527
    }

528 529
    private Iterator<Value[]> complexIterator(ArrayList<Value[]> orderedRows, SortOrder sortOrder, int currentRow,
            int startIndex, int endIndex, boolean reverse) {
530
        if (exclusion == WindowFrameExclusion.EXCLUDE_CURRENT_ROW) {
531
            if (currentRow < startIndex || currentRow > endIndex) {
532
                // Nothing to exclude
533 534 535 536 537 538 539
            } else if (currentRow == startIndex) {
                startIndex++;
            } else if (currentRow == endIndex) {
                endIndex--;
            } else {
                return biIterator(orderedRows, startIndex, currentRow - 1, currentRow + 1, endIndex, reverse);
            }
540
        } else {
541
            // Do not include previous rows if they are not in the range
542
            int exStart = toGroupStart(orderedRows, sortOrder, currentRow, startIndex);
543
            // Do not include next rows if they are not in the range
544
            int exEnd = toGroupEnd(orderedRows, sortOrder, currentRow, endIndex);
545 546
            boolean includeCurrentRow = exclusion == WindowFrameExclusion.EXCLUDE_TIES;
            if (includeCurrentRow) {
547
                // Simplify exclusion if possible
548 549 550 551 552 553 554 555 556
                if (currentRow == exStart) {
                    exStart++;
                    includeCurrentRow = false;
                } else if (currentRow == exEnd) {
                    exEnd--;
                    includeCurrentRow = false;
                }
            }
            if (exStart > exEnd || exEnd < startIndex || exStart > endIndex) {
557
                // Empty range or nothing to exclude
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
            } else if (includeCurrentRow) {
                if (startIndex == exStart) {
                    if (endIndex == exEnd) {
                        return Collections.singleton(orderedRows.get(currentRow)).iterator();
                    } else {
                        return biIterator(orderedRows, currentRow, currentRow, exEnd + 1, endIndex, reverse);
                    }
                } else {
                    if (endIndex == exEnd) {
                        return biIterator(orderedRows, startIndex, exStart - 1, currentRow, currentRow, reverse);
                    } else {
                        return triIterator(orderedRows, startIndex, exStart - 1, currentRow, currentRow, exEnd + 1,
                                endIndex, reverse);
                    }
                }
573
            } else {
574 575 576 577 578 579
                if (startIndex >= exStart) {
                    startIndex = exEnd + 1;
                } else if (endIndex <= exEnd) {
                    endIndex = exStart - 1;
                } else {
                    return biIterator(orderedRows, startIndex, exStart - 1, exEnd + 1, endIndex, reverse);
580
                }
581
            }
582
        }
583
        return plainIterator(orderedRows, startIndex, endIndex, reverse);
584 585 586
    }

    /**
587
     * Append SQL representation to the specified builder.
588
     *
589 590 591 592
     * @param builder
     *            string builder
     * @return the specified string builder
     * @see org.h2.expression.Expression#getSQL(StringBuilder)
593
     */
594
    public StringBuilder getSQL(StringBuilder builder) {
595 596
        builder.append(units.getSQL());
        if (following == null) {
597 598
            builder.append(' ');
            starting.getSQL(builder, false);
599
        } else {
600 601 602
            builder.append(" BETWEEN ");
            starting.getSQL(builder, false).append(" AND ");
            following.getSQL(builder, true);
603
        }
604
        if (exclusion != WindowFrameExclusion.EXCLUDE_NO_OTHERS) {
605
            builder.append(' ').append(exclusion.getSQL());
606
        }
607
        return builder;
608 609 610
    }

}