Debian Codegraph @

src/main/org/h2/table/DerivedTable.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.table;
7
8 import java.util.ArrayList;
9
10 import org.h2.api.ErrorCode;
11 import org.h2.command.query.Query;
12 import org.h2.engine.SessionLocal;
13 import org.h2.expression.ExpressionVisitor;
14 import org.h2.expression.Parameter;
15 import org.h2.index.QueryExpressionIndex;
16 import org.h2.message.DbException;
17 import org.h2.util.StringUtils;
18
19 /**
20 * A derived table.
21 */
22 public final class DerivedTable extends QueryExpressionTable {
23
24 private String querySQL;
25
26 private Query topQuery;
27
28 /**
29 * Create a derived table out of the given query.
30 *
31 * @param session the session
32 * @param name the view name
33 * @param columnTemplates column templates, or {@code null}
34 * @param query the initialized query
35 * @param topQuery the top level query
36 */
37 public DerivedTable(SessionLocal session, String name, Column[] columnTemplates, Query query, Query topQuery) {
38 super(session.getDatabase().getMainSchema(), 0, name);
39 setTemporary(true);
40 this.topQuery = topQuery;
41 query.prepareExpressions();
42 try {
43 this.querySQL = query.getPlanSQL(DEFAULT_SQL_FLAGS);
44 ArrayList<Parameter> params = query.getParameters();
45 index = new QueryExpressionIndex(this, querySQL, params, false);
46 tables = new ArrayList<>(query.getTables());
47 setColumns(initColumns(session, columnTemplates, query, true));
48 viewQuery = query;
49 } catch (DbException e) {
50 if (e.getErrorCode() == ErrorCode.COLUMN_ALIAS_IS_NOT_SPECIFIED_1) {
51 throw e;
52 }
53 e.addSQL(getCreateSQL());
54 throw e;
55 }
56 }
57
58 @Override
59 public boolean isQueryComparable() {
60 if (!super.isQueryComparable()) {
61 return false;
62 }
63 if (topQuery != null && !topQuery.isEverything(ExpressionVisitor.QUERY_COMPARABLE_VISITOR)) {
64 return false;
65 }
66 return true;
67 }
68
69 @Override
70 public boolean canDrop() {
71 return false;
72 }
73
74 @Override
75 public TableType getTableType() {
76 return null;
77 }
78
79 @Override
80 public Query getTopQuery() {
81 return topQuery;
82 }
83
84 @Override
85 public String getCreateSQL() {
86 return null;
87 }
88
89 @Override
90 public StringBuilder getSQL(StringBuilder builder, int sqlFlags) {
91 return StringUtils.indent(builder.append("(\n"), querySQL, 4, true).append(')');
92 }
93
94 }