Debian Codegraph @

src/main/org/h2/result/MergedResult.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.Collections;
10 import java.util.HashMap;
11 import java.util.Map;
12
13 import org.h2.util.Utils;
14 import org.h2.value.Value;
15
16 /**
17 * Merged result. Used to combine several results into one. Merged result will
18 * contain rows from all appended results. Results are not required to have the
19 * same lists of columns, but required to have compatible column definitions,
20 * for example, if one result has a {@link java.sql.Types#VARCHAR} column
21 * {@code NAME} then another results that have {@code NAME} column should also
22 * define it with the same type.
23 */
24 public final class MergedResult {
25 private final ArrayList<Map<SimpleResult.Column, Value>> data = Utils.newSmallArrayList();
26
27 private final ArrayList<SimpleResult.Column> columns = Utils.newSmallArrayList();
28
29 /**
30 * Appends a result.
31 *
32 * @param result
33 * result to append
34 */
35 public void add(ResultInterface result) {
36 int count = result.getVisibleColumnCount();
37 if (count == 0) {
38 return;
39 }
40 SimpleResult.Column[] cols = new SimpleResult.Column[count];
41 for (int i = 0; i < count; i++) {
42 SimpleResult.Column c = new SimpleResult.Column(result.getAlias(i), result.getColumnName(i),
43 result.getColumnType(i));
44 cols[i] = c;
45 if (!columns.contains(c)) {
46 columns.add(c);
47 }
48 }
49 while (result.next()) {
50 if (count == 1) {
51 data.add(Collections.singletonMap(cols[0], result.currentRow()[0]));
52 } else {
53 HashMap<SimpleResult.Column, Value> map = new HashMap<>();
54 for (int i = 0; i < count; i++) {
55 SimpleResult.Column ci = cols[i];
56 map.put(ci, result.currentRow()[i]);
57 }
58 data.add(map);
59 }
60 }
61 }
62
63 /**
64 * Returns merged results.
65 *
66 * @return result with rows from all appended result sets
67 */
68 public SimpleResult getResult() {
69 SimpleResult result = new SimpleResult();
70 for (SimpleResult.Column c : columns) {
71 result.addColumn(c);
72 }
73 for (Map<SimpleResult.Column, Value> map : data) {
74 Value[] row = new Value[columns.size()];
75 for (Map.Entry<SimpleResult.Column, Value> entry : map.entrySet()) {
76 row[columns.indexOf(entry.getKey())] = entry.getValue();
77 }
78 result.addRow(row);
79 }
80 return result;
81 }
82
83 @Override
84 public String toString() {
85 return columns + ": " + data.size();
86 }
87
88 }