Debian Codegraph @

src/main/org/h2/table/TableView.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.List;
11
12 import org.h2.api.ErrorCode;
13 import org.h2.command.Prepared;
14 import org.h2.command.ddl.CreateTableData;
15 import org.h2.command.query.AllColumnsForPlan;
16 import org.h2.command.query.Query;
17 import org.h2.engine.Database;
18 import org.h2.engine.SessionLocal;
19 import org.h2.expression.Parameter;
20 import org.h2.index.Index;
21 import org.h2.index.QueryExpressionIndex;
22 import org.h2.message.DbException;
23 import org.h2.result.ResultInterface;
24 import org.h2.result.SortOrder;
25 import org.h2.schema.Schema;
26 import org.h2.util.StringUtils;
27 import org.h2.util.Utils;
28
29 /**
30 * A view is a virtual table that is defined by a query.
31 * @author Thomas Mueller
32 * @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
33 */
34 public final class TableView extends QueryExpressionTable {
35
36 private String querySQL;
37 private Column[] columnTemplates;
38 private boolean allowRecursive;
39 private DbException createException;
40 private ResultInterface recursiveResult;
41 private boolean isRecursiveQueryDetected;
42 private boolean isTableExpression;
43
44 public TableView(Schema schema, int id, String name, String querySQL,
45 ArrayList<Parameter> params, Column[] columnTemplates, SessionLocal session,
46 boolean allowRecursive, boolean literalsChecked, boolean isTableExpression, boolean isTemporary) {
47 super(schema, id, name);
48 setTemporary(isTemporary);
49 init(querySQL, params, columnTemplates, session, allowRecursive, literalsChecked, isTableExpression);
50 }
51
52 /**
53 * Try to replace the SQL statement of the view and re-compile this and all
54 * dependent views.
55 *
56 * @param querySQL the SQL statement
57 * @param newColumnTemplates the columns
58 * @param session the session
59 * @param recursive whether this is a recursive view
60 * @param force if errors should be ignored
61 * @param literalsChecked if literals have been checked
62 */
63 public void replace(String querySQL, Column[] newColumnTemplates, SessionLocal session,
64 boolean recursive, boolean force, boolean literalsChecked) {
65 String oldQuerySQL = this.querySQL;
66 Column[] oldColumnTemplates = this.columnTemplates;
67 boolean oldRecursive = this.allowRecursive;
68 init(querySQL, null, newColumnTemplates, session, recursive, literalsChecked, isTableExpression);
69 DbException e = recompile(session, force, true);
70 if (e != null) {
71 init(oldQuerySQL, null, oldColumnTemplates, session, oldRecursive,
72 literalsChecked, isTableExpression);
73 recompile(session, true, false);
74 throw e;
75 }
76 }
77
78 private synchronized void init(String querySQL, ArrayList<Parameter> params,
79 Column[] columnTemplates, SessionLocal session, boolean allowRecursive, boolean literalsChecked,
80 boolean isTableExpression) {
81 this.querySQL = querySQL;
82 this.columnTemplates = columnTemplates;
83 this.allowRecursive = allowRecursive;
84 this.isRecursiveQueryDetected = false;
85 this.isTableExpression = isTableExpression;
86 index = new QueryExpressionIndex(this, querySQL, params, allowRecursive);
87 initColumnsAndTables(session, literalsChecked);
88 }
89
90 private Query compileViewQuery(SessionLocal session, String sql, boolean literalsChecked) {
91 Prepared p;
92 session.setParsingCreateView(true);
93 try {
94 p = session.prepare(sql, false, literalsChecked);
95 } finally {
96 session.setParsingCreateView(false);
97 }
98 if (!(p instanceof Query)) {
99 throw DbException.getSyntaxError(sql, 0);
100 }
101 Query q = (Query) p;
102 // only potentially recursive cte queries need to be non-lazy
103 if (isTableExpression && allowRecursive) {
104 q.setNeverLazy(true);
105 }
106 return q;
107 }
108
109 /**
110 * Re-compile the view query and all views that depend on this object.
111 *
112 * @param session the session
113 * @param force if exceptions should be ignored
114 * @param clearIndexCache if we need to clear view index cache
115 * @return the exception if re-compiling this or any dependent view failed
116 * (only when force is disabled)
117 */
118 public synchronized DbException recompile(SessionLocal session, boolean force,
119 boolean clearIndexCache) {
120 try {
121 compileViewQuery(session, querySQL, false);
122 } catch (DbException e) {
123 if (!force) {
124 return e;
125 }
126 }
127 ArrayList<TableView> dependentViews = new ArrayList<>(getDependentViews());
128 initColumnsAndTables(session, false);
129 for (TableView v : dependentViews) {
130 DbException e = v.recompile(session, force, false);
131 if (e != null && !force) {
132 return e;
133 }
134 }
135 if (clearIndexCache) {
136 clearIndexCaches(database);
137 }
138 return force ? null : createException;
139 }
140
141 private void initColumnsAndTables(SessionLocal session, boolean literalsChecked) {
142 Column[] cols;
143 removeCurrentViewFromOtherTables();
144 setTableExpression(isTableExpression);
145 try {
146 Query compiledQuery = compileViewQuery(session, querySQL, literalsChecked);
147 this.querySQL = compiledQuery.getPlanSQL(DEFAULT_SQL_FLAGS);
148 tables = new ArrayList<>(compiledQuery.getTables());
149 cols = initColumns(session, columnTemplates, compiledQuery, false);
150 createException = null;
151 viewQuery = compiledQuery;
152 } catch (DbException e) {
153 if (e.getErrorCode() == ErrorCode.COLUMN_ALIAS_IS_NOT_SPECIFIED_1) {
154 throw e;
155 }
156 e.addSQL(getCreateSQL());
157 createException = e;
158 // If it can't be compiled, then it's a 'zero column table'
159 // this avoids problems when creating the view when opening the
160 // database.
161 // If it can not be compiled - it could also be a recursive common
162 // table expression query.
163 if (isRecursiveQueryExceptionDetected(createException)) {
164 this.isRecursiveQueryDetected = true;
165 }
166 tables = Utils.newSmallArrayList();
167 cols = new Column[0];
168 if (allowRecursive && columnTemplates != null) {
169 cols = new Column[columnTemplates.length];
170 for (int i = 0; i < columnTemplates.length; i++) {
171 cols[i] = columnTemplates[i].getClone();
172 }
173 index.setRecursive(true);
174 createException = null;
175 }
176 }
177 setColumns(cols);
178 if (getId() != 0) {
179 addDependentViewToTables();
180 }
181 }
182
183 /**
184 * Check if this view is currently invalid.
185 *
186 * @return true if it is
187 */
188 public boolean isInvalid() {
189 return createException != null;
190 }
191
192 @Override
193 public Query getTopQuery() {
194 return null;
195 }
196
197 @Override
198 public String getDropSQL() {
199 return getSQL(new StringBuilder("DROP VIEW IF EXISTS "), DEFAULT_SQL_FLAGS).append(" CASCADE").toString();
200 }
201
202 @Override
203 public String getCreateSQLForCopy(Table table, String quotedName) {
204 return getCreateSQL(false, true, quotedName);
205 }
206
207
208 @Override
209 public String getCreateSQL() {
210 return getCreateSQL(false, true);
211 }
212
213 /**
214 * Generate "CREATE" SQL statement for the view.
215 *
216 * @param orReplace if true, then include the OR REPLACE clause
217 * @param force if true, then include the FORCE clause
218 * @return the SQL statement
219 */
220 public String getCreateSQL(boolean orReplace, boolean force) {
221 return getCreateSQL(orReplace, force, getSQL(DEFAULT_SQL_FLAGS));
222 }
223
224 private String getCreateSQL(boolean orReplace, boolean force, String quotedName) {
225 StringBuilder builder = new StringBuilder("CREATE ");
226 if (orReplace) {
227 builder.append("OR REPLACE ");
228 }
229 if (force) {
230 builder.append("FORCE ");
231 }
232 builder.append("VIEW ");
233 if (isTableExpression) {
234 builder.append("TABLE_EXPRESSION ");
235 }
236 builder.append(quotedName);
237 if (comment != null) {
238 builder.append(" COMMENT ");
239 StringUtils.quoteStringSQL(builder, comment);
240 }
241 if (columns != null && columns.length > 0) {
242 builder.append('(');
243 Column.writeColumns(builder, columns, DEFAULT_SQL_FLAGS);
244 builder.append(')');
245 } else if (columnTemplates != null) {
246 builder.append('(');
247 Column.writeColumns(builder, columnTemplates, DEFAULT_SQL_FLAGS);
248 builder.append(')');
249 }
250 return builder.append(" AS\n").append(querySQL).toString();
251 }
252
253 @Override
254 public boolean canDrop() {
255 return true;
256 }
257
258 @Override
259 public TableType getTableType() {
260 return TableType.VIEW;
261 }
262
263 @Override
264 public void removeChildrenAndResources(SessionLocal session) {
265 removeCurrentViewFromOtherTables();
266 super.removeChildrenAndResources(session);
267 querySQL = null;
268 index = null;
269 clearIndexCaches(database);
270 invalidate();
271 }
272
273 /**
274 * Clear the cached indexes for all sessions.
275 *
276 * @param database the database
277 */
278 public static void clearIndexCaches(Database database) {
279 for (SessionLocal s : database.getSessions(true)) {
280 s.clearViewIndexCache();
281 }
282 }
283
284 @Override
285 public StringBuilder getSQL(StringBuilder builder, int sqlFlags) {
286 if (isTemporary() && querySQL != null) {
287 builder.append("(\n");
288 return StringUtils.indent(builder, querySQL, 4, true).append(')');
289 }
290 return super.getSQL(builder, sqlFlags);
291 }
292
293 public String getQuerySQL() {
294 return querySQL;
295 }
296
297 @Override
298 public Index getScanIndex(SessionLocal session, int[] masks,
299 TableFilter[] filters, int filter, SortOrder sortOrder,
300 AllColumnsForPlan allColumnsSet) {
301 if (createException != null) {
302 String msg = createException.getMessage();
303 throw DbException.get(ErrorCode.VIEW_IS_INVALID_2, createException, getTraceSQL(), msg);
304 }
305 return super.getScanIndex(session, masks, filters, filter, sortOrder, allColumnsSet);
306 }
307
308 @Override
309 public long getMaxDataModificationId() {
310 if (createException != null || viewQuery == null) {
311 return Long.MAX_VALUE;
312 }
313 return super.getMaxDataModificationId();
314 }
315
316 private void removeCurrentViewFromOtherTables() {
317 if (tables != null) {
318 for (Table t : tables) {
319 t.removeDependentView(this);
320 }
321 tables.clear();
322 }
323 }
324
325 private void addDependentViewToTables() {
326 for (Table t : tables) {
327 t.addDependentView(this);
328 }
329 }
330
331 public boolean isRecursive() {
332 return allowRecursive;
333 }
334
335 @Override
336 public boolean isDeterministic() {
337 if (allowRecursive || viewQuery == null) {
338 return false;
339 }
340 return super.isDeterministic();
341 }
342
343 public void setRecursiveResult(ResultInterface value) {
344 if (recursiveResult != null) {
345 recursiveResult.close();
346 }
347 this.recursiveResult = value;
348 }
349
350 public ResultInterface getRecursiveResult() {
351 return recursiveResult;
352 }
353
354 /**
355 * Was query recursion detected during compiling.
356 *
357 * @return true if yes
358 */
359 public boolean isRecursiveQueryDetected() {
360 return isRecursiveQueryDetected;
361 }
362
363 /**
364 * Does exception indicate query recursion?
365 */
366 private boolean isRecursiveQueryExceptionDetected(DbException exception) {
367 if (exception == null) {
368 return false;
369 }
370 int errorCode = exception.getErrorCode();
371 if (errorCode != ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1 &&
372 errorCode != ErrorCode.TABLE_OR_VIEW_NOT_FOUND_DATABASE_EMPTY_1 &&
373 errorCode != ErrorCode.TABLE_OR_VIEW_NOT_FOUND_WITH_CANDIDATES_2
374 ) {
375 return false;
376 }
377 return exception.getMessage().contains("\"" + this.getName() + "\"");
378 }
379
380 public List<Table> getTables() {
381 return tables;
382 }
383
384 /**
385 * Create a view.
386 *
387 * @param schema the schema
388 * @param id the view id
389 * @param name the view name
390 * @param querySQL the query
391 * @param parameters the parameters
392 * @param columnTemplates the columns
393 * @param session the session
394 * @param literalsChecked whether literals in the query are checked
395 * @param isTableExpression if this is a table expression
396 * @param isTemporary whether the view is persisted
397 * @param db the database
398 * @return the view
399 */
400 public static TableView createTableViewMaybeRecursive(Schema schema, int id, String name, String querySQL,
401 ArrayList<Parameter> parameters, Column[] columnTemplates, SessionLocal session,
402 boolean literalsChecked, boolean isTableExpression, boolean isTemporary, Database db) {
403
404
405 Table recursiveTable = createShadowTableForRecursiveTableExpression(isTemporary, session, name,
406 schema, Arrays.asList(columnTemplates), db);
407
408 List<Column> columnTemplateList;
409 String[] querySQLOutput = new String[1];
410 ArrayList<String> columnNames = new ArrayList<>();
411 for (Column columnTemplate: columnTemplates) {
412 columnNames.add(columnTemplate.getName());
413 }
414
415 try {
416 Prepared withQuery = session.prepare(querySQL, false, false);
417 if (!isTemporary) {
418 withQuery.setSession(session);
419 }
420 columnTemplateList = createQueryColumnTemplateList(columnNames.toArray(new String[1]),
421 (Query) withQuery, querySQLOutput);
422
423 } finally {
424 destroyShadowTableForRecursiveExpression(isTemporary, session, recursiveTable);
425 }
426
427 // build with recursion turned on
428 TableView view = new TableView(schema, id, name, querySQL,
429 parameters, columnTemplateList.toArray(columnTemplates), session,
430 true/* try recursive */, literalsChecked, isTableExpression, isTemporary);
431
432 // is recursion really detected ? if not - recreate it without recursion flag
433 // and no recursive index
434 if (!view.isRecursiveQueryDetected()) {
435 if (!isTemporary) {
436 db.addSchemaObject(session, view);
437 view.lock(session, Table.EXCLUSIVE_LOCK);
438 session.getDatabase().removeSchemaObject(session, view);
439
440 // during database startup - this method does not normally get called - and it
441 // needs to be to correctly un-register the table which the table expression
442 // uses...
443 view.removeChildrenAndResources(session);
444 } else {
445 session.removeLocalTempTable(view);
446 }
447 view = new TableView(schema, id, name, querySQL, parameters,
448 columnTemplates, session,
449 false/* detected not recursive */, literalsChecked, isTableExpression, isTemporary);
450 }
451
452 return view;
453 }
454
455 /**
456 * Create a table for a recursive query.
457 *
458 * @param isTemporary whether the table is persisted
459 * @param targetSession the session
460 * @param cteViewName the name
461 * @param schema the schema
462 * @param columns the columns
463 * @param db the database
464 * @return the table
465 */
466 public static Table createShadowTableForRecursiveTableExpression(boolean isTemporary, SessionLocal targetSession,
467 String cteViewName, Schema schema, List<Column> columns, Database db) {
468
469 // create table data object
470 CreateTableData recursiveTableData = new CreateTableData();
471 recursiveTableData.id = db.allocateObjectId();
472 recursiveTableData.columns = new ArrayList<>(columns);
473 recursiveTableData.tableName = cteViewName;
474 recursiveTableData.temporary = isTemporary;
475 recursiveTableData.persistData = true;
476 recursiveTableData.persistIndexes = !isTemporary;
477 recursiveTableData.session = targetSession;
478
479 // this gets a meta table lock that is not released
480 Table recursiveTable = schema.createTable(recursiveTableData);
481
482 if (!isTemporary) {
483 // this unlock is to prevent lock leak from schema.createTable()
484 db.unlockMeta(targetSession);
485 synchronized (targetSession) {
486 db.addSchemaObject(targetSession, recursiveTable);
487 }
488 } else {
489 targetSession.addLocalTempTable(recursiveTable);
490 }
491 return recursiveTable;
492 }
493
494 /**
495 * Remove a table for a recursive query.
496 *
497 * @param isTemporary whether the table is persisted
498 * @param targetSession the session
499 * @param recursiveTable the table
500 */
501 public static void destroyShadowTableForRecursiveExpression(boolean isTemporary, SessionLocal targetSession,
502 Table recursiveTable) {
503 if (recursiveTable != null) {
504 if (!isTemporary) {
505 recursiveTable.lock(targetSession, Table.EXCLUSIVE_LOCK);
506 targetSession.getDatabase().removeSchemaObject(targetSession, recursiveTable);
507
508 } else {
509 targetSession.removeLocalTempTable(recursiveTable);
510 }
511
512 // both removeSchemaObject and removeLocalTempTable hold meta locks - release them here
513 targetSession.getDatabase().unlockMeta(targetSession);
514 }
515 }
516 }