Debian Codegraph @

src/main/org/h2/command/query/SelectUnion.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 java.util.ArrayList;
9 import java.util.HashSet;
10
11 import org.h2.api.ErrorCode;
12 import org.h2.engine.Database;
13 import org.h2.engine.SessionLocal;
14 import org.h2.expression.Expression;
15 import org.h2.expression.ExpressionColumn;
16 import org.h2.expression.ExpressionVisitor;
17 import org.h2.expression.Parameter;
18 import org.h2.message.DbException;
19 import org.h2.result.LazyResult;
20 import org.h2.result.LocalResult;
21 import org.h2.result.ResultInterface;
22 import org.h2.result.ResultTarget;
23 import org.h2.table.Column;
24 import org.h2.table.ColumnResolver;
25 import org.h2.table.Table;
26 import org.h2.table.TableFilter;
27 import org.h2.value.TypeInfo;
28 import org.h2.value.Value;
29
30 /**
31 * Represents a union SELECT statement.
32 */
33 public class SelectUnion extends Query {
34
35 public enum UnionType {
36 /**
37 * The type of a UNION statement.
38 */
39 UNION,
40
41 /**
42 * The type of a UNION ALL statement.
43 */
44 UNION_ALL,
45
46 /**
47 * The type of an EXCEPT statement.
48 */
49 EXCEPT,
50
51 /**
52 * The type of an INTERSECT statement.
53 */
54 INTERSECT
55 }
56
57 private final UnionType unionType;
58
59 /**
60 * The left hand side of the union (the first subquery).
61 */
62 final Query left;
63
64 /**
65 * The right hand side of the union (the second subquery).
66 */
67 final Query right;
68
69 private ForUpdate forUpdate;
70
71 public SelectUnion(SessionLocal session, UnionType unionType, Query query, Query right) {
72 super(session);
73 this.unionType = unionType;
74 this.left = query;
75 this.right = right;
76 }
77
78 @Override
79 public boolean isUnion() {
80 return true;
81 }
82
83 public UnionType getUnionType() {
84 return unionType;
85 }
86
87 public Query getLeft() {
88 return left;
89 }
90
91 public Query getRight() {
92 return right;
93 }
94
95 private Value[] convert(Value[] values, int columnCount) {
96 Value[] newValues;
97 if (columnCount == values.length) {
98 // re-use the array if possible
99 newValues = values;
100 } else {
101 // create a new array if needed,
102 // for the value hash set
103 newValues = new Value[columnCount];
104 }
105 for (int i = 0; i < columnCount; i++) {
106 Expression e = expressions.get(i);
107 newValues[i] = values[i].convertTo(e.getType(), session);
108 }
109 return newValues;
110 }
111
112 public LocalResult getEmptyResult() {
113 int columnCount = left.getColumnCount();
114 return createLocalResult(columnCount);
115 }
116
117 @Override
118 protected ResultInterface queryWithoutCache(long maxRows, ResultTarget target) {
119 OffsetFetch offsetFetch = getOffsetFetch(maxRows);
120 long offset = offsetFetch.offset;
121 long fetch = offsetFetch.fetch;
122 boolean fetchPercent = offsetFetch.fetchPercent;
123 Database db = session.getDatabase();
124 if (db.getSettings().optimizeInsertFromSelect) {
125 if (unionType == UnionType.UNION_ALL && target != null) {
126 if (sort == null && !distinct && fetch < 0 && offset == 0) {
127 left.query(0, target);
128 right.query(0, target);
129 return null;
130 }
131 }
132 }
133 int columnCount = left.getColumnCount();
134 if (session.isLazyQueryExecution() && unionType == UnionType.UNION_ALL && !distinct &&
135 sort == null && !randomAccessResult && forUpdate == null &&
136 offset == 0 && !fetchPercent && !withTies && isReadOnly()) {
137 // limit 0 means no rows
138 if (fetch != 0) {
139 LazyResultUnion lazyResult = new LazyResultUnion(expressionArray, columnCount);
140 if (fetch > 0) {
141 lazyResult.setLimit(fetch);
142 }
143 return lazyResult;
144 }
145 }
146 LocalResult result = createLocalResult(columnCount);
147 if (sort != null) {
148 result.setSortOrder(sort);
149 }
150 if (distinct) {
151 left.setDistinctIfPossible();
152 right.setDistinctIfPossible();
153 result.setDistinct();
154 }
155 switch (unionType) {
156 case UNION:
157 case EXCEPT:
158 left.setDistinctIfPossible();
159 right.setDistinctIfPossible();
160 result.setDistinct();
161 break;
162 case UNION_ALL:
163 break;
164 case INTERSECT:
165 left.setDistinctIfPossible();
166 right.setDistinctIfPossible();
167 break;
168 default:
169 throw DbException.getInternalError("type=" + unionType);
170 }
171 ResultInterface l = left.query(0);
172 ResultInterface r = right.query(0);
173 l.reset();
174 r.reset();
175 switch (unionType) {
176 case UNION_ALL:
177 case UNION: {
178 while (l.next()) {
179 result.addRow(convert(l.currentRow(), columnCount));
180 }
181 while (r.next()) {
182 result.addRow(convert(r.currentRow(), columnCount));
183 }
184 break;
185 }
186 case EXCEPT: {
187 while (l.next()) {
188 result.addRow(convert(l.currentRow(), columnCount));
189 }
190 while (r.next()) {
191 result.removeDistinct(convert(r.currentRow(), columnCount));
192 }
193 break;
194 }
195 case INTERSECT: {
196 LocalResult temp = createLocalResult(columnCount);
197 temp.setDistinct();
198 while (l.next()) {
199 temp.addRow(convert(l.currentRow(), columnCount));
200 }
201 while (r.next()) {
202 Value[] values = convert(r.currentRow(), columnCount);
203 if (temp.containsDistinct(values)) {
204 result.addRow(values);
205 }
206 }
207 temp.close();
208 break;
209 }
210 default:
211 throw DbException.getInternalError("type=" + unionType);
212 }
213 l.close();
214 r.close();
215 return finishResult(result, offset, fetch, fetchPercent, target);
216 }
217
218 private LocalResult createLocalResult(int columnCount) {
219 return new LocalResult(session, expressionArray, columnCount, columnCount);
220 }
221
222 @Override
223 public void init() {
224 if (checkInit) {
225 throw DbException.getInternalError();
226 }
227 checkInit = true;
228 left.init();
229 right.init();
230 int len = left.getColumnCount();
231 if (len != right.getColumnCount()) {
232 throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
233 }
234 ArrayList<Expression> le = left.getExpressions();
235 // set the expressions to get the right column count and names,
236 // but can't validate at this time
237 expressions = new ArrayList<>(len);
238 for (int i = 0; i < len; i++) {
239 Expression l = le.get(i);
240 expressions.add(l);
241 }
242 visibleColumnCount = len;
243 if (withTies && !hasOrder()) {
244 throw DbException.get(ErrorCode.WITH_TIES_WITHOUT_ORDER_BY);
245 }
246 }
247
248 @Override
249 public void prepareExpressions() {
250 left.prepareExpressions();
251 right.prepareExpressions();
252 int len = left.getColumnCount();
253 // set the correct expressions now
254 expressions = new ArrayList<>(len);
255 ArrayList<Expression> le = left.getExpressions();
256 ArrayList<Expression> re = right.getExpressions();
257 for (int i = 0; i < len; i++) {
258 Expression l = le.get(i);
259 Expression r = re.get(i);
260 Column col = new Column(l.getAlias(session, i), TypeInfo.getHigherType(l.getType(), r.getType()));
261 Expression e = new ExpressionColumn(session.getDatabase(), col);
262 expressions.add(e);
263 }
264 if (orderList != null) {
265 if (initOrder(null, true, null)) {
266 prepareOrder(orderList, expressions.size());
267 cleanupOrder();
268 }
269 }
270 resultColumnCount = expressions.size();
271 expressionArray = expressions.toArray(new Expression[0]);
272 }
273
274 @Override
275 public void preparePlan() {
276 left.preparePlan();
277 right.preparePlan();
278 isPrepared = true;
279 }
280
281 @Override
282 public double getCost() {
283 return left.getCost() + right.getCost();
284 }
285
286 @Override
287 public HashSet<Table> getTables() {
288 HashSet<Table> set = left.getTables();
289 set.addAll(right.getTables());
290 return set;
291 }
292
293 @Override
294 public ForUpdate getForUpdate() {
295 return forUpdate;
296 }
297
298 @Override
299 public void setForUpdate(ForUpdate forUpdate) {
300 left.setForUpdate(forUpdate);
301 right.setForUpdate(forUpdate);
302 this.forUpdate = forUpdate;
303 }
304
305 @Override
306 public void mapColumns(ColumnResolver resolver, int level) {
307 left.mapColumns(resolver, level);
308 right.mapColumns(resolver, level);
309 }
310
311 @Override
312 public void setEvaluatable(TableFilter tableFilter, boolean b) {
313 left.setEvaluatable(tableFilter, b);
314 right.setEvaluatable(tableFilter, b);
315 }
316
317 @Override
318 public void addGlobalCondition(Parameter param, int columnId,
319 int comparisonType) {
320 addParameter(param);
321 switch (unionType) {
322 case UNION_ALL:
323 case UNION:
324 case INTERSECT: {
325 left.addGlobalCondition(param, columnId, comparisonType);
326 right.addGlobalCondition(param, columnId, comparisonType);
327 break;
328 }
329 case EXCEPT: {
330 left.addGlobalCondition(param, columnId, comparisonType);
331 break;
332 }
333 default:
334 throw DbException.getInternalError("type=" + unionType);
335 }
336 }
337
338 @Override
339 public String getPlanSQL(int sqlFlags) {
340 StringBuilder builder = new StringBuilder().append('(').append(left.getPlanSQL(sqlFlags)).append(')');
341 switch (unionType) {
342 case UNION_ALL:
343 builder.append("\nUNION ALL\n");
344 break;
345 case UNION:
346 builder.append("\nUNION\n");
347 break;
348 case INTERSECT:
349 builder.append("\nINTERSECT\n");
350 break;
351 case EXCEPT:
352 builder.append("\nEXCEPT\n");
353 break;
354 default:
355 throw DbException.getInternalError("type=" + unionType);
356 }
357 builder.append('(').append(right.getPlanSQL(sqlFlags)).append(')');
358 appendEndOfQueryToSQL(builder, sqlFlags, expressions.toArray(new Expression[0]));
359 if (forUpdate != null) {
360 forUpdate.getSQL(builder, sqlFlags);
361 }
362 return builder.toString();
363 }
364
365 @Override
366 public boolean isEverything(ExpressionVisitor visitor) {
367 return left.isEverything(visitor) && right.isEverything(visitor);
368 }
369
370 @Override
371 public void updateAggregate(SessionLocal s, int stage) {
372 left.updateAggregate(s, stage);
373 right.updateAggregate(s, stage);
374 }
375
376 @Override
377 public void fireBeforeSelectTriggers() {
378 left.fireBeforeSelectTriggers();
379 right.fireBeforeSelectTriggers();
380 }
381
382 @Override
383 public boolean allowGlobalConditions() {
384 return left.allowGlobalConditions() && right.allowGlobalConditions();
385 }
386
387 @Override
388 public boolean isConstantQuery() {
389 return super.isConstantQuery() && left.isConstantQuery() && right.isConstantQuery();
390 }
391
392 /**
393 * Lazy execution for this union.
394 */
395 private final class LazyResultUnion extends LazyResult {
396
397 int columnCount;
398 ResultInterface l;
399 ResultInterface r;
400 boolean leftDone;
401 boolean rightDone;
402
403 LazyResultUnion(Expression[] expressions, int columnCount) {
404 super(getSession(), expressions);
405 this.columnCount = columnCount;
406 }
407
408 @Override
409 public int getVisibleColumnCount() {
410 return columnCount;
411 }
412
413 @Override
414 protected Value[] fetchNextRow() {
415 if (rightDone) {
416 return null;
417 }
418 if (!leftDone) {
419 if (l == null) {
420 l = left.query(0);
421 l.reset();
422 }
423 if (l.next()) {
424 return l.currentRow();
425 }
426 leftDone = true;
427 }
428 if (r == null) {
429 r = right.query(0);
430 r.reset();
431 }
432 if (r.next()) {
433 return r.currentRow();
434 }
435 rightDone = true;
436 return null;
437 }
438
439 @Override
440 public void close() {
441 super.close();
442 if (l != null) {
443 l.close();
444 }
445 if (r != null) {
446 r.close();
447 }
448 }
449
450 @Override
451 public void reset() {
452 super.reset();
453 if (l != null) {
454 l.reset();
455 }
456 if (r != null) {
457 r.reset();
458 }
459 leftDone = false;
460 rightDone = false;
461 }
462 }
463 }