org.apache.derby.impl.sql.compile
Class UnionNode

java.lang.Object
  extended byorg.apache.derby.impl.sql.compile.QueryTreeNode
      extended byorg.apache.derby.impl.sql.compile.ResultSetNode
          extended byorg.apache.derby.impl.sql.compile.FromTable
              extended byorg.apache.derby.impl.sql.compile.TableOperatorNode
                  extended byorg.apache.derby.impl.sql.compile.UnionNode
All Implemented Interfaces:
Optimizable, Visitable

public class UnionNode
extends TableOperatorNode

A UnionNode represents a UNION in a DML statement. It contains a boolean telling whether the union operation should eliminate duplicate rows.

Author:
Jeff Lichtman

Field Summary
private  boolean addNewNodesCalled
           
(package private)  boolean all
          Tells whether to eliminate duplicate rows.
private  OrderByList orderByList
           
(package private)  boolean tableConstructor
           
(package private)  boolean topTableConstructor
           
 
Fields inherited from class org.apache.derby.impl.sql.compile.TableOperatorNode
leftOptimizer, leftResultSet, nestedInParens, rightOptimizer, rightResultSet
 
Fields inherited from class org.apache.derby.impl.sql.compile.FromTable
bestAccessPath, bestCostEstimate, bestSortAvoidancePath, correlationName, corrTableName, currentAccessPath, hashKeyColumns, initialCapacity, level, loadFactor, maxCapacity, tableNumber, tableProperties, trulyTheBestAccessPath, userSpecifiedJoinStrategy
 
Fields inherited from class org.apache.derby.impl.sql.compile.ResultSetNode
costEstimate, cursorTargetTable, insertSource, optimizer, referencedTableMap, resultColumns, resultSetNumber, scratchCostEstimate, statementResultSet
 
Fields inherited from class org.apache.derby.impl.sql.compile.QueryTreeNode
AUTOINCREMENT_INC_INDEX, AUTOINCREMENT_IS_AUTOINCREMENT_INDEX, AUTOINCREMENT_START_INDEX, beginOffset, endOffset
 
Constructor Summary
UnionNode()
           
 
Method Summary
private  ResultSetNode addNewNodes()
          Add any new ResultSetNodes that are necessary to the tree.
 void bindExpressions(FromList fromListParam)
          Bind the expressions under this TableOperatorNode.
 void bindResultColumns(FromList fromListParam)
          Bind the result columns of this ResultSetNode when there is no base table to bind them to.
 void bindResultColumns(TableDescriptor targetTableDescriptor, FromVTI targetVTI, ResultColumnList targetColumnList, DMLStatementNode statement, FromList fromListParam)
          Bind the result columns for this ResultSetNode to a base table.
 void bindTargetExpressions(FromList fromListParam)
          Bind the expressions in the target list.
 void bindUntypedNullsToResultColumns(ResultColumnList rcl)
          Bind the result columns of a table constructor to the types in the given ResultColumnList.
private  void buildRCL()
          Build the RCL for this node.
 ResultSetNode enhanceRCLForInsert(int numTargetColumns, int[] colMap, DataDictionary dataDictionary, TableDescriptor targetTD, FromVTI targetVTI)
          This ResultSet is the source for an Insert.
 ResultSetNode ensurePredicateList(int numTables)
          Ensure that the top of the RSN tree has a PredicateList.
 boolean flattenableInFromSubquery(FromList fromList)
          Evaluate whether or not the subquery in a FromSubquery is flattenable.
 void generate(ActivationClassBuilder acb, MethodBuilder mb)
          Generate the code for this UnionNode.
protected  FromTable getFromTableByName(java.lang.String name, java.lang.String schemaName, boolean exactMatch)
          Determine whether or not the specified name is an exposed name in the current query block.
