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

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

public class UnionNode
extends SetOperatorNode

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


Field Summary
private  boolean addNewNodesCalled
           
(package private)  boolean tableConstructor
           
(package private)  boolean topTableConstructor
           
 
Fields inherited from class org.apache.derby.impl.sql.compile.SetOperatorNode
all, fetchFirst, offset, orderByList
 
Fields inherited from class org.apache.derby.impl.sql.compile.TableOperatorNode
leftOptimizer, leftResultSet, rightOptimizer, rightResultSet
 
Fields inherited from class org.apache.derby.impl.sql.compile.FromTable
ADD_PLAN, bestAccessPath, bestCostEstimate, bestSortAvoidancePath, correlationName, corrTableName, currentAccessPath, hashKeyColumns, initialCapacity, level, LOAD_PLAN, loadFactor, maxCapacity, origTableName, REMOVE_PLAN, tableNumber, tableProperties, trulyTheBestAccessPath, userSpecifiedJoinStrategy
 
Fields inherited from class org.apache.derby.impl.sql.compile.ResultSetNode
costEstimate, cursorTargetTable, finalCostEstimate, insertSource, optimizer, referencedTableMap, resultColumns, resultSetNumber, scratchCostEstimate, statementResultSet
 
Fields inherited from class org.apache.derby.impl.sql.compile.QueryTreeNode
AUTOINCREMENT_CREATE_MODIFY, AUTOINCREMENT_INC_INDEX, AUTOINCREMENT_IS_AUTOINCREMENT_INDEX, AUTOINCREMENT_START_INDEX, isPrivilegeCollectionRequired
 
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.
(package private)  ResultSetNode enhanceRCLForInsert(InsertNode target, boolean inOrder, int[] colMap)
          Make the RCL of this node match the target node for the insert.
 void generate(ActivationClassBuilder acb, MethodBuilder mb)
          Generate the code for this UnionNode.
 CostEstimate getFinalCostEstimate()
          Get the final CostEstimate for this FromTable.
(package private)  java.lang.String getOperatorName()
           
 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.
 void pushExpressions(PredicateList predicateList)
          DERBY-649: Handle pushing predicates into UnionNodes.
 void rejectParameters()
          Check for (and reject) ?
(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.
 
Methods inherited from class org.apache.derby.impl.sql.compile.SetOperatorNode
bindResultColumns, bindResultColumns, bindTargetExpressions, bindUntypedNullsToResultColumns, ensurePredicateList, flattenableInFromSubquery, getFromTableByName, getLeftOptPredicateList, getParamColumnTypes, getRightOptPredicateList, hasUnPushedPredicates, init, modifyAccessPath, performMaterialization, preprocess, printSubNodes, pullOptPredicates, pushOffsetFetchFirst, pushOptPredicate, pushOrderByList, replaceOrForbidDefaults, setParamColumnTypes, setResultToBooleanTrueNode, verifySelectStarSubquery
 
Methods inherited from class org.apache.derby.impl.sql.compile.TableOperatorNode
acceptChildren, adjustForSortElimination, adjustForSortElimination, bindExpressionsWithTables, bindNonVTITables, bindVTITables, decrementLevel, getExposedName, getLeftmostResultSet, getLeftResultSet, getRightResultSet, init, needsSpecialRCLBinding, optimize, optimizeSource, projectResultColumns, referencesSessionSchema, referencesTarget, setLeftmostResultSet, setLevel, setNestedInParens, setReferencedColumns, updateBestPlanMap, verifyProperties
 
Methods inherited from class org.apache.derby.impl.sql.compile.FromTable
assignCostEstimate, canBeOrdered, considerSortAvoidancePath, convertAbsoluteToRelativeColumnPosition, cursorTargetTable, estimateCost, feasibleJoinStrategy, fillInReferencedTableMap, flatten, forUpdate, getBaseTableName, getBestAccessPath, getBestSortAvoidancePath, getCorrelationName, getCostEstimate, getCurrentAccessPath, getLevel, getName, getNumColumnsReturned, getOrigTableName, 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, memoryUsageOK, nextAccessPath, optimizeSubqueries, rememberAsBest, rememberJoinStrategyAsBest, rememberSortAvoidancePath, resetJoinStrategies, setCostEstimate, setHashKeyColumns, setOrigTableName, setProperties, setTableNumber, startOptimizing, supportsMultipleInstantiations, tellRowOrderingAboutConstantColumns, transformOuterJoins, uniqueJoin
 
Methods inherited from class org.apache.derby.impl.sql.compile.ResultSetNode
addNewPredicate, assignResultSetNumber, changeAccessPath, columnTypesAndLengthsMatch, considerMaterialization, disablePrivilegeCollection, generateNormalizationResultSet, generateResultSet, genProjectRestrict, genProjectRestrict, genProjectRestrictForReordering, getAllResultColumns, getCostEstimate, getCursorTargetTable, getFromList, getMatchingColumn, getNewCostEstimate, getOptimizer, getOptimizerImpl, getRCLForInsert, getReferencedTableMap, getResultColumns, getResultSetNumber, isNotExists, isOneRowResultSet, isOrderedOn, isPossibleDistinctScan, isUpdatableCursor, LOJgetReferencedTables, makeResultDescription, makeResultDescriptors, markAsCursorTargetTable, markForDistinctScan, markStatementResultSet, modifyAccessPaths, notCursorTargetTable, notFlattenableJoin, numDistinctAggregates, parseDefault, rejectXMLValues, renameGeneratedResultNames, returnsAtMostOneRow, setInsertSource, setReferencedTableMap, setResultColumns, subqueryReferencesTarget, updateTargetLockMode
 
Methods inherited from class org.apache.derby.impl.sql.compile.QueryTreeNode
accept, bindOffsetFetch, bindRowMultiSet, bindUserType, checkReliability, checkReliability, convertDefaultNode, createTypeDependency, debugFlush, debugPrint, formatNodeString, foundString, generateAuthorizeCheck, getBeginOffset, getClassFactory, getCompilerContext, getContextManager, getCursorInfo, getDataDictionary, getDependencyManager, getEndOffset, getExecutionFactory, getGenericConstantActionFactory, getIntProperty, getLanguageConnectionContext, getNodeFactory, getNodeType, getNullNode, getParameterTypes, getRowEstimate, getSchemaDescriptor, getSchemaDescriptor, getStatementType, getTableDescriptor, getTypeCompiler, init, init, init, init, init, init, init, init, init, init, isAtomic, isInstanceOf, isPrivilegeCollectionRequired, isSessionSchema, isSessionSchema, makeConstantAction, makeTableName, makeTableName, nodeHeader, orReliability, parseStatement, printLabel, resolveTableToSynonym, setBeginOffset, setContextManager, setEndOffset, setNodeType, setRefActionInfo, stackPrint, 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

addNewNodesCalled

private boolean addNewNodesCalled

tableConstructor

boolean tableConstructor

topTableConstructor

boolean topTableConstructor
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
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

enhanceRCLForInsert

ResultSetNode enhanceRCLForInsert(InsertNode target,
                                  boolean inOrder,
                                  int[] colMap)
                            throws StandardException
Make the RCL of this node match the target node for the insert. If this node represents a table constructor (a VALUES clause), we replace the RCL with an enhanced one if necessary, and recursively enhance the RCL of each child node. For table constructors, we also need to check that we don't attempt to override auto-increment columns in each child node (checking the top-level RCL isn't sufficient since a table constructor may contain the DEFAULT keyword, which makes it possible to specify a column without overriding its value). If this node represents a regular UNION, put a ProjectRestrictNode on top of this node and enhance the RCL in that node.

Overrides:
enhanceRCLForInsert in class ResultSetNode
Parameters:
target - the target node for the insert
inOrder - are source cols in same order as target cols?
colMap - int array representation of correspondence between RCLs - colmap[i] = -1 -> missing in current RCL colmap[i] = j -> targetRCL(i) <-> thisRCL(j+1)
Returns:
a node that replaces this node and whose RCL matches the target RCL. May return this node if no changes to the RCL are needed, or if the RCL is modified in-place.
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
Parameters:
optimizer - Optimizer to use.
predList - The predicate list to optimize against
outerCost - The CostEstimate for the outer tables in the join order, telling how many times this Optimizable will be scanned.
rowOrdering - The row ordering for all the tables in the join order, including this one.
Returns:
The optimizer's estimated cost of the best access path.
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)

pushExpressions

public void pushExpressions(PredicateList predicateList)
                     throws StandardException
DERBY-649: Handle pushing predicates into UnionNodes. It is possible to push single table predicates that are binaryOperations or inListOperations. Predicates of the form or IN are currently handled. Since these predicates would allow optimizer to pick available indices, pushing them provides maximum benifit. It should be possible to expand this logic to cover more cases. Even pushing expressions (like a+b = 10) into SELECTs would improve performance, even if they don't allow use of index. It would mean evaluating expressions closer to data and hence could avoid sorting or other overheads that UNION may require. Note that the predicates are not removed after pushing. This is to ensure if pushing is not possible or only partially feasible.

Overrides:
pushExpressions in class FromTable
Parameters:
predicateList - List of single table predicates to push
Throws:
StandardException - Thrown on error

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
Parameters:
outerTables - Bit map of the tables that are outer to this one in the join order.
Returns:
The (potentially new) Optimizable at the top of the tree.
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
Returns:
The modified query tree
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 SetOperatorNode
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
Parameters:
fromListParam - FromList to use/append to.
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

getFinalCostEstimate

public CostEstimate getFinalCostEstimate()
                                  throws StandardException
Description copied from class: FromTable
Get the final CostEstimate for this FromTable.

Overrides:
getFinalCostEstimate in class FromTable
Returns:
The final CostEstimate for this UnionNode, which is the sum of the two child costs.
Throws:
StandardException
See Also:
Get the final CostEstimate for this UnionNode.

getOperatorName

java.lang.String getOperatorName()
Specified by:
getOperatorName in class SetOperatorNode
Returns:
the operator name: "UNION", "INTERSECT", or "EXCEPT"

Built on Thu 2012-03-29 21:53:33+0000, from revision ???

Apache Derby V10.6 Internals - Copyright © 2004,2007 The Apache Software Foundation. All Rights Reserved.