Class Table
java.lang.Object
org.h2.engine.DbObject
org.h2.schema.SchemaObject
org.h2.table.Table
- All Implemented Interfaces:
HasSQL
- Direct Known Subclasses:
MetaTable, TableBase, TableLink, TableView, VirtualTable
This is the base class for most tables.
A table contains a list of columns and a list of rows.
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate booleanIs foreign key constraint checking enabled for this table.protected Column[]The columns of this table.protected CompareModeThe compare mode used for this table.private ArrayList<Constraint> private final CopyOnWriteArrayList<TableView> views that depend on this tablestatic final intExclusive lock.protected booleanProtected tables are not listed in the meta data and are excluded when using the SCRIPT command.private Rowprivate booleanprivate booleanprivate final booleanprivate final booleanstatic final intRead lock.private RowFactoryprivate ArrayList<TableSynonym> private booleanprivate ArrayList<TriggerObject> static final intThe table type that means this table is a regular persistent table.static final intThe table type that means this table is a regular persistent table.static final intWrite lock.Fields inherited from class 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 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 TypeMethodDescriptionprivate static <T> ArrayList<T> voidaddConstraint(Constraint constraint) Add a constraint to the table.voidaddDependencies(HashSet<DbObject> dependencies) Add all objects that this table depends on to the hash set.voidaddDependentView(TableView view) Add a view to this table.abstract IndexaddIndex(SessionLocal session, String indexName, int indexId, IndexColumn[] cols, int uniqueColumnCount, IndexType indexType, boolean create, String indexComment) Create an index for this tableabstract voidaddRow(SessionLocal session, Row row) Add a row to the table and all indexes.voidaddSequence(Sequence sequence) Add a sequence to this table.voidaddSynonym(TableSynonym synonym) Add a synonym to this table.voidaddTrigger(TriggerObject trigger) Add a trigger to this table.abstract booleancanDrop()Check if this table can be dropped.abstract booleancanGetRowCount(SessionLocal session) Check if the row count can be retrieved quickly.booleanCheck if this table can be referenced.booleanCheck if this table can be truncated.checkDeadlock(SessionLocal session, SessionLocal clash, Set<SessionLocal> visited) Check if a deadlock occurred.abstract voidCheck if this table supports ALTER TABLE.voidTests if the table can be written.abstract voidclose(SessionLocal session) Close the table object and flush changes.intcompareValues(CastDataProvider provider, Value a, Value b) Compare two values with the current comparison mode.voidconvertInsertRow(SessionLocal session, Row row, Boolean overridingSystem) Prepares the specified row for INSERT operation.voidconvertUpdateRow(SessionLocal session, Row row, boolean fromTrigger) Prepares the specified row for UPDATE operation.Create a new row for this table.booleandoesColumnExist(String columnName) Does the column with the given name exist?voiddropMultipleColumnsConstraintsAndIndexes(SessionLocal session, ArrayList<Column> columnsToDrop) Check that these columns are not referenced by a multi-column constraint or multi-column index.findColumn(String columnName) Get the column with the given name if it exists.Get the primary key index if there is one, or null if there is none.voidfire(SessionLocal session, int type, boolean beforeAction) Fire the triggers for this table.voidfireAfterRow(SessionLocal session, Row oldRow, Row newRow, boolean rollback) Fire all triggers that need to be called after a row is updated.booleanfireBeforeRow(SessionLocal session, Row oldRow, Row newRow) Fire all triggers that need to be called before a row is updated.private voidfireConstraints(SessionLocal session, Row oldRow, Row newRow, boolean before) booleanfireRow()Check if row based triggers or constraints are defined.private booleanfireRow(SessionLocal session, Row oldRow, Row newRow, boolean beforeAction, boolean rollback) getBestPlanItem(SessionLocal session, int[] masks, TableFilter[] filters, int filter, SortOrder sortOrder, AllColumnsForPlan allColumnsSet) Get the best plan for the given search mask.booleanGet the list of dependent children (for tables, this includes indexes and so on).getColumn(int index) Get the column at the given index.Get the column with the given name.Get the column with the given name.Column[]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 tablelongReturns first identity column, ornull.Get an index by name.Get all indexes for this table.getIndexForColumn(Column column, boolean needGetFirstOrLast, boolean needFindNext) Get the index that has the given column as the first element.private static IndexHintsgetIndexHints(TableFilter[] filters, int filter) intReturns ID of main index column, orSearchRow.ROWID_INDEX.abstract longGet the last data modification id.booleanbooleangetRow(SessionLocal session, long key) Get the given row.abstract longgetRowCount(SessionLocal session) Get the row count for this table.abstract longgetRowCountApproximation(SessionLocal session) Get the approximated row count for this table.Get the row id column if this table has one.abstract IndexgetScanIndex(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.Return SQL table type for INFORMATION_SCHEMA.abstract TableTypeGet the table type namegetTemplateSimpleRow(boolean singleColumn) Get a new simple row object.Return list of triggers.intgetType()Get the object type.booleanCheck whether this table has a select trigger.abstract booleanCheck if the table is deterministic.booleanbooleanisHidden()Check whether this is a hidden object that doesn't appear in the meta data and in the script, and is not dropped on DROP ALL OBJECTS.private static booleanisIndexExcludedByHints(IndexHints indexHints, Index index) booleanReturns whether this table is insertable.booleanCheck if this table is locked exclusively.booleanisLockedExclusivelyBy(SessionLocal session) Check if the table is exclusively locked by this session.booleanbooleanbooleanCheck whether the table (or view) contains no columns that prevent index conditions to be used.booleanViews, function tables, links, etc.booleanbooleanisView()booleanlock(SessionLocal session, int lockType) Lock the table for the given session.lockRow(SessionLocal session, Row row) Locks row, preventing any updated to it, except from the session specified.private static voidvoidremoveChildrenAndResources(SessionLocal session) Delete all dependent children objects and resources of this object.voidRemoves dependencies of column expressions, used for tables with circular dependencies.voidremoveConstraint(Constraint constraint) Remove the given constraint from the list.voidremoveDependentView(TableView view) Remove the given view from the dependent views list.voidremoveIndex(Index index) Remove the given index from the list.voidremoveIndexOrTransferOwnership(SessionLocal session, Index index) If the index is still required by a constraint, transfer the ownership to it.abstract voidremoveRow(SessionLocal session, Row row) Remove a row from the table and all indexes.final voidremoveSequence(Sequence sequence) Remove a sequence from the table.voidremoveSynonym(TableSynonym synonym) Remove the given view from the list.voidremoveTrigger(TriggerObject trigger) Remove the given trigger from the list.voidRename the object.voidrenameColumn(Column column, String newName) Rename a column of this table.voidsetCheckForeignKeyConstraints(SessionLocal session, boolean enabled, boolean checkExisting) Enable or disable foreign key constraint checking for this table.protected voidsetColumns(Column[] columns) voidsetHidden(boolean hidden) voidsetOnCommitDrop(boolean onCommitDrop) voidsetOnCommitTruncate(boolean onCommitTruncate) voidsetTableExpression(boolean tableExpression) abstract longtruncate(SessionLocal session) Remove all rows from the table and indexes.voidRelease the lock for this session.voidupdateRow(SessionLocal session, Row oldRow, Row newRow) Update a row to the table and all indexes.voidupdateRows(Prepared prepared, SessionLocal session, LocalResult rows) Update a list of rows in this table.Methods inherited from class SchemaObject
getSchema, getSQL, getSQLMethods inherited from class DbObject
checkRename, getComment, getCreateSQL, getCreateSQLForMeta, getDatabase, getDropSQL, getId, getModificationId, getName, invalidate, isTemporary, isValid, setComment, setModified, setObjectName, setTemporary, toStringMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface HasSQL
getTraceSQL
-
Field Details
-
TYPE_CACHED
public static final int TYPE_CACHEDThe table type that means this table is a regular persistent table.- See Also:
-
TYPE_MEMORY
public static final int TYPE_MEMORYThe table type that means this table is a regular persistent table.- See Also:
-
READ_LOCK
public static final int READ_LOCKRead lock.- See Also:
-
WRITE_LOCK
public static final int WRITE_LOCKWrite lock.- See Also:
-
EXCLUSIVE_LOCK
public static final int EXCLUSIVE_LOCKExclusive lock.- See Also:
-
columns
The columns of this table. -
compareMode
The compare mode used for this table. -
isHidden
protected boolean isHiddenProtected tables are not listed in the meta data and are excluded when using the SCRIPT command. -
columnMap
-
persistIndexes
private final boolean persistIndexes -
persistData
private final boolean persistData -
triggers
-
constraints
-
sequences
-
dependentViews
views that depend on this table -
synonyms
-
checkForeignKeyConstraints
private boolean checkForeignKeyConstraintsIs foreign key constraint checking enabled for this table. -
onCommitDrop
private boolean onCommitDrop -
onCommitTruncate
private boolean onCommitTruncate -
nullRow
-
rowFactory
-
tableExpression
private boolean tableExpression
-
-
Constructor Details
-
Table
-
-
Method Details
-
rename
-
isView
public boolean isView() -
lock
Lock the table for the given session. This method waits until the lock is granted.- Parameters:
session- the sessionlockType- the type of lock- Returns:
- true if the table was already exclusively locked by this session.
- Throws:
DbException- if a lock timeout occurred
-
close
Close the table object and flush changes.- Parameters:
session- the session
-
unlock
-
addIndex
public abstract Index addIndex(SessionLocal session, String indexName, int indexId, IndexColumn[] cols, int uniqueColumnCount, IndexType indexType, boolean create, String indexComment) Create an index for this table- 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
-
getRow
Get the given row.- Parameters:
session- the sessionkey- the primary key- Returns:
- the row
-
isInsertable
public boolean isInsertable()Returns whether this table is insertable.- Returns:
- whether this table is insertable
-
removeRow
Remove a row from the table and all indexes.- Parameters:
session- the sessionrow- the row
-
lockRow
Locks row, preventing any updated to it, except from the session specified.- Parameters:
session- the sessionrow- to lock- Returns:
- locked row, or null if row does not exist anymore
-
truncate
Remove all rows from the table and indexes.- Parameters:
session- the session- Returns:
- number of removed rows, possibly including uncommitted rows
-
addRow
Add a row to the table and all indexes.- Parameters:
session- the sessionrow- the row- Throws:
DbException- if a constraint was violated
-
updateRow
Update a row to the table and all indexes.- Parameters:
session- the sessionoldRow- the row to updatenewRow- the row with updated values (_rowid_ suppose to be the same)- Throws:
DbException- if a constraint was violated
-
checkSupportAlter
public abstract void checkSupportAlter()Check if this table supports ALTER TABLE.- Throws:
DbException- if it is not supported
-
getTableType
-
getSQLTableType
Return SQL table type for INFORMATION_SCHEMA.- Returns:
- SQL table type for INFORMATION_SCHEMA
-
getScanIndex
Get the scan index to iterate through all rows.- Parameters:
session- the session- Returns:
- the index
-
getScanIndex
public Index getScanIndex(SessionLocal session, int[] masks, TableFilter[] filters, int filter, SortOrder sortOrder, AllColumnsForPlan allColumnsSet) Get the scan index for this table.- Parameters:
session- the sessionmasks- the search maskfilters- the table filtersfilter- the filter indexsortOrder- the sort orderallColumnsSet- all columns- Returns:
- the scan index
-
getIndexes
-
getIndex
-
isLockedExclusively
public boolean isLockedExclusively()Check if this table is locked exclusively.- Returns:
- true if it is.
-
getMaxDataModificationId
public abstract long getMaxDataModificationId()Get the last data modification id.- Returns:
- the modification id
-
isDeterministic
public abstract boolean isDeterministic()Check if the table is deterministic.- Returns:
- true if it is
-
canGetRowCount
Check if the row count can be retrieved quickly.- Parameters:
session- the session- Returns:
- true if it can
-
canReference
public boolean canReference()Check if this table can be referenced.- Returns:
- true if it can
-
canDrop
public abstract boolean canDrop()Check if this table can be dropped.- Returns:
- true if it can
-
getRowCount
Get the row count for this table.- Parameters:
session- the session- Returns:
- the row count
-
getRowCountApproximation
Get the approximated row count for this table.- Parameters:
session- the session- Returns:
- the approximated row count
-
getDiskSpaceUsed
public long getDiskSpaceUsed() -
getRowIdColumn
Get the row id column if this table has one.- Returns:
- the row id column, or null
-
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- Specified by:
getCreateSQLForCopyin classDbObject- Parameters:
table- the new tablequotedName- the quoted name- Returns:
- the SQL statement
-
isQueryComparable
public boolean isQueryComparable()Check 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.- Returns:
- true if the table contains no query-comparable column
-
addDependencies
-
getChildren
Description copied from class:DbObjectGet the list of dependent children (for tables, this includes indexes and so on).- Overrides:
getChildrenin classDbObject- Returns:
- the list of children, or
null
-
setColumns
-
renameColumn
-
isLockedExclusivelyBy
Check if the table is exclusively locked by this session.- Parameters:
session- the session- Returns:
- true if it is
-
updateRows
Update a list of rows in this table.- Parameters:
prepared- the prepared statementsession- the sessionrows- a list of row pairs of the form old row, new row, old row, new row,...
-
getDependentViews
-
removeChildrenAndResources
Description copied from class:DbObjectDelete all dependent children objects and resources of this object.- Specified by:
removeChildrenAndResourcesin classDbObject- Parameters:
session- the session
-
dropMultipleColumnsConstraintsAndIndexes
public void dropMultipleColumnsConstraintsAndIndexes(SessionLocal session, ArrayList<Column> columnsToDrop) Check that these columns are not referenced by a multi-column constraint or multi-column index. If it is, an exception is thrown. Single-column references and indexes are dropped.- Parameters:
session- the sessioncolumnsToDrop- the columns to drop- Throws:
DbException- if the column is referenced by multi-column constraints or indexes
-
getRowFactory
-
createRow
-
getTemplateRow
-
getTemplateSimpleRow
Get a new simple row object.- Parameters:
singleColumn- if only one value need to be stored- Returns:
- the simple row object
-
getNullRow
-
getColumns
-
getType
-
getColumn
Get the column at the given index.- Parameters:
index- the column index (0, 1,...)- Returns:
- the column
-
getColumn
Get the column with the given name.- Parameters:
columnName- the column name- Returns:
- the column
- Throws:
DbException- if the column was not found
-
getColumn
Get the column with the given name.- Parameters:
columnName- the column nameifExists- if (@code true) returnnullif column does not exist- Returns:
- the column
- Throws:
DbException- if the column was not found
-
findColumn
-
doesColumnExist
Does the column with the given name exist?- Parameters:
columnName- the column name- Returns:
- true if the column exists
-
getIdentityColumn
Returns first identity column, ornull.- Returns:
- first identity column, or
null
-
getBestPlanItem
public PlanItem getBestPlanItem(SessionLocal session, int[] masks, TableFilter[] filters, int filter, SortOrder sortOrder, AllColumnsForPlan allColumnsSet) Get the best plan for the given search mask.- 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
-
isIndexExcludedByHints
-
getIndexHints
-
findPrimaryKey
Get the primary key index if there is one, or null if there is none.- Returns:
- the primary key index or null
-
getPrimaryKey
-
convertInsertRow
Prepares the specified row for INSERT operation. Identity, default, and generated values are evaluated, all values are converted to target data types and validated. Base value of identity column is updated when required by compatibility mode.- Parameters:
session- the sessionrow- the rowoverridingSystem-Boolean.TRUEforOVERRIDING SYSTEM VALUES,Boolean.FALSEforOVERRIDING USER VALUES,nullif override clause is not specified
-
convertUpdateRow
Prepares the specified row for UPDATE operation. Default and generated values are evaluated, all values are converted to target data types and validated. Base value of identity column is updated when required by compatibility mode.- Parameters:
session- the sessionrow- the rowfromTrigger-trueif row was modified by INSERT or UPDATE trigger
-
remove
-
removeIndex
Remove the given index from the list.- Parameters:
index- the index to remove
-
removeDependentView
Remove the given view from the dependent views list.- Parameters:
view- the view to remove
-
removeSynonym
Remove the given view from the list.- Parameters:
synonym- the synonym to remove
-
removeConstraint
Remove the given constraint from the list.- Parameters:
constraint- the constraint to remove
-
removeSequence
Remove a sequence from the table. Sequences are used as identity columns.- Parameters:
sequence- the sequence to remove
-
removeTrigger
Remove the given trigger from the list.- Parameters:
trigger- the trigger to remove
-
addDependentView
Add a view to this table.- Parameters:
view- the view to add
-
addSynonym
Add a synonym to this table.- Parameters:
synonym- the synonym to add
-
addConstraint
Add a constraint to the table.- Parameters:
constraint- the constraint to add
-
getConstraints
-
addSequence
Add a sequence to this table.- Parameters:
sequence- the sequence to add
-
addTrigger
Add a trigger to this table.- Parameters:
trigger- the trigger to add
-
add
-
fire
Fire the triggers for this table.- Parameters:
session- the sessiontype- the trigger typebeforeAction- whether 'before' triggers should be called
-
hasSelectTrigger
public boolean hasSelectTrigger()Check whether this table has a select trigger.- Returns:
- true if it has
-
fireRow
public boolean fireRow()Check if row based triggers or constraints are defined. In this case the fire after and before row methods need to be called.- Returns:
- if there are any triggers or rows defined
-
fireBeforeRow
Fire all triggers that need to be called before a row is updated.- Parameters:
session- the sessionoldRow- the old data or null for an insertnewRow- the new data or null for a delete- Returns:
- true if no further action is required (for 'instead of' triggers)
-
fireConstraints
-
fireAfterRow
Fire all triggers that need to be called after a row is updated.- Parameters:
session- the sessionoldRow- the old data or null for an insertnewRow- the new data or null for a deleterollback- when the operation occurred within a rollback
-
fireRow
private boolean fireRow(SessionLocal session, Row oldRow, Row newRow, boolean beforeAction, boolean rollback) -
isGlobalTemporary
public boolean isGlobalTemporary() -
canTruncate
public boolean canTruncate()Check if this table can be truncated.- Returns:
- true if it can
-
setCheckForeignKeyConstraints
public void setCheckForeignKeyConstraints(SessionLocal session, boolean enabled, boolean checkExisting) Enable or disable foreign key constraint checking for this table.- Parameters:
session- the sessionenabled- true if checking should be enabledcheckExisting- true if existing rows must be checked during this call
-
getCheckForeignKeyConstraints
public boolean getCheckForeignKeyConstraints()- Returns:
- is foreign key constraint checking enabled for this table.
-
getIndexForColumn
Get the index that has the given column as the first element. This method returns null if no matching index is found.- Parameters:
column- the columnneedGetFirstOrLast- if the returned index must be able to doIndex.canGetFirstOrLast()needFindNext- if the returned index must be able to doIndex.findNext(SessionLocal, SearchRow, SearchRow)- Returns:
- the index or null
-
getOnCommitDrop
public boolean getOnCommitDrop() -
setOnCommitDrop
public void setOnCommitDrop(boolean onCommitDrop) -
getOnCommitTruncate
public boolean getOnCommitTruncate() -
setOnCommitTruncate
public void setOnCommitTruncate(boolean onCommitTruncate) -
removeIndexOrTransferOwnership
If the index is still required by a constraint, transfer the ownership to it. Otherwise, the index is removed.- Parameters:
session- the sessionindex- the index that is no longer required
-
removeColumnExpressionsDependencies
Removes dependencies of column expressions, used for tables with circular dependencies.- Parameters:
session- the session
-
checkDeadlock
public ArrayList<SessionLocal> checkDeadlock(SessionLocal session, SessionLocal clash, Set<SessionLocal> visited) Check if a deadlock occurred. This method is called recursively. There is a circle if the session to be tested has already being visited. If this session is part of the circle (if it is the clash session), the method must return an empty object array. Once a deadlock has been detected, the methods must add the session to the list. If this session is not part of the circle, or if no deadlock is detected, this method returns null.- Parameters:
session- the session to be tested forclash- set with sessions already visited, and null when starting verificationvisited- set with sessions already visited, and null when starting verification- Returns:
- an object array with the sessions involved in the deadlock, or null
-
isPersistIndexes
public boolean isPersistIndexes() -
isPersistData
public boolean isPersistData() -
compareValues
Compare two values with the current comparison mode. The values may be of different type.- Parameters:
provider- the cast information providera- the first valueb- the second value- Returns:
- 0 if both values are equal, -1 if the first value is smaller, and 1 otherwise
-
getCompareMode
-
checkWritingAllowed
public void checkWritingAllowed()Tests if the table can be written. Usually, this depends on the database.checkWritingAllowed method, but some tables (eg. TableLink) overwrite this default behaviour. -
isHidden
public boolean isHidden()Description copied from class:SchemaObjectCheck whether this is a hidden object that doesn't appear in the meta data and in the script, and is not dropped on DROP ALL OBJECTS.- Overrides:
isHiddenin classSchemaObject- Returns:
- true if it is hidden
-
setHidden
public void setHidden(boolean hidden) -
isRowLockable
public boolean isRowLockable()Views, function tables, links, etc. do not support locks- Returns:
- true if table supports row-level locks
-
setTableExpression
public void setTableExpression(boolean tableExpression) -
isTableExpression
public boolean isTableExpression() -
getTriggers
-
getMainIndexColumn
public int getMainIndexColumn()Returns ID of main index column, orSearchRow.ROWID_INDEX.- Returns:
- ID of main index column, or
SearchRow.ROWID_INDEX
-