Package org.h2.command.query
Class Select
java.lang.Object
org.h2.command.Prepared
org.h2.command.query.Query
org.h2.command.query.Select
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 ClassesModifier and TypeClassDescriptionprivate final class
Lazy execution for a group sorted query.private final class
Lazy execution for a flat query.private class
Lazy execution for this select.Nested classes/interfaces inherited from class org.h2.command.query.Query
Query.OffsetFetch
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate Expression
WHERE condition.private double
private Expression[]
DISTINCT ON(...)
expressions.private int[]
private final ArrayList
<TableFilter> private ArrayList
<Expression> private int[]
(package private) boolean[]
Whether a column in the expression list is part of a group-by.(package private) SelectGroups
Grouped data for aggregates.(package private) int[]
The indexes of the group-by columns.private Expression
HAVING condition.private int
private boolean
private boolean
Whether this SELECT is an explicit table (TABLE tableName).private boolean
(package private) boolean
This flag is set when SELECT statement contains (non-window) aggregate functions, GROUP BY clause or HAVING clause.private boolean
private boolean
private boolean
private boolean
private Select
Parent select for selects in table filters.private Expression
QUALIFY condition.private int
private boolean
private final ArrayList
<TableFilter> (package private) TableFilter
The main (top) table filter.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 -
Method Summary
Modifier and TypeMethodDescriptionvoid
addCondition
(Expression cond) Add a condition to the list of conditions.private int
addExpandedColumn
(TableFilter filter, int index, HashMap<Column, ExpressionColumn> except, String schema, String alias, Column c) private static Expression
addGlobalCondition
(Expression condition, Expression additional) void
addGlobalCondition
(Parameter param, int columnId, int comparisonType) Add a condition to the query.void
addTableFilter
(TableFilter filter, boolean isTop) Add a table to the query.boolean
Adds a named window definition.boolean
Check whether adding condition to the query is allowed.private Value[]
constructGroupResultRow
(Value[] keyValues, int columnCount) private static boolean
containsAggregate
(Expression expression) (package private) Value[]
createGroupSortedRow
(Value[] keyValues, int columnCount) Create a row with the current values, for queries with group-sort.private LocalResult
private void
private void
private int
expandColumnList
(TableFilter filter, int index, boolean forAlias, HashMap<Column, ExpressionColumn> except) void
Call the before triggers on all tables.private void
gatherGroup
(int columnCount, int stage) double
getCost()
Calculate the cost to execute this query.private static void
getFilterSQL
(StringBuilder builder, String sql, Expression[] exprList, Expression condition, int conditionIndex, int sqlFlags) private static void
getFilterSQL
(StringBuilder builder, String sql, Expression condition, int sqlFlags) getGroupDataIfCurrent
(boolean window) Get the group data if there is currently a group-by active.private Index
If this query is determined as a single-row query, returns a replacement expression.Returns parent select, or null.private static boolean
getPlanFromFilter
(StringBuilder builder, int sqlFlags, TableFilter f, boolean isJoin) getPlanSQL
(int sqlFlags) Get the SQL statement with the execution plan.private Index
Get the index that matches the ORDER BY list, if one exists.Get all tables that are involved in this query.Returns a window with specified name, or null.void
init()
Initialize the query.private void
initGroupData
(int columnCount) boolean
boolean
(package private) boolean
(package private) boolean
boolean
Check if this query will always return the same value and has no side effects.boolean
isEverything
(ExpressionVisitor visitor) Check if this expression and all sub-expressions can fulfill a criteria.boolean
Checks if this query is a group query.private boolean
isGroupSortedIndex
(TableFilter tableFilter, Index index) boolean
Checks if window stage of group window query is performed.private boolean
isHavingNullOrFalse
(Value[] row) private boolean
boolean
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.boolean
isUnion()
Check if this is a UNION query.boolean
Checks if this query contains window functions.void
mapColumns
(ColumnResolver resolver, int level) Map the columns to the given column resolver.private void
mapCondition
(int index) private int
mergeGroupByExpressions
(Database db, int index, ArrayList<String> expressionSQL, boolean scanPrevious) private void
void
prepare()
Prepare this statement.private double
preparePlan
(boolean parse) private void
processGroupResult
(int columnCount, LocalResult result, long offset, boolean quickOffset, boolean withHaving) private void
queryDistinct
(ResultTarget result, long offset, long limitRows, boolean withTies, boolean quickOffset) private LazyResult
queryFlat
(int columnCount, ResultTarget result, long offset, long limitRows, boolean withTies, boolean quickOffset) private void
queryGroup
(int columnCount, LocalResult result, long offset, boolean quickOffset) private LazyResult
queryGroupSorted
(int columnCount, ResultTarget result, long offset, boolean quickOffset) private void
queryGroupWindow
(int columnCount, LocalResult result, long offset, boolean quickOffset) private void
queryQuick
(int columnCount, ResultTarget result, boolean skipResult) private void
queryWindow
(int columnCount, LocalResult result, long offset, boolean quickOffset) protected ResultInterface
queryWithoutCache
(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.void
Set the distinct flag.void
setDistinct
(Expression[] distinctExpressions) Set the DISTINCT ON expressions.void
setEvaluatable
(TableFilter tableFilter, boolean b) Change the evaluatable flag.private void
void
Convert this SELECT to an explicit table (TABLE tableName).void
setExpressions
(ArrayList<Expression> expressions) void
setForUpdate
(boolean b) Set the 'for update' flag.void
setGroupBy
(ArrayList<Expression> group) (package private) void
setGroupData
(SelectGroups groupData) void
Set when SELECT statement contains (non-window) aggregate functions, GROUP BY clause or HAVING clause.void
setHaving
(Expression having) void
setQualify
(Expression qualify) void
Sets a wildcard expression as in "SELECT * FROM TEST".void
Called if this query contains window functions.private static void
skipOffset
(Select.LazyResultSelect lazyResult, long offset, boolean quickOffset) (package private) void
updateAgg
(int columnCount, int stage) Update any aggregate expressions with the query stage.void
updateAggregate
(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 Details
-
topTableFilter
TableFilter topTableFilterThe main (top) table filter. -
filters
-
topFilters
-
parentSelect
Parent select for selects in table filters. -
condition
WHERE condition. -
having
HAVING condition. -
qualify
QUALIFY condition. -
distinctExpressions
DISTINCT ON(...)
expressions. -
distinctIndexes
private int[] distinctIndexes -
group
-
groupIndex
int[] groupIndexThe indexes of the group-by columns. -
groupByExpression
boolean[] groupByExpressionWhether a column in the expression list is part of a group-by. -
groupData
SelectGroups groupDataGrouped data for aggregates. -
havingIndex
private int havingIndex -
qualifyIndex
private int qualifyIndex -
groupByCopies
private int[] groupByCopies -
isExplicitTable
private boolean isExplicitTableWhether this SELECT is an explicit table (TABLE tableName). It is used ingetPlanSQL(int)
to generate SQL similar to original query. -
isGroupQuery
boolean isGroupQueryThis 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
-
-
Constructor Details
-
Select
-
-
Method Details
-
isUnion
public boolean isUnion()Description copied from class:Query
Check if this is a UNION query. -
addTableFilter
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
-
setExpressions
-
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
-
getGroupBy
-
getGroupDataIfCurrent
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
Set the DISTINCT ON expressions.- Parameters:
distinctExpressions
- array of expressions
-
isAnyDistinct
public boolean isAnyDistinct()- Overrides:
isAnyDistinct
in classQuery
- Returns:
- whether this query is a
DISTINCT
orDISTINCT ON (...)
query
-
addWindow
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
Returns a window with specified name, or null.- Parameters:
name
- name of the window- Returns:
- the window with specified name, or null
-
addCondition
Add a condition to the list of conditions.- Parameters:
cond
- the condition to add
-
getCondition
-
queryGroupSorted
private LazyResult queryGroupSorted(int columnCount, ResultTarget result, long offset, boolean quickOffset) -
createGroupSortedRow
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
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
-
getGroupSortedIndex
-
isGroupSortedIndex
-
isConditionMetForUpdate
boolean isConditionMetForUpdate() -
isConditionMet
boolean isConditionMet() -
queryWindow
-
queryGroupWindow
private void queryGroupWindow(int columnCount, LocalResult result, long offset, boolean quickOffset) -
queryGroup
-
initGroupData
private void initGroupData(int columnCount) -
setGroupData
-
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
-
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
-
queryWithoutCache
Description copied from class:Query
Execute 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:
queryWithoutCache
in classQuery
- Parameters:
maxRows
- the limit as specified in the JDBC method calltarget
- the target to write results to- Returns:
- the result
-
disableLazyForJoinSubqueries
-
createLocalResult
-
expandColumnList
private void expandColumnList() -
expandColumnList
private int expandColumnList(TableFilter filter, int index, boolean forAlias, HashMap<Column, ExpressionColumn> except) -
addExpandedColumn
private int addExpandedColumn(TableFilter filter, int index, HashMap<Column, ExpressionColumn> except, String schema, String alias, Column c) -
init
public void init()Description copied from class:Query
Initialize the query. -
mapCondition
private void mapCondition(int index) -
mergeGroupByExpressions
-
prepare
public void prepare()Description copied from class:Prepared
Prepare this statement. -
optimizeExpressionsAndPreserveAliases
private void optimizeExpressionsAndPreserveAliases() -
getCost
public double getCost()Description copied from class:Query
Calculate the cost to execute this query. -
getTables
Description copied from class:Query
Get all tables that are involved in this query. -
fireBeforeSelectTriggers
public void fireBeforeSelectTriggers()Description copied from class:Query
Call the before triggers on all tables.- Specified by:
fireBeforeSelectTriggers
in classQuery
-
preparePlan
private double preparePlan(boolean parse) -
setEvaluatableRecursive
-
getPlanSQL
Description copied from class:Prepared
Get the SQL statement with the execution plan.- Overrides:
getPlanSQL
in classPrepared
- Parameters:
sqlFlags
- formatting flags- Returns:
- the execution plan
-
getPlanFromFilter
private static boolean getPlanFromFilter(StringBuilder builder, int sqlFlags, TableFilter f, boolean isJoin) -
getFilterSQL
private static void getFilterSQL(StringBuilder builder, String sql, Expression[] exprList, Expression condition, int conditionIndex, int sqlFlags) -
getFilterSQL
private static void getFilterSQL(StringBuilder builder, String sql, Expression condition, int sqlFlags) -
containsAggregate
-
setHaving
-
getHaving
-
setQualify
-
getQualify
-
getTopTableFilter
-
setForUpdate
public void setForUpdate(boolean b) Description copied from class:Query
Set the 'for update' flag.- Specified by:
setForUpdate
in classQuery
- Parameters:
b
- the new setting
-
mapColumns
Description copied from class:Query
Map the columns to the given column resolver.- Specified by:
mapColumns
in classQuery
- Parameters:
resolver
- the resolverlevel
- the subquery level (0 is the top level query, 1 is the first subquery level)
-
setEvaluatable
Description copied from class:Query
Change the evaluatable flag. This is used when building the execution plan.- Specified by:
setEvaluatable
in 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
Description copied from class:Query
Add a condition to the query. This is used for views.- Specified by:
addGlobalCondition
in classQuery
- Parameters:
param
- the parametercolumnId
- the column index (0 meaning the first column)comparisonType
- the comparison type
-
addGlobalCondition
-
updateAggregate
Description copied from class:Query
Update all aggregate function values.- Specified by:
updateAggregate
in classQuery
- Parameters:
s
- the sessionstage
- select stage
-
isEverything
Description copied from class:Query
Check if this expression and all sub-expressions can fulfill a criteria. If any part returns false, the result is false.- Specified by:
isEverything
in classQuery
- Parameters:
visitor
- the visitor- Returns:
- if the criteria can be fulfilled
-
isCacheable
public boolean isCacheable()- Overrides:
isCacheable
in classPrepared
-
allowGlobalConditions
public boolean allowGlobalConditions()Description copied from class:Query
Check 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:
allowGlobalConditions
in classQuery
- Returns:
- true if adding global conditions is allowed
-
getSortOrder
-
getParentSelect
Returns parent select, or null.- Returns:
- parent select, or null
-
isConstantQuery
public boolean isConstantQuery()Description copied from class:Query
Check if this query will always return the same value and has no side effects.- Overrides:
isConstantQuery
in classQuery
- Returns:
- if this query will always return the same value and has no side effects.
-
getIfSingleRow
Description copied from class:Query
If this query is determined as a single-row query, returns a replacement expression.- Overrides:
getIfSingleRow
in classQuery
- Returns:
- the expression, or
null
-
isNoFromClause
private boolean isNoFromClause()
-