Package org.h2.table
Class Table
java.lang.Object
org.h2.engine.DbObject
org.h2.schema.SchemaObject
org.h2.table.Table
- All Implemented Interfaces:
HasSQL
- Direct Known Subclasses:
MaterializedView,MetaTable,QueryExpressionTable,TableBase,TableLink,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 TypeFieldDescriptionprotected Column[]The columns of this table.protected CompareModeThe compare mode used for this table.static final intExclusive lock.static final intRead lock.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 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 TypeMethodDescriptionvoidaddConstraint(Constraint constraint) Add a constraint to the table.voidaddDependencies(HashSet<DbObject> dependencies) Add all objects that this table depends on to the hash set.voidAdd a materialized view to this table.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.booleanfireRow()Check if row based triggers or constraints are defined.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.final Column[]longgetDiskSpaceUsed(boolean total, boolean approximate) Returns 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.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.final Column[]booleanCheck whether this table has a select trigger.abstract booleanCheck if the table is deterministic.booleanbooleanReturns 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.booleanisView()booleanlock(SessionLocal session, int lockType) Lock the table for the given session.lockRow(SessionLocal session, Row row, int timeoutMillis) Locks row, preventing any updated to it, except from the session specified.voidremoveChildrenAndResources(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.voidRemove the given view from the dependent views 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) voidsetOnCommitDrop(boolean onCommitDrop) voidsetOnCommitTruncate(boolean onCommitTruncate) 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 org.h2.schema.SchemaObject
getSchema, getSQL, getSQLMethods inherited from class org.h2.engine.DbObject
checkRename, getComment, getCreateSQL, getCreateSQLForCopy, getCreateSQLForMeta, getDatabase, getDropSQL, 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
-
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.
-
-
Constructor Details
-
Table
-
-
Method Details
-
rename
Description copied from class:DbObjectRename the object. -
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
Release the lock for this session.- Parameters:
s- the session
-
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 locktimeoutMillis- timeout in milliseconds,-1for default,-2to skip locking if row is already locked by another session- Returns:
- locked row, or null if row does not exist anymore or if it was skipped
-
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
Get the table type name- Returns:
- the table type name
-
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
Get all indexes for this table.- Returns:
- the list of indexes
-
getIndex
Get an index by name.- Parameters:
indexName- the index name to search for- Returns:
- the found index
-
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(boolean total, boolean approximate) -
getRowIdColumn
Get the row id column if this table has one.- Returns:
- the row id column, or null
-
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
Add all objects that this table depends on to the hash set.- Parameters:
dependencies- the current set of dependencies
-
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
Rename a column of this table.- Parameters:
column- the column to renamenewName- the new column name
-
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
-
getDependentMaterializedViews
-
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
Create a new row for this table.- Parameters:
data- the valuesmemory- the estimated memory usage in bytes- Returns:
- the created row
-
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
-
getVisibleColumns
-
getType
public int getType()Description copied from class:DbObjectGet the object type. -
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- iftruereturnnullif column does not exist- Returns:
- the column
- Throws:
DbException- if the column was not found
-
findColumn
Get the column with the given name if it exists.- Parameters:
columnName- the column name, ornull- Returns:
- the column
-
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
-
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 sessionoverridingSystem-Boolean.TRUEforOVERRIDING SYSTEM VALUES,Boolean.FALSEforOVERRIDING USER VALUES,nullif override clause is not specifiedrow- the row
-
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
-
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
-
removeDependentMaterializedView
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
-
addDependentMaterializedView
Add a materialized 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
-
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)
-
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
-
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. -
isRowLockable
public boolean isRowLockable()Views, function tables, links, etc. do not support locks- Returns:
- true if table supports row-level locks
-
getTriggers
Return list of triggers.- Returns:
- list of triggers
-
getMainIndexColumn
public int getMainIndexColumn()Returns ID of main index column, orSearchRow.ROWID_INDEX.- Returns:
- ID of main index column, or
SearchRow.ROWID_INDEX
-