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:
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 boolean
Is foreign key constraint checking enabled for this table.protected Column[]
The columns of this table.protected CompareMode
The compare mode used for this table.private ArrayList
<Constraint> private final CopyOnWriteArrayList
<TableView> views that depend on this tablestatic final int
Exclusive lock.protected boolean
Protected tables are not listed in the meta data and are excluded when using the SCRIPT command.private Row
private boolean
private boolean
private final boolean
private final boolean
static final int
Read lock.private RowFactory
private ArrayList
<TableSynonym> private boolean
private ArrayList
<TriggerObject> static final int
The table type that means this table is a regular persistent table.static final int
The table type that means this table is a regular persistent table.static final int
Write 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, USER
Fields 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 TypeMethodDescriptionprivate static <T> ArrayList
<T> void
addConstraint
(Constraint constraint) Add a constraint to the table.void
addDependencies
(HashSet<DbObject> dependencies) Add all objects that this table depends on to the hash set.void
addDependentView
(TableView view) Add a view to this table.abstract Index
addIndex
(SessionLocal session, String indexName, int indexId, IndexColumn[] cols, int uniqueColumnCount, IndexType indexType, boolean create, String indexComment) Create an index for this tableabstract void
addRow
(SessionLocal session, Row row) Add a row to the table and all indexes.void
addSequence
(Sequence sequence) Add a sequence to this table.void
addSynonym
(TableSynonym synonym) Add a synonym to this table.void
addTrigger
(TriggerObject trigger) Add a trigger to this table.abstract boolean
canDrop()
Check if this table can be dropped.abstract boolean
canGetRowCount
(SessionLocal session) Check if the row count can be retrieved quickly.boolean
Check if this table can be referenced.boolean
Check if this table can be truncated.checkDeadlock
(SessionLocal session, SessionLocal clash, Set<SessionLocal> visited) Check if a deadlock occurred.abstract void
Check if this table supports ALTER TABLE.void
Tests if the table can be written.abstract void
close
(SessionLocal session) Close the table object and flush changes.int
compareValues
(CastDataProvider provider, Value a, Value b) Compare two values with the current comparison mode.void
convertInsertRow
(SessionLocal session, Row row, Boolean overridingSystem) Prepares the specified row for INSERT operation.void
convertUpdateRow
(SessionLocal session, Row row, boolean fromTrigger) Prepares the specified row for UPDATE operation.Create a new row for this table.boolean
doesColumnExist
(String columnName) Does the column with the given name exist?void
dropMultipleColumnsConstraintsAndIndexes
(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.void
fire
(SessionLocal session, int type, boolean beforeAction) Fire the triggers for this table.void
fireAfterRow
(SessionLocal session, Row oldRow, Row newRow, boolean rollback) Fire all triggers that need to be called after a row is updated.boolean
fireBeforeRow
(SessionLocal session, Row oldRow, Row newRow) Fire all triggers that need to be called before a row is updated.private void
fireConstraints
(SessionLocal session, Row oldRow, Row newRow, boolean before) boolean
fireRow()
Check if row based triggers or constraints are defined.private boolean
fireRow
(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.boolean
Get 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 tablelong
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.private static IndexHints
getIndexHints
(TableFilter[] filters, int filter) int
Returns ID of main index column, orSearchRow.ROWID_INDEX
.abstract long
Get the last data modification id.boolean
boolean
getRow
(SessionLocal session, long key) Get the given row.abstract long
getRowCount
(SessionLocal session) Get the row count for this table.abstract long
getRowCountApproximation
(SessionLocal session) Get the approximated row count for this table.Get the row id column if this table has one.abstract Index
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.Return SQL table type for INFORMATION_SCHEMA.abstract TableType
Get the table type namegetTemplateSimpleRow
(boolean singleColumn) Get a new simple row object.Return list of triggers.int
getType()
Get the object type.boolean
Check whether this table has a select trigger.abstract boolean
Check if the table is deterministic.boolean
boolean
isHidden()
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 boolean
isIndexExcludedByHints
(IndexHints indexHints, Index index) boolean
Returns whether this table is insertable.boolean
Check if this table is locked exclusively.boolean
isLockedExclusivelyBy
(SessionLocal session) Check if the table is exclusively locked by this session.boolean
boolean
boolean
Check whether the table (or view) contains no columns that prevent index conditions to be used.boolean
Views, function tables, links, etc.boolean
boolean
isView()
boolean
lock
(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 void
void
removeChildrenAndResources
(SessionLocal session) Delete all dependent children objects and resources of this object.void
Removes dependencies of column expressions, used for tables with circular dependencies.void
removeConstraint
(Constraint constraint) Remove the given constraint from the list.void
removeDependentView
(TableView view) Remove the given view from the dependent views list.void
removeIndex
(Index index) Remove the given index from the list.void
removeIndexOrTransferOwnership
(SessionLocal session, Index index) If the index is still required by a constraint, transfer the ownership to it.abstract void
removeRow
(SessionLocal session, Row row) Remove a row from the table and all indexes.final void
removeSequence
(Sequence sequence) Remove a sequence from the table.void
removeSynonym
(TableSynonym synonym) Remove the given view from the list.void
removeTrigger
(TriggerObject trigger) Remove the given trigger from the list.void
Rename the object.void
renameColumn
(Column column, String newName) Rename a column of this table.void
setCheckForeignKeyConstraints
(SessionLocal session, boolean enabled, boolean checkExisting) Enable or disable foreign key constraint checking for this table.protected void
setColumns
(Column[] columns) void
setHidden
(boolean hidden) void
setOnCommitDrop
(boolean onCommitDrop) void
setOnCommitTruncate
(boolean onCommitTruncate) void
setTableExpression
(boolean tableExpression) abstract long
truncate
(SessionLocal session) Remove all rows from the table and indexes.void
Release the lock for this session.void
updateRow
(SessionLocal session, Row oldRow, Row newRow) Update a row to the table and all indexes.void
updateRows
(Prepared prepared, SessionLocal session, LocalResult rows) Update a list of rows in this table.Methods inherited from class org.h2.schema.SchemaObject
getSchema, getSQL, getSQL
Methods inherited from class org.h2.engine.DbObject
checkRename, getComment, getCreateSQL, getCreateSQLForMeta, getDatabase, getDropSQL, getId, getModificationId, getName, invalidate, isTemporary, isValid, setComment, setModified, setObjectName, setTemporary, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods 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. -
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
Description copied from class:DbObject
Rename 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 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
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() -
getRowIdColumn
Get the row id column if this table has one.- Returns:
- the row id column, or null
-
getCreateSQLForCopy
Description copied from class:DbObject
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 table- Specified by:
getCreateSQLForCopy
in 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
Add all objects that this table depends on to the hash set.- Parameters:
dependencies
- the current set of dependencies
-
getChildren
Description copied from class:DbObject
Get the list of dependent children (for tables, this includes indexes and so on).- Overrides:
getChildren
in 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
-
removeChildrenAndResources
Description copied from class:DbObject
Delete all dependent children objects and resources of this object.- Specified by:
removeChildrenAndResources
in 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
-
getType
public int getType()Description copied from class:DbObject
Get 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
- if (@code true) returnnull
if 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
-
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.TRUE
forOVERRIDING SYSTEM VALUES
,Boolean.FALSE
forOVERRIDING USER VALUES
,null
if 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
-true
if 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:SchemaObject
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.- Overrides:
isHidden
in 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
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
-