Debian Codegraph @

src/main/org/h2/command/query/TableValueConstructor.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.DEFAULT_SQL_FLAGS;
10
11 import java.util.ArrayList;
12 import java.util.HashSet;
13
14 import org.h2.api.ErrorCode;
15 import org.h2.engine.Constants;
16 import org.h2.engine.Database;
17 import org.h2.engine.SessionLocal;
18 import org.h2.expression.Expression;
19 import org.h2.expression.ExpressionColumn;
20 import org.h2.expression.ExpressionList;
21 import org.h2.expression.ExpressionVisitor;
22 import org.h2.expression.Parameter;
23 import org.h2.message.DbException;
24 import org.h2.result.LocalResult;
25 import org.h2.result.ResultInterface;
26 import org.h2.result.ResultTarget;
27 import org.h2.table.Column;
28 import org.h2.table.ColumnResolver;
29 import org.h2.table.Table;
30 import org.h2.table.TableFilter;
31 import org.h2.table.TableValueConstructorTable;
32 import org.h2.value.TypeInfo;
33 import org.h2.value.Value;
34
35 /**
36 * Table value constructor.
37 */
38 public class TableValueConstructor extends Query {
39
40 private final ArrayList<ArrayList<Expression>> rows;
41
42 /**
43 * The table.
44 */
45 TableValueConstructorTable table;
46
47 private TableValueColumnResolver columnResolver;
48
49 private double cost;
50
51 /**
52 * Creates new instance of table value constructor.
53 *
54 * @param session
55 * the session
56 * @param rows
57 * the rows
58 */
59 public TableValueConstructor(SessionLocal session, ArrayList<ArrayList<Expression>> rows) {
60 super(session);
61 this.rows = rows;
62 if ((visibleColumnCount = rows.get(0).size()) > Constants.MAX_COLUMNS) {
63 throw DbException.get(ErrorCode.TOO_MANY_COLUMNS_1, "" + Constants.MAX_COLUMNS);
64 }
65 for (ArrayList<Expression> row : rows) {
66 for (Expression column : row) {
67 if (!column.isConstant()) {
68 return;
69 }
70 }
71 }
72 createTable();
73 }
74
75 /**
76 * Appends visible columns of all rows to the specified result.
77 *
78 * @param session
79 * the session
80 * @param result
81 * the result
82 * @param columns
83 * the columns
84 * @param rows
85 * the rows with data
86 */
87 public static void getVisibleResult(SessionLocal session, ResultTarget result, Column[] columns,
88 ArrayList<ArrayList<Expression>> rows) {
89 int count = columns.length;
90 for (ArrayList<Expression> row : rows) {
91 Value[] values = new Value[count];
92 for (int i = 0; i < count; i++) {
93 values[i] = row.get(i).getValue(session).convertTo(columns[i].getType(), session);
94 }
95 result.addRow(values);
96 }
97 }
98
99 /**
100 * Appends the SQL of the values to the specified string builder..
101 *
102 * @param builder
103 * string builder
104 * @param sqlFlags
105 * formatting flags
106 * @param rows
107 * the values
108 */
109 public static void getValuesSQL(StringBuilder builder, int sqlFlags, ArrayList<ArrayList<Expression>> rows) {
110 builder.append("VALUES ");
111 int rowCount = rows.size();
112 for (int i = 0; i < rowCount; i++) {
113 if (i > 0) {
114 builder.append(", ");
115 }
116 Expression.writeExpressions(builder.append('('), rows.get(i), sqlFlags).append(')');
117 }
118 }
119
120 @Override
121 public boolean isUnion() {
122 return false;
123 }
124
125 @Override
126 protected ResultInterface queryWithoutCache(long limit, ResultTarget target) {
127 OffsetFetch offsetFetch = getOffsetFetch(limit);
128 long offset = offsetFetch.offset;
129 long fetch = offsetFetch.fetch;
130 boolean fetchPercent = offsetFetch.fetchPercent;
131 int visibleColumnCount = this.visibleColumnCount, resultColumnCount = this.resultColumnCount;
132 LocalResult result = new LocalResult(session, expressionArray, visibleColumnCount, resultColumnCount);
133 if (sort != null) {
134 result.setSortOrder(sort);
135 }
136 if (distinct) {
137 result.setDistinct();
138 }
139 Column[] columns = table.getColumns();
140 if (visibleColumnCount == resultColumnCount) {
141 getVisibleResult(session, result, columns, rows);
142 } else {
143 for (ArrayList<Expression> row : rows) {
144 Value[] values = new Value[resultColumnCount];
145 for (int i = 0; i < visibleColumnCount; i++) {
146 values[i] = row.get(i).getValue(session).convertTo(columns[i].getType(), session);
147 }
148 columnResolver.currentRow = values;
149 for (int i = visibleColumnCount; i < resultColumnCount; i++) {
150 values[i] = expressionArray[i].getValue(session);
151 }
152 result.addRow(values);
153 }
154 columnResolver.currentRow = null;
155 }
156 return finishResult(result, offset, fetch, fetchPercent, target);
157 }
158
159 @Override
160 public void init() {
161 if (checkInit) {
162 throw DbException.getInternalError();
163 }
164 checkInit = true;
165 if (withTies && !hasOrder()) {
166 throw DbException.get(ErrorCode.WITH_TIES_WITHOUT_ORDER_BY);
167 }
168 }
169
170 @Override
171 public void prepareExpressions() {
172 if (columnResolver == null) {
173 createTable();
174 }
175 if (orderList != null) {
176 ArrayList<String> expressionsSQL = new ArrayList<>();
177 for (Expression e : expressions) {
178 expressionsSQL.add(e.getSQL(DEFAULT_SQL_FLAGS, WITHOUT_PARENTHESES));
179 }
180 if (initOrder(expressionsSQL, false, null)) {
181 prepareOrder(orderList, expressions.size());
182 }
183 }
184 resultColumnCount = expressions.size();
185 for (int i = 0; i < resultColumnCount; i++) {
186 expressions.get(i).mapColumns(columnResolver, 0, Expression.MAP_INITIAL);
187 }
188 for (int i = visibleColumnCount; i < resultColumnCount; i++) {
189 expressions.set(i, expressions.get(i).optimize(session));
190 }
191 if (sort != null) {
192 cleanupOrder();
193 }
194 expressionArray = expressions.toArray(new Expression[0]);
195 }
196
197 @Override
198 public void preparePlan() {
199 double cost = 0;
200 int columnCount = visibleColumnCount;
201 for (ArrayList<Expression> r : rows) {
202 for (int i = 0; i < columnCount; i++) {
203 cost += r.get(i).getCost();
204 }
205 }
206 this.cost = cost + rows.size();
207 isPrepared = true;
208 }
209
210 private void createTable() {
211 int rowCount = rows.size();
212 ArrayList<Expression> row = rows.get(0);
213 int columnCount = row.size();
214 TypeInfo[] types = new TypeInfo[columnCount];
215 for (int c = 0; c < columnCount; c++) {
216 Expression e = row.get(c).optimize(session);
217 row.set(c, e);
218 TypeInfo type = e.getType();
219 if (type.getValueType() == Value.UNKNOWN) {
220 type = TypeInfo.TYPE_VARCHAR;
221 }
222 types[c] = type;
223 }
224 for (int r = 1; r < rowCount; r++) {
225 row = rows.get(r);
226 for (int c = 0; c < columnCount; c++) {
227 Expression e = row.get(c).optimize(session);
228 row.set(c, e);
229 types[c] = TypeInfo.getHigherType(types[c], e.getType());
230 }
231 }
232 Column[] columns = new Column[columnCount];
233 for (int c = 0; c < columnCount;) {
234 TypeInfo type = types[c];
235 columns[c] = new Column("C" + ++c, type);
236 }
237 Database database = session.getDatabase();
238 ArrayList<Expression> expressions = new ArrayList<>(columnCount);
239 for (int i = 0; i < columnCount; i++) {
240 expressions.add(new ExpressionColumn(database, null, null, columns[i].getName()));
241 }
242 this.expressions = expressions;
243 table = new TableValueConstructorTable(database.getMainSchema(), session, columns, rows);
244 columnResolver = new TableValueColumnResolver();
245 }
246
247 @Override
248 public double getCost() {
249 return cost;
250 }
251
252 @Override
253 public HashSet<Table> getTables() {
254 HashSet<Table> tables = new HashSet<>(1, 1f);
255 tables.add(table);
256 return tables;
257 }
258
259 @Override
260 public void setForUpdate(ForUpdate forUpdate) {
261 throw DbException.get(ErrorCode.RESULT_SET_READONLY);
262 }
263
264 @Override
265 public void mapColumns(ColumnResolver resolver, int level) {
266 int columnCount = visibleColumnCount;
267 for (ArrayList<Expression> row : rows) {
268 for (int i = 0; i < columnCount; i++) {
269 row.get(i).mapColumns(resolver, level, Expression.MAP_INITIAL);
270 }
271 }
272 }
273
274 @Override
275 public void setEvaluatable(TableFilter tableFilter, boolean b) {
276 int columnCount = visibleColumnCount;
277 for (ArrayList<Expression> row : rows) {
278 for (int i = 0; i < columnCount; i++) {
279 row.get(i).setEvaluatable(tableFilter, b);
280 }
281 }
282 }
283
284 @Override
285 public void addGlobalCondition(Parameter param, int columnId, int comparisonType) {
286 // Can't add
287 }
288
289 @Override
290 public boolean allowGlobalConditions() {
291 return false;
292 }
293
294 @Override
295 public boolean isEverything(ExpressionVisitor visitor) {
296 ExpressionVisitor v2 = visitor.incrementQueryLevel(1);
297 for (Expression e : expressionArray) {
298 if (!e.isEverything(v2)) {
299 return false;
300 }
301 }
302 return true;
303 }
304
305 @Override
306 public void updateAggregate(SessionLocal s, int stage) {
307 int columnCount = visibleColumnCount;
308 for (ArrayList<Expression> row : rows) {
309 for (int i = 0; i < columnCount; i++) {
310 row.get(i).updateAggregate(s, stage);
311 }
312 }
313 }
314
315 @Override
316 public void fireBeforeSelectTriggers() {
317 // Nothing to do
318 }
319
320 @Override
321 public String getPlanSQL(int sqlFlags) {
322 StringBuilder builder = new StringBuilder();
323 getValuesSQL(builder, sqlFlags, rows);
324 appendEndOfQueryToSQL(builder, sqlFlags, expressionArray);
325 return builder.toString();
326 }
327
328 @Override
329 public Table toTable(String alias, Column[] columnTemplates, ArrayList<Parameter> parameters,
330 boolean forCreateView, Query topQuery) {
331 if (!hasOrder() && offsetExpr == null && fetchExpr == null && table != null) {
332 return table;
333 }
334 return super.toTable(alias, columnTemplates, parameters, forCreateView, topQuery);
335 }
336
337 @Override
338 public boolean isConstantQuery() {
339 if (!super.isConstantQuery()) {
340 return false;
341 }
342 for (ArrayList<Expression> row : rows) {
343 for (int i = 0; i < visibleColumnCount; i++) {
344 if (!row.get(i).isConstant()) {
345 return false;
346 }
347 }
348 }
349 return true;
350 }
351
352 @Override
353 public Expression getIfSingleRow() {
354 if (offsetExpr != null || fetchExpr != null || rows.size() != 1) {
355 return null;
356 }
357 ArrayList<Expression> row = rows.get(0);
358 if (visibleColumnCount == 1) {
359 return row.get(0);
360 }
361 Expression[] array = new Expression[visibleColumnCount];
362 for (int i = 0; i < visibleColumnCount; i++) {
363 array[i] = row.get(i);
364 }
365 return new ExpressionList(array, false);
366 }
367
368 private final class TableValueColumnResolver implements ColumnResolver {
369
370 Value[] currentRow;
371
372 TableValueColumnResolver() {
373 }
374
375 @Override
376 public Column[] getColumns() {
377 return table.getColumns();
378 }
379
380 @Override
381 public Column findColumn(String name) {
382 return table.findColumn(name);
383 }
384
385 @Override
386 public Value getValue(Column column) {
387 return currentRow[column.getColumnId()];
388 }
389
390 @Override
391 public Expression optimize(ExpressionColumn expressionColumn, Column column) {
392 return expressions.get(column.getColumnId());
393 }
394
395 }
396
397 }