Debian Codegraph @

src/main/org/h2/command/query/Select.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.command.query;
7
8 import static org.h2.expression.Expression.WITHOUT_PARENTHESES;
9 import static org.h2.util.HasSQL.ADD_PLAN_INFORMATION;
10 import static org.h2.util.HasSQL.DEFAULT_SQL_FLAGS;
11
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.BitSet;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.LinkedHashMap;
18 import java.util.Map.Entry;
19 import org.h2.api.ErrorCode;
20 import org.h2.api.Trigger;
21 import org.h2.engine.Constants;
22 import org.h2.engine.Database;
23 import org.h2.engine.Mode.ExpressionNames;
24 import org.h2.engine.SessionLocal;
25 import org.h2.expression.Alias;
26 import org.h2.expression.Expression;
27 import org.h2.expression.ExpressionColumn;
28 import org.h2.expression.ExpressionList;
29 import org.h2.expression.ExpressionVisitor;
30 import org.h2.expression.Parameter;
31 import org.h2.expression.Wildcard;
32 import org.h2.expression.analysis.DataAnalysisOperation;
33 import org.h2.expression.analysis.Window;
34 import org.h2.expression.condition.Comparison;
35 import org.h2.expression.condition.ConditionAndOr;
36 import org.h2.expression.condition.ConditionLocalAndGlobal;
37 import org.h2.expression.function.CoalesceFunction;
38 import org.h2.index.Cursor;
39 import org.h2.index.Index;
40 import org.h2.index.QueryExpressionIndex;
41 import org.h2.message.DbException;
42 import org.h2.mode.DefaultNullOrdering;
43 import org.h2.result.LazyResult;
44 import org.h2.result.LocalResult;
45 import org.h2.result.ResultInterface;
46 import org.h2.result.ResultTarget;
47 import org.h2.result.Row;
48 import org.h2.result.SearchRow;
49 import org.h2.result.SortOrder;
50 import org.h2.table.Column;
51 import org.h2.table.ColumnResolver;
52 import org.h2.table.IndexColumn;
53 import org.h2.table.Table;
54 import org.h2.table.TableFilter;
55 import org.h2.table.TableType;
56 import org.h2.table.TableView;
57 import org.h2.util.ParserUtil;
58 import org.h2.util.StringUtils;
59 import org.h2.util.Utils;
60 import org.h2.value.DataType;
61 import org.h2.value.Value;
62 import org.h2.value.ValueRow;
63
64 /**
65 * This class represents a simple SELECT statement.
66 *
67 * For each select statement,
68 * visibleColumnCount <= distinctColumnCount <= expressionCount.
69 * The expression list count could include ORDER BY and GROUP BY expressions
70 * that are not in the select list.
71 *
72 * The call sequence is init(), mapColumns() if it's a subquery, prepare().
73 *
74 * @author Thomas Mueller
75 * @author Joel Turkel (Group sorted query)
76 */
77 public class Select extends Query {
78
79 /**
80 * The main (top) table filter.
81 */
82 TableFilter topTableFilter;
83
84 private final ArrayList<TableFilter> filters = Utils.newSmallArrayList();
85 private final ArrayList<TableFilter> topFilters = Utils.newSmallArrayList();
86
87 /**
88 * Parent select for selects in table filters.
89 */
90 private Select parentSelect;
91
92 /**
93 * WHERE condition.
94 */
95 private Expression condition;
96
97 /**
98 * HAVING condition.
99 */
100 private Expression having;
101
102 /**
103 * QUALIFY condition.
104 */
105 private Expression qualify;
106
107 /**
108 * {@code DISTINCT ON(...)} expressions.
109 */
110 private Expression[] distinctExpressions;
111
112 private int[] distinctIndexes;
113
114 private ArrayList<Expression> group;
115
116 /**
117 * The indexes of the group-by columns.
118 */
119 int[] groupIndex;
120
121 /**
122 * Whether a column in the expression list is part of a group-by.
123 */
124 boolean[] groupByExpression;
125
126 /**
127 * Grouped data for aggregates.
128 */
129 SelectGroups groupData;
130
131 private int havingIndex;
132
133 private int qualifyIndex;
134
135 private int[] groupByCopies;
136
137 /**
138 * Whether this SELECT is an explicit table (TABLE tableName). It is used in
139 * {@link #getPlanSQL(int)} to generate SQL similar to original query.
140 */
141 private boolean isExplicitTable;
142
143 /**
144 * This flag is set when SELECT statement contains (non-window) aggregate
145 * functions, GROUP BY clause or HAVING clause.
146 */
147 boolean isGroupQuery;
148 private boolean isGroupSortedQuery;
149 private boolean isWindowQuery;
150 private ForUpdate forUpdate;
151 private double cost;
152 private boolean isQuickAggregateQuery, isDistinctQuery;
153 private boolean sortUsingIndex;
154
155 private boolean isGroupWindowStage2;
156
157 private HashMap<String, Window> windows;
158
159 public Select(SessionLocal session, Select parentSelect) {
160 super(session);
161 this.parentSelect = parentSelect;
162 }
163
164 @Override
165 public boolean isUnion() {
166 return false;
167 }
168
169 /**
170 * Add a table to the query.
171 *
172 * @param filter the table to add
173 * @param isTop if the table can be the first table in the query plan
174 */
175 public void addTableFilter(TableFilter filter, boolean isTop) {
176 // Oracle doesn't check on duplicate aliases
177 // String alias = filter.getAlias();
178 // if (filterNames.contains(alias)) {
179 // throw Message.getSQLException(
180 // ErrorCode.DUPLICATE_TABLE_ALIAS, alias);
181 // }
182 // filterNames.add(alias);
183 filters.add(filter);
184 if (isTop) {
185 topFilters.add(filter);
186 }
187 }
188
189 public ArrayList<TableFilter> getTopFilters() {
190 return topFilters;
191 }
192
193 public void setExpressions(ArrayList<Expression> expressions) {
194 this.expressions = expressions;
195 }
196
197 /**
198 * Convert this SELECT to an explicit table (TABLE tableName).
199 */
200 public void setExplicitTable() {
201 setWildcard();
202 isExplicitTable = true;
203 }
204
205 /**
206 * Sets a wildcard expression as in "SELECT * FROM TEST".
207 */
208 public void setWildcard() {
209 expressions = new ArrayList<>(1);
210 expressions.add(new Wildcard(null, null));
211 }
212
213 /**
214 * Set when SELECT statement contains (non-window) aggregate functions,
215 * GROUP BY clause or HAVING clause.
216 */
217 public void setGroupQuery() {
218 isGroupQuery = true;
219 }
220
221 /**
222 * Called if this query contains window functions.
223 */
224 public void setWindowQuery() {
225 isWindowQuery = true;
226 }
227
228 public void setGroupBy(ArrayList<Expression> group) {
229 this.group = group;
230 }
231
232 public ArrayList<Expression> getGroupBy() {
233 return group;
234 }
235
236 /**
237 * Get the group data if there is currently a group-by active.
238 *
239 * @param window is this a window function
240 * @return the grouped data
241 */
242 public SelectGroups getGroupDataIfCurrent(boolean window) {
243 return groupData != null && (window || groupData.isCurrentGroup()) ? groupData : null;
244 }
245
246 /**
247 * Set the distinct flag.
248 */
249 public void setDistinct() {
250 if (distinctExpressions != null) {
251 throw DbException.getUnsupportedException("DISTINCT ON together with DISTINCT");
252 }
253 distinct = true;
254 }
255
256 /**
257 * Set the DISTINCT ON expressions.
258 *
259 * @param distinctExpressions array of expressions
260 */
261 public void setDistinct(Expression[] distinctExpressions) {
262 if (distinct) {
263 throw DbException.getUnsupportedException("DISTINCT ON together with DISTINCT");
264 }
265 this.distinctExpressions = distinctExpressions;
266 }
267
268 @Override
269 public boolean isAnyDistinct() {
270 return distinct || distinctExpressions != null;
271 }
272
273 /**
274 * Adds a named window definition.
275 *
276 * @param name name
277 * @param window window definition
278 * @return true if a new definition was added, false if old definition was replaced
279 */
280 public boolean addWindow(String name, Window window) {
281 if (windows == null) {
282 windows = new HashMap<>();
283 }
284 return windows.put(name, window) == null;
285 }
286
287 /**
288 * Returns a window with specified name, or null.
289 *
290 * @param name name of the window
291 * @return the window with specified name, or null
292 */
293 public Window getWindow(String name) {
294 return windows != null ? windows.get(name) : null;
295 }
296
297 /**
298 * Add a condition to the list of conditions.
299 *
300 * @param cond the condition to add
301 */
302 public void addCondition(Expression cond) {
303 if (condition == null) {
304 condition = cond;
305 } else {
306 condition = new ConditionAndOr(ConditionAndOr.AND, cond, condition);
307 }
308 }
309
310 public Expression getCondition() {
311 return condition;
312 }
313
314 private LazyResult queryGroupSorted(int columnCount, ResultTarget result, long offset, boolean quickOffset) {
315 LazyResultGroupSorted lazyResult = new LazyResultGroupSorted(expressionArray, columnCount);
316 skipOffset(lazyResult, offset, quickOffset);
317 if (result == null) {
318 return lazyResult;
319 }
320 while (lazyResult.next()) {
321 result.addRow(lazyResult.currentRow());
322 }
323 return null;
324 }
325
326 /**
327 * Create a row with the current values, for queries with group-sort.
328 *
329 * @param keyValues the key values
330 * @param columnCount the number of columns
331 * @return the row
332 */
333 Value[] createGroupSortedRow(Value[] keyValues, int columnCount) {
334 Value[] row = constructGroupResultRow(keyValues, columnCount);
335 if (isHavingNullOrFalse(row)) {
336 return null;
337 }
338 return rowForResult(row, columnCount);
339 }
340
341 /**
342 * Removes HAVING and QUALIFY columns from the row.
343 *
344 * @param row
345 * the complete row
346 * @param columnCount
347 * the number of columns to keep
348 * @return the same or the truncated row
349 */
350 private Value[] rowForResult(Value[] row, int columnCount) {
351 if (columnCount == resultColumnCount) {
352 return row;
353 }
354 return Arrays.copyOf(row, resultColumnCount);
355 }
356
357 private boolean isHavingNullOrFalse(Value[] row) {
358 return havingIndex >= 0 && !row[havingIndex].isTrue();
359 }
360
361 private Index getGroupSortedIndex() {
362 if (groupIndex == null || groupByExpression == null) {
363 return null;
364 }
365 ArrayList<Index> indexes = topTableFilter.getTable().getIndexes();
366 if (indexes != null) {
367 for (Index index : indexes) {
368 if (index.getIndexType().isScan()) {
369 continue;
370 }
371 if (index.getIndexType().isHash()) {
372 // does not allow scanning entries
373 continue;
374 }
375 if (isGroupSortedIndex(topTableFilter, index)) {
376 return index;
377 }
378 }
379 }
380 return null;
381 }
382
383 private boolean isGroupSortedIndex(TableFilter tableFilter, Index index) {
384 // check that all the GROUP BY expressions are part of the index
385 Column[] indexColumns = index.getColumns();
386 // also check that the first columns in the index are grouped
387 boolean[] grouped = new boolean[indexColumns.length];
388 outerLoop:
389 for (int i = 0, size = expressions.size(); i < size; i++) {
390 if (!groupByExpression[i]) {
391 continue;
392 }
393 Expression expr = expressions.get(i).getNonAliasExpression();
394 if (!(expr instanceof ExpressionColumn)) {
395 return false;
396 }
397 ExpressionColumn exprCol = (ExpressionColumn) expr;
398 for (int j = 0; j < indexColumns.length; ++j) {
399 if (tableFilter == exprCol.getTableFilter()) {
400 if (indexColumns[j].equals(exprCol.getColumn())) {
401 grouped[j] = true;
402 continue outerLoop;
403 }
404 }
405 }
406 // We didn't find a matching index column
407 // for one group by expression
408 return false;
409 }
410 // check that the first columns in the index are grouped
411 // good: index(a, b, c); group by b, a
412 // bad: index(a, b, c); group by a, c
413 for (int i = 1; i < grouped.length; i++) {
414 if (!grouped[i - 1] && grouped[i]) {
415 return false;
416 }
417 }
418 return true;
419 }
420
421 boolean isConditionMetForUpdate() {
422 if (isConditionMet()) {
423 int count = filters.size();
424 boolean notChanged = true;
425 for (int i = 0; i < count; i++) {
426 TableFilter tableFilter = filters.get(i);
427 if (!tableFilter.isJoinOuter() && !tableFilter.isJoinOuterIndirect()) {
428 Row row = tableFilter.get();
429 Table table = tableFilter.getTable();
430 // Views, function tables, links, etc. do not support locks
431 if (table.isRowLockable()) {
432 Row lockedRow = table.lockRow(session, row, forUpdate.getTimeoutMillis());
433 if (lockedRow == null) {
434 return false;
435 }
436 if (!row.hasSharedData(lockedRow)) {
437 tableFilter.set(lockedRow);
438 notChanged = false;
439 }
440 }
441 }
442 }
443 return notChanged || isConditionMet();
444 }
445 return false;
446 }
447
448 boolean isConditionMet() {
449 return condition == null || condition.getBooleanValue(session);
450 }
451
452 private void queryWindow(int columnCount, LocalResult result, long offset, boolean quickOffset) {
453 initGroupData(columnCount);
454 try {
455 gatherGroup(columnCount, DataAnalysisOperation.STAGE_WINDOW);
456 processGroupResult(columnCount, result, offset, quickOffset, false);
457 } finally {
458 groupData.reset();
459 }
460 }
461
462 private void queryGroupWindow(int columnCount, LocalResult result, long offset, boolean quickOffset) {
463 initGroupData(columnCount);
464 try {
465 gatherGroup(columnCount, DataAnalysisOperation.STAGE_GROUP);
466 try {
467 isGroupWindowStage2 = true;
468 while (groupData.next() != null) {
469 if (havingIndex < 0 || expressions.get(havingIndex).getBooleanValue(session)) {
470 updateAgg(columnCount, DataAnalysisOperation.STAGE_WINDOW);
471 } else {
472 groupData.remove();
473 }
474 }
475 groupData.done();
476 processGroupResult(columnCount, result, offset, quickOffset, /* Having was performed earlier */ false);
477 } finally {
478 isGroupWindowStage2 = false;
479 }
480 } finally {
481 groupData.reset();
482 }
483 }
484
485 private void queryGroup(int columnCount, LocalResult result, long offset, boolean quickOffset) {
486 initGroupData(columnCount);
487 try {
488 gatherGroup(columnCount, DataAnalysisOperation.STAGE_GROUP);
489 processGroupResult(columnCount, result, offset, quickOffset, true);
490 } finally {
491 groupData.reset();
492 }
493 }
494
495 private void initGroupData(int columnCount) {
496 if (groupData == null) {
497 setGroupData(SelectGroups.getInstance(session, expressions, isGroupQuery, groupIndex));
498 } else {
499 updateAgg(columnCount, DataAnalysisOperation.STAGE_RESET);
500 }
501 groupData.reset();
502 }
503
504 void setGroupData(final SelectGroups groupData) {
505 this.groupData = groupData;
506 topTableFilter.visit(f -> {
507 Select s = f.getSelect();
508 if (s != null) {
509 s.groupData = groupData;
510 }
511 });
512 }
513
514 private void gatherGroup(int columnCount, int stage) {
515 long rowNumber = 0;
516 setCurrentRowNumber(0);
517 while (topTableFilter.next()) {
518 setCurrentRowNumber(rowNumber + 1);
519 if (forUpdate != null ? isConditionMetForUpdate() : isConditionMet()) {
520 rowNumber++;
521 groupData.nextSource();
522 updateAgg(columnCount, stage);
523 }
524 }
525 groupData.done();
526 }
527
528
529 /**
530 * Update any aggregate expressions with the query stage.
531 * @param columnCount number of columns
532 * @param stage see STAGE_RESET/STAGE_GROUP/STAGE_WINDOW in DataAnalysisOperation
533 */
534 void updateAgg(int columnCount, int stage) {
535 for (int i = 0; i < columnCount; i++) {
536 if ((groupByExpression == null || !groupByExpression[i])
537 && (groupByCopies == null || groupByCopies[i] < 0)) {
538 Expression expr = expressions.get(i);
539 expr.updateAggregate(session, stage);
540 }
541 }
542 }
543
544 private void processGroupResult(int columnCount, LocalResult result, long offset, boolean quickOffset,
545 boolean withHaving) {
546 for (ValueRow currentGroupsKey; (currentGroupsKey = groupData.next()) != null;) {
547 Value[] row = constructGroupResultRow(currentGroupsKey.getList(), columnCount);
548 if (withHaving && isHavingNullOrFalse(row)) {
549 continue;
550 }
551 if (qualifyIndex >= 0 && !row[qualifyIndex].isTrue()) {
552 continue;
553 }
554 if (quickOffset && offset > 0) {
555 offset--;
556 continue;
557 }
558 result.addRow(rowForResult(row, columnCount));
559 }
560 }
561
562 private Value[] constructGroupResultRow(Value[] keyValues, int columnCount) {
563 Value[] row = new Value[columnCount];
564 if (groupIndex != null) {
565 for (int i = 0, l = groupIndex.length; i < l; i++) {
566 row[groupIndex[i]] = keyValues[i];
567 }
568 }
569 for (int i = 0; i < columnCount; i++) {
570 if (groupByExpression != null && groupByExpression[i]) {
571 continue;
572 }
573 if (groupByCopies != null) {
574 int original = groupByCopies[i];
575 if (original >= 0) {
576 row[i] = row[original];
577 continue;
578 }
579 }
580 row[i] = expressions.get(i).getValue(session);
581 }
582 return row;
583 }
584
585 /**
586 * Get the index that matches the ORDER BY list, if one exists. This is to
587 * avoid running a separate ORDER BY if an index can be used. This is
588 * specially important for large result sets, if only the first few rows are
589 * important (LIMIT is used)
590 *
591 * @return the index if one is found
592 */
593 private Index getSortIndex() {
594 if (sort == null) {
595 return null;
596 }
597 ArrayList<Column> sortColumns = Utils.newSmallArrayList();
598 int[] queryColumnIndexes = sort.getQueryColumnIndexes();
599 int queryIndexesLength = queryColumnIndexes.length;
600 int[] sortIndex = new int[queryIndexesLength];
601 for (int i = 0, j = 0; i < queryIndexesLength; i++) {
602 int idx = queryColumnIndexes[i];
603 if (idx < 0 || idx >= expressions.size()) {
604 throw DbException.getInvalidValueException("ORDER BY", idx + 1);
605 }
606 Expression expr = expressions.get(idx);
607 expr = expr.getNonAliasExpression();
608 if (expr.isConstant()) {
609 continue;
610 }
611 if (!(expr instanceof ExpressionColumn)) {
612 return null;
613 }
614 ExpressionColumn exprCol = (ExpressionColumn) expr;
615 if (exprCol.getTableFilter() != topTableFilter) {
616 return null;
617 }
618 sortColumns.add(exprCol.getColumn());
619 sortIndex[j++] = i;
620 }
621 Column[] sortCols = sortColumns.toArray(new Column[0]);
622 if (sortCols.length == 0) {
623 // sort just on constants - can use scan index
624 return topTableFilter.getTable().getScanIndex(session);
625 }
626 ArrayList<Index> list = topTableFilter.getTable().getIndexes();
627 if (list != null) {
628 int[] sortTypes = sort.getSortTypesWithNullOrdering();
629 DefaultNullOrdering defaultNullOrdering = getDatabase().getDefaultNullOrdering();
630 loop: for (Index index : list) {
631 if (index.getCreateSQL() == null) {
632 // can't use the scan index
633 continue;
634 }
635 if (index.getIndexType().isHash()) {
636 continue;
637 }
638 IndexColumn[] indexCols = index.getIndexColumns();
639 if (indexCols.length < sortCols.length) {
640 continue;
641 }
642 for (int j = 0; j < sortCols.length; j++) {
643 // the index and the sort order must start
644 // with the exact same columns
645 IndexColumn idxCol = indexCols[j];
646 Column sortCol = sortCols[j];
647 if (idxCol.column != sortCol) {
648 continue loop;
649 }
650 int sortType = sortTypes[sortIndex[j]];
651 if (sortCol.isNullable()
652 ? defaultNullOrdering.addExplicitNullOrdering(idxCol.sortType) != sortType
653 : (idxCol.sortType & SortOrder.DESCENDING) != (sortType & SortOrder.DESCENDING)) {
654 continue loop;
655 }
656 }
657 return index;
658 }
659 }
660 if (sortCols.length == 1 && sortCols[0].getColumnId() == -1) {
661 // special case: order by _ROWID_
662 Index index = topTableFilter.getTable().getScanIndex(session);
663 if (index.isRowIdIndex()) {
664 return index;
665 }
666 }
667 return null;
668 }
669
670 private void queryDistinct(ResultTarget result, long offset, long limitRows, boolean withTies,
671 boolean quickOffset) {
672 if (limitRows > 0 && offset > 0) {
673 limitRows += offset;
674 if (limitRows < 0) {
675 // Overflow
676 limitRows = Long.MAX_VALUE;
677 }
678 }
679 long rowNumber = 0;
680 setCurrentRowNumber(0);
681 Index index = topTableFilter.getIndex();
682 SearchRow first = null;
683 int columnIndex = index.getColumns()[0].getColumnId();
684 if (!quickOffset) {
685 offset = 0;
686 }
687 while (true) {
688 setCurrentRowNumber(++rowNumber);
689 Cursor cursor = index.findNext(session, first, null);
690 if (!cursor.next()) {
691 break;
692 }
693 SearchRow found = cursor.getSearchRow();
694 Value value = found.getValue(columnIndex);
695 if (first == null) {
696 first = index.getRowFactory().createRow();
697 }
698 first.setValue(columnIndex, value);
699 if (offset > 0) {
700 offset--;
701 continue;
702 }
703 result.addRow(value);
704 if ((sort == null || sortUsingIndex) && limitRows > 0 && rowNumber >= limitRows && !withTies) {
705 break;
706 }
707 }
708 }
709
710 private LazyResult queryFlat(int columnCount, ResultTarget result, long offset, long limitRows, boolean withTies,
711 boolean quickOffset) {
712 if (limitRows > 0 && offset > 0 && !quickOffset) {
713 limitRows += offset;
714 if (limitRows < 0) {
715 // Overflow
716 limitRows = Long.MAX_VALUE;
717 }
718 }
719 LazyResultQueryFlat lazyResult = new LazyResultQueryFlat(expressionArray, columnCount, forUpdate != null);
720 skipOffset(lazyResult, offset, quickOffset);
721 if (result == null) {
722 return lazyResult;
723 }
724 if (limitRows < 0 || sort != null && !sortUsingIndex || withTies && !quickOffset) {
725 limitRows = Long.MAX_VALUE;
726 }
727 Value[] row = null;
728 while (result.getRowCount() < limitRows && lazyResult.next()) {
729 row = lazyResult.currentRow();
730 result.addRow(row);
731 }
732 if (limitRows != Long.MAX_VALUE && withTies && sort != null && row != null) {
733 Value[] expected = row;
734 while (lazyResult.next()) {
735 row = lazyResult.currentRow();
736 if (sort.compare(expected, row) != 0) {
737 break;
738 }
739 result.addRow(row);
740 }
741 result.limitsWereApplied();
742 }
743 return null;
744 }
745
746 private static void skipOffset(LazyResultSelect lazyResult, long offset, boolean quickOffset) {
747 if (quickOffset) {
748 while (offset > 0 && lazyResult.skip()) {
749 offset--;
750 }
751 }
752 }
753
754 private void queryQuick(int columnCount, ResultTarget result, boolean skipResult) {
755 Value[] row = new Value[columnCount];
756 for (int i = 0; i < columnCount; i++) {
757 Expression expr = expressions.get(i);
758 row[i] = expr.getValue(session);
759 }
760 if (!skipResult) {
761 result.addRow(row);
762 }
763 }
764
765 @Override
766 protected ResultInterface queryWithoutCache(long maxRows, ResultTarget target) {
767 disableLazyForJoinSubqueries(topTableFilter);
768 OffsetFetch offsetFetch = getOffsetFetch(maxRows);
769 long offset = offsetFetch.offset;
770 long fetch = offsetFetch.fetch;
771 boolean fetchPercent = offsetFetch.fetchPercent;
772 boolean lazy = session.isLazyQueryExecution() &&
773 target == null && forUpdate == null && !isQuickAggregateQuery &&
774 fetch != 0 && !fetchPercent && !withTies && offset == 0 && isReadOnly();
775 int columnCount = expressions.size();
776 LocalResult result = null;
777 if (!lazy && (target == null ||
778 !getDatabase().getSettings().optimizeInsertFromSelect)) {
779 result = createLocalResult(result);
780 }
781 // Do not add rows before OFFSET to result if possible
782 boolean quickOffset = !fetchPercent;
783 if (sort != null && (!sortUsingIndex || isAnyDistinct())) {
784 result = createLocalResult(result);
785 result.setSortOrder(sort);
786 if (!sortUsingIndex) {
787 quickOffset = false;
788 }
789 }
790 if (distinct) {
791 result = createLocalResult(result);
792 if (!isDistinctQuery) {
793 quickOffset = false;
794 result.setDistinct();
795 }
796 } else if (distinctExpressions != null) {
797 quickOffset = false;
798 result = createLocalResult(result);
799 result.setDistinct(distinctIndexes);
800 }
801 if (isWindowQuery || isGroupQuery && !isGroupSortedQuery) {
802 result = createLocalResult(result);
803 }
804 if (!lazy && (fetch >= 0 || offset > 0)) {
805 result = createLocalResult(result);
806 }
807 topTableFilter.startQuery(session);
808 topTableFilter.reset();
809 topTableFilter.lock(session);
810 ResultTarget to = result != null ? result : target;
811 lazy &= to == null;
812 LazyResult lazyResult = null;
813 if (fetch != 0) {
814 // Cannot apply limit now if percent is specified
815 long limit = fetchPercent ? -1 : fetch;
816 if (isQuickAggregateQuery) {
817 queryQuick(columnCount, to, quickOffset && offset > 0);
818 } else if (isWindowQuery) {
819 if (isGroupQuery) {
820 queryGroupWindow(columnCount, result, offset, quickOffset);
821 } else {
822 queryWindow(columnCount, result, offset, quickOffset);
823 }
824 } else if (isGroupQuery) {
825 if (isGroupSortedQuery) {
826 lazyResult = queryGroupSorted(columnCount, to, offset, quickOffset);
827 } else {
828 queryGroup(columnCount, result, offset, quickOffset);
829 }
830 } else if (isDistinctQuery) {
831 queryDistinct(to, offset, limit, withTies, quickOffset);
832 } else {
833 lazyResult = queryFlat(columnCount, to, offset, limit, withTies, quickOffset);
834 }
835 if (quickOffset) {
836 offset = 0;
837 }
838 }
839 assert lazy == (lazyResult != null) : lazy;
840 if (lazyResult != null) {
841 if (fetch > 0) {
842 lazyResult.setLimit(fetch);
843 }
844 if (randomAccessResult) {
845 return convertToDistinct(lazyResult);
846 } else {
847 return lazyResult;
848 }
849 }
850 if (result != null) {
851 return finishResult(result, offset, fetch, fetchPercent, target);
852 }
853 return null;
854 }
855
856 private void disableLazyForJoinSubqueries(final TableFilter top) {
857 if (session.isLazyQueryExecution()) {
858 top.visit(f -> {
859 if (f != top && f.getTable().getTableType() == TableType.VIEW) {
860 QueryExpressionIndex idx = (QueryExpressionIndex) f.getIndex();
861 if (idx != null && idx.getQuery() != null) {
862 idx.getQuery().setNeverLazy(true);
863 }
864 }
865 });
866 }
867 }
868
869 private LocalResult createLocalResult(LocalResult old) {
870 return old != null ? old : new LocalResult(session, expressionArray, visibleColumnCount, resultColumnCount);
871 }
872
873 private void expandColumnList() {
874 // the expressions may change within the loop
875 for (int i = 0; i < expressions.size();) {
876 Expression expr = expressions.get(i);
877 if (!(expr instanceof Wildcard)) {
878 i++;
879 continue;
880 }
881 expressions.remove(i);
882 Wildcard w = (Wildcard) expr;
883 String tableAlias = w.getTableAlias();
884 boolean hasExceptColumns = w.getExceptColumns() != null;
885 HashMap<Column, ExpressionColumn> exceptTableColumns = null;
886 if (tableAlias == null) {
887 if (hasExceptColumns) {
888 for (TableFilter filter : filters) {
889 w.mapColumns(filter, 1, Expression.MAP_INITIAL);
890 }
891 exceptTableColumns = w.mapExceptColumns();
892 }
893 for (TableFilter filter : filters) {
894 i = expandColumnList(filter, i, false, exceptTableColumns);
895 }
896 } else {
897 Database db = getDatabase();
898 String schemaName = w.getSchemaName();
899 TableFilter filter = null;
900 for (TableFilter f : filters) {
901 if (db.equalsIdentifiers(tableAlias, f.getTableAlias())) {
902 if (schemaName == null || db.equalsIdentifiers(schemaName, f.getSchemaName())) {
903 if (hasExceptColumns) {
904 w.mapColumns(f, 1, Expression.MAP_INITIAL);
905 exceptTableColumns = w.mapExceptColumns();
906 }
907 filter = f;
908 break;
909 }
910 }
911 }
912 if (filter == null) {
913 throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableAlias);
914 }
915 i = expandColumnList(filter, i, true, exceptTableColumns);
916 }
917 }
918 }
919
920 private int expandColumnList(TableFilter filter, int index, boolean forAlias,
921 HashMap<Column, ExpressionColumn> except) {
922 String schema = filter.getSchemaName();
923 String alias = filter.getTableAlias();
924 if (forAlias) {
925 for (Column c : filter.getTable().getColumns()) {
926 index = addExpandedColumn(filter, index, except, schema, alias, c);
927 }
928 } else {
929 LinkedHashMap<Column, Column> commonJoinColumns = filter.getCommonJoinColumns();
930 if (commonJoinColumns != null) {
931 TableFilter replacementFilter = filter.getCommonJoinColumnsFilter();
932 String replacementSchema = replacementFilter.getSchemaName();
933 String replacementAlias = replacementFilter.getTableAlias();
934 for (Entry<Column, Column> entry : commonJoinColumns.entrySet()) {
935 Column left = entry.getKey(), right = entry.getValue();
936 if (!filter.isCommonJoinColumnToExclude(right)
937 && (except == null || except.remove(left) == null && except.remove(right) == null)) {
938 Database database = getDatabase();
939 Expression e;
940 if (left == right
941 || DataType.hasTotalOrdering(left.getType().getValueType())
942 && DataType.hasTotalOrdering(right.getType().getValueType())) {
943 e = new ExpressionColumn(database, replacementSchema, replacementAlias,
944 replacementFilter.getColumnName(right));
945 } else {
946 e = new Alias(new CoalesceFunction(CoalesceFunction.COALESCE,
947 new ExpressionColumn(database, schema, alias, filter.getColumnName(left)),
948 new ExpressionColumn(database, replacementSchema, replacementAlias,
949 replacementFilter.getColumnName(right))), //
950 left.getName(), true);
951 }
952 expressions.add(index++, e);
953 }
954 }
955 }
956 for (Column c : filter.getTable().getColumns()) {
957 if (commonJoinColumns == null || !commonJoinColumns.containsKey(c)) {
958 if (!filter.isCommonJoinColumnToExclude(c)) {
959 index = addExpandedColumn(filter, index, except, schema, alias, c);
960 }
961 }
962 }
963 }
964 return index;
965 }
966
967 private int addExpandedColumn(TableFilter filter, int index, HashMap<Column, ExpressionColumn> except,
968 String schema, String alias, Column c) {
969 if ((except == null || except.remove(c) == null) && c.getVisible()) {
970 ExpressionColumn ec = new ExpressionColumn(getDatabase(), schema, alias, filter.getColumnName(c));
971 expressions.add(index++, ec);
972 }
973 return index;
974 }
975
976 @Override
977 public void init() {
978 if (checkInit) {
979 throw DbException.getInternalError();
980 }
981 filters.sort(TableFilter.ORDER_IN_FROM_COMPARATOR);
982 expandColumnList();
983 if ((visibleColumnCount = expressions.size()) > Constants.MAX_COLUMNS) {
984 throw DbException.get(ErrorCode.TOO_MANY_COLUMNS_1, "" + Constants.MAX_COLUMNS);
985 }
986 ArrayList<String> expressionSQL;
987 if (distinctExpressions != null || orderList != null || group != null) {
988 expressionSQL = new ArrayList<>(visibleColumnCount);
989 for (int i = 0; i < visibleColumnCount; i++) {
990 Expression expr = expressions.get(i);
991 expr = expr.getNonAliasExpression();
992 expressionSQL.add(expr.getSQL(DEFAULT_SQL_FLAGS, WITHOUT_PARENTHESES));
993 }
994 } else {
995 expressionSQL = null;
996 }
997 if (distinctExpressions != null) {
998 BitSet set = new BitSet();
999 for (Expression e : distinctExpressions) {
1000 set.set(initExpression(expressionSQL, e, false, filters));
1001 }
1002 int idx = 0, cnt = set.cardinality();
1003 distinctIndexes = new int[cnt];
1004 for (int i = 0; i < cnt; i++) {
1005 idx = set.nextSetBit(idx);
1006 distinctIndexes[i] = idx;
1007 idx++;
1008 }
1009 }
1010 if (orderList != null) {
1011 initOrder(expressionSQL, isAnyDistinct(), filters);
1012 }
1013 resultColumnCount = expressions.size();
1014 if (having != null) {
1015 expressions.add(having);
1016 havingIndex = expressions.size() - 1;
1017 having = null;
1018 } else {
1019 havingIndex = -1;
1020 }
1021 if (qualify != null) {
1022 expressions.add(qualify);
1023 qualifyIndex = expressions.size() - 1;
1024 qualify = null;
1025 } else {
1026 qualifyIndex = -1;
1027 }
1028
1029 if (withTies && !hasOrder()) {
1030 throw DbException.get(ErrorCode.WITH_TIES_WITHOUT_ORDER_BY);
1031 }
1032
1033 Database db = getDatabase();
1034
1035 // first the select list (visible columns),
1036 // then 'ORDER BY' expressions,
1037 // then 'HAVING' expressions,
1038 // and 'GROUP BY' expressions at the end
1039 if (group != null) {
1040 int size = group.size();
1041 int expSize = expressionSQL.size();
1042 int fullExpSize = expressions.size();
1043 if (fullExpSize > expSize) {
1044 expressionSQL.ensureCapacity(fullExpSize);
1045 for (int i = expSize; i < fullExpSize; i++) {
1046 expressionSQL.add(expressions.get(i).getSQL(DEFAULT_SQL_FLAGS, WITHOUT_PARENTHESES));
1047 }
1048 }
1049 groupIndex = new int[size];
1050 for (int i = 0; i < size; i++) {
1051 Expression expr = group.get(i);
1052 String sql = expr.getSQL(DEFAULT_SQL_FLAGS, WITHOUT_PARENTHESES);
1053 int found = -1;
1054 for (int j = 0; j < expSize; j++) {
1055 String s2 = expressionSQL.get(j);
1056 if (db.equalsIdentifiers(s2, sql)) {
1057 found = mergeGroupByExpressions(db, j, expressionSQL, false);
1058 break;
1059 }
1060 }
1061 if (found < 0) {
1062 // special case: GROUP BY a column alias
1063 for (int j = 0; j < expSize; j++) {
1064 Expression e = expressions.get(j);
1065 if (db.equalsIdentifiers(sql, e.getAlias(session, j))) {
1066 found = mergeGroupByExpressions(db, j, expressionSQL, true);
1067 break;
1068 }
1069 sql = expr.getAlias(session, j);
1070 if (db.equalsIdentifiers(sql, e.getAlias(session, j))) {
1071 found = mergeGroupByExpressions(db, j, expressionSQL, true);
1072 break;
1073 }
1074 }
1075 }
1076 if (found < 0) {
1077 int index = expressions.size();
1078 groupIndex[i] = index;
1079 expressions.add(expr);
1080 } else {
1081 groupIndex[i] = found;
1082 }
1083 }
1084 checkUsed: if (groupByCopies != null) {
1085 for (int i : groupByCopies) {
1086 if (i >= 0) {
1087 break checkUsed;
1088 }
1089 }
1090 groupByCopies = null;
1091 }
1092 groupByExpression = new boolean[expressions.size()];
1093 for (int gi : groupIndex) {
1094 groupByExpression[gi] = true;
1095 }
1096 group = null;
1097 }
1098 // map columns in select list and condition
1099 for (TableFilter f : filters) {
1100 mapColumns(f, 0);
1101 }
1102 mapCondition(havingIndex);
1103 mapCondition(qualifyIndex);
1104 checkInit = true;
1105 }
1106
1107 private void mapCondition(int index) {
1108 if (index >= 0) {
1109 Expression expr = expressions.get(index);
1110 SelectListColumnResolver res = new SelectListColumnResolver(this);
1111 expr.mapColumns(res, 0, Expression.MAP_INITIAL);
1112 }
1113 }
1114
1115 private int mergeGroupByExpressions(Database db, int index, ArrayList<String> expressionSQL, //
1116 boolean scanPrevious) {
1117
1118 /*
1119 * -1: uniqueness of expression is not known yet
1120 *
1121 * -2: expression that is used as a source for a copy or does not have
1122 * copies
1123 *
1124 * >=0: expression is a copy of expression at this index
1125 */
1126 if (groupByCopies != null) {
1127 int c = groupByCopies[index];
1128 if (c >= 0) {
1129 return c;
1130 } else if (c == -2) {
1131 return index;
1132 }
1133 } else {
1134 groupByCopies = new int[expressionSQL.size()];
1135 Arrays.fill(groupByCopies, -1);
1136 }
1137 String sql = expressionSQL.get(index);
1138 if (scanPrevious) {
1139 /*
1140 * If expression was matched using an alias previous expressions may
1141 * be identical.
1142 */
1143 for (int i = 0; i < index; i++) {
1144 if (db.equalsIdentifiers(sql, expressionSQL.get(i))) {
1145 index = i;
1146 break;
1147 }
1148 }
1149 }
1150 int l = expressionSQL.size();
1151 for (int i = index + 1; i < l; i++) {
1152 if (db.equalsIdentifiers(sql, expressionSQL.get(i))) {
1153 groupByCopies[i] = index;
1154 }
1155 }
1156 groupByCopies[index] = -2;
1157 return index;
1158 }
1159
1160 @Override
1161 public void prepareExpressions() {
1162 if (orderList != null) {
1163 prepareOrder(orderList, expressions.size());
1164 }
1165 ExpressionNames expressionNames = session.getMode().expressionNames;
1166 if (expressionNames == ExpressionNames.ORIGINAL_SQL || expressionNames == ExpressionNames.POSTGRESQL_STYLE) {
1167 optimizeExpressionsAndPreserveAliases();
1168 } else {
1169 for (int i = 0; i < expressions.size(); i++) {
1170 expressions.set(i, expressions.get(i).optimize(session));
1171 }
1172 }
1173 if (sort != null) {
1174 cleanupOrder();
1175 }
1176 if (condition != null) {
1177 condition = condition.optimizeCondition(session);
1178 }
1179 if (isGroupQuery && groupIndex == null && havingIndex < 0 && qualifyIndex < 0 && condition == null
1180 && filters.size() == 1) {
1181 isQuickAggregateQuery = isEverything(ExpressionVisitor.getOptimizableVisitor(filters.get(0).getTable()));
1182 }
1183 expressionArray = expressions.toArray(new Expression[0]);
1184 }
1185
1186 @Override
1187 public void preparePlan() {
1188 if (condition != null) {
1189 for (TableFilter f : filters) {
1190 // outer joins: must not add index conditions such as
1191 // "c is null" - example:
1192 // create table parent(p int primary key) as select 1;
1193 // create table child(c int primary key, pc int);
1194 // insert into child values(2, 1);
1195 // select p, c from parent
1196 // left outer join child on p = pc where c is null;
1197 if (!f.isJoinOuter() && !f.isJoinOuterIndirect()) {
1198 condition.createIndexConditions(session, f);
1199 }
1200 }
1201 }
1202 cost = preparePlan(session.isParsingCreateView());
1203 if (distinct && getDatabase().getSettings().optimizeDistinct &&
1204 !isGroupQuery && filters.size() == 1 &&
1205 expressions.size() == 1 && condition == null) {
1206 Expression expr = expressions.get(0);
1207 expr = expr.getNonAliasExpression();
1208 if (expr instanceof ExpressionColumn) {
1209 Column column = ((ExpressionColumn) expr).getColumn();
1210 int selectivity = column.getSelectivity();
1211 Index columnIndex = topTableFilter.getTable().
1212 getIndexForColumn(column, false, true);
1213 if (columnIndex != null &&
1214 selectivity != Constants.SELECTIVITY_DEFAULT &&
1215 selectivity < 20) {
1216 Index current = topTableFilter.getIndex();
1217 // if another index is faster
1218 if (current == null || current.getIndexType().isScan() || columnIndex == current) {
1219 topTableFilter.setIndex(columnIndex);
1220 isDistinctQuery = true;
1221 }
1222 }
1223 }
1224 }
1225 if (sort != null && !isQuickAggregateQuery && !isGroupQuery) {
1226 Index index = getSortIndex();
1227 Index current = topTableFilter.getIndex();
1228 if (index != null && current != null) {
1229 if (current.getIndexType().isScan() || current == index) {
1230 topTableFilter.setIndex(index);
1231 if (!topTableFilter.hasInComparisons()) {
1232 // in(select ...) and in(1,2,3) may return the key in
1233 // another order
1234 sortUsingIndex = true;
1235 }
1236 } else if (index.getIndexColumns() != null
1237 && index.getIndexColumns().length >= current
1238 .getIndexColumns().length) {
1239 IndexColumn[] sortColumns = index.getIndexColumns();
1240 IndexColumn[] currentColumns = current.getIndexColumns();
1241 boolean swapIndex = false;
1242 for (int i = 0; i < currentColumns.length; i++) {
1243 if (sortColumns[i].column != currentColumns[i].column) {
1244 swapIndex = false;
1245 break;
1246 }
1247 if (sortColumns[i].sortType != currentColumns[i].sortType) {
1248 swapIndex = true;
1249 }
1250 }
1251 if (swapIndex) {
1252 topTableFilter.setIndex(index);
1253 sortUsingIndex = true;
1254 }
1255 }
1256 }
1257 if (sortUsingIndex && forUpdate != null && !topTableFilter.getIndex().isRowIdIndex()) {
1258 sortUsingIndex = false;
1259 }
1260 }
1261 if (!isQuickAggregateQuery && isGroupQuery) {
1262 Index index = getGroupSortedIndex();
1263 if (index != null) {
1264 Index current = topTableFilter.getIndex();
1265 if (current != null && (current.getIndexType().isScan() || current == index)) {
1266 topTableFilter.setIndex(index);
1267 isGroupSortedQuery = true;
1268 }
1269 }
1270 }
1271 isPrepared = true;
1272 }
1273
1274 private void optimizeExpressionsAndPreserveAliases() {
1275 for (int i = 0; i < expressions.size(); i++) {
1276 Expression original = expressions.get(i);
1277 /*
1278 * TODO cannot evaluate optimized now, because some optimize()
1279 * methods violate their contract and modify the original
1280 * expression.
1281 */
1282 Expression optimized;
1283 if (i < visibleColumnCount) {
1284 String alias = original.getAlias(session, i);
1285 optimized = original.optimize(session);
1286 if (!optimized.getAlias(session, i).equals(alias)) {
1287 optimized = new Alias(optimized, alias, true);
1288 }
1289 } else {
1290 optimized = original.optimize(session);
1291 }
1292 expressions.set(i, optimized);
1293 }
1294 }
1295
1296 @Override
1297 public double getCost() {
1298 return cost;
1299 }
1300
1301 @Override
1302 public HashSet<Table> getTables() {
1303 HashSet<Table> set = new HashSet<>();
1304 for (TableFilter filter : filters) {
1305 set.add(filter.getTable());
1306 }
1307 return set;
1308 }
1309
1310 @Override
1311 public void fireBeforeSelectTriggers() {
1312 for (TableFilter filter : filters) {
1313 filter.getTable().fire(session, Trigger.SELECT, true);
1314 }
1315 }
1316
1317 private double preparePlan(boolean parse) {
1318 TableFilter[] topArray = topFilters.toArray(new TableFilter[0]);
1319 for (TableFilter t : topArray) {
1320 t.createIndexConditions();
1321 t.setFullCondition(condition);
1322 }
1323
1324 Optimizer optimizer = new Optimizer(topArray, condition, session);
1325 optimizer.optimize(parse);
1326 topTableFilter = optimizer.getTopFilter();
1327 double planCost = optimizer.getCost();
1328
1329 setEvaluatableRecursive(topTableFilter);
1330
1331 if (!parse) {
1332 topTableFilter.prepare();
1333 }
1334 return planCost;
1335 }
1336
1337 private void setEvaluatableRecursive(TableFilter f) {
1338 for (; f != null; f = f.getJoin()) {
1339 f.setEvaluatable(f, true);
1340 if (condition != null) {
1341 condition.setEvaluatable(f, true);
1342 }
1343 TableFilter n = f.getNestedJoin();
1344 if (n != null) {
1345 setEvaluatableRecursive(n);
1346 }
1347 Expression on = f.getJoinCondition();
1348 if (on != null) {
1349 if (!on.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR)) {
1350 // need to check that all added are bound to a table
1351 on = on.optimize(session);
1352 if (!f.isJoinOuter() && !f.isJoinOuterIndirect()) {
1353 f.removeJoinCondition();
1354 addCondition(on);
1355 }
1356 }
1357 }
1358 on = f.getFilterCondition();
1359 if (on != null) {
1360 if (!on.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR)) {
1361 f.removeFilterCondition();
1362 addCondition(on);
1363 }
1364 }
1365 // this is only important for subqueries, so they know
1366 // the result columns are evaluatable
1367 for (Expression e : expressions) {
1368 e.setEvaluatable(f, true);
1369 }
1370 }
1371 }
1372
1373 @Override
1374 public String getPlanSQL(int sqlFlags) {
1375 // can not use the field sqlStatement because the parameter
1376 // indexes may be incorrect: ? may be in fact ?2 for a subquery
1377 // but indexes may be set manually as well
1378 Expression[] exprList = expressions.toArray(new Expression[0]);
1379 StringBuilder builder = new StringBuilder();
1380 for (TableFilter f : topFilters) {
1381 Table t = f.getTable();
1382 TableView tableView = t instanceof TableView ? (TableView) t : null;
1383 if (tableView != null && tableView.isRecursive() && tableView.isTableExpression()) {
1384
1385 if (!tableView.isTemporary()) {
1386 // skip the generation of plan SQL for this already recursive persistent CTEs,
1387 // since using a with statement will re-create the common table expression
1388 // views.
1389 } else {
1390 builder.append("WITH RECURSIVE ");
1391 t.getSchema().getSQL(builder, sqlFlags).append('.');
1392 ParserUtil.quoteIdentifier(builder, t.getName(), sqlFlags).append('(');
1393 Column.writeColumns(builder, t.getColumns(), sqlFlags);
1394 builder.append(") AS ");
1395 t.getSQL(builder, sqlFlags).append('\n');
1396 }
1397 }
1398 }
1399 if (isExplicitTable) {
1400 builder.append("TABLE ");
1401 filters.get(0).getPlanSQL(builder, false, sqlFlags);
1402 } else {
1403 builder.append("SELECT");
1404 if (isAnyDistinct()) {
1405 builder.append(" DISTINCT");
1406 if (distinctExpressions != null) {
1407 Expression.writeExpressions(builder.append(" ON("), distinctExpressions, sqlFlags).append(')');
1408 }
1409 }
1410 for (int i = 0; i < visibleColumnCount; i++) {
1411 if (i > 0) {
1412 builder.append(',');
1413 }
1414 builder.append('\n');
1415 StringUtils.indent(builder, exprList[i].getSQL(sqlFlags, WITHOUT_PARENTHESES), 4, false);
1416 }
1417 TableFilter filter = topTableFilter;
1418 if (filter == null) {
1419 int count = topFilters.size();
1420 if (count != 1 || !topFilters.get(0).isNoFromClauseFilter()) {
1421 builder.append("\nFROM ");
1422 boolean isJoin = false;
1423 for (int i = 0; i < count; i++) {
1424 isJoin = getPlanFromFilter(builder, sqlFlags, topFilters.get(i), isJoin);
1425 }
1426 }
1427 } else if (!filter.isNoFromClauseFilter()) {
1428 getPlanFromFilter(builder.append("\nFROM "), sqlFlags, filter, false);
1429 }
1430 if (condition != null) {
1431 getFilterSQL(builder, "\nWHERE ", condition, sqlFlags);
1432 }
1433 if (groupIndex != null) {
1434 builder.append("\nGROUP BY ");
1435 for (int i = 0, l = groupIndex.length; i < l; i++) {
1436 if (i > 0) {
1437 builder.append(", ");
1438 }
1439 exprList[groupIndex[i]].getNonAliasExpression().getUnenclosedSQL(builder, sqlFlags);
1440 }
1441 } else if (group != null) {
1442 builder.append("\nGROUP BY ");
1443 for (int i = 0, l = group.size(); i < l; i++) {
1444 if (i > 0) {
1445 builder.append(", ");
1446 }
1447 group.get(i).getUnenclosedSQL(builder, sqlFlags);
1448 }
1449 } else emptyGroupingSet: if (isGroupQuery && having == null && havingIndex < 0) {
1450 for (int i = 0; i < visibleColumnCount; i++) {
1451 if (containsAggregate(exprList[i])) {
1452 break emptyGroupingSet;
1453 }
1454 }
1455 builder.append("\nGROUP BY ()");
1456 }
1457 getFilterSQL(builder, "\nHAVING ", exprList, having, havingIndex, sqlFlags);
1458 getFilterSQL(builder, "\nQUALIFY ", exprList, qualify, qualifyIndex, sqlFlags);
1459 }
1460 appendEndOfQueryToSQL(builder, sqlFlags, exprList);
1461 if (forUpdate != null) {
1462 forUpdate.getSQL(builder, sqlFlags);
1463 }
1464 if ((sqlFlags & ADD_PLAN_INFORMATION) != 0) {
1465 if (isQuickAggregateQuery) {
1466 builder.append("\n/* direct lookup */");
1467 }
1468 if (isDistinctQuery) {
1469 builder.append("\n/* distinct */");
1470 }
1471 if (sortUsingIndex) {
1472 builder.append("\n/* index sorted */");
1473 }
1474 if (isGroupQuery) {
1475 if (isGroupSortedQuery) {
1476 builder.append("\n/* group sorted */");
1477 }
1478 }
1479 // builder.append("\n/* cost: " + cost + " */");
1480 }
1481 return builder.toString();
1482 }
1483
1484 private static boolean getPlanFromFilter(StringBuilder builder, int sqlFlags, TableFilter f, boolean isJoin) {
1485 do {
1486 if (isJoin) {
1487 builder.append('\n');
1488 }
1489 f.getPlanSQL(builder, isJoin, sqlFlags);
1490 isJoin = true;
1491 } while ((f = f.getJoin()) != null);
1492 return isJoin;
1493 }
1494
1495 private static void getFilterSQL(StringBuilder builder, String sql, Expression[] exprList, Expression condition,
1496 int conditionIndex, int sqlFlags) {
1497 if (condition != null) {
1498 getFilterSQL(builder, sql, condition, sqlFlags);
1499 } else if (conditionIndex >= 0) {
1500 getFilterSQL(builder, sql, exprList[conditionIndex], sqlFlags);
1501 }
1502 }
1503
1504 private static void getFilterSQL(StringBuilder builder, String sql, Expression condition, int sqlFlags) {
1505 condition.getNonAliasExpression().getUnenclosedSQL(builder.append(sql), sqlFlags);
1506 }
1507
1508 private static boolean containsAggregate(Expression expression) {
1509 if (expression instanceof DataAnalysisOperation) {
1510 if (((DataAnalysisOperation) expression).isAggregate()) {
1511 return true;
1512 }
1513 }
1514 for (int i = 0, l = expression.getSubexpressionCount(); i < l; i++) {
1515 if (containsAggregate(expression.getSubexpression(i))) {
1516 return true;
1517 }
1518 }
1519 return false;
1520 }
1521
1522 public void setHaving(Expression having) {
1523 this.having = having;
1524 }
1525
1526 public Expression getHaving() {
1527 return having;
1528 }
1529
1530 public void setQualify(Expression qualify) {
1531 this.qualify = qualify;
1532 }
1533
1534 public Expression getQualify() {
1535 return qualify;
1536 }
1537
1538 public TableFilter getTopTableFilter() {
1539 return topTableFilter;
1540 }
1541
1542 @Override
1543 public ForUpdate getForUpdate() {
1544 return forUpdate;
1545 }
1546
1547 @Override
1548 public void setForUpdate(ForUpdate b) {
1549 if (b != null && (isAnyDistinct() || isGroupQuery)) {
1550 throw DbException.get(ErrorCode.FOR_UPDATE_IS_NOT_ALLOWED_IN_DISTINCT_OR_GROUPED_SELECT);
1551 }
1552 this.forUpdate = b;
1553 }
1554
1555 @Override
1556 public void mapColumns(ColumnResolver resolver, int level) {
1557 for (Expression e : expressions) {
1558 e.mapColumns(resolver, level, Expression.MAP_INITIAL);
1559 }
1560 if (condition != null) {
1561 condition.mapColumns(resolver, level, Expression.MAP_INITIAL);
1562 }
1563 }
1564
1565 @Override
1566 public void setEvaluatable(TableFilter tableFilter, boolean b) {
1567 for (Expression e : expressions) {
1568 e.setEvaluatable(tableFilter, b);
1569 }
1570 if (condition != null) {
1571 condition.setEvaluatable(tableFilter, b);
1572 }
1573 }
1574
1575 /**
1576 * Check if this is an aggregate query with direct lookup, for example a
1577 * query of the type SELECT COUNT(*) FROM TEST or
1578 * SELECT MAX(ID) FROM TEST.
1579 *
1580 * @return true if a direct lookup is possible
1581 */
1582 public boolean isQuickAggregateQuery() {
1583 return isQuickAggregateQuery;
1584 }
1585
1586 /**
1587 * Checks if this query is a group query.
1588 *
1589 * @return whether this query is a group query.
1590 */
1591 public boolean isGroupQuery() {
1592 return isGroupQuery;
1593 }
1594
1595 /**
1596 * Checks if this query contains window functions.
1597 *
1598 * @return whether this query contains window functions
1599 */
1600 public boolean isWindowQuery() {
1601 return isWindowQuery;
1602 }
1603
1604 /**
1605 * Checks if window stage of group window query is performed. If true,
1606 * column resolver may not be used.
1607 *
1608 * @return true if window stage of group window query is performed
1609 */
1610 public boolean isGroupWindowStage2() {
1611 return isGroupWindowStage2;
1612 }
1613
1614 @Override
1615 public void addGlobalCondition(Parameter param, int columnId, int comparisonType) {
1616 addParameter(param);
1617 Expression comp;
1618 Expression col = expressions.get(columnId);
1619 col = col.getNonAliasExpression();
1620 if (col.isEverything(ExpressionVisitor.QUERY_COMPARABLE_VISITOR)) {
1621 comp = new Comparison(comparisonType, col, param, false);
1622 } else {
1623 // this condition will always evaluate to true, but need to
1624 // add the parameter, so it can be set later
1625 comp = new Comparison(Comparison.EQUAL_NULL_SAFE, param, param, false);
1626 }
1627 comp = comp.optimize(session);
1628 if (isWindowQuery) {
1629 qualify = addGlobalCondition(qualify, comp);
1630 } else if (isGroupQuery) {
1631 for (int i = 0; groupIndex != null && i < groupIndex.length; i++) {
1632 if (groupIndex[i] == columnId) {
1633 condition = addGlobalCondition(condition, comp);
1634 return;
1635 }
1636 }
1637 if (havingIndex >= 0) {
1638 having = expressions.get(havingIndex);
1639 }
1640 having = addGlobalCondition(having, comp);
1641 } else {
1642 condition = addGlobalCondition(condition, comp);
1643 }
1644 }
1645
1646 private static Expression addGlobalCondition(Expression condition, Expression additional) {
1647 if (!(condition instanceof ConditionLocalAndGlobal)) {
1648 return new ConditionLocalAndGlobal(condition, additional);
1649 }
1650 Expression oldLocal, oldGlobal;
1651 if (condition.getSubexpressionCount() == 1) {
1652 oldLocal = null;
1653 oldGlobal = condition.getSubexpression(0);
1654 } else {
1655 oldLocal = condition.getSubexpression(0);
1656 oldGlobal = condition.getSubexpression(1);
1657 }
1658 return new ConditionLocalAndGlobal(oldLocal, new ConditionAndOr(ConditionAndOr.AND, oldGlobal, additional));
1659 }
1660
1661 @Override
1662 public void updateAggregate(SessionLocal s, int stage) {
1663 for (Expression e : expressions) {
1664 e.updateAggregate(s, stage);
1665 }
1666 if (condition != null) {
1667 condition.updateAggregate(s, stage);
1668 }
1669 if (having != null) {
1670 having.updateAggregate(s, stage);
1671 }
1672 if (qualify != null) {
1673 qualify.updateAggregate(s, stage);
1674 }
1675 }
1676
1677 @Override
1678 public boolean isEverything(ExpressionVisitor visitor) {
1679 switch (visitor.getType()) {
1680 case ExpressionVisitor.DETERMINISTIC: {
1681 if (forUpdate != null) {
1682 return false;
1683 }
1684 for (TableFilter f : filters) {
1685 if (!f.getTable().isDeterministic()) {
1686 return false;
1687 }
1688 }
1689 break;
1690 }
1691 case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID: {
1692 for (TableFilter f : filters) {
1693 long m = f.getTable().getMaxDataModificationId();
1694 visitor.addDataModificationId(m);
1695 }
1696 break;
1697 }
1698 case ExpressionVisitor.EVALUATABLE: {
1699 if (!getDatabase().getSettings().optimizeEvaluatableSubqueries) {
1700 return false;
1701 }
1702 break;
1703 }
1704 case ExpressionVisitor.GET_DEPENDENCIES: {
1705 for (TableFilter f : filters) {
1706 Table table = f.getTable();
1707 visitor.addDependency(table);
1708 table.addDependencies(visitor.getDependencies());
1709 }
1710 break;
1711 }
1712 default:
1713 }
1714 ExpressionVisitor v2 = visitor.incrementQueryLevel(1);
1715 for (Expression e : expressions) {
1716 if (!e.isEverything(v2)) {
1717 return false;
1718 }
1719 }
1720 for (TableFilter f : filters) {
1721 Expression c = f.getJoinCondition();
1722 if (c != null && !c.isEverything(v2)) {
1723 return false;
1724 }
1725 }
1726 if (condition != null && !condition.isEverything(v2)) {
1727 return false;
1728 }
1729 if (having != null && !having.isEverything(v2)) {
1730 return false;
1731 }
1732 if (qualify != null && !qualify.isEverything(v2)) {
1733 return false;
1734 }
1735 return true;
1736 }
1737
1738
1739 @Override
1740 public boolean isCacheable() {
1741 return forUpdate == null;
1742 }
1743
1744 @Override
1745 public boolean allowGlobalConditions() {
1746 return offsetExpr == null && fetchExpr == null && distinctExpressions == null;
1747 }
1748
1749 public SortOrder getSortOrder() {
1750 return sort;
1751 }
1752
1753 /**
1754 * Returns parent select, or null.
1755 *
1756 * @return parent select, or null
1757 */
1758 public Select getParentSelect() {
1759 return parentSelect;
1760 }
1761
1762 @Override
1763 public boolean isConstantQuery() {
1764 if (!super.isConstantQuery() || distinctExpressions != null || condition != null || isGroupQuery
1765 || isWindowQuery || !isNoFromClause()) {
1766 return false;
1767 }
1768 for (int i = 0; i < visibleColumnCount; i++) {
1769 if (!expressions.get(i).isConstant()) {
1770 return false;
1771 }
1772 }
1773 return true;
1774 }
1775
1776 @Override
1777 public Expression getIfSingleRow() {
1778 if (offsetExpr != null || fetchExpr != null || condition != null || isGroupQuery || isWindowQuery
1779 || !isNoFromClause()) {
1780 return null;
1781 }
1782 if (visibleColumnCount == 1) {
1783 return expressions.get(0);
1784 }
1785 Expression[] array = new Expression[visibleColumnCount];
1786 for (int i = 0; i < visibleColumnCount; i++) {
1787 array[i] = expressions.get(i);
1788 }
1789 return new ExpressionList(array, false);
1790 }
1791
1792 private boolean isNoFromClause() {
1793 if (topTableFilter != null) {
1794 return topTableFilter.isNoFromClauseFilter();
1795 } else if (topFilters.size() == 1) {
1796 return topFilters.get(0).isNoFromClauseFilter();
1797 }
1798 return false;
1799 }
1800
1801 /**
1802 * Lazy execution for this select.
1803 */
1804 private abstract class LazyResultSelect extends LazyResult {
1805
1806 long rowNumber;
1807 int columnCount;
1808
1809 LazyResultSelect(Expression[] expressions, int columnCount) {
1810 super(getSession(), expressions);
1811 this.columnCount = columnCount;
1812 setCurrentRowNumber(0);
1813 }
1814
1815 @Override
1816 public final int getVisibleColumnCount() {
1817 return visibleColumnCount;
1818 }
1819
1820 @Override
1821 public void reset() {
1822 super.reset();
1823 topTableFilter.reset();
1824 setCurrentRowNumber(0);
1825 rowNumber = 0;
1826 }
1827 }
1828
1829 /**
1830 * Lazy execution for a flat query.
1831 */
1832 private final class LazyResultQueryFlat extends LazyResultSelect {
1833
1834 private boolean forUpdate;
1835
1836 LazyResultQueryFlat(Expression[] expressions, int columnCount, boolean forUpdate) {
1837 super(expressions, columnCount);
1838 this.forUpdate = forUpdate;
1839 }
1840
1841 @Override
1842 protected Value[] fetchNextRow() {
1843 while (topTableFilter.next()) {
1844 setCurrentRowNumber(rowNumber + 1);
1845 // This method may lock rows
1846 if (forUpdate ? isConditionMetForUpdate() : isConditionMet()) {
1847 ++rowNumber;
1848 Value[] row = new Value[columnCount];
1849 for (int i = 0; i < columnCount; i++) {
1850 Expression expr = expressions.get(i);
1851 row[i] = expr.getValue(getSession());
1852 }
1853 return row;
1854 }
1855 }
1856 return null;
1857 }
1858
1859 @Override
1860 protected boolean skipNextRow() {
1861 while (topTableFilter.next()) {
1862 setCurrentRowNumber(rowNumber + 1);
1863 // This method does not lock rows
1864 if (isConditionMet()) {
1865 ++rowNumber;
1866 return true;
1867 }
1868 }
1869 return false;
1870 }
1871
1872 }
1873
1874 /**
1875 * Lazy execution for a group sorted query.
1876 */
1877 private final class LazyResultGroupSorted extends LazyResultSelect {
1878
1879 private Value[] previousKeyValues;
1880
1881 LazyResultGroupSorted(Expression[] expressions, int columnCount) {
1882 super(expressions, columnCount);
1883 if (groupData == null) {
1884 setGroupData(SelectGroups.getInstance(getSession(), Select.this.expressions, isGroupQuery,
1885 groupIndex));
1886 } else {
1887 updateAgg(columnCount, DataAnalysisOperation.STAGE_RESET);
1888 groupData.resetLazy();
1889 }
1890 }
1891
1892 @Override
1893 public void reset() {
1894 super.reset();
1895 groupData.resetLazy();
1896 previousKeyValues = null;
1897 }
1898
1899 @Override
1900 protected Value[] fetchNextRow() {
1901 while (topTableFilter.next()) {
1902 setCurrentRowNumber(rowNumber + 1);
1903 if (isConditionMet()) {
1904 rowNumber++;
1905 int groupSize = groupIndex.length;
1906 Value[] keyValues = new Value[groupSize];
1907 // update group
1908 for (int i = 0; i < groupSize; i++) {
1909 int idx = groupIndex[i];
1910 Expression expr = expressions.get(idx);
1911 keyValues[i] = expr.getValue(getSession());
1912 }
1913
1914 Value[] row = null;
1915 if (previousKeyValues == null) {
1916 previousKeyValues = keyValues;
1917 groupData.nextLazyGroup();
1918 } else {
1919 SessionLocal session = getSession();
1920 for (int i = 0; i < groupSize; i++) {
1921 if (session.compare(previousKeyValues[i], keyValues[i]) != 0) {
1922 row = createGroupSortedRow(previousKeyValues, columnCount);
1923 previousKeyValues = keyValues;
1924 groupData.nextLazyGroup();
1925 break;
1926 }
1927 }
1928 }
1929 groupData.nextLazyRow();
1930 updateAgg(columnCount, DataAnalysisOperation.STAGE_GROUP);
1931 if (row != null) {
1932 return row;
1933 }
1934 }
1935 }
1936 Value[] row = null;
1937 if (previousKeyValues != null) {
1938 row = createGroupSortedRow(previousKeyValues, columnCount);
1939 previousKeyValues = null;
1940 }
1941 return row;
1942 }
1943 }
1944
1945 }