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

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.FromSubquery
All Implemented Interfaces:
Optimizable, Visitable

public class FromSubquery
extends FromTable

A FromSubquery represents a subquery in the FROM list of a DML statement. The current implementation of this class is only sufficient for Insert's need to push a new select on top of the one the user specified, to make the selected structure match that of the insert target table.


Field Summary
private  ValueNode fetchFirst
           
private  ValueNode offset
           
private  OrderByList orderByList
           
private  SchemaDescriptor origCompilationSchema
          DERBY-3270: If this subquery represents an expanded view, this holds the current compilation schema at view definition time.
(package private)  ResultSetNode subquery
           
 
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
FromSubquery()
           
 
Method Summary
 void bindExpressions(FromList fromListParam)
          Bind the expressions in this FromSubquery.
 ResultSetNode bindNonVTITables(DataDictionary dataDictionary, FromList fromListParam)
          Bind this subquery that appears in the FROM list.
 void bindUntypedNullsToResultColumns(ResultColumnList bindingRCL)
          Bind any untyped null nodes to the types in the given ResultColumnList.
 ResultSetNode bindVTITables(FromList fromListParam)
          Bind this subquery that appears in the FROM list.
(package private)  void decrementLevel(int decrement)
          Decrement (query block) level (0-based) for this FromTable.
 void disablePrivilegeCollection()
          Triggers, constraints and views get executed with their definer's privileges and they can exist in the system only if their definers' still have all the privileges to creeate them.
 ResultSetNode extractSubquery(int numTables)
          Extract out and return the subquery, with a PRN on top.
 FromList flatten(ResultColumnList rcl, PredicateList outerPList, SubqueryList sql, GroupByList gbl, ValueNode havingClause)
          Flatten this FSqry into the outer query block.
 ResultColumnList getAllResultColumns(TableName allTableName)
          Expand a "*" into a ResultColumnList with all of the result columns from the subquery.
 java.lang.String getExposedName()
          Get the exposed name for this table, which is the name that can be used to refer to it in the rest of the query.
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.
 ResultColumn getMatchingColumn(ColumnReference columnReference)
          Try to find a ResultColumn in the table represented by this FromBaseTable that matches the name in the given ColumnReference.
 ResultSetNode getSubquery()
          Return the "subquery" from this node.
 void init(java.lang.Object subquery, java.lang.Object orderByList, java.lang.Object offset, java.lang.Object fetchFirst, java.lang.Object correlationName, java.lang.Object derivedRCL, java.lang.Object tableProperties)
          Intializer for a table in a FROM list.
 ResultSetNode preprocess(int numTables, GroupByList gbl, FromList fromList)
          Preprocess a ResultSetNode - this currently means: o Generating a referenced table map for each ResultSetNode.
 void printSubNodes(int depth)
          Prints the sub-nodes of this object.
 boolean referencesSessionSchema()
          Return true if the node references SESSION schema tables (temporary or permanent)
 boolean referencesTarget(java.lang.String name, boolean baseTable)
          Search to see if a query references the specifed table name.
 void rejectParameters()
          Check for (and reject) ?
 void setOrigCompilationSchema(SchemaDescriptor sd)
          Associate this subquery with the original compilation schema of a view.
 
Methods inherited from class org.apache.derby.impl.sql.compile.FromTable
assignCostEstimate, canBeOrdered, considerSortAvoidancePath, convertAbsoluteToRelativeColumnPosition, cursorTargetTable, estimateCost, feasibleJoinStrategy, fillInReferencedTableMap, forUpdate, getBaseTableName, getBestAccessPath, getBestSortAvoidancePath, getCorrelationName, getCostEstimate, getCurrentAccessPath, getFinalCostEstimate, 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, modifyAccessPath, needsSpecialRCLBinding, nextAccessPath, optimizeIt, optimizeSubqueries, pullOptPredicates, pushExpressions, pushOptPredicate, rememberAsBest, rememberJoinStrategyAsBest, rememberSortAvoidancePath, resetJoinStrategies, setCostEstimate, setHashKeyColumns, setLevel, setOrigTableName, setProperties, setTableNumber, startOptimizing, supportsMultipleInstantiations, tellRowOrderingAboutConstantColumns, toString, transformOuterJoins, uniqueJoin, updateBestPlanMap, verifyProperties
 
