Package org.h2.command.query
Class Select
- java.lang.Object
-
- org.h2.command.Prepared
-
- org.h2.command.query.Query
-
- org.h2.command.query.Select
-
public class Select extends Query
This class represents a simple SELECT statement. For each select statement, visibleColumnCount <= distinctColumnCount <= expressionCount. The expression list count could include ORDER BY and GROUP BY expressions that are not in the select list. The call sequence is init(), mapColumns() if it's a subquery, prepare().
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private classSelect.LazyResultGroupSortedLazy execution for a group sorted query.private classSelect.LazyResultQueryFlatLazy execution for a flat query.private classSelect.LazyResultSelectLazy execution for this select.-
Nested classes/interfaces inherited from class org.h2.command.query.Query
Query.OffsetFetch
-
-
Field Summary
Fields Modifier and Type Field Description private ExpressionconditionWHERE condition.private doublecostprivate Expression[]distinctExpressionsDISTINCT ON(...)expressions.private int[]distinctIndexesprivate java.util.ArrayList<TableFilter>filtersprivate java.util.ArrayList<Expression>groupprivate int[]groupByCopies(package private) boolean[]groupByExpressionWhether a column in the expression list is part of a group-by.(package private) SelectGroupsgroupDataGrouped data for aggregates.(package private) int[]groupIndexThe indexes of the group-by columns.private ExpressionhavingHAVING condition.private inthavingIndexprivate booleanisDistinctQueryprivate booleanisExplicitTableWhether this SELECT is an explicit table (TABLE tableName).private booleanisForUpdate(package private) booleanisGroupQueryThis flag is set when SELECT statement contains (non-window) aggregate functions, GROUP BY clause or HAVING clause.private booleanisGroupSortedQueryprivate booleanisGroupWindowStage2private booleanisQuickAggregateQueryprivate booleanisWindowQueryprivate SelectparentSelectParent select for selects in table filters.private ExpressionqualifyQUALIFY condition.private intqualifyIndexprivate booleansortUsingIndexprivate java.util.ArrayList<TableFilter>topFilters(package private) TableFiltertopTableFilterThe main (top) table filter.private java.util.HashMap<java.lang.String,Window>windows-
Fields inherited from class org.h2.command.query.Query
checkInit, distinct, expressionArray, expressions, fetchExpr, fetchPercent, isPrepared, offsetExpr, orderList, randomAccessResult, resultColumnCount, sort, visibleColumnCount, withTies
-
Fields inherited from class org.h2.command.Prepared
create, parameters, prepareAlways, session, sqlStatement, sqlTokens
-
-
Constructor Summary
Constructors Constructor Description Select(SessionLocal session, Select parentSelect)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddCondition(Expression cond)Add a condition to the list of conditions.private intaddExpandedColumn(TableFilter filter, int index, java.util.HashMap<Column,ExpressionColumn> except, java.lang.String schema, java.lang.String alias, Column c)private static ExpressionaddGlobalCondition(Expression condition, Expression additional)voidaddGlobalCondition(Parameter param, int columnId, int comparisonType)Add a condition to the query.voidaddTableFilter(TableFilter filter, boolean isTop)Add a table to the query.booleanaddWindow(java.lang.String name, Window window)Adds a named window definition.booleanallowGlobalConditions()Check whether adding condition to the query is allowed.private Value[]constructGroupResultRow(Value[] keyValues, int columnCount)private static booleancontainsAggregate(Expression expression)(package private) Value[]createGroupSortedRow(Value[] keyValues, int columnCount)Create a row with the current values, for queries with group-sort.private LocalResultcreateLocalResult(LocalResult old)private voiddisableLazyForJoinSubqueries(TableFilter top)private voidexpandColumnList()private intexpandColumnList(TableFilter filter, int index, boolean forAlias, java.util.HashMap<Column,ExpressionColumn> except)voidfireBeforeSelectTriggers()Call the before triggers on all tables.private voidgatherGroup(int columnCount, int stage)ExpressiongetCondition()doublegetCost()Calculate the cost to execute this query.private static voidgetFilterSQL(java.lang.StringBuilder builder, java.lang.String sql, Expression[] exprList, Expression condition, int conditionIndex, int sqlFlags)private static voidgetFilterSQL(java.lang.StringBuilder builder, java.lang.String sql, Expression condition, int sqlFlags)java.util.ArrayList<Expression>getGroupBy()SelectGroupsgetGroupDataIfCurrent(boolean window)Get the group data if there is currently a group-by active.private IndexgetGroupSortedIndex()ExpressiongetHaving()ExpressiongetIfSingleRow()If this query is determined as a single-row query, returns a replacement expression.SelectgetParentSelect()Returns parent select, or null.private static booleangetPlanFromFilter(java.lang.StringBuilder builder, int sqlFlags, TableFilter f, boolean isJoin)java.lang.StringgetPlanSQL(int sqlFlags)Get the SQL statement with the execution plan.ExpressiongetQualify()private IndexgetSortIndex()Get the index that matches the ORDER BY list, if one exists.SortOrdergetSortOrder()java.util.HashSet<Table>getTables()Get all tables that are involved in this query.java.util.ArrayList<TableFilter>getTopFilters()TableFiltergetTopTableFilter()WindowgetWindow(java.lang.String name)Returns a window with specified name, or null.voidinit()Initialize the query.private voidinitGroupData(int columnCount)booleanisAnyDistinct()booleanisCacheable()(package private) booleanisConditionMet()(package private) booleanisConditionMetForUpdate()booleanisConstantQuery()Check if this query will always return the same value and has no side effects.booleanisEverything(ExpressionVisitor visitor)Check if this expression and all sub-expressions can fulfill a criteria.booleanisGroupQuery()Checks if this query is a group query.private booleanisGroupSortedIndex(TableFilter tableFilter, Index index)booleanisGroupWindowStage2()Checks if window stage of group window query is performed.private booleanisHavingNullOrFalse(Value[] row)private booleanisNoFromClause()booleanisQuickAggregateQuery()Check if this is an aggregate query with direct lookup, for example a query of the type SELECT COUNT(*) FROM TEST or SELECT MAX(ID) FROM TEST.booleanisUnion()Check if this is a UNION query.booleanisWindowQuery()Checks if this query contains window functions.voidmapColumns(ColumnResolver resolver, int level)Map the columns to the given column resolver.private voidmapCondition(int index)private intmergeGroupByExpressions(Database db, int index, java.util.ArrayList<java.lang.String> expressionSQL, boolean scanPrevious)private voidoptimizeExpressionsAndPreserveAliases()voidprepare()Prepare this statement.private doublepreparePlan(boolean parse)private voidprocessGroupResult(int columnCount, LocalResult result, long offset, boolean quickOffset, boolean withHaving)private voidqueryDistinct(ResultTarget result, long offset, long limitRows, boolean withTies, boolean quickOffset)private LazyResultqueryFlat(int columnCount, ResultTarget result, long offset, long limitRows, boolean withTies, boolean quickOffset)private voidqueryGroup(int columnCount, LocalResult result, long offset, boolean quickOffset)private LazyResultqueryGroupSorted(int columnCount, ResultTarget result, long offset, boolean quickOffset)private voidqueryGroupWindow(int columnCount, LocalResult result, long offset, boolean quickOffset)private voidqueryQuick(int columnCount, ResultTarget result, boolean skipResult)private voidqueryWindow(int columnCount, LocalResult result, long offset, boolean quickOffset)protected ResultInterfacequeryWithoutCache(long maxRows, ResultTarget target)Execute the query without checking the cache.private Value[]rowForResult(Value[] row, int columnCount)Removes HAVING and QUALIFY columns from the row.voidsetDistinct()Set the distinct flag.voidsetDistinct(Expression[] distinctExpressions)Set the DISTINCT ON expressions.voidsetEvaluatable(TableFilter tableFilter, boolean b)Change the evaluatable flag.private voidsetEvaluatableRecursive(TableFilter f)voidsetExplicitTable()Convert this SELECT to an explicit table (TABLE tableName).voidsetExpressions(java.util.ArrayList<Expression> expressions)voidsetForUpdate(boolean b)Set the 'for update' flag.voidsetGroupBy(java.util.ArrayList<Expression> group)(package private) voidsetGroupData(SelectGroups groupData)voidsetGroupQuery()Set when SELECT statement contains (non-window) aggregate functions, GROUP BY clause or HAVING clause.voidsetHaving(Expression having)voidsetQualify(Expression qualify)voidsetWildcard()Sets a wildcard expression as in "SELECT * FROM TEST".voidsetWindowQuery()Called if this query contains window functions.private static voidskipOffset(Select.LazyResultSelect lazyResult, long offset, boolean quickOffset)(package private) voidupdateAgg(int columnCount, int stage)Update any aggregate expressions with the query stage.voidupdateAggregate(SessionLocal s, int stage)Update all aggregate function values.-
Methods inherited from class org.h2.command.query.Query
addParameter, appendEndOfQueryToSQL, cleanupOrder, collectDependencies, convertToDistinct, disableCache, exists, finishResult, getColumnCount, getCostAsExpression, getExpressions, getFetch, getMaxDataModificationId, getOffset, getOffsetFetch, getRowDataType, getType, hasOrder, initExpression, initOrder, isFetchPercent, isNeverLazy, isQuery, isRandomAccessResult, isReadOnly, isStandardDistinct, isTransactional, isWithTies, prepareOrder, query, query, queryMeta, setDistinctIfPossible, setFetch, setFetchPercent, setNeverLazy, setOffset, setOrder, setRandomAccessResult, setWithTies, toTable
-
Methods inherited from class org.h2.command.Prepared
checkCanceled, checkParameters, getCteCleanups, getCurrentRowNumber, getObjectId, getParameters, getPersistedObjectId, getSession, getSimpleSQL, getSQL, getSQLTokens, needRecompile, setCommand, setCteCleanups, setCurrentRowNumber, setParameterList, setPersistedObjectId, setPrepareAlways, setRow, setSession, setSQL, toString, update
-
-
-
-
Field Detail
-
topTableFilter
TableFilter topTableFilter
The main (top) table filter.
-
filters
private final java.util.ArrayList<TableFilter> filters
-
topFilters
private final java.util.ArrayList<TableFilter> topFilters
-
parentSelect
private Select parentSelect
Parent select for selects in table filters.
-
condition
private Expression condition
WHERE condition.
-
having
private Expression having
HAVING condition.
-
qualify
private Expression qualify
QUALIFY condition.
-
distinctExpressions
private Expression[] distinctExpressions
DISTINCT ON(...)expressions.
-
distinctIndexes
private int[] distinctIndexes
-
group
private java.util.ArrayList<Expression> group
-
groupIndex
int[] groupIndex
The indexes of the group-by columns.
-
groupByExpression
boolean[] groupByExpression
Whether a column in the expression list is part of a group-by.
-
groupData
SelectGroups groupData
Grouped data for aggregates.
-
havingIndex
private int havingIndex
-
qualifyIndex
private int qualifyIndex
-
groupByCopies
private int[] groupByCopies
-
isExplicitTable
private boolean isExplicitTable
Whether this SELECT is an explicit table (TABLE tableName). It is used ingetPlanSQL(int)to generate SQL similar to original query.
-
isGroupQuery
boolean isGroupQuery
This flag is set when SELECT statement contains (non-window) aggregate functions, GROUP BY clause or HAVING clause.
-
isGroupSortedQuery
private boolean isGroupSortedQuery
-
isWindowQuery
private boolean isWindowQuery
-
isForUpdate
private boolean isForUpdate
-
cost
private double cost
-
isQuickAggregateQuery
private boolean isQuickAggregateQuery
-
isDistinctQuery
private boolean isDistinctQuery
-
sortUsingIndex
private boolean sortUsingIndex
-
isGroupWindowStage2
private boolean isGroupWindowStage2
-
windows
private java.util.HashMap<java.lang.String,Window> windows
-
-
Constructor Detail
-
Select
public Select(SessionLocal session, Select parentSelect)
-
-
Method Detail
-
isUnion
public boolean isUnion()
Description copied from class:QueryCheck if this is a UNION query.
-
addTableFilter
public void addTableFilter(TableFilter filter, boolean isTop)
Add a table to the query.- Parameters:
filter- the table to addisTop- if the table can be the first table in the query plan
-
getTopFilters
public java.util.ArrayList<TableFilter> getTopFilters()
-
setExpressions
public void setExpressions(java.util.ArrayList<Expression> expressions)
-
setExplicitTable
public void setExplicitTable()
Convert this SELECT to an explicit table (TABLE tableName).
-
setWildcard
public void setWildcard()
Sets a wildcard expression as in "SELECT * FROM TEST".
-
setGroupQuery
public void setGroupQuery()
Set when SELECT statement contains (non-window) aggregate functions, GROUP BY clause or HAVING clause.
-
setWindowQuery
public void setWindowQuery()
Called if this query contains window functions.
-
setGroupBy
public void setGroupBy(java.util.ArrayList<Expression> group)
-
getGroupBy
public java.util.ArrayList<Expression> getGroupBy()
-
getGroupDataIfCurrent
public SelectGroups getGroupDataIfCurrent(boolean window)
Get the group data if there is currently a group-by active.- Parameters:
window- is this a window function- Returns:
- the grouped data
-
setDistinct
public void setDistinct()
Set the distinct flag.
-
setDistinct
public void setDistinct(Expression[] distinctExpressions)
Set the DISTINCT ON expressions.- Parameters:
distinctExpressions- array of expressions
-
isAnyDistinct
public boolean isAnyDistinct()
- Overrides:
isAnyDistinctin classQuery- Returns:
- whether this query is a
DISTINCTorDISTINCT ON (...)query
-
addWindow
public boolean addWindow(java.lang.String name, Window window)Adds a named window definition.- Parameters:
name- namewindow- window definition- Returns:
- true if a new definition was added, false if old definition was replaced
-
getWindow
public Window getWindow(java.lang.String name)
Returns a window with specified name, or null.- Parameters:
name- name of the window- Returns:
- the window with specified name, or null
-
addCondition
public void addCondition(Expression cond)
Add a condition to the list of conditions.- Parameters:
cond- the condition to add
-
getCondition
public Expression getCondition()
-
queryGroupSorted
private LazyResult queryGroupSorted(int columnCount, ResultTarget result, long offset, boolean quickOffset)
-
createGroupSortedRow
Value[] createGroupSortedRow(Value[] keyValues, int columnCount)
Create a row with the current values, for queries with group-sort.- Parameters:
keyValues- the key valuescolumnCount- the number of columns- Returns:
- the row
-
rowForResult
private Value[] rowForResult(Value[] row, int columnCount)
Removes HAVING and QUALIFY columns from the row.- Parameters:
row- the complete rowcolumnCount- the number of columns to keep- Returns:
- the same or the truncated row
-
isHavingNullOrFalse
private boolean isHavingNullOrFalse(Value[] row)
-
getGroupSortedIndex
private Index getGroupSortedIndex()
-
isGroupSortedIndex
private boolean isGroupSortedIndex(TableFilter tableFilter, Index index)
-
isConditionMetForUpdate
boolean isConditionMetForUpdate()
-
isConditionMet
boolean isConditionMet()
-
queryWindow
private void queryWindow(int columnCount, LocalResult result, long offset, boolean quickOffset)
-
queryGroupWindow
private void queryGroupWindow(int columnCount, LocalResult result, long offset, boolean quickOffset)
-
queryGroup
private void queryGroup(int columnCount, LocalResult result, long offset, boolean quickOffset)
-
initGroupData
private void initGroupData(int columnCount)
-
setGroupData
void setGroupData(SelectGroups groupData)
-
gatherGroup
private void gatherGroup(int columnCount, int stage)
-
updateAgg
void updateAgg(int columnCount, int stage)Update any aggregate expressions with the query stage.- Parameters:
columnCount- number of columnsstage- see STAGE_RESET/STAGE_GROUP/STAGE_WINDOW in DataAnalysisOperation
-
processGroupResult
private void processGroupResult(int columnCount, LocalResult result, long offset, boolean quickOffset, boolean withHaving)
-
constructGroupResultRow
private Value[] constructGroupResultRow(Value[] keyValues, int columnCount)
-
getSortIndex
private Index getSortIndex()
Get the index that matches the ORDER BY list, if one exists. This is to avoid running a separate ORDER BY if an index can be used. This is specially important for large result sets, if only the first few rows are important (LIMIT is used)- Returns:
- the index if one is found
-
queryDistinct
private void queryDistinct(ResultTarget result, long offset, long limitRows, boolean withTies, boolean quickOffset)
-
queryFlat
private LazyResult queryFlat(int columnCount, ResultTarget result, long offset, long limitRows, boolean withTies, boolean quickOffset)
-
skipOffset
private static void skipOffset(Select.LazyResultSelect lazyResult, long offset, boolean quickOffset)
-
queryQuick
private void queryQuick(int columnCount, ResultTarget result, boolean skipResult)
-
queryWithoutCache
protected ResultInterface queryWithoutCache(long maxRows, ResultTarget target)
Description copied from class:QueryExecute the query without checking the cache. If a target is specified, the results are written to it, and the method returns null. If no target is specified, a new LocalResult is created and returned.- Specified by:
queryWithoutCachein classQuery- Parameters:
maxRows- the limit as specified in the JDBC method calltarget- the target to write results to- Returns:
- the result
-
disableLazyForJoinSubqueries
private void disableLazyForJoinSubqueries(TableFilter top)
-
createLocalResult
private LocalResult createLocalResult(LocalResult old)
-
expandColumnList
private void expandColumnList()
-
expandColumnList
private int expandColumnList(TableFilter filter, int index, boolean forAlias, java.util.HashMap<Column,ExpressionColumn> except)
-
addExpandedColumn
private int addExpandedColumn(TableFilter filter, int index, java.util.HashMap<Column,ExpressionColumn> except, java.lang.String schema, java.lang.String alias, Column c)
-
init
public void init()
Description copied from class:QueryInitialize the query.
-
mapCondition
private void mapCondition(int index)
-
mergeGroupByExpressions
private int mergeGroupByExpressions(Database db, int index, java.util.ArrayList<java.lang.String> expressionSQL, boolean scanPrevious)
-
prepare
public void prepare()
Description copied from class:PreparedPrepare this statement.
-
optimizeExpressionsAndPreserveAliases
private void optimizeExpressionsAndPreserveAliases()
-
getCost
public double getCost()
Description copied from class:QueryCalculate the cost to execute this query.
-
getTables
public java.util.HashSet<Table> getTables()
Description copied from class:QueryGet all tables that are involved in this query.
-
fireBeforeSelectTriggers
public void fireBeforeSelectTriggers()
Description copied from class:QueryCall the before triggers on all tables.- Specified by:
fireBeforeSelectTriggersin classQuery
-
preparePlan
private double preparePlan(boolean parse)
-
setEvaluatableRecursive
private void setEvaluatableRecursive(TableFilter f)
-
getPlanSQL
public java.lang.String getPlanSQL(int sqlFlags)
Description copied from class:PreparedGet the SQL statement with the execution plan.- Overrides:
getPlanSQLin classPrepared- Parameters:
sqlFlags- formatting flags- Returns:
- the execution plan
-
getPlanFromFilter
private static boolean getPlanFromFilter(java.lang.StringBuilder builder, int sqlFlags, TableFilter f, boolean isJoin)
-
getFilterSQL
private static void getFilterSQL(java.lang.StringBuilder builder, java.lang.String sql, Expression[] exprList, Expression condition, int conditionIndex, int sqlFlags)
-
getFilterSQL
private static void getFilterSQL(java.lang.StringBuilder builder, java.lang.String sql, Expression condition, int sqlFlags)
-
containsAggregate
private static boolean containsAggregate(Expression expression)
-
setHaving
public void setHaving(Expression having)
-
getHaving
public Expression getHaving()
-
setQualify
public void setQualify(Expression qualify)
-
getQualify
public Expression getQualify()
-
getTopTableFilter
public TableFilter getTopTableFilter()
-
setForUpdate
public void setForUpdate(boolean b)
Description copied from class:QuerySet the 'for update' flag.- Specified by:
setForUpdatein classQuery- Parameters:
b- the new setting
-
mapColumns
public void mapColumns(ColumnResolver resolver, int level)
Description copied from class:QueryMap the columns to the given column resolver.- Specified by:
mapColumnsin classQuery- Parameters:
resolver- the resolverlevel- the subquery level (0 is the top level query, 1 is the first subquery level)
-
setEvaluatable
public void setEvaluatable(TableFilter tableFilter, boolean b)
Description copied from class:QueryChange the evaluatable flag. This is used when building the execution plan.- Specified by:
setEvaluatablein classQuery- Parameters:
tableFilter- the table filterb- the new value
-
isQuickAggregateQuery
public boolean isQuickAggregateQuery()
Check if this is an aggregate query with direct lookup, for example a query of the type SELECT COUNT(*) FROM TEST or SELECT MAX(ID) FROM TEST.- Returns:
- true if a direct lookup is possible
-
isGroupQuery
public boolean isGroupQuery()
Checks if this query is a group query.- Returns:
- whether this query is a group query.
-
isWindowQuery
public boolean isWindowQuery()
Checks if this query contains window functions.- Returns:
- whether this query contains window functions
-
isGroupWindowStage2
public boolean isGroupWindowStage2()
Checks if window stage of group window query is performed. If true, column resolver may not be used.- Returns:
- true if window stage of group window query is performed
-
addGlobalCondition
public void addGlobalCondition(Parameter param, int columnId, int comparisonType)
Description copied from class:QueryAdd a condition to the query. This is used for views.- Specified by:
addGlobalConditionin classQuery- Parameters:
param- the parametercolumnId- the column index (0 meaning the first column)comparisonType- the comparison type
-
addGlobalCondition
private static Expression addGlobalCondition(Expression condition, Expression additional)
-
updateAggregate
public void updateAggregate(SessionLocal s, int stage)
Description copied from class:QueryUpdate all aggregate function values.- Specified by:
updateAggregatein classQuery- Parameters:
s- the sessionstage- select stage
-
isEverything
public boolean isEverything(ExpressionVisitor visitor)
Description copied from class:QueryCheck if this expression and all sub-expressions can fulfill a criteria. If any part returns false, the result is false.- Specified by:
isEverythingin classQuery- Parameters:
visitor- the visitor- Returns:
- if the criteria can be fulfilled
-
isCacheable
public boolean isCacheable()
- Overrides:
isCacheablein classPrepared
-
allowGlobalConditions
public boolean allowGlobalConditions()
Description copied from class:QueryCheck whether adding condition to the query is allowed. This is not allowed for views that have an order by and a limit, as it would affect the returned results.- Specified by:
allowGlobalConditionsin classQuery- Returns:
- true if adding global conditions is allowed
-
getSortOrder
public SortOrder getSortOrder()
-
getParentSelect
public Select getParentSelect()
Returns parent select, or null.- Returns:
- parent select, or null
-
isConstantQuery
public boolean isConstantQuery()
Description copied from class:QueryCheck if this query will always return the same value and has no side effects.- Overrides:
isConstantQueryin classQuery- Returns:
- if this query will always return the same value and has no side effects.
-
getIfSingleRow
public Expression getIfSingleRow()
Description copied from class:QueryIf this query is determined as a single-row query, returns a replacement expression.- Overrides:
getIfSingleRowin classQuery- Returns:
- the expression, or
null
-
isNoFromClause
private boolean isNoFromClause()
-
-