(package private)  int getParamColumnTypes(DataTypeDescriptor[] types, RowResultSetNode rrsn)
          Get the parameter types from the given RowResultSetNode into the given array of types.
 void init(java.lang.Object leftResult, java.lang.Object rightResult, java.lang.Object all, java.lang.Object tableConstructor, java.lang.Object tableProperties)
          Initializer for a UnionNode.
 void markTopTableConstructor()
          Mark this as the top node of a table constructor.
 Optimizable modifyAccessPath(JBitSet outerTables)
          Modify the access path for this Optimizable, as necessary.
 ResultSetNode modifyAccessPaths()
          Modify the access paths according to the decisions the optimizer made.
 CostEstimate optimizeIt(Optimizer optimizer, OptimizablePredicateList predList, CostEstimate outerCost, RowOrdering rowOrdering)
          Choose the best access path for this Optimizable.
 boolean performMaterialization(JBitSet outerTables)
          Return whether or not to materialize this ResultSet tree.
 ResultSetNode preprocess(int numTables, GroupByList gbl, FromList fromList)
          Put a ProjectRestrictNode on top of each FromTable in the FromList.
(package private)  void pushOrderByList(OrderByList orderByList)
          Push the order by list down from the cursor node into its child result set so that the optimizer has all of the information that it needs to consider sort avoidance.
 void rejectParameters()
          Check for (and reject) ?
(package private)  void setParamColumnTypes(DataTypeDescriptor[] types, RowResultSetNode rrsn)
          Set the type of each ?
 void setResultToBooleanTrueNode(boolean onlyConvertAlls)
          Set the result column for the subquery to a boolean true, Useful for transformations such as changing: where exists (select ... from ...)
(package private)  void setTableConstructorTypes(ResultColumnList typeColumns)
          Set the type of column in the result column lists of each source of this union tree to the type in the given result column list (which represents the result columns for an insert).
(package private)  boolean tableConstructor()
          Tell whether this is a UNION for a table constructor.
 java.lang.String toString()
          Convert this object to a String.
 void verifySelectStarSubquery(FromList outerFromList, int subqueryType)
          Verify that a SELECT * is valid for this type of subquery.
 
Methods inherited from class org.apache.derby.impl.sql.compile.TableOperatorNode
accept, bindExpressionsWithTables, bindNonVTITables, bindVTITables, decrementLevel, getExposedName, getLeftmostResultSet, getLeftResultSet, getNestedInParens, getRightResultSet, init, markOrderingDependent, needsSpecialRCLBinding, optimize, optimizeSource, printSubNodes, projectResultColumns, referencesSessionSchema, referencesTarget, replaceDefaults, setLeftmostResultSet, setLevel, setNestedInParens, setReferencedColumns, verifyProperties
 
Methods inherited from class org.apache.derby.impl.sql.compile.FromTable
areAllColumnsProjected, assignCostEstimate, canBeOrdered, considerSortAvoidancePath, convertAbsoluteToRelativeColumnPosition, cursorTargetTable, estimateCost, feasibleJoinStrategy, fillInReferencedTableMap, flatten, forUpdate, getBaseTableName, getBestAccessPath, getBestSortAvoidancePath, getCostEstimate, getCurrentAccessPath, getLevel, getName, getNumColumnsReturned, getProperties, getResultColumnsForList, getSchemaDescriptor, getSchemaDescriptor, getScratchCostEstimate, getTableDescriptor, getTableName, getTableNumber, getTrulyTheBestAccessPath, getUserSpecifiedJoinStrategy, hashKeyColumns, hasTableNumber, init, initAccessPaths, initialCapacity, isBaseTable, isCoveringIndex, isFlattenableJoinNode, isMaterializable, isOneRowScan, isTargetTable, legalJoinOrder, loadFactor, LOJ_reorderable, markUpdatableByCursor, maxCapacity, memoryUsage, nextAccessPath, optimizeSubqueries, pullOptPredicates, pushExpressions, pushOptPredicate, rememberAsBest, rememberJoinStrategyAsBest, rememberSortAvoidancePath, resetJoinStrategies, setAllColumnsProjected, setCostEstimate, setHashKeyColumns, setProperties, setTableNumber, startOptimizing, supportsMultipleInstantiations, tellRowOrderingAboutConstantColumns, transformOuterJoins, uniqueJoin
 
Methods inherited from class org.apache.derby.impl.sql.compile.ResultSetNode
addNewPredicate, assignResultSetNumber, changeAccessPath, closeMethodArgument, columnTypesAndLengthsMatch, considerMaterialization, generateNormalizationResultSet, generateResultSet, genNewRCForInsert, genNormalizeResultSetNode, genProjectRestrict, genProjectRestrict, genProjectRestrictForReordering, getAllResultColumns, getCostEstimate, getCursorTargetTable, getFinalCostEstimate, getFromList, getMatchingColumn, getNewCostEstimate, getOptimizer, getReferencedTableMap, getResultColumns, getResultSetNumber, isNotExists, isOneRowResultSet, isOrderedOn, isPossibleDistinctScan, isUpdatableCursor, LOJgetReferencedTables, makeResultDescription, makeResultDescriptors, markAsCursorTargetTable, markForDistinctScan, markStatementResultSet, notCursorTargetTable, notFlattenableJoin, numDistinctAggregates, parseDefault, renameGeneratedResultNames, returnsAtMostOneRow, setInsertSource, setReferencedTableMap, setResultColumns, subqueryReferencesTarget, updateTargetLockMode
 
Methods inherited from class org.apache.derby.impl.sql.compile.QueryTreeNode
bind, convertDefaultNode, debugFlush, debugPrint, executeSchemaName, executeStatementName, formatNodeString, foundString, generate, generateAuthorizeCheck, getBeginOffset, getClassFactory, getCompilerContext, getContextManager, getCursorInfo, getDataDictionary, getDependencyManager, getEndOffset, getExecutionFactory, getGenericConstantActionFactory, getIntProperty, getLanguageConnectionContext, getNodeFactory, getNodeType, getNullNode, getParameterTypes, getRowEstimate, getSchemaDescriptor, getSchemaDescriptor, getSPSName, getStatementType, getTableDescriptor, getTypeCompiler, init, init, init, init, init, init, init, init, init, init, init, isAtomic, isInstanceOf, isSessionSchema, isSessionSchema, makeConstantAction, makeTableName, needsSavepoint, nodeHeader, optimize, parseQueryText, printLabel, setBeginOffset, setContextManager, setEndOffset, setNodeType, setRefActionInfo, treePrint, treePrint, verifyClassExist
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface org.apache.derby.iapi.sql.compile.Optimizable
getDataDictionary, getReferencedTableMap, getResultSetNumber
 

Field Detail

all

boolean all
Tells whether to eliminate duplicate rows. all == TRUE means do not eliminate duplicates, all == FALSE means eliminate duplicates.


tableConstructor

boolean tableConstructor

topTableConstructor

boolean topTableConstructor

addNewNodesCalled

private boolean addNewNodesCalled

orderByList

private OrderByList orderByList
Constructor Detail

UnionNode

public UnionNode()
Method Detail

init

public void init(java.lang.Object leftResult,
                 java.lang.Object rightResult,
                 java.lang.Object all,
                 java.lang.Object tableConstructor,
                 java.lang.Object tableProperties)
          throws StandardException
Initializer for a UnionNode.

Overrides:
init in class QueryTreeNode
Parameters:
leftResult - The ResultSetNode on the left side of this union
rightResult - The ResultSetNode on the right side of this union
all - Whether or not this is a UNION ALL.
tableConstructor - Whether or not this is from a table constructor.
tableProperties - Properties list associated with the table
Throws:
StandardException - Thrown on error

markTopTableConstructor

public void markTopTableConstructor()
Mark this as the top node of a table constructor.


tableConstructor

boolean tableConstructor()
Tell whether this is a UNION for a table constructor.


rejectParameters

public void rejectParameters()
                      throws StandardException
Check for (and reject) ? parameters directly under the ResultColumns. This is done for SELECT statements. Don't reject parameters that are in a table constructor - these are allowed, as long as the table constructor is in an INSERT statement or each column of the table constructor has at least one non-? column. The latter case is checked below, in bindExpressions().

Overrides:
rejectParameters in class TableOperatorNode
Returns:
Nothing
Throws:
StandardException - Thrown if a ? parameter found directly under a ResultColumn

setTableConstructorTypes

void setTableConstructorTypes(ResultColumnList typeColumns)
                        throws StandardException
Set the type of column in the result column lists of each source of this union tree to the type in the given result column list (which represents the result columns for an insert). This is only for table constructors that appear in insert statements.

Overrides:
setTableConstructorTypes in class ResultSetNode
Parameters:
typeColumns - The ResultColumnList containing the desired result types.
Throws:
StandardException - Thrown on error

optimizeIt

public CostEstimate optimizeIt(Optimizer optimizer,
                               OptimizablePredicateList predList,
                               CostEstimate outerCost,
                               RowOrdering rowOrdering)
                        throws StandardException
Description copied from interface: Optimizable
Choose the best access path for this Optimizable.

Specified by:
optimizeIt in interface Optimizable
Overrides:
optimizeIt in class FromTable
Throws:
StandardException - Thrown on error
See Also:
Optimizable.optimizeIt(org.apache.derby.iapi.sql.compile.Optimizer, org.apache.derby.iapi.sql.compile.OptimizablePredicateList, org.apache.derby.iapi.sql.compile.CostEstimate, org.apache.derby.iapi.sql.compile.RowOrdering)

modifyAccessPath

public Optimizable modifyAccessPath(JBitSet outerTables)
                             throws StandardException
Description copied from interface: Optimizable
Modify the access path for this Optimizable, as necessary. This includes things like adding a result set to translate from index rows to base rows

Specified by:
modifyAccessPath in interface Optimizable
Overrides:
modifyAccessPath in class TableOperatorNode
Throws:
StandardException - Thrown on error
See Also:
Optimizable.modifyAccessPath(org.apache.derby.iapi.util.JBitSet)

modifyAccessPaths

public ResultSetNode modifyAccessPaths()
                                throws StandardException
Description copied from class: ResultSetNode
Modify the access paths according to the decisions the optimizer made. This can include adding project/restrict nodes, index-to-base-row nodes, etc.

Overrides:
modifyAccessPaths in class TableOperatorNode
Throws:
StandardException - Thrown on error
See Also:
ResultSetNode.modifyAccessPaths()

addNewNodes

private ResultSetNode addNewNodes()
                           throws StandardException
Add any new ResultSetNodes that are necessary to the tree. We wait until after optimization to do this in order to make it easier on the optimizer.

Returns:
(Potentially new) head of the ResultSetNode tree.
Throws:
StandardException - Thrown on error

toString

public java.lang.String toString()
Convert this object to a String. See comments in QueryTreeNode.java for how this should be done for tree printing.

Overrides:
toString in class TableOperatorNode
Returns:
This object as a String

bindExpressions

public void bindExpressions(FromList fromListParam)
                     throws StandardException
Bind the expressions under this TableOperatorNode. This means binding the sub-expressions, as well as figuring out what the return type is for each expression.

Overrides:
bindExpressions in class TableOperatorNode
Returns:
Nothing
Throws:
StandardException - Thrown on error

bindResultColumns

public void bindResultColumns(FromList fromListParam)
                       throws StandardException
Bind the result columns of this ResultSetNode when there is no base table to bind them to. This is useful for SELECT statements, where the result columns get their types from the expressions that live under them.

Overrides:
bindResultColumns in class TableOperatorNode
Parameters:
fromListParam - FromList to use/append to.
Returns:
Nothing
Throws:
StandardException - Thrown on error

bindResultColumns

public void bindResultColumns(TableDescriptor targetTableDescriptor,
                              FromVTI targetVTI,
                              ResultColumnList targetColumnList,
                              DMLStatementNode statement,
                              FromList fromListParam)
                       throws StandardException
Bind the result columns for this ResultSetNode to a base table. This is useful for INSERT and UPDATE statements, where the result columns get their types from the table being updated or inserted into. If a result column list is specified, then the verification that the result column list does not contain any duplicates will be done when binding them by name.

Overrides:
bindResultColumns in class TableOperatorNode
Parameters:
targetTableDescriptor - The TableDescriptor for the table being updated or inserted into
targetColumnList - For INSERT statements, the user does not have to supply column names (for example, "insert into t values (1,2,3)". When this parameter is null, it means that the user did not supply column names, and so the binding should be done based on order. When it is not null, it means do the binding by name, not position.
statement - Calling DMLStatementNode (Insert or Update)
fromListParam - FromList to use/append to.
Returns:
Nothing
Throws:
StandardException - Thrown on error

buildRCL

private void buildRCL()
               throws StandardException
Build the RCL for this node. We propagate the RCL up from the left child to form this node's RCL.

Returns:
Nothing
Throws:
StandardException - Thrown on error

bindUntypedNullsToResultColumns

public void bindUntypedNullsToResultColumns(ResultColumnList rcl)
                                     throws StandardException
Bind the result columns of a table constructor to the types in the given ResultColumnList. Use when inserting from a table constructor, and there are nulls in the values clauses.

Overrides:
bindUntypedNullsToResultColumns in class ResultSetNode
Parameters:
rcl - The ResultColumnList with the types to bind to
Throws:
StandardException - Thrown on error.

getParamColumnTypes

int getParamColumnTypes(DataTypeDescriptor[] types,
                        RowResultSetNode rrsn)
Get the parameter types from the given RowResultSetNode into the given array of types. If an array position is already filled in, don't clobber it.

Parameters:
types - The array of types to fill in
rrsn - The RowResultSetNode from which to take the param types
Returns:
The number of new types found in the RowResultSetNode

setParamColumnTypes

void setParamColumnTypes(DataTypeDescriptor[] types,
                         RowResultSetNode rrsn)
                   throws StandardException
Set the type of each ? parameter in the given RowResultSetNode according to its ordinal position in the given array of types.

Parameters:
types - An array of types containing the proper type for each ? parameter, by ordinal position.
rrsn - A RowResultSetNode that could contain ? parameters whose types need to be set.
Throws:
StandardException - Thrown on error

bindTargetExpressions

public void bindTargetExpressions(FromList fromListParam)
                           throws StandardException
Bind the expressions in the target list. This means binding the sub-expressions, as well as figuring out what the return type is for each expression. This is useful for EXISTS subqueries, where we need to validate the target list before blowing it away and replacing it with a SELECT true.

Overrides:
bindTargetExpressions in class ResultSetNode
Returns:
Nothing
Throws:
StandardException - Thrown on error

pushOrderByList

void pushOrderByList(OrderByList orderByList)
Push the order by list down from the cursor node into its child result set so that the optimizer has all of the information that it needs to consider sort avoidance.

Overrides:
pushOrderByList in class ResultSetNode
Parameters:
orderByList - The order by list
Returns:
Nothing.

preprocess

public ResultSetNode preprocess(int numTables,
                                GroupByList gbl,
                                FromList fromList)
                         throws StandardException
Put a ProjectRestrictNode on top of each FromTable in the FromList. ColumnReferences must continue to point to the same ResultColumn, so that ResultColumn must percolate up to the new PRN. However, that ResultColumn will point to a new expression, a VirtualColumnNode, which points to the FromTable and the ResultColumn that is the source for the ColumnReference. (The new PRN will have the original of the ResultColumnList and the ResultColumns from that list. The FromTable will get shallow copies of the ResultColumnList and its ResultColumns. ResultColumn.expression will remain at the FromTable, with the PRN getting a new VirtualColumnNode for each ResultColumn.expression.) We then project out the non-referenced columns. If there are no referenced columns, then the PRN's ResultColumnList will consist of a single ResultColumn whose expression is 1.

Overrides:
preprocess in class TableOperatorNode
Parameters:
numTables - Number of tables in the DML Statement
gbl - The group by list, if any
fromList - The from list, if any
Returns:
The generated ProjectRestrictNode atop the original FromTable.
Throws:
StandardException - Thrown on error

ensurePredicateList

public ResultSetNode ensurePredicateList(int numTables)
                                  throws StandardException
Ensure that the top of the RSN tree has a PredicateList.

Overrides:
ensurePredicateList in class ResultSetNode
Parameters:
numTables - The number of tables in the query.
Returns:
ResultSetNode A RSN tree with a node which has a PredicateList on top.
Throws:
StandardException - Thrown on error

verifySelectStarSubquery

public void verifySelectStarSubquery(FromList outerFromList,
                                     int subqueryType)
                              throws StandardException
Verify that a SELECT * is valid for this type of subquery.

Overrides:
verifySelectStarSubquery in class ResultSetNode
Parameters:
outerFromList - The FromList from the outer query block(s)
subqueryType - The subquery type
Returns:
None
Throws:
StandardException - Thrown on error

getFromTableByName

protected FromTable getFromTableByName(java.lang.String name,
                                       java.lang.String schemaName,
                                       boolean exactMatch)
                                throws StandardException
Determine whether or not the specified name is an exposed name in the current query block.

Overrides:
getFromTableByName in class TableOperatorNode
Parameters:
name - The specified name to search for as an exposed name.
schemaName - Schema name, if non-null.
exactMatch - Whether or not we need an exact match on specified schema and table names or match on table id.
Returns:
The FromTable, if any, with the exposed name.
Throws:
StandardException - Thrown on error

setResultToBooleanTrueNode

public void setResultToBooleanTrueNode(boolean onlyConvertAlls)
                                throws StandardException
Set the result column for the subquery to a boolean true, Useful for transformations such as changing: where exists (select ... from ...) to: where (select true from ...) NOTE: No transformation is performed if the ResultColumn.expression is already the correct boolean constant.

Overrides:
setResultToBooleanTrueNode in class ResultSetNode
Parameters:
onlyConvertAlls - Boolean, whether or not to just convert *'s
Returns:
Nothing.
Throws:
StandardException - Thrown on error

enhanceRCLForInsert

public ResultSetNode enhanceRCLForInsert(int numTargetColumns,
                                         int[] colMap,
                                         DataDictionary dataDictionary,
                                         TableDescriptor targetTD,
                                         FromVTI targetVTI)
                                  throws StandardException
This ResultSet is the source for an Insert. The target RCL is in a different order and/or a superset of this RCL. In most cases we will reorder and/or add defaults to the current RCL so that is matches the target RCL. Those RSNs whose generate() method does not handle projects will insert a PRN, with a new RCL which matches the target RCL, above the current RSN. NOTE - The new or enhanced RCL will be fully bound.

Overrides:
enhanceRCLForInsert in class ResultSetNode
Parameters:
numTargetColumns - # of columns in target RCL
dataDictionary - DataDictionary to use
targetTD - TableDescriptor for target if the target is not a VTI, null if a VTI
targetVTI - Target description if it is a VTI, null if not a VTI
Returns:
ResultSetNode The new top of the tree
Throws:
StandardException - Thrown on error

flattenableInFromSubquery

public boolean flattenableInFromSubquery(FromList fromList)
Evaluate whether or not the subquery in a FromSubquery is flattenable. Currently, a FSqry is flattenable if all of the following are true: o Subquery is a SelectNode. (ie, not a RowResultSetNode or a UnionNode) o It contains no top level subqueries. (RESOLVE - we can relax this) o It does not contain a group by or having clause o It does not contain aggregates.

Overrides:
flattenableInFromSubquery in class ResultSetNode
Parameters:
fromList - The outer from list
Returns:
boolean Whether or not the FromSubquery is flattenable.

performMaterialization

public boolean performMaterialization(JBitSet outerTables)
                               throws StandardException
Return whether or not to materialize this ResultSet tree.

Overrides:
performMaterialization in class ResultSetNode
Returns:
Whether or not to materialize this ResultSet tree. would return valid results.
Throws:
StandardException - Thrown on error

generate

public void generate(ActivationClassBuilder acb,
                     MethodBuilder mb)
              throws StandardException
Generate the code for this UnionNode.

Overrides:
generate in class QueryTreeNode
Parameters:
acb - The ActivationClassBuilder for the class being built
mb - The method for the generated code to go into
Throws:
StandardException - Thrown on error


Apache Derby V10.0 Engine Documentation - Copyright © 1997,2004 The Apache Software Foundation or its licensors, as applicable.