Methods inherited from class org.apache.derby.impl.sql.compile.ResultSetNode
acceptChildren, addNewPredicate, adjustForSortElimination, adjustForSortElimination, assignResultSetNumber, bindExpressionsWithTables, bindResultColumns, bindResultColumns, bindTargetExpressions, changeAccessPath, columnTypesAndLengthsMatch, considerMaterialization, enhanceRCLForInsert, ensurePredicateList, flattenableInFromSubquery, generateNormalizationResultSet, generateResultSet, genProjectRestrict, genProjectRestrict, genProjectRestrictForReordering, getCostEstimate, getCursorTargetTable, getFromList, getNewCostEstimate, getOptimizer, getOptimizerImpl, getRCLForInsert, getReferencedTableMap, getResultColumns, getResultSetNumber, isNotExists, isOneRowResultSet, isOrderedOn, isPossibleDistinctScan, isUpdatableCursor, LOJgetReferencedTables, makeResultDescription, makeResultDescriptors, markAsCursorTargetTable, markForDistinctScan, markStatementResultSet, modifyAccessPaths, modifyAccessPaths, notCursorTargetTable, notFlattenableJoin, numDistinctAggregates, optimize, parseDefault, performMaterialization, projectResultColumns, pushOffsetFetchFirst, pushOrderByList, rejectXMLValues, renameGeneratedResultNames, replaceOrForbidDefaults, returnsAtMostOneRow, setInsertSource, setReferencedTableMap, setResultColumns, setResultToBooleanTrueNode, setTableConstructorTypes, subqueryReferencesTarget, updateTargetLockMode, verifySelectStarSubquery
 
Methods inherited from class org.apache.derby.impl.sql.compile.QueryTreeNode
accept, bindOffsetFetch, bindRowMultiSet, bindUserType, checkReliability, checkReliability, convertDefaultNode, createTypeDependency, debugFlush, debugPrint, formatNodeString, foundString, generate, 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, 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

subquery

ResultSetNode subquery

orderByList

private OrderByList orderByList

offset

private ValueNode offset

fetchFirst

private ValueNode fetchFirst

origCompilationSchema

private SchemaDescriptor origCompilationSchema
DERBY-3270: If this subquery represents an expanded view, this holds the current compilation schema at view definition time.

Constructor Detail

FromSubquery

public FromSubquery()
Method Detail

init

public void init(java.lang.Object subquery,
                 java.lang.Object orderByList,
                 java.lang.Object offset,
                 java.lang.Object fetchFirst,
                 java.lang.Object correlationName,
                 java.lang.Object derivedRCL,
                 java.lang.Object tableProperties)
Intializer for a table in a FROM list.

Overrides:
init in class QueryTreeNode
Parameters:
subquery - The subquery
orderByList - ORDER BY list if any, or null
offset - OFFSET if any, or null
fetchFirst - FETCH FIRST if any, or null
correlationName - The correlation name
derivedRCL - The derived column list
tableProperties - Properties list associated with the table

printSubNodes

public void printSubNodes(int depth)
Prints the sub-nodes of this object. See QueryTreeNode.java for how tree printing is supposed to work.

Overrides:
printSubNodes in class ResultSetNode
Parameters:
depth - The depth of this node in the tree

getSubquery

public ResultSetNode getSubquery()
Return the "subquery" from this node.

Returns:
ResultSetNode The "subquery" from this node.

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 FromTable
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

bindNonVTITables

public ResultSetNode bindNonVTITables(DataDictionary dataDictionary,
                                      FromList fromListParam)
                               throws StandardException
Bind this subquery that appears in the FROM list.

Overrides:
bindNonVTITables in class ResultSetNode
Parameters:
dataDictionary - The DataDictionary to use for binding
fromListParam - FromList to use/append to.
Returns:
ResultSetNode The bound FromSubquery.
Throws:
StandardException - Thrown on error

bindVTITables

public ResultSetNode bindVTITables(FromList fromListParam)
                            throws StandardException
Bind this subquery that appears in the FROM list.

Overrides:
bindVTITables in class ResultSetNode
Parameters:
fromListParam - FromList to use/append to.
Returns:
ResultSetNode The bound FromSubquery.
Throws:
StandardException - Thrown on error

rejectParameters

public void rejectParameters()
                      throws StandardException
Check for (and reject) ? parameters directly under the ResultColumns. This is done for SELECT statements. For FromSubquery, we simply pass the check through to the subquery.

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

bindExpressions

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

Overrides:
bindExpressions in class ResultSetNode
Parameters:
fromListParam - FromList to use/append to.
Throws:
StandardException - Thrown on error

getMatchingColumn

public ResultColumn getMatchingColumn(ColumnReference columnReference)
                               throws StandardException
Try to find a ResultColumn in the table represented by this FromBaseTable that matches the name in the given ColumnReference.

Overrides:
getMatchingColumn in class ResultSetNode
Parameters:
columnReference - The columnReference whose name we're looking for in the given table.
Returns:
A ResultColumn whose expression is the ColumnNode that matches the ColumnReference. Returns null if there is no match.
Throws:
StandardException - Thrown on error

preprocess

public ResultSetNode preprocess(int numTables,
                                GroupByList gbl,
                                FromList fromList)
                         throws StandardException
