Debian Codegraph @

src/main/org/h2/table/QueryExpressionTable.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 import java.util.Arrays;
10 import java.util.HashSet;
11 import java.util.List;
12 import java.util.Map;
13
14 import org.h2.command.query.AllColumnsForPlan;
15 import org.h2.command.query.Query;
16 import org.h2.engine.DbObject;
17 import org.h2.engine.SessionLocal;
18 import org.h2.expression.Expression;
19 import org.h2.expression.ExpressionVisitor;
20 import org.h2.expression.Parameter;
21 import org.h2.index.Index;
22 import org.h2.index.IndexType;
23 import org.h2.index.QueryExpressionIndex;
24 import org.h2.message.DbException;
25 import org.h2.result.Row;
26 import org.h2.result.SortOrder;
27 import org.h2.schema.Schema;
28 import org.h2.util.StringUtils;
29 import org.h2.value.TypeInfo;
30 import org.h2.value.Value;
31
32 /**
33 * A derived table or view.
34 */
35 public abstract class QueryExpressionTable extends Table {
36
37 /**
38 * The key of the index cache for views.
39 */
40 static final class CacheKey {
41
42 private final int[] masks;
43
44 private final QueryExpressionTable queryExpressionTable;
45
46 CacheKey(int[] masks, QueryExpressionTable queryExpressionTable) {
47 this.masks = masks;
48 this.queryExpressionTable = queryExpressionTable;
49 }
50
51 @Override
52 public int hashCode() {
53 final int prime = 31;
54 int result = 1;
55 result = prime * result + Arrays.hashCode(masks);
56 result = prime * result + queryExpressionTable.hashCode();
57 return result;
58 }
59
60 @Override
61 public boolean equals(Object obj) {
62 if (this == obj) {
63 return true;
64 }
65 if (obj == null) {
66 return false;
67 }
68 if (getClass() != obj.getClass()) {
69 return false;
70 }
71 CacheKey other = (CacheKey) obj;
72 if (queryExpressionTable != other.queryExpressionTable) {
73 return false;
74 }
75 return Arrays.equals(masks, other.masks);
76 }
77 }
78
79 private static final long ROW_COUNT_APPROXIMATION = 100;
80
81 /**
82 * Creates a list of column templates from a query (usually from WITH query,
83 * but could be any query)
84 *
85 * @param cols
86 * - an optional list of column names (can be specified by WITH
87 * clause overriding usual select names)
88 * @param theQuery
89 * - the query object we want the column list for
90 * @param querySQLOutput
91 * - array of length 1 to receive extra 'output' field in
92 * addition to return value - containing the SQL query of the
93 * Query object
94 * @return a list of column object returned by withQuery
95 */
96 public static List<Column> createQueryColumnTemplateList(String[] cols, Query theQuery, String[] querySQLOutput) {
97 ArrayList<Column> columnTemplateList = new ArrayList<>();
98 theQuery.prepare();
99 // String array of length 1 is to receive extra 'output' field in
100 // addition to
101 // return value
102 querySQLOutput[0] = StringUtils.cache(theQuery.getPlanSQL(ADD_PLAN_INFORMATION));
103 SessionLocal session = theQuery.getSession();
104 ArrayList<Expression> withExpressions = theQuery.getExpressions();
105 for (int i = 0; i < withExpressions.size(); ++i) {
106 Expression columnExp = withExpressions.get(i);
107 // use the passed in column name if supplied, otherwise use alias
108 // (if found) otherwise use column name derived from column
109 // expression
110 String columnName = cols != null && cols.length > i ? cols[i] : columnExp.getColumnNameForView(session, i);
111 columnTemplateList.add(new Column(columnName, columnExp.getType()));
112 }
113 return columnTemplateList;
114 }
115
116 static int getMaxParameterIndex(ArrayList<Parameter> parameters) {
117 int result = -1;
118 for (Parameter p : parameters) {
119 if (p != null) {
120 result = Math.max(result, p.getIndex());
121 }
122 }
123 return result;
124 }
125
126 Query viewQuery;
127
128 QueryExpressionIndex index;
129
130 ArrayList<Table> tables;
131
132 private long lastModificationCheck;
133
134 private long maxDataModificationId;
135
136 QueryExpressionTable(Schema schema, int id, String name) {
137 super(schema, id, name, false, true);
138 }
139
140 Column[] initColumns(SessionLocal session, Column[] columnTemplates, Query query, boolean isDerivedTable) {
141 ArrayList<Expression> expressions = query.getExpressions();
142 final int count = query.getColumnCount();
143 ArrayList<Column> list = new ArrayList<>(count);
144 for (int i = 0; i < count; i++) {
145 Expression expr = expressions.get(i);
146 String name = null;
147 TypeInfo type = TypeInfo.TYPE_UNKNOWN;
148 if (columnTemplates != null && columnTemplates.length > i) {
149 name = columnTemplates[i].getName();
150 type = columnTemplates[i].getType();
151 }
152 if (name == null) {
153 name = isDerivedTable ? expr.getAlias(session, i) : expr.getColumnNameForView(session, i);
154 }
155 if (type.getValueType() == Value.UNKNOWN) {
156 type = expr.getType();
157 }
158 list.add(new Column(name, type, this, i));
159 }
160 return list.toArray(new Column[0]);
161 }
162
163 public final Query getQuery() {
164 return viewQuery;
165 }
166
167 public abstract Query getTopQuery();
168
169 @Override
170 public final void close(SessionLocal session) {
171 // nothing to do
172 }
173
174 @Override
175 public final Index addIndex(SessionLocal session, String indexName, int indexId, IndexColumn[] cols,
176 int uniqueColumnCount, IndexType indexType, boolean create, String indexComment) {
177 throw DbException.getUnsupportedException(getClass().getSimpleName() + ".addIndex");
178 }
179
180 @Override
181 public final boolean isView() {
182 return true;
183 }
184
185 @Override
186 public final PlanItem getBestPlanItem(SessionLocal session, int[] masks, TableFilter[] filters, int filter,
187 SortOrder sortOrder, AllColumnsForPlan allColumnsSet) {
188 final CacheKey cacheKey = new CacheKey(masks, this);
189 Map<Object, QueryExpressionIndex> indexCache = session.getViewIndexCache(getTableType() == null);
190 QueryExpressionIndex i = indexCache.get(cacheKey);
191 if (i == null || i.isExpired()) {
192 i = new QueryExpressionIndex(this, index, session, masks, filters, filter, sortOrder);
193 indexCache.put(cacheKey, i);
194 }
195 PlanItem item = new PlanItem();
196 item.cost = i.getCost(session, masks, filters, filter, sortOrder, allColumnsSet);
197 item.setIndex(i);
198 return item;
199 }
200
201 @Override
202 public boolean isQueryComparable() {
203 for (Table t : tables) {
204 if (!t.isQueryComparable()) {
205 return false;
206 }
207 }
208 return true;
209 }
210
211 @Override
212 public final boolean isInsertable() {
213 return false;
214 }
215
216 @Override
217 public final void removeRow(SessionLocal session, Row row) {
218 throw DbException.getUnsupportedException(getClass().getSimpleName() + ".removeRow");
219 }
220
221 @Override
222 public final void addRow(SessionLocal session, Row row) {
223 throw DbException.getUnsupportedException(getClass().getSimpleName() + ".addRow");
224 }
225
226 @Override
227 public final void checkSupportAlter() {
228 throw DbException.getUnsupportedException(getClass().getSimpleName() + ".checkSupportAlter");
229 }
230
231 @Override
232 public final long truncate(SessionLocal session) {
233 throw DbException.getUnsupportedException(getClass().getSimpleName() + ".truncate");
234 }
235
236 @Override
237 public final long getRowCount(SessionLocal session) {
238 throw DbException.getInternalError(toString());
239 }
240
241 @Override
242 public final boolean canGetRowCount(SessionLocal session) {
243 // TODO could get the row count, but not that easy
244 return false;
245 }
246
247 @Override
248 public final long getRowCountApproximation(SessionLocal session) {
249 return ROW_COUNT_APPROXIMATION;
250 }
251
252 /**
253 * Get the index of the first parameter.
254 *
255 * @param additionalParameters
256 * additional parameters
257 * @return the index of the first parameter
258 */
259 public final int getParameterOffset(ArrayList<Parameter> additionalParameters) {
260 Query topQuery = getTopQuery();
261 int result = topQuery == null ? -1 : getMaxParameterIndex(topQuery.getParameters());
262 if (additionalParameters != null) {
263 result = Math.max(result, getMaxParameterIndex(additionalParameters));
264 }
265 return result + 1;
266 }
267
268 @Override
269 public final boolean canReference() {
270 return false;
271 }
272
273 @Override
274 public final ArrayList<Index> getIndexes() {
275 return null;
276 }
277
278 @Override
279 public long getMaxDataModificationId() {
280 // if nothing was modified in the database since the last check, and the
281 // last is known, then we don't need to check again
282 // this speeds up nested views
283 long dbMod = database.getModificationDataId();
284 if (dbMod > lastModificationCheck && maxDataModificationId <= dbMod) {
285 maxDataModificationId = viewQuery.getMaxDataModificationId();
286 lastModificationCheck = dbMod;
287 }
288 return maxDataModificationId;
289 }
290
291 @Override
292 public final Index getScanIndex(SessionLocal session) {
293 return getBestPlanItem(session, null, null, -1, null, null).getIndex();
294 }
295
296 @Override
297 public Index getScanIndex(SessionLocal session, int[] masks, TableFilter[] filters, int filter, //
298 SortOrder sortOrder, AllColumnsForPlan allColumnsSet) {
299 return getBestPlanItem(session, masks, filters, filter, sortOrder, allColumnsSet).getIndex();
300 }
301
302 @Override
303 public boolean isDeterministic() {
304 return viewQuery.isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR);
305 }
306
307 @Override
308 public final void addDependencies(HashSet<DbObject> dependencies) {
309 super.addDependencies(dependencies);
310 if (tables != null) {
311 for (Table t : tables) {
312 if (TableType.VIEW != t.getTableType()) {
313 t.addDependencies(dependencies);
314 }
315 }
316 }
317 }
318
319 }