Debian Codegraph @

src/main/org/h2/result/LocalResult.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.result;
7
8 import java.util.ArrayList;
9 import java.util.Arrays;
10 import java.util.TreeMap;
11
12 import org.h2.engine.Database;
13 import org.h2.engine.Session;
14 import org.h2.engine.SessionLocal;
15 import org.h2.engine.SysProperties;
16 import org.h2.expression.Expression;
17 import org.h2.expression.ExpressionColumn;
18 import org.h2.message.DbException;
19 import org.h2.mvstore.db.MVTempResult;
20 import org.h2.table.Column;
21 import org.h2.table.Table;
22 import org.h2.util.Utils;
23 import org.h2.value.TypeInfo;
24 import org.h2.value.Value;
25 import org.h2.value.ValueBigint;
26 import org.h2.value.ValueLob;
27 import org.h2.value.ValueRow;
28
29 /**
30 * A local result set contains all row data of a result set.
31 * This is the object generated by engine,
32 * and it is also used directly by the ResultSet class in the embedded mode.
33 * If the result does not fit in memory, it is written to a temporary file.
34 */
35 public class LocalResult implements ResultInterface, ResultTarget {
36
37 /**
38 * Constructs a new local result object for the specified table.
39 *
40 * @param session
41 * the session
42 * @param table
43 * the table
44 * @return the local result
45 */
46 public static LocalResult forTable(SessionLocal session, Table table) {
47 Column[] columns = table.getColumns();
48 int degree = columns.length;
49 Expression[] expressions = new Expression[degree + 1];
50 Database database = session.getDatabase();
51 for (int i = 0; i < degree; i++) {
52 expressions[i] = new ExpressionColumn(database, columns[i]);
53 }
54 Column rowIdColumn = table.getRowIdColumn();
55 expressions[degree] = rowIdColumn != null ? new ExpressionColumn(database, rowIdColumn)
56 : new ExpressionColumn(database, null, table.getName());
57 return new LocalResult(session, expressions, degree, degree + 1);
58 }
59
60 private int maxMemoryRows;
61 private final SessionLocal session;
62 private int visibleColumnCount;
63 private int resultColumnCount;
64 private Expression[] expressions;
65 private boolean forDataChangeDeltaTable;
66 private long rowId, rowCount;
67 private ArrayList<Value[]> rows;
68 private SortOrder sort;
69 // HashSet cannot be used here, because we need to compare values of
70 // different type or scale properly.
71 private TreeMap<ValueRow, Value[]> distinctRows;
72 private Value[] currentRow;
73 private long offset;
74 private long limit = -1;
75 private boolean fetchPercent;
76 private SortOrder withTiesSortOrder;
77 private boolean limitsWereApplied;
78 private ResultExternal external;
79 private boolean distinct;
80 private int[] distinctIndexes;
81 private boolean closed;
82 private boolean containsLobs;
83 private Boolean containsNull;
84
85 /**
86 * Construct a local result object.
87 */
88 public LocalResult() {
89 this(null);
90 }
91
92 private LocalResult(SessionLocal session) {
93 this.session = session;
94 }
95
96 /**
97 * Construct a local result object.
98 *
99 * @param session
100 * the session
101 * @param expressions
102 * the expression array
103 * @param visibleColumnCount
104 * the number of visible columns
105 * @param resultColumnCount
106 * the number of columns including visible columns and additional
107 * virtual columns for ORDER BY and DISTINCT ON clauses
108 */
109 public LocalResult(SessionLocal session, Expression[] expressions, int visibleColumnCount, int resultColumnCount) {
110 this.session = session;
111 if (session == null) {
112 this.maxMemoryRows = Integer.MAX_VALUE;
113 } else {
114 Database db = session.getDatabase();
115 if (db.isPersistent() && !db.isReadOnly()) {
116 this.maxMemoryRows = session.getDatabase().getMaxMemoryRows();
117 } else {
118 this.maxMemoryRows = Integer.MAX_VALUE;
119 }
120 }
121 rows = Utils.newSmallArrayList();
122 this.visibleColumnCount = visibleColumnCount;
123 this.resultColumnCount = resultColumnCount;
124 rowId = -1;
125 this.expressions = expressions;
126 }
127
128 @Override
129 public boolean isLazy() {
130 return false;
131 }
132
133 /**
134 * Redefine count of maximum rows holds in memory for the result.
135 *
136 * @param maxValue Maximum rows count in memory.
137 *
138 * @see SysProperties#MAX_MEMORY_ROWS
139 */
140 public void setMaxMemoryRows(int maxValue) {
141 this.maxMemoryRows = maxValue;
142 }
143
144 /**
145 * Sets value collection mode for data change delta tables.
146 */
147 public void setForDataChangeDeltaTable() {
148 forDataChangeDeltaTable = true;
149 }
150
151 /**
152 * Create a shallow copy of the result set. The data and a temporary table
153 * (if there is any) is not copied.
154 *
155 * @param targetSession the session of the copy
156 * @return the copy if possible, or null if copying is not possible
157 */
158 @Override
159 public LocalResult createShallowCopy(Session targetSession) {
160 if (external == null && (rows == null || rows.size() < rowCount)) {
161 return null;
162 }
163 if (containsLobs) {
164 return null;
165 }
166 ResultExternal e2 = null;
167 if (external != null) {
168 e2 = external.createShallowCopy();
169 if (e2 == null) {
170 return null;
171 }
172 }
173 LocalResult copy = new LocalResult((SessionLocal) targetSession);
174 copy.maxMemoryRows = this.maxMemoryRows;
175 copy.visibleColumnCount = this.visibleColumnCount;
176 copy.resultColumnCount = this.resultColumnCount;
177 copy.expressions = this.expressions;
178 copy.rowId = -1;
179 copy.rowCount = this.rowCount;
180 copy.rows = this.rows;
181 copy.sort = this.sort;
182 copy.distinctRows = this.distinctRows;
183 copy.distinct = distinct;
184 copy.distinctIndexes = distinctIndexes;
185 copy.currentRow = null;
186 copy.offset = 0;
187 copy.limit = -1;
188 copy.external = e2;
189 copy.containsNull = containsNull;
190 return copy;
191 }
192
193 /**
194 * Sets sort order to be used by this result. When rows are presorted by the
195 * query this method should not be used.
196 *
197 * @param sort the sort order
198 */
199 public void setSortOrder(SortOrder sort) {
200 this.sort = sort;
201 }
202
203 /**
204 * Remove duplicate rows.
205 */
206 public void setDistinct() {
207 assert distinctIndexes == null;
208 distinct = true;
209 distinctRows = new TreeMap<>(session.getDatabase().getCompareMode());
210 }
211
212 /**
213 * Remove rows with duplicates in columns with specified indexes.
214 *
215 * @param distinctIndexes distinct indexes
216 */
217 public void setDistinct(int[] distinctIndexes) {
218 assert !distinct;
219 this.distinctIndexes = distinctIndexes;
220 distinctRows = new TreeMap<>(session.getDatabase().getCompareMode());
221 }
222
223 /**
224 * @return whether this result is a distinct result
225 */
226 private boolean isAnyDistinct() {
227 return distinct || distinctIndexes != null;
228 }
229
230 /**
231 * Check if this result set contains the given row.
232 *
233 * @param values the row
234 * @return true if the row exists
235 */
236 public boolean containsDistinct(Value[] values) {
237 assert values.length == visibleColumnCount;
238 if (external != null) {
239 return external.contains(values);
240 }
241 if (distinctRows == null) {
242 distinctRows = new TreeMap<>(session.getDatabase().getCompareMode());
243 for (Value[] row : rows) {
244 ValueRow array = getDistinctRow(row);
245 distinctRows.put(array, array.getList());
246 }
247 }
248 ValueRow array = ValueRow.get(values);
249 return distinctRows.get(array) != null;
250 }
251
252 /**
253 * Check if this result set contains a NULL value. This method may reset
254 * this result.
255 *
256 * @return true if there is a NULL value
257 */
258 public boolean containsNull() {
259 Boolean r = containsNull;
260 if (r == null) {
261 r = false;
262 reset();
263 loop: while (next()) {
264 Value[] row = currentRow;
265 for (int i = 0; i < visibleColumnCount; i++) {
266 if (row[i].containsNull()) {
267 r = true;
268 break loop;
269 }
270 }
271 }
272 reset();
273 containsNull = r;
274 }
275 return r;
276 }
277
278 /**
279 * Remove the row from the result set if it exists.
280 *
281 * @param values the row
282 */
283 public void removeDistinct(Value[] values) {
284 if (!distinct) {
285 throw DbException.getInternalError();
286 }
287 assert values.length == visibleColumnCount;
288 if (distinctRows != null) {
289 distinctRows.remove(ValueRow.get(values));
290 rowCount = distinctRows.size();
291 } else {
292 rowCount = external.removeRow(values);
293 }
294 }
295
296 @Override
297 public void reset() {
298 rowId = -1;
299 currentRow = null;
300 if (external != null) {
301 external.reset();
302 }
303 }
304
305 /**
306 * Retrieve the current row
307 * @return row
308 */
309 public Row currentRowForTable() {
310 int degree = visibleColumnCount;
311 Value[] currentRow = this.currentRow;
312 Row row = session.getDatabase().getRowFactory()
313 .createRow(Arrays.copyOf(currentRow, degree), SearchRow.MEMORY_CALCULATE);
314 row.setKey(currentRow[degree].getLong());
315 return row;
316 }
317
318 @Override
319 public Value[] currentRow() {
320 return currentRow;
321 }
322
323 @Override
324 public boolean next() {
325 if (!closed && rowId < rowCount) {
326 rowId++;
327 if (rowId < rowCount) {
328 if (external != null) {
329 currentRow = external.next();
330 } else {
331 currentRow = rows.get((int) rowId);
332 }
333 return true;
334 }
335 currentRow = null;
336 }
337 return false;
338 }
339
340 @Override
341 public long getRowId() {
342 return rowId;
343 }
344
345 @Override
346 public boolean isAfterLast() {
347 return rowId >= rowCount;
348 }
349
350 private void cloneLobs(Value[] values) {
351 for (int i = 0; i < values.length; i++) {
352 Value v = values[i];
353 if (v instanceof ValueLob) {
354 if (forDataChangeDeltaTable) {
355 containsLobs = true;
356 } else {
357 ValueLob v2 = ((ValueLob) v).copyToResult();
358 if (v2 != v) {
359 containsLobs = true;
360 values[i] = session.addTemporaryLob(v2);
361 }
362 }
363 }
364 }
365 }
366
367 private ValueRow getDistinctRow(Value[] values) {
368 if (distinctIndexes != null) {
369 int cnt = distinctIndexes.length;
370 Value[] newValues = new Value[cnt];
371 for (int i = 0; i < cnt; i++) {
372 newValues[i] = values[distinctIndexes[i]];
373 }
374 values = newValues;
375 } else if (values.length > visibleColumnCount) {
376 values = Arrays.copyOf(values, visibleColumnCount);
377 }
378 return ValueRow.get(values);
379 }
380
381 private void createExternalResult() {
382 external = MVTempResult.of(session.getDatabase(), expressions, distinct, distinctIndexes, visibleColumnCount,
383 resultColumnCount, sort);
384 }
385
386 /**
387 * Add a row for a table.
388 *
389 * @param row the row to add
390 */
391 public void addRowForTable(Row row) {
392 int degree = visibleColumnCount;
393 Value[] values = new Value[degree + 1];
394 for (int i = 0; i < degree; i++) {
395 values[i] = row.getValue(i);
396 }
397 values[degree] = ValueBigint.get(row.getKey());
398 addRowInternal(values);
399 }
400
401 /**
402 * Add a row to this object.
403 *
404 * @param values the row to add
405 */
406 @Override
407 public void addRow(Value... values) {
408 assert values.length == resultColumnCount;
409 cloneLobs(values);
410 addRowInternal(values);
411 }
412
413 private void addRowInternal(Value... values) {
414 if (isAnyDistinct()) {
415 if (distinctRows != null) {
416 ValueRow distinctRow = getDistinctRow(values);
417 Value[] previous = distinctRows.get(distinctRow);
418 if (previous == null || sort != null && sort.compare(previous, values) > 0) {
419 distinctRows.put(distinctRow, values);
420 }
421 rowCount = distinctRows.size();
422 if (rowCount > maxMemoryRows) {
423 createExternalResult();
424 rowCount = external.addRows(distinctRows.values());
425 distinctRows = null;
426 }
427 } else {
428 rowCount = external.addRow(values);
429 }
430 } else {
431 rows.add(values);
432 rowCount++;
433 if (rows.size() > maxMemoryRows) {
434 addRowsToDisk();
435 }
436 }
437 }
438
439 private void addRowsToDisk() {
440 if (external == null) {
441 createExternalResult();
442 }
443 rowCount = external.addRows(rows);
444 rows.clear();
445 }
446
447 @Override
448 public int getVisibleColumnCount() {
449 return visibleColumnCount;
450 }
451
452 /**
453 * This method is called after all rows have been added.
454 */
455 public void done() {
456 if (external != null) {
457 addRowsToDisk();
458 } else {
459 if (isAnyDistinct()) {
460 rows = new ArrayList<>(distinctRows.values());
461 }
462 if (sort != null && limit != 0 && !limitsWereApplied) {
463 boolean withLimit = limit > 0 && withTiesSortOrder == null;
464 if (offset > 0 || withLimit) {
465 int endExclusive = rows.size();
466 if (offset < endExclusive) {
467 int fromInclusive = (int) offset;
468 if (withLimit && limit < endExclusive - fromInclusive) {
469 endExclusive = fromInclusive + (int) limit;
470 }
471 sort.sort(rows, fromInclusive, endExclusive);
472 }
473 } else {
474 sort.sort(rows);
475 }
476 }
477 }
478 applyOffsetAndLimit();
479 reset();
480 }
481
482 private void applyOffsetAndLimit() {
483 if (limitsWereApplied) {
484 return;
485 }
486 long offset = Math.max(this.offset, 0);
487 long limit = this.limit;
488 if (offset == 0 && limit < 0 && !fetchPercent || rowCount == 0) {
489 return;
490 }
491 if (fetchPercent) {
492 if (limit < 0 || limit > 100) {
493 throw DbException.getInvalidValueException("FETCH PERCENT", limit);
494 }
495 // Oracle rounds percent up, do the same for now
496 limit = (limit * rowCount + 99) / 100;
497 }
498 boolean clearAll = offset >= rowCount || limit == 0;
499 if (!clearAll) {
500 long remaining = rowCount - offset;
501 limit = limit < 0 ? remaining : Math.min(remaining, limit);
502 if (offset == 0 && remaining <= limit) {
503 return;
504 }
505 } else {
506 limit = 0;
507 }
508 distinctRows = null;
509 rowCount = limit;
510 if (external == null) {
511 if (clearAll) {
512 rows.clear();
513 return;
514 }
515 int to = (int) (offset + limit);
516 if (withTiesSortOrder != null) {
517 Value[] expected = rows.get(to - 1);
518 while (to < rows.size() && withTiesSortOrder.compare(expected, rows.get(to)) == 0) {
519 to++;
520 rowCount++;
521 }
522 }
523 if (offset != 0 || to != rows.size()) {
524 // avoid copying the whole array for each row
525 rows = new ArrayList<>(rows.subList((int) offset, to));
526 }
527 } else {
528 if (clearAll) {
529 external.close();
530 external = null;
531 return;
532 }
533 trimExternal(offset, limit);
534 }
535 }
536
537 private void trimExternal(long offset, long limit) {
538 ResultExternal temp = external;
539 external = null;
540 temp.reset();
541 while (--offset >= 0) {
542 temp.next();
543 }
544 Value[] row = null;
545 while (--limit >= 0) {
546 row = temp.next();
547 rows.add(row);
548 if (rows.size() > maxMemoryRows) {
549 addRowsToDisk();
550 }
551 }
552 if (withTiesSortOrder != null && row != null) {
553 Value[] expected = row;
554 while ((row = temp.next()) != null && withTiesSortOrder.compare(expected, row) == 0) {
555 rows.add(row);
556 rowCount++;
557 if (rows.size() > maxMemoryRows) {
558 addRowsToDisk();
559 }
560 }
561 }
562 if (external != null) {
563 addRowsToDisk();
564 }
565 temp.close();
566 }
567
568 @Override
569 public long getRowCount() {
570 return rowCount;
571 }
572
573 @Override
574 public void limitsWereApplied() {
575 this.limitsWereApplied = true;
576 }
577
578 @Override
579 public boolean hasNext() {
580 return !closed && rowId < rowCount - 1;
581 }
582
583 /**
584 * Set the number of rows that this result will return at the maximum.
585 *
586 * @param limit the limit (-1 means no limit, 0 means no rows)
587 */
588 public void setLimit(long limit) {
589 this.limit = limit;
590 }
591
592 /**
593 * @param fetchPercent whether limit expression specifies percentage of rows
594 */
595 public void setFetchPercent(boolean fetchPercent) {
596 this.fetchPercent = fetchPercent;
597 }
598
599 /**
600 * Enables inclusion of tied rows to result and sets the sort order for tied
601 * rows. The specified sort order must be the same as sort order if sort
602 * order was set. Passed value will be used if sort order was not set that
603 * is possible when rows are presorted.
604 *
605 * @param withTiesSortOrder the sort order for tied rows
606 */
607 public void setWithTies(SortOrder withTiesSortOrder) {
608 assert sort == null || sort == withTiesSortOrder;
609 this.withTiesSortOrder = withTiesSortOrder;
610 }
611
612 @Override
613 public boolean needToClose() {
614 return external != null;
615 }
616
617 @Override
618 public void close() {
619 if (external != null) {
620 external.close();
621 external = null;
622 closed = true;
623 }
624 }
625
626 @Override
627 public String getAlias(int i) {
628 return expressions[i].getAlias(session, i);
629 }
630
631 @Override
632 public String getTableName(int i) {
633 return expressions[i].getTableName();
634 }
635
636 @Override
637 public String getSchemaName(int i) {
638 return expressions[i].getSchemaName();
639 }
640
641 @Override
642 public String getColumnName(int i) {
643 return expressions[i].getColumnName(session, i);
644 }
645
646 @Override
647 public TypeInfo getColumnType(int i) {
648 return expressions[i].getType();
649 }
650
651 @Override
652 public int getNullable(int i) {
653 return expressions[i].getNullable();
654 }
655
656 @Override
657 public boolean isIdentity(int i) {
658 return expressions[i].isIdentity();
659 }
660
661 /**
662 * Set the offset of the first row to return.
663 *
664 * @param offset the offset
665 */
666 public void setOffset(long offset) {
667 this.offset = offset;
668 }
669
670 @Override
671 public String toString() {
672 return super.toString() + " columns: " + visibleColumnCount +
673 " rows: " + rowCount + " pos: " + rowId;
674 }
675
676 /**
677 * Check if this result set is closed.
678 *
679 * @return true if it is
680 */
681 @Override
682 public boolean isClosed() {
683 return closed;
684 }
685
686 @Override
687 public int getFetchSize() {
688 return 0;
689 }
690
691 @Override
692 public void setFetchSize(int fetchSize) {
693 // ignore
694 }
695
696 }