Preprocess a ResultSetNode - this currently means: o Generating a referenced table map for each ResultSetNode. o Putting the WHERE and HAVING clauses in conjunctive normal form (CNF). o Converting the WHERE and HAVING clauses into PredicateLists and classifying them. o Ensuring that a ProjectRestrictNode is generated on top of every FromBaseTable and generated in place of every FromSubquery. o Pushing single table predicates down to the new ProjectRestrictNodes.

Overrides:
preprocess in class ResultSetNode
Parameters:
numTables - The number of tables in the DML Statement
gbl - The group by list, if any
fromList - The from list, if any
Returns:
ResultSetNode at top of preprocessed tree.
Throws:
StandardException - Thrown on error

extractSubquery

public ResultSetNode extractSubquery(int numTables)
                              throws StandardException
Extract out and return the subquery, with a PRN on top. (See FromSubquery.preprocess() for more details.)

Parameters:
numTables - The number of tables in the DML Statement
Returns:
ResultSetNode at top of extracted tree.
Throws:
StandardException - Thrown on error

flatten

public FromList flatten(ResultColumnList rcl,
                        PredicateList outerPList,
                        SubqueryList sql,
                        GroupByList gbl,
                        ValueNode havingClause)
                 throws StandardException
Flatten this FSqry into the outer query block. The steps in flattening are: o Mark all ResultColumns as redundant, so that they are "skipped over" at generate(). o Append the wherePredicates to the outer list. o Return the fromList so that the caller will merge the 2 lists RESOLVE - FSqrys with subqueries are currently not flattenable. Some of them can be flattened, however. We need to merge the subquery list when we relax this restriction. NOTE: This method returns NULL when flattening RowResultSetNodes (the node for a VALUES clause). The reason is that no reference is left to the RowResultSetNode after flattening is done - the expressions point directly to the ValueNodes in the RowResultSetNode's ResultColumnList.

Overrides:
flatten in class FromTable
Parameters:
rcl - The RCL from the outer query
outerPList - PredicateList to append wherePredicates to.
sql - The SubqueryList from the outer query
gbl - The group by list, if any
havingClause - The HAVING clause, if any
Returns:
FromList The fromList from the underlying SelectNode.
Throws:
StandardException - Thrown on error

getExposedName

public java.lang.String getExposedName()
Get the exposed name for this table, which is the name that can be used to refer to it in the rest of the query.

Overrides:
getExposedName in class FromTable
Returns:
The exposed name for this table.

getAllResultColumns

public ResultColumnList getAllResultColumns(TableName allTableName)
                                     throws StandardException
Expand a "*" into a ResultColumnList with all of the result columns from the subquery.

Overrides:
getAllResultColumns in class ResultSetNode
Parameters:
allTableName - The qualifier on the "*"
Returns:
ResultColumnList The expanded list, or null if allTableName is non-null and doesn't match a table name in this result set
Throws:
StandardException - Thrown on error

disablePrivilegeCollection

public void disablePrivilegeCollection()
Description copied from class: QueryTreeNode
Triggers, constraints and views get executed with their definer's privileges and they can exist in the system only if their definers' still have all the privileges to creeate them. Based on this, any time a trigger/view/constraint is executing, we do not need to waste time in checking if the definer still has the right set of privileges. At compile time, we wil make sure that we do not collect the privilege requirement for objects accessed with definer privileges by calling the following method.

Overrides:
disablePrivilegeCollection in class ResultSetNode
See Also:
QueryTreeNode.disablePrivilegeCollection()

referencesTarget

public boolean referencesTarget(java.lang.String name,
                                boolean baseTable)
                         throws StandardException
Search to see if a query references the specifed table name.

Overrides:
referencesTarget in class ResultSetNode
Parameters:
name - Table name (String) to search for.
baseTable - Whether or not name is for a base table
Returns:
true if found, else false
Throws:
StandardException - Thrown on error

referencesSessionSchema

public boolean referencesSessionSchema()
                                throws StandardException
Return true if the node references SESSION schema tables (temporary or permanent)

Overrides:
referencesSessionSchema in class QueryTreeNode
Returns:
true if references SESSION schema tables, else false
Throws:
StandardException - Thrown on error

bindUntypedNullsToResultColumns

public void bindUntypedNullsToResultColumns(ResultColumnList bindingRCL)
                                     throws StandardException
Bind any untyped null nodes to the types in the given ResultColumnList.

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

decrementLevel

void decrementLevel(int decrement)
Decrement (query block) level (0-based) for this FromTable. This is useful when flattening a subquery.

Overrides:
decrementLevel in class FromTable
Parameters:
decrement - The amount to decrement by.

setOrigCompilationSchema

public void setOrigCompilationSchema(SchemaDescriptor sd)
Associate this subquery with the original compilation schema of a view.

Parameters:
sd - schema descriptor of the original compilation schema of the view.

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.