Package org.h2.table
Class TableView
java.lang.Object
org.h2.engine.DbObject
org.h2.schema.SchemaObject
org.h2.table.Table
org.h2.table.TableView
- All Implemented Interfaces:
HasSQL
A view is a virtual table that is defined by a query.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final classThe key of the index cache for views. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate booleanprivate Column[]private DbExceptionprivate ViewIndexprivate booleanprivate booleanprivate longprivate longprivate Userprivate Stringprivate ResultInterfaceprivate static final longprivate Queryprivate QueryFields inherited from class org.h2.table.Table
columns, compareMode, EXCLUSIVE_LOCK, isHidden, READ_LOCK, TYPE_CACHED, TYPE_MEMORY, WRITE_LOCKFields inherited from class org.h2.engine.DbObject
AGGREGATE, comment, COMMENT, CONSTANT, CONSTRAINT, database, DOMAIN, FUNCTION_ALIAS, INDEX, RIGHT, ROLE, SCHEMA, SEQUENCE, SETTING, SYNONYM, TABLE_OR_VIEW, trace, TRIGGER, USERFields inherited from interface org.h2.util.HasSQL
ADD_PLAN_INFORMATION, DEFAULT_SQL_FLAGS, NO_CASTS, QUOTE_ONLY_WHEN_REQUIRED, REPLACE_LOBS_FOR_TRACE, TRACE_SQL_FLAGS -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddDependencies(HashSet<DbObject> dependencies) Add all objects that this table depends on to the hash set.private voidaddIndex(SessionLocal session, String indexName, int indexId, IndexColumn[] cols, int uniqueColumnCount, IndexType indexType, boolean create, String indexComment) Create an index for this tablevoidaddRow(SessionLocal session, Row row) Add a row to the table and all indexes.booleancanDrop()Check if this table can be dropped.booleancanGetRowCount(SessionLocal session) Check if the row count can be retrieved quickly.booleanCheck if this table can be referenced.voidCheck if this table supports ALTER TABLE.static voidclearIndexCaches(Database database) Clear the cached indexes for all sessions.voidclose(SessionLocal session) Close the table object and flush changes.private QuerycompileViewQuery(SessionLocal session, String sql, boolean literalsChecked) createQueryColumnTemplateList(String[] cols, Query theQuery, String[] querySQLOutput) Creates a list of column templates from a query (usually from WITH query, but could be any query)static TablecreateShadowTableForRecursiveTableExpression(boolean isTemporary, SessionLocal targetSession, String cteViewName, Schema schema, List<Column> columns, Database db) Create a table for a recursive query.static TableViewcreateTableViewMaybeRecursive(Schema schema, int id, String name, String querySQL, ArrayList<Parameter> parameters, Column[] columnTemplates, SessionLocal session, boolean literalsChecked, boolean isTableExpression, boolean isTemporary, Database db) Create a view.static TableViewcreateTempView(SessionLocal session, User owner, String name, Column[] columnTemplates, Query query, Query topQuery) Create a temporary view out of the given query.static voiddestroyShadowTableForRecursiveExpression(boolean isTemporary, SessionLocal targetSession, Table recursiveTable) Remove a table for a recursive query.getBestPlanItem(SessionLocal session, int[] masks, TableFilter[] filters, int filter, SortOrder sortOrder, AllColumnsForPlan allColumnsSet) Get the best plan for the given search mask.Construct the CREATE ...getCreateSQL(boolean orReplace, boolean force) Generate "CREATE" SQL statement for the view.private StringgetCreateSQL(boolean orReplace, boolean force, String quotedName) getCreateSQLForCopy(Table table, String quotedName) Build a SQL statement to re-create the object, or to create a copy of the object with a different name or referencing a different tableConstruct a DROP ...Get all indexes for this table.longGet the last data modification id.private static intgetMaxParameterIndex(ArrayList<Parameter> parameters) getOwner()intgetParameterOffset(ArrayList<Parameter> additionalParameters) Get the index of the first parameter.getQuery()longgetRowCount(SessionLocal session) Get the row count for this table.longgetRowCountApproximation(SessionLocal session) Get the approximated row count for this table.getScanIndex(SessionLocal session) Get the scan index to iterate through all rows.getScanIndex(SessionLocal session, int[] masks, TableFilter[] filters, int filter, SortOrder sortOrder, AllColumnsForPlan allColumnsSet) Get the scan index for this table.getSQL(StringBuilder builder, int sqlFlags) Appends the SQL statement of this object to the specified builder.Get the table type nameprivate voidinit(String querySQL, ArrayList<Parameter> params, Column[] columnTemplates, SessionLocal session, boolean allowRecursive, boolean literalsChecked, boolean isTableExpression) private voidinitColumnsAndTables(SessionLocal session, boolean literalsChecked) booleanCheck if the table is deterministic.booleanReturns whether this table is insertable.booleanCheck if this view is currently invalid.booleanCheck whether the table (or view) contains no columns that prevent index conditions to be used.booleanbooleanWas query recursion detected during compiling.private booleanisRecursiveQueryExceptionDetected(DbException exception) Does exception indicate query recursion?booleanisView()recompile(SessionLocal session, boolean force, boolean clearIndexCache) Re-compile the view query and all views that depend on this object.voidremoveChildrenAndResources(SessionLocal session) Delete all dependent children objects and resources of this object.private voidvoidremoveRow(SessionLocal session, Row row) Remove a row from the table and all indexes.voidreplace(String querySQL, Column[] newColumnTemplates, SessionLocal session, boolean recursive, boolean force, boolean literalsChecked) Try to replace the SQL statement of the view and re-compile this and all dependent views.private voidvoidprivate voidsetTopQuery(Query topQuery) longtruncate(SessionLocal session) Remove all rows from the table and indexes.Methods inherited from class org.h2.table.Table
addConstraint, addDependentView, addSequence, addSynonym, addTrigger, canTruncate, checkDeadlock, checkWritingAllowed, compareValues, convertInsertRow, convertUpdateRow, createRow, doesColumnExist, dropMultipleColumnsConstraintsAndIndexes, findColumn, findPrimaryKey, fire, fireAfterRow, fireBeforeRow, fireRow, getCheckForeignKeyConstraints, getChildren, getColumn, getColumn, getColumn, getColumns, getCompareMode, getConstraints, getDependentViews, getDiskSpaceUsed, getIdentityColumn, getIndex, getIndexForColumn, getMainIndexColumn, getNullRow, getOnCommitDrop, getOnCommitTruncate, getPrimaryKey, getRow, getRowFactory, getRowIdColumn, getSQLTableType, getTemplateRow, getTemplateSimpleRow, getTriggers, getType, hasSelectTrigger, isGlobalTemporary, isHidden, isLockedExclusively, isLockedExclusivelyBy, isPersistData, isPersistIndexes, isRowLockable, isTableExpression, lock, lockRow, removeColumnExpressionsDependencies, removeConstraint, removeDependentView, removeIndex, removeIndexOrTransferOwnership, removeSequence, removeSynonym, removeTrigger, rename, renameColumn, setCheckForeignKeyConstraints, setColumns, setHidden, setOnCommitDrop, setOnCommitTruncate, setTableExpression, unlock, updateRow, updateRowsMethods inherited from class org.h2.schema.SchemaObject
getSchema, getSQLMethods inherited from class org.h2.engine.DbObject
checkRename, getComment, getCreateSQLForMeta, getDatabase, getId, getModificationId, getName, invalidate, isTemporary, isValid, setComment, setModified, setObjectName, setTemporary, toStringMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface org.h2.util.HasSQL
getTraceSQL
-
Field Details
-
ROW_COUNT_APPROXIMATION
private static final long ROW_COUNT_APPROXIMATION- See Also:
-
querySQL
-
tables
-
columnTemplates
-
viewQuery
-
index
-
allowRecursive
private boolean allowRecursive -
createException
-
lastModificationCheck
private long lastModificationCheck -
maxDataModificationId
private long maxDataModificationId -
owner
-
topQuery
-
recursiveResult
-
isRecursiveQueryDetected
private boolean isRecursiveQueryDetected -
isTableExpression
private boolean isTableExpression
-
-
Constructor Details
-
TableView
-
-
Method Details
-
replace
public void replace(String querySQL, Column[] newColumnTemplates, SessionLocal session, boolean recursive, boolean force, boolean literalsChecked) Try to replace the SQL statement of the view and re-compile this and all dependent views.- Parameters:
querySQL- the SQL statementnewColumnTemplates- the columnssession- the sessionrecursive- whether this is a recursive viewforce- if errors should be ignoredliteralsChecked- if literals have been checked
-
init
private void init(String querySQL, ArrayList<Parameter> params, Column[] columnTemplates, SessionLocal session, boolean allowRecursive, boolean literalsChecked, boolean isTableExpression) -
compileViewQuery
-
recompile
Re-compile the view query and all views that depend on this object.- Parameters:
session- the sessionforce- if exceptions should be ignoredclearIndexCache- if we need to clear view index cache- Returns:
- the exception if re-compiling this or any dependent view failed (only when force is disabled)
-
initColumnsAndTables
-
isView
public boolean isView() -
isInvalid
public boolean isInvalid()Check if this view is currently invalid.- Returns:
- true if it is
-
getBestPlanItem
public PlanItem getBestPlanItem(SessionLocal session, int[] masks, TableFilter[] filters, int filter, SortOrder sortOrder, AllColumnsForPlan allColumnsSet) Description copied from class:TableGet the best plan for the given search mask.- Overrides:
getBestPlanItemin classTable- Parameters:
session- the sessionmasks- per-column comparison bit masks, null means 'always false', see constants in IndexConditionfilters- all joined table filtersfilter- the current table filter indexsortOrder- the sort orderallColumnsSet- the set of all columns- Returns:
- the plan item
-
isQueryComparable
public boolean isQueryComparable()Description copied from class:TableCheck whether the table (or view) contains no columns that prevent index conditions to be used. For example, a view that contains the ROWNUM() pseudo-column prevents this.- Overrides:
isQueryComparablein classTable- Returns:
- true if the table contains no query-comparable column
-
getTopQuery
-
getDropSQL
Description copied from class:DbObjectConstruct a DROP ... SQL statement for this object.- Overrides:
getDropSQLin classDbObject- Returns:
- the SQL statement
-
getCreateSQLForCopy
Description copied from class:DbObjectBuild a SQL statement to re-create the object, or to create a copy of the object with a different name or referencing a different table- Overrides:
getCreateSQLForCopyin classTable- Parameters:
table- the new tablequotedName- the quoted name- Returns:
- the SQL statement
-
getCreateSQL
Description copied from class:DbObjectConstruct the CREATE ... SQL statement for this object.- Specified by:
getCreateSQLin classDbObject- Returns:
- the SQL statement
-
getCreateSQL
Generate "CREATE" SQL statement for the view.- Parameters:
orReplace- if true, then include the OR REPLACE clauseforce- if true, then include the FORCE clause- Returns:
- the SQL statement
-
getCreateSQL
-
close
Description copied from class:TableClose the table object and flush changes. -
addIndex
public Index addIndex(SessionLocal session, String indexName, int indexId, IndexColumn[] cols, int uniqueColumnCount, IndexType indexType, boolean create, String indexComment) Description copied from class:TableCreate an index for this table- Specified by:
addIndexin classTable- Parameters:
session- the sessionindexName- the name of the indexindexId- the idcols- the index columnsuniqueColumnCount- the count of unique columnsindexType- the index typecreate- whether this is a new indexindexComment- the comment- Returns:
- the index
-
isInsertable
public boolean isInsertable()Description copied from class:TableReturns whether this table is insertable.- Overrides:
isInsertablein classTable- Returns:
- whether this table is insertable
-
removeRow
Description copied from class:TableRemove a row from the table and all indexes. -
addRow
Description copied from class:TableAdd a row to the table and all indexes. -
checkSupportAlter
public void checkSupportAlter()Description copied from class:TableCheck if this table supports ALTER TABLE.- Specified by:
checkSupportAlterin classTable
-
truncate
Description copied from class:TableRemove all rows from the table and indexes. -
getRowCount
Description copied from class:TableGet the row count for this table.- Specified by:
getRowCountin classTable- Parameters:
session- the session- Returns:
- the row count
-
canGetRowCount
Description copied from class:TableCheck if the row count can be retrieved quickly.- Specified by:
canGetRowCountin classTable- Parameters:
session- the session- Returns:
- true if it can
-
canDrop
public boolean canDrop()Description copied from class:TableCheck if this table can be dropped. -
getTableType
Description copied from class:TableGet the table type name- Specified by:
getTableTypein classTable- Returns:
- the table type name
-
removeChildrenAndResources
Description copied from class:DbObjectDelete all dependent children objects and resources of this object.- Overrides:
removeChildrenAndResourcesin classTable- Parameters:
session- the session
-
clearIndexCaches
Clear the cached indexes for all sessions.- Parameters:
database- the database
-
getSQL
Description copied from interface:HasSQLAppends the SQL statement of this object to the specified builder.- Specified by:
getSQLin interfaceHasSQL- Overrides:
getSQLin classSchemaObject- Parameters:
builder- string buildersqlFlags- formatting flags- Returns:
- the specified string builder
-
getQuery
-
getScanIndex
Description copied from class:TableGet the scan index to iterate through all rows.- Specified by:
getScanIndexin classTable- Parameters:
session- the session- Returns:
- the index
-
getScanIndex
public Index getScanIndex(SessionLocal session, int[] masks, TableFilter[] filters, int filter, SortOrder sortOrder, AllColumnsForPlan allColumnsSet) Description copied from class:TableGet the scan index for this table.- Overrides:
getScanIndexin classTable- Parameters:
session- the sessionmasks- the search maskfilters- the table filtersfilter- the filter indexsortOrder- the sort orderallColumnsSet- all columns- Returns:
- the scan index
-
canReference
public boolean canReference()Description copied from class:TableCheck if this table can be referenced.- Overrides:
canReferencein classTable- Returns:
- true if it can
-
getIndexes
Description copied from class:TableGet all indexes for this table.- Specified by:
getIndexesin classTable- Returns:
- the list of indexes
-
getMaxDataModificationId
public long getMaxDataModificationId()Description copied from class:TableGet the last data modification id.- Specified by:
getMaxDataModificationIdin classTable- Returns:
- the modification id
-
removeCurrentViewFromOtherTables
private void removeCurrentViewFromOtherTables() -
addDependentViewToTables
private void addDependentViewToTables() -
setOwner
-
getOwner
-
createTempView
public static TableView createTempView(SessionLocal session, User owner, String name, Column[] columnTemplates, Query query, Query topQuery) Create a temporary view out of the given query.- Parameters:
session- the sessionowner- the owner of the queryname- the view namecolumnTemplates- column templates, ornullquery- the querytopQuery- the top level query- Returns:
- the view table
-
setTopQuery
-
getRowCountApproximation
Description copied from class:TableGet the approximated row count for this table.- Specified by:
getRowCountApproximationin classTable- Parameters:
session- the session- Returns:
- the approximated row count
-
getParameterOffset
Get the index of the first parameter.- Parameters:
additionalParameters- additional parameters- Returns:
- the index of the first parameter
-
getMaxParameterIndex
-
isRecursive
public boolean isRecursive() -
isDeterministic
public boolean isDeterministic()Description copied from class:TableCheck if the table is deterministic.- Specified by:
isDeterministicin classTable- Returns:
- true if it is
-
setRecursiveResult
-
getRecursiveResult
-
addDependencies
Description copied from class:TableAdd all objects that this table depends on to the hash set.- Overrides:
addDependenciesin classTable- Parameters:
dependencies- the current set of dependencies
-
isRecursiveQueryDetected
public boolean isRecursiveQueryDetected()Was query recursion detected during compiling.- Returns:
- true if yes
-
isRecursiveQueryExceptionDetected
Does exception indicate query recursion? -
getTables
-
createTableViewMaybeRecursive
public static TableView createTableViewMaybeRecursive(Schema schema, int id, String name, String querySQL, ArrayList<Parameter> parameters, Column[] columnTemplates, SessionLocal session, boolean literalsChecked, boolean isTableExpression, boolean isTemporary, Database db) Create a view.- Parameters:
schema- the schemaid- the view idname- the view namequerySQL- the queryparameters- the parameterscolumnTemplates- the columnssession- the sessionliteralsChecked- whether literals in the query are checkedisTableExpression- if this is a table expressionisTemporary- whether the view is persisteddb- the database- Returns:
- the view
-
createQueryColumnTemplateList
public static List<Column> createQueryColumnTemplateList(String[] cols, Query theQuery, String[] querySQLOutput) Creates a list of column templates from a query (usually from WITH query, but could be any query)- Parameters:
cols- - an optional list of column names (can be specified by WITH clause overriding usual select names)theQuery- - the query object we want the column list forquerySQLOutput- - array of length 1 to receive extra 'output' field in addition to return value - containing the SQL query of the Query object- Returns:
- a list of column object returned by withQuery
-
createShadowTableForRecursiveTableExpression
public static Table createShadowTableForRecursiveTableExpression(boolean isTemporary, SessionLocal targetSession, String cteViewName, Schema schema, List<Column> columns, Database db) Create a table for a recursive query.- Parameters:
isTemporary- whether the table is persistedtargetSession- the sessioncteViewName- the nameschema- the schemacolumns- the columnsdb- the database- Returns:
- the table
-
destroyShadowTableForRecursiveExpression
public static void destroyShadowTableForRecursiveExpression(boolean isTemporary, SessionLocal targetSession, Table recursiveTable) Remove a table for a recursive query.- Parameters:
isTemporary- whether the table is persistedtargetSession- the sessionrecursiveTable- the table
-