Package org.h2.command.query
Class Query
- java.lang.Object
-
- org.h2.command.Prepared
-
- org.h2.command.query.Query
-
- Direct Known Subclasses:
Select
,SelectUnion
,TableValueConstructor
public abstract class Query extends Prepared
Represents a SELECT statement (simple, or union).
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description (package private) static class
Query.OffsetFetch
Evaluated values of OFFSET and FETCH clauses.
-
Field Summary
Fields Modifier and Type Field Description private boolean
cacheableChecked
(package private) boolean
checkInit
(package private) boolean
distinct
Whether the result must only contain distinct rows.(package private) Expression[]
expressionArray
Array of expressions.(package private) java.util.ArrayList<Expression>
expressions
The column list, including invisible expressions such as order by expressions.(package private) Expression
fetchExpr
The fetch expression as specified in the FETCH, LIMIT, or TOP clause.(package private) boolean
fetchPercent
Whether limit expression specifies percentage of rows.(package private) boolean
isPrepared
private long
lastEvaluated
private java.lang.Boolean
lastExists
private long
lastLimit
private Value[]
lastParameters
private ResultInterface
lastResult
private boolean
neverLazy
private boolean
noCache
(package private) Expression
offsetExpr
The offset expression as specified in the OFFSET clause.(package private) java.util.ArrayList<QueryOrderBy>
orderList
Describes elements of the ORDER BY clause of a query.(package private) boolean
randomAccessResult
Whether the result needs to support random access.(package private) int
resultColumnCount
Number of columns including visible columns and additional virtual columns for ORDER BY and DISTINCT ON clauses.(package private) SortOrder
sort
A sort order represents an ORDER BY clause in a query.(package private) int
visibleColumnCount
The visible columns (the ones required in the result).(package private) boolean
withTies
Whether tied rows should be included in result too.-
Fields inherited from class org.h2.command.Prepared
create, parameters, prepareAlways, session, sqlStatement, sqlTokens
-
-
Constructor Summary
Constructors Constructor Description Query(SessionLocal session)
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description abstract void
addGlobalCondition(Parameter param, int columnId, int comparisonType)
Add a condition to the query.(package private) void
addParameter(Parameter param)
Add a parameter to the parameter list.abstract boolean
allowGlobalConditions()
Check whether adding condition to the query is allowed.(package private) void
appendEndOfQueryToSQL(java.lang.StringBuilder builder, int sqlFlags, Expression[] expressions)
Appends ORDER BY, OFFSET, and FETCH clauses to the plan.private static boolean
checkOrderOther(SessionLocal session, Expression expr, java.util.ArrayList<java.lang.String> expressionSQL)
An additional check for expression in ORDER BY list for DISTINCT selects that was not matched with selected expressions in regular way.(package private) void
cleanupOrder()
Removes constant expressions from the sort order.private void
closeLastResult()
void
collectDependencies(java.util.HashSet<DbObject> dependencies)
Find and collect all DbObjects, this Prepared depends on.(package private) LocalResult
convertToDistinct(ResultInterface result)
Convert a result into a distinct result, using the current columns.void
disableCache()
Disable caching of result sets.private boolean
executeExists()
boolean
exists()
Execute the EXISTS predicate over the query.(package private) LocalResult
finishResult(LocalResult result, long offset, long fetch, boolean fetchPercent, ResultTarget target)
Applies limits, if any, to a result and makes it ready for value retrieval.abstract void
fireBeforeSelectTriggers()
Call the before triggers on all tables.int
getColumnCount()
Get the column count of this query.abstract double
getCost()
Calculate the cost to execute this query.int
getCostAsExpression()
Calculate the cost when used as a subquery.java.util.ArrayList<Expression>
getExpressions()
The the list of select expressions.Expression
getFetch()
Expression
getIfSingleRow()
If this query is determined as a single-row query, returns a replacement expression.long
getMaxDataModificationId()
Expression
getOffset()
(package private) Query.OffsetFetch
getOffsetFetch(long maxRows)
Evaluates OFFSET and FETCH expressions.private Value[]
getParameterValues()
TypeInfo
getRowDataType()
Returns data type of rows.abstract java.util.HashSet<Table>
getTables()
Get all tables that are involved in this query.int
getType()
Get the command type as defined in CommandInterfaceboolean
hasOrder()
Whether the query has an order.abstract void
init()
Initialize the query.(package private) int
initExpression(java.util.ArrayList<java.lang.String> expressionSQL, Expression e, boolean mustBeInResult, java.util.ArrayList<TableFilter> filters)
Initialize the 'ORDER BY' or 'DISTINCT' expressions.(package private) boolean
initOrder(java.util.ArrayList<java.lang.String> expressionSQL, boolean mustBeInResult, java.util.ArrayList<TableFilter> filters)
Initialize the order by list.boolean
isAnyDistinct()
boolean
isConstantQuery()
Check if this query will always return the same value and has no side effects.abstract boolean
isEverything(ExpressionVisitor visitor)
Check if this expression and all sub-expressions can fulfill a criteria.boolean
isFetchPercent()
boolean
isNeverLazy()
boolean
isQuery()
Check if this object is a query.boolean
isRandomAccessResult()
Returns whether results support random access.boolean
isReadOnly()
Check if this command is read only.boolean
isStandardDistinct()
boolean
isTransactional()
Check if this command is transactional.abstract boolean
isUnion()
Check if this is a UNION query.boolean
isWithTies()
abstract void
mapColumns(ColumnResolver resolver, int level)
Map the columns to the given column resolver.(package private) void
prepareOrder(java.util.ArrayList<QueryOrderBy> orderList, int expressionCount)
Create aSortOrder
object given the list ofQueryOrderBy
objects.ResultInterface
query(long maxrows)
Execute the query.ResultInterface
query(long limit, ResultTarget target)
Execute the query, writing the result to the target result.ResultInterface
queryMeta()
Get an empty result set containing the meta data.protected abstract ResultInterface
queryWithoutCache(long limit, ResultTarget target)
Execute the query without checking the cache.private ResultInterface
queryWithoutCacheLazyCheck(long limit, ResultTarget target)
private boolean
sameResultAsLast(Value[] params, Value[] lastParams, long lastEval)
void
setDistinctIfPossible()
Set the distinct flag only if it is possible, may be used as a possible optimization only.abstract void
setEvaluatable(TableFilter tableFilter, boolean b)
Change the evaluatable flag.void
setFetch(Expression fetch)
void
setFetchPercent(boolean fetchPercent)
abstract void
setForUpdate(boolean forUpdate)
Set the 'for update' flag.void
setNeverLazy(boolean b)
void
setOffset(Expression offset)
void
setOrder(java.util.ArrayList<QueryOrderBy> order)
Set the order by list.void
setRandomAccessResult(boolean b)
Whether results need to support random access.void
setWithTies(boolean withTies)
Table
toTable(java.lang.String alias, Column[] columnTemplates, java.util.ArrayList<Parameter> parameters, boolean forCreateView, Query topQuery)
Converts this query to a table or a view.abstract void
updateAggregate(SessionLocal s, int stage)
Update all aggregate function values.-
Methods inherited from class org.h2.command.Prepared
checkCanceled, checkParameters, getCteCleanups, getCurrentRowNumber, getObjectId, getParameters, getPersistedObjectId, getPlanSQL, getSession, getSimpleSQL, getSQL, getSQLTokens, isCacheable, needRecompile, prepare, setCommand, setCteCleanups, setCurrentRowNumber, setParameterList, setPersistedObjectId, setPrepareAlways, setRow, setSession, setSQL, toString, update
-
-
-
-
Field Detail
-
expressions
java.util.ArrayList<Expression> expressions
The column list, including invisible expressions such as order by expressions.
-
expressionArray
Expression[] expressionArray
Array of expressions.- See Also:
expressions
-
orderList
java.util.ArrayList<QueryOrderBy> orderList
Describes elements of the ORDER BY clause of a query.
-
sort
SortOrder sort
A sort order represents an ORDER BY clause in a query.
-
fetchExpr
Expression fetchExpr
The fetch expression as specified in the FETCH, LIMIT, or TOP clause.
-
fetchPercent
boolean fetchPercent
Whether limit expression specifies percentage of rows.
-
withTies
boolean withTies
Whether tied rows should be included in result too.
-
offsetExpr
Expression offsetExpr
The offset expression as specified in the OFFSET clause.
-
distinct
boolean distinct
Whether the result must only contain distinct rows.
-
randomAccessResult
boolean randomAccessResult
Whether the result needs to support random access.
-
visibleColumnCount
int visibleColumnCount
The visible columns (the ones required in the result).
-
resultColumnCount
int resultColumnCount
Number of columns including visible columns and additional virtual columns for ORDER BY and DISTINCT ON clauses. This number does not include virtual columns for HAVING and QUALIFY.
-
noCache
private boolean noCache
-
lastLimit
private long lastLimit
-
lastEvaluated
private long lastEvaluated
-
lastResult
private ResultInterface lastResult
-
lastExists
private java.lang.Boolean lastExists
-
lastParameters
private Value[] lastParameters
-
cacheableChecked
private boolean cacheableChecked
-
neverLazy
private boolean neverLazy
-
checkInit
boolean checkInit
-
isPrepared
boolean isPrepared
-
-
Constructor Detail
-
Query
Query(SessionLocal session)
-
-
Method Detail
-
setNeverLazy
public void setNeverLazy(boolean b)
-
isNeverLazy
public boolean isNeverLazy()
-
isUnion
public abstract boolean isUnion()
Check if this is a UNION query.- Returns:
true
if this is a UNION query
-
queryMeta
public ResultInterface queryMeta()
Description copied from class:Prepared
Get an empty result set containing the meta data.
-
queryWithoutCache
protected abstract ResultInterface queryWithoutCache(long limit, ResultTarget target)
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.- Parameters:
limit
- the limit as specified in the JDBC method calltarget
- the target to write results to- Returns:
- the result
-
queryWithoutCacheLazyCheck
private ResultInterface queryWithoutCacheLazyCheck(long limit, ResultTarget target)
-
init
public abstract void init()
Initialize the query.
-
getExpressions
public java.util.ArrayList<Expression> getExpressions()
The the list of select expressions. This may include invisible expressions such as order by expressions.- Returns:
- the list of expressions
-
getCost
public abstract double getCost()
Calculate the cost to execute this query.- Returns:
- the cost
-
getCostAsExpression
public int getCostAsExpression()
Calculate the cost when used as a subquery. This method returns a value between 10 and 1000000, to ensure adding other values can't result in an integer overflow.- Returns:
- the estimated cost as an integer
-
getTables
public abstract java.util.HashSet<Table> getTables()
Get all tables that are involved in this query.- Returns:
- the set of tables
-
setOrder
public void setOrder(java.util.ArrayList<QueryOrderBy> order)
Set the order by list.- Parameters:
order
- the order by list
-
hasOrder
public boolean hasOrder()
Whether the query has an order.- Returns:
- true if it has
-
setForUpdate
public abstract void setForUpdate(boolean forUpdate)
Set the 'for update' flag.- Parameters:
forUpdate
- the new setting
-
getColumnCount
public int getColumnCount()
Get the column count of this query.- Returns:
- the column count
-
getRowDataType
public TypeInfo getRowDataType()
Returns data type of rows.- Returns:
- data type of rows
-
mapColumns
public abstract void mapColumns(ColumnResolver resolver, int level)
Map the columns to the given column resolver.- Parameters:
resolver
- the resolverlevel
- the subquery level (0 is the top level query, 1 is the first subquery level)
-
setEvaluatable
public abstract void setEvaluatable(TableFilter tableFilter, boolean b)
Change the evaluatable flag. This is used when building the execution plan.- Parameters:
tableFilter
- the table filterb
- the new value
-
addGlobalCondition
public abstract void addGlobalCondition(Parameter param, int columnId, int comparisonType)
Add a condition to the query. This is used for views.- Parameters:
param
- the parametercolumnId
- the column index (0 meaning the first column)comparisonType
- the comparison type
-
allowGlobalConditions
public abstract boolean allowGlobalConditions()
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.- Returns:
- true if adding global conditions is allowed
-
isEverything
public abstract boolean isEverything(ExpressionVisitor visitor)
Check if this expression and all sub-expressions can fulfill a criteria. If any part returns false, the result is false.- Parameters:
visitor
- the visitor- Returns:
- if the criteria can be fulfilled
-
isReadOnly
public boolean isReadOnly()
Description copied from class:Prepared
Check if this command is read only.- Overrides:
isReadOnly
in classPrepared
- Returns:
- true if it is
-
updateAggregate
public abstract void updateAggregate(SessionLocal s, int stage)
Update all aggregate function values.- Parameters:
s
- the sessionstage
- select stage
-
fireBeforeSelectTriggers
public abstract void fireBeforeSelectTriggers()
Call the before triggers on all tables.
-
setDistinctIfPossible
public void setDistinctIfPossible()
Set the distinct flag only if it is possible, may be used as a possible optimization only.
-
isStandardDistinct
public boolean isStandardDistinct()
- Returns:
- whether this query is a plain
DISTINCT
query
-
isAnyDistinct
public boolean isAnyDistinct()
- Returns:
- whether this query is a
DISTINCT
orDISTINCT ON (...)
query
-
isRandomAccessResult
public boolean isRandomAccessResult()
Returns whether results support random access.- Returns:
- whether results support random access
-
setRandomAccessResult
public void setRandomAccessResult(boolean b)
Whether results need to support random access.- Parameters:
b
- the new value
-
isQuery
public boolean isQuery()
Description copied from class:Prepared
Check if this object is a query.
-
isTransactional
public boolean isTransactional()
Description copied from class:Prepared
Check if this command is transactional. If it is not, then it forces the current transaction to commit.- Specified by:
isTransactional
in classPrepared
- Returns:
- true if it is
-
disableCache
public void disableCache()
Disable caching of result sets.
-
sameResultAsLast
private boolean sameResultAsLast(Value[] params, Value[] lastParams, long lastEval)
-
getParameterValues
private Value[] getParameterValues()
-
query
public final ResultInterface query(long maxrows)
Description copied from class:Prepared
Execute the query.
-
query
public final ResultInterface query(long limit, ResultTarget target)
Execute the query, writing the result to the target result.- Parameters:
limit
- the maximum number of rows to returntarget
- the target result (null will return the result)- Returns:
- the result set (if the target is not set).
-
closeLastResult
private void closeLastResult()
-
exists
public final boolean exists()
Execute the EXISTS predicate over the query.- Returns:
- EXISTS predicate result
-
executeExists
private boolean executeExists()
-
initOrder
boolean initOrder(java.util.ArrayList<java.lang.String> expressionSQL, boolean mustBeInResult, java.util.ArrayList<TableFilter> filters)
Initialize the order by list. This call may extend the expressions list.- Parameters:
expressionSQL
- the select list SQL snippetsmustBeInResult
- all order by expressions must be in the select listfilters
- the table filters- Returns:
true
if ORDER BY clause is preserved,false
otherwise
-
initExpression
int initExpression(java.util.ArrayList<java.lang.String> expressionSQL, Expression e, boolean mustBeInResult, java.util.ArrayList<TableFilter> filters)
Initialize the 'ORDER BY' or 'DISTINCT' expressions.- Parameters:
expressionSQL
- the select list SQL snippetse
- the expression.mustBeInResult
- all order by expressions must be in the select listfilters
- the table filters.- Returns:
- index on the expression in the
expressions
list.
-
checkOrderOther
private static boolean checkOrderOther(SessionLocal session, Expression expr, java.util.ArrayList<java.lang.String> expressionSQL)
An additional check for expression in ORDER BY list for DISTINCT selects that was not matched with selected expressions in regular way. This method allows expressions based only on selected expressions in different complicated ways with functions, comparisons, or operators.- Parameters:
session
- sessionexpr
- expression to checkexpressionSQL
- SQL of allowed expressions- Returns:
- whether the specified expression should be allowed in ORDER BY list of DISTINCT select
-
prepareOrder
void prepareOrder(java.util.ArrayList<QueryOrderBy> orderList, int expressionCount)
Create aSortOrder
object given the list ofQueryOrderBy
objects.- Parameters:
orderList
- a list ofQueryOrderBy
elementsexpressionCount
- the number of columns in the query
-
cleanupOrder
void cleanupOrder()
Removes constant expressions from the sort order. Some constants are detected only after optimization of expressions, this method removes them from the sort order only. They are currently preserved in the list of expressions.
-
getType
public int getType()
Description copied from class:Prepared
Get the command type as defined in CommandInterface
-
setOffset
public void setOffset(Expression offset)
-
getOffset
public Expression getOffset()
-
setFetch
public void setFetch(Expression fetch)
-
getFetch
public Expression getFetch()
-
setFetchPercent
public void setFetchPercent(boolean fetchPercent)
-
isFetchPercent
public boolean isFetchPercent()
-
setWithTies
public void setWithTies(boolean withTies)
-
isWithTies
public boolean isWithTies()
-
addParameter
void addParameter(Parameter param)
Add a parameter to the parameter list.- Parameters:
param
- the parameter to add
-
getMaxDataModificationId
public final long getMaxDataModificationId()
-
appendEndOfQueryToSQL
void appendEndOfQueryToSQL(java.lang.StringBuilder builder, int sqlFlags, Expression[] expressions)
Appends ORDER BY, OFFSET, and FETCH clauses to the plan.- Parameters:
builder
- query plan string builder.sqlFlags
- formatting flagsexpressions
- the array of expressions
-
getOffsetFetch
Query.OffsetFetch getOffsetFetch(long maxRows)
Evaluates OFFSET and FETCH expressions.- Parameters:
maxRows
- additional limit- Returns:
- the evaluated values
-
finishResult
LocalResult finishResult(LocalResult result, long offset, long fetch, boolean fetchPercent, ResultTarget target)
Applies limits, if any, to a result and makes it ready for value retrieval.- Parameters:
result
- the resultoffset
- OFFSET valuefetch
- FETCH valuefetchPercent
- whether FETCH value is a PERCENT valuetarget
- target result or null- Returns:
- the result or null
-
convertToDistinct
LocalResult convertToDistinct(ResultInterface result)
Convert a result into a distinct result, using the current columns.- Parameters:
result
- the source- Returns:
- the distinct result
-
toTable
public Table toTable(java.lang.String alias, Column[] columnTemplates, java.util.ArrayList<Parameter> parameters, boolean forCreateView, Query topQuery)
Converts this query to a table or a view.- Parameters:
alias
- alias name for the viewcolumnTemplates
- column templates, ornull
parameters
- the parametersforCreateView
- if true, a system session will be used for the viewtopQuery
- the top level query- Returns:
- the table or the view
-
collectDependencies
public void collectDependencies(java.util.HashSet<DbObject> dependencies)
Description copied from class:Prepared
Find and collect all DbObjects, this Prepared depends on.- Overrides:
collectDependencies
in classPrepared
- Parameters:
dependencies
- collection of dependencies to populate
-
isConstantQuery
public boolean isConstantQuery()
Check if this query will always return the same value and has no side effects.- Returns:
- if this query will always return the same value and has no side effects.
-
getIfSingleRow
public Expression getIfSingleRow()
If this query is determined as a single-row query, returns a replacement expression.- Returns:
- the expression, or
null
-
-