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

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

public class FromBaseTable
extends FromTable

A FromBaseTable represents a table in the FROM list of a DML statement, as distinguished from a FromSubquery, which represents a subquery in the FROM list. A FromBaseTable may actually represent a view. During parsing, we can't distinguish views from base tables. During binding, when we find FromBaseTables that represent views, we replace them with FromSubqueries. By the time we get to code generation, all FromSubqueries have been eliminated, and all FromBaseTables will represent only true base tables.

Positioned Update: Currently, all columns of an updatable cursor are selected to deal with a positioned update. This is because we don't know what columns will ultimately be needed from the UpdateNode above us. For example, consider:



 	get c as 'select cint from t for update of ctinyint'
  update t set ctinyint = csmallint

 
Ideally, the cursor only selects cint. Then, something akin to an IndexRowToBaseRow is generated to take the CursorResultSet and get the appropriate columns out of the base table from the RowLocation retunrned by the cursor. Then the update node can generate the appropriate NormalizeResultSet (or whatever else it might need) to get things into the correct format for the UpdateResultSet. See CurrentOfNode for more information.

Author:
Jeff Lichtman

Field Summary
(package private)  ConglomerateDescriptor baseConglomerateDescriptor
           
(package private)  PredicateList baseTableRestrictionList
          Restriction as a PredicateList
(package private)  int bulkFetch
           
(package private)  boolean bulkFetchTurnedOff
           
private  java.lang.String[] columnNames
           
(package private)  ConglomerateDescriptor[] conglomDescs
           
static int DELETE
           
private  JBitSet dependencyMap
           
private  boolean distinctScan
           
private  boolean existsBaseTable
           
private  int[] fkColArray
           
private  long fkIndexConglomId
           
private  boolean getUpdateLocks
           
private  boolean gotRowCount
           
private  boolean isNotExists
           
(package private)  PredicateList nonBaseTableRestrictionList
           
(package private)  PredicateList nonStoreRestrictionList
           
private  boolean raDependentScan
          Information for dependent table scan for Referential Actions
private  java.lang.String raParentResultSetId
           
private  FormatableBitSet referencedCols
           
(package private)  PredicateList requalificationRestrictionList
           
(package private)  PredicateList restrictionList
           
private  long rowCount
           
private  double singleScanRowCount
           
private  boolean specialMaxScan
           
(package private)  PredicateList storeRestrictionList
           
(package private)  TableDescriptor tableDescriptor
           
(package private)  TableName tableName
           
private  ResultColumnList templateColumns
           
(package private) static int UNSET
           
static int UPDATE
           
(package private)  int updateOrDelete
           
 
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
FromBaseTable()
           
 
Method Summary
 ResultColumnList addColsToList(ResultColumnList inputRcl, FormatableBitSet colsWeWant)
          Augment the RCL to include the columns in the FormatableBitSet.
private  long baseRowCount()
           
 void bindExpressions(FromList fromListParam)
          Bind the expressions in this FromBaseTable.
 ResultSetNode bindNonVTITables(DataDictionary dataDictionary, FromList fromListParam)
          Bind the table in this FromBaseTable.
 void bindResultColumns(FromList fromListParam)
          Bind the result columns of this ResultSetNode when there is no base table to bind them to.
private  TableDescriptor bindTableDescriptor()
          Bind the table descriptor for this table.
protected  boolean canBeOrdered()
          Tell super-class that this Optimizable can be ordered
 ResultSetNode changeAccessPath()
          The optimizer's decision on the access path for a result set may require the generation of extra result sets.
(package private)  void clearDependency(java.util.Vector locations)
          Clear the bits from the dependency map when join nodes are flattened
 int convertAbsoluteToRelativeColumnPosition(int absolutePosition)
          Convert an absolute to a relative 0-based column position.
protected  boolean cursorTargetTable()
          Is this a table that has a FOR UPDATE clause?
(package private)  void disableBulkFetch()
          Turn off bulk fetch
(package private)  void doSpecialMaxScan()
          Do a special scan for max.
 CostEstimate estimateCost(OptimizablePredicateList predList, ConglomerateDescriptor cd, CostEstimate outerCost, Optimizer optimizer, RowOrdering rowOrdering)
          Estimate the cost of scanning this Optimizable using the given predicate list with the given conglomerate.
 boolean forUpdate()
          Return true if this is the target table of an update
 void generate(ActivationClassBuilder acb, MethodBuilder mb)
          Generation on a FromBaseTable creates a scan on the optimizer-selected conglomerate.
private  void generateDistinctScan(ExpressionClassBuilder acb, MethodBuilder mb)
           
private  void generateMaxSpecialResultSet(ExpressionClassBuilder acb, MethodBuilder mb)
           
private  void generateRefActionDependentTableScan(ExpressionClassBuilder acb, MethodBuilder mb)
          Generation on a FromBaseTable for a referential action dependent table.
 void generateResultSet(ExpressionClassBuilder acb, MethodBuilder mb)
          Generation on a FromBaseTable for a SELECT.
protected  ResultSetNode genProjectRestrict(int numTables)
          Put a ProjectRestrictNode on top of each FromTable in the FromList.
 ResultColumnList genResultColList()
          Build a ResultColumnList based on all of the columns in this FromBaseTable.
 ResultColumnList getAllResultColumns(TableName allTableName)
          Return a ResultColumnList with all of the columns in this table.
private  StoreCostController getBaseCostController()
           
 java.lang.String getBaseTableName()
          Get the table name of this Optimizable.
private  void getConglomDescs()
           
private  int getDefaultBulkFetch()
           
(package private)  boolean getExistsBaseTable()
          Does this FBT represent an EXISTS FBT.
 java.lang.String getExposedName()
          Return the exposed name for this table, which is the name that can be used to refer to this table in the rest of the query.
 CostEstimate getFinalCostEstimate()
          Get the final CostEstimate for this ResultSetNode.
private  ConglomerateDescriptor getFirstConglom()
           
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.
private  ConglomerateDescriptor getNextConglom(ConglomerateDescriptor currCD)
           
private  DataValueDescriptor[] getRowTemplate(ConglomerateDescriptor cd, StoreCostController scc)
           
private  int getScanArguments(ExpressionClassBuilder acb, MethodBuilder mb)
           
private  StoreCostController getStoreCostController(ConglomerateDescriptor cd)
           
 TableDescriptor getTableDescriptor()
          Get the table descriptor for this table (if any).
 TableName getTableName()
          Return a TableName node representing this FromTable.
 TableName getTableNameField()
          Return the table name for this table.
private  java.lang.String getUserSpecifiedIndexName()
           
 void init(java.lang.Object arg1, java.lang.Object arg2, java.lang.Object arg3, java.lang.Object arg4)
          Initializer for a table in a FROM list.
 int initialCapacity()
          Return the initial capacity of the hash table, for hash join strategy
 boolean isBaseTable()
          Tell whether this Optimizable represents a base table
 boolean isCoveringIndex(ConglomerateDescriptor cd)
          Return whether or not this is a covering index.
 boolean isMaterializable()
          Tell whether this Optimizable is materializable
 boolean isNotExists()
          Return whether or not this is actually a EBT for NOT EXISTS.
 boolean isOneRowResultSet()
          Return whether or not the underlying ResultSet tree will return a single row, at most.
private  boolean isOneRowResultSet(ConglomerateDescriptor cd, OptimizablePredicateList predList)
          Is this a one-row result set with the given conglomerate descriptor?
 boolean isOneRowResultSet(OptimizablePredicateList predList)
           
 boolean isOneRowScan()
          Will the optimizable return at most 1 row per scan?
private  boolean isOrdered(ColumnReference[] crs, ConglomerateDescriptor cd)
          Return whether or not this index is ordered on a permutation of the specified columns.
(package private)  boolean isOrderedOn(ColumnReference[] crs, boolean permuteOrdering, java.util.Vector fbtVector)
          Return whether or not the underlying ResultSet tree is ordered on the specified columns.
(package private)  boolean isPossibleDistinctScan()
          Is it possible to do a distinct scan on this ResultSet tree.
private  boolean isStrictlyOrdered(ColumnReference[] crs, ConglomerateDescriptor cd)
          Return whether or not this index is ordered on a permutation of the specified columns.
 boolean isTargetTable()
          Is the optimizable the target table of an update or delete?
 boolean legalJoinOrder(JBitSet assignedTableMap)
          Can this Optimizable appear at the current location in the join order.
 float loadFactor()
          Return the load factor of the hash table, for hash join strategy
 boolean LOJ_reorderable(int numTables)
          no LOJ reordering for base table.
 JBitSet LOJgetReferencedTables(int numTables)
           
private  int mapAbsoluteToRelativeColumnPosition(int absolutePosition)
          Convert an absolute to a relative 0-based column position.
 boolean markAsCursorTargetTable()
          Mark this ResultSetNode as the target table of an updatable cursor.
(package private)  void markForDistinctScan()
          Mark the underlying scan as a distinct scan.
(package private)  void markOrderingDependent()
          Notify the underlying result set tree that the result is ordering dependent.
(package private)  void markUpdated(ResultColumnList updateColumns)
          Mark as updatable all the columns in the result column list of this FromBaseTable that match the columns in the given update column list.
 boolean memoryUsageOK(double rowCount, int maxMemoryPerTable)
           
private  ResultColumnList newResultColumns(ResultColumnList oldColumns, ConglomerateDescriptor idxCD, ConglomerateDescriptor heapCD, boolean cloneRCs)
          Create a new ResultColumnList to reflect the columns in the index described by the given ConglomerateDescriptor.
 boolean nextAccessPath(Optimizer optimizer, OptimizablePredicateList predList, RowOrdering rowOrdering)
          Choose the next access path to evaluate for this Optimizable.
 CostEstimate optimizeIt(Optimizer optimizer, OptimizablePredicateList predList, CostEstimate outerCost, RowOrdering rowOrdering)
          Choose the best access path for this Optimizable.
 ResultSetNode preprocess(int numTables, GroupByList gbl, FromList fromList)
          Preprocess a ResultSetNode - this currently means: o Generating a referenced table map for each ResultSetNode.
 void pullOptPredicates(OptimizablePredicateList optimizablePredicates)
          Pull all the OptimizablePredicates from this Optimizable and put them in the given OptimizablePredicateList.
 boolean pushOptPredicate(OptimizablePredicate optimizablePredicate)
          Push an OptimizablePredicate down, if this node accepts it.
 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.
private  double scanCostAfterSelectivity(double originalScanCost, double initialPositionCost, double selectivity, boolean anotherIndexUnique)
           
(package private)  void setExistsBaseTable(boolean existsBaseTable, JBitSet dependencyMap, boolean isNotExists)
          Set whether or not this FBT represents an EXISTS FBT.
private  void setLockingBasedOnThreshold(Optimizer optimizer, double rowsTouched)
           
 void setRefActionInfo(long fkIndexConglomId, int[] fkColArray, java.lang.String parentResultSetId, boolean dependentScan)
          set the Information gathered from the parent table that is required to peform a referential action on dependent table.
 void setTableProperties(java.util.Properties tableProperties)
          Set the table properties for this table.
 void startOptimizing(Optimizer optimizer, RowOrdering rowOrdering)
          Begin the optimization process for this Optimizable.
protected  boolean supersetOfUniqueIndex(boolean[] eqCols)
          Determine whether or not the columns marked as true in the passed in array are a superset of any unique index on this table.
protected  boolean supersetOfUniqueIndex(JBitSet[] tableColMap)
          Determine whether or not the columns marked as true in the passed in join table matrix are a superset of any single column unique index on this table.
 java.lang.String toString()
          Convert this object to a String.
 double uniqueJoin(OptimizablePredicateList predList)
          Does this optimizable have a uniqueness condition on the given predicate list, and if so, how many unique keys will be returned per scan.
 int updateTargetLockMode()
          Get the lock mode for the target table heap of an update or delete statement.
 void verifyProperties(DataDictionary dDictionary)
          Verify that the Properties list with optimizer overrides, if specified, is valid
 
Methods inherited from class org.apache.derby.impl.sql.compile.FromTable
areAllColumnsProjected, assignCostEstimate, considerSortAvoidancePath, decrementLevel, feasibleJoinStrategy, fillInReferencedTableMap, flatten, getBestAccessPath, getBestSortAvoidancePath, getCostEstimate, getCurrentAccessPath, getLevel, getName, getNumColumnsReturned, getProperties, getResultColumnsForList, getSchemaDescriptor, getSchemaDescriptor, getScratchCostEstimate, getTableNumber, getTrulyTheBestAccessPath, getUserSpecifiedJoinStrategy, hashKeyColumns, hasTableNumber, init, initAccessPaths, isFlattenableJoinNode, markUpdatableByCursor, maxCapacity, modifyAccessPath, needsSpecialRCLBinding, optimizeSubqueries, pushExpressions, rememberAsBest, rememberJoinStrategyAsBest, rememberSortAvoidancePath, resetJoinStrategies, setAllColumnsProjected, setCostEstimate, setHashKeyColumns, setLevel, setProperties, setTableNumber, supportsMultipleInstantiations, tellRowOrderingAboutConstantColumns, transformOuterJoins
 
Methods inherited from class org.apache.derby.impl.sql.compile.ResultSetNode
accept, addNewPredicate, assignResultSetNumber, bindExpressionsWithTables, bindResultColumns, bindTargetExpressions, bindUntypedNullsToResultColumns, bindVTITables, closeMethodArgument, columnTypesAndLengthsMatch, considerMaterialization, enhanceRCLForInsert, ensurePredicateList, flattenableInFromSubquery, generateNormalizationResultSet, genNewRCForInsert, genNormalizeResultSetNode, genProjectRestrict, genProjectRestrictForReordering, getCostEstimate, getCursorTargetTable, getFromList, getNewCostEstimate, getOptimizer, getReferencedTableMap, getResultColumns, getResultSetNumber, isUpdatableCursor, makeResultDescription, makeResultDescriptors, markStatementResultSet, modifyAccessPaths, notCursorTargetTable, notFlattenableJoin, numDistinctAggregates, optimize, parseDefault, performMaterialization, printSubNodes, projectResultColumns, pushOrderByList, rejectParameters, rejectXMLValues, renameGeneratedResultNames, replaceDefaults, returnsAtMostOneRow, setInsertSource, setReferencedTableMap, setResultColumns, setResultToBooleanTrueNode, setTableConstructorTypes, subqueryReferencesTarget, verifySelectStarSubquery
 
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, init, isAtomic, isInstanceOf, isSessionSchema, isSessionSchema, makeConstantAction, makeTableName, needsSavepoint, nodeHeader, optimize, parseQueryText, printLabel, resolveTableToSynonym, setBeginOffset, setContextManager, setEndOffset, setNodeType, 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

UNSET

static final int UNSET
See Also:
Constant Field Values

tableName

TableName tableName

tableDescriptor

TableDescriptor tableDescriptor

baseConglomerateDescriptor

ConglomerateDescriptor baseConglomerateDescriptor

conglomDescs

ConglomerateDescriptor[] conglomDescs

updateOrDelete

int updateOrDelete

bulkFetch

int bulkFetch

bulkFetchTurnedOff

boolean bulkFetchTurnedOff

singleScanRowCount

private double singleScanRowCount

referencedCols

private FormatableBitSet referencedCols

templateColumns

private ResultColumnList templateColumns

columnNames

private java.lang.String[] columnNames

specialMaxScan

private boolean specialMaxScan

distinctScan

private boolean distinctScan

raDependentScan

private boolean raDependentScan
Information for dependent table scan for Referential Actions


raParentResultSetId

private java.lang.String raParentResultSetId

fkIndexConglomId

private long fkIndexConglomId

fkColArray

private int[] fkColArray

baseTableRestrictionList

PredicateList baseTableRestrictionList
Restriction as a PredicateList


nonBaseTableRestrictionList

PredicateList nonBaseTableRestrictionList

restrictionList

PredicateList restrictionList

storeRestrictionList

PredicateList storeRestrictionList

nonStoreRestrictionList

PredicateList nonStoreRestrictionList

requalificationRestrictionList

PredicateList requalificationRestrictionList

UPDATE

public static final int UPDATE
See Also:
Constant Field Values

DELETE

public static final int DELETE
See Also:
Constant Field Values

existsBaseTable

private boolean existsBaseTable

isNotExists

private boolean isNotExists

dependencyMap

private JBitSet dependencyMap

getUpdateLocks

private boolean getUpdateLocks

gotRowCount

private boolean gotRowCount

rowCount

private long rowCount
Constructor Detail

FromBaseTable

public FromBaseTable()
Method Detail

init

public void init(java.lang.Object arg1,
                 java.lang.Object arg2,
                 java.lang.Object arg3,
                 java.lang.Object arg4)
Initializer for a table in a FROM list.

Overrides:
init in class QueryTreeNode

LOJ_reorderable

public boolean LOJ_reorderable(int numTables)
                        throws StandardException
no LOJ reordering for base table.

Overrides:
LOJ_reorderable in class FromTable
Throws:
StandardException

LOJgetReferencedTables

public JBitSet LOJgetReferencedTables(int numTables)
                               throws StandardException
Overrides:
LOJgetReferencedTables in class ResultSetNode
Throws:
StandardException

nextAccessPath

public boolean nextAccessPath(Optimizer optimizer,
                              OptimizablePredicateList predList,
                              RowOrdering rowOrdering)
                       throws StandardException
Description copied from interface: Optimizable
Choose the next access path to evaluate for this Optimizable.

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

canBeOrdered

protected boolean canBeOrdered()
Tell super-class that this Optimizable can be ordered

Overrides:
canBeOrdered in class FromTable

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)

getTableDescriptor

public TableDescriptor getTableDescriptor()
Description copied from interface: Optimizable
Get the table descriptor for this table (if any). Only base tables have table descriptors - for the rest of the optimizables, this method returns null.

Specified by:
getTableDescriptor in interface Optimizable
Overrides:
getTableDescriptor in class FromTable
See Also:
Optimizable.getTableDescriptor()

isMaterializable

public boolean isMaterializable()
                         throws StandardException
Description copied from interface: Optimizable
Tell whether this Optimizable is materializable

Specified by:
isMaterializable in interface Optimizable
Overrides:
isMaterializable in class FromTable
Throws:
StandardException - Thrown on error
See Also:
Optimizable.isMaterializable()

pushOptPredicate

public boolean pushOptPredicate(OptimizablePredicate optimizablePredicate)
                         throws StandardException
Description copied from interface: Optimizable
Push an OptimizablePredicate down, if this node accepts it.

Specified by:
pushOptPredicate in interface Optimizable
Overrides:
pushOptPredicate in class FromTable
Throws:
StandardException - Thrown on error
See Also:
Optimizable.pushOptPredicate(org.apache.derby.iapi.sql.compile.OptimizablePredicate)

pullOptPredicates

public void pullOptPredicates(OptimizablePredicateList optimizablePredicates)
                       throws StandardException
Description copied from interface: Optimizable
Pull all the OptimizablePredicates from this Optimizable and put them in the given OptimizablePredicateList.

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

isCoveringIndex

public boolean isCoveringIndex(ConglomerateDescriptor cd)
                        throws StandardException
Description copied from interface: Optimizable
Return whether or not this is a covering index. We expect to call this during generation, after access path selection is complete.

Specified by:
isCoveringIndex in interface Optimizable
Overrides:
isCoveringIndex in class FromTable
Throws:
StandardException - Thrown on error
See Also:
Optimizable.isCoveringIndex(org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor)

verifyProperties

public void verifyProperties(DataDictionary dDictionary)
                      throws StandardException
Description copied from interface: Optimizable
Verify that the Properties list with optimizer overrides, if specified, is valid

Specified by:
verifyProperties in interface Optimizable
Overrides:
verifyProperties in class FromTable
Throws:
StandardException - Thrown on error
See Also:
Optimizable.verifyProperties(org.apache.derby.iapi.sql.dictionary.DataDictionary)

getBaseTableName

public java.lang.String getBaseTableName()
Description copied from interface: Optimizable
Get the table name of this Optimizable. Only base tables have table names (by the time we use this method, all views will have been resolved).

Specified by:
getBaseTableName in interface Optimizable
Overrides:
getBaseTableName in class FromTable
See Also:
Optimizable.getBaseTableName()

startOptimizing

public void startOptimizing(Optimizer optimizer,
                            RowOrdering rowOrdering)
Description copied from interface: Optimizable
Begin the optimization process for this Optimizable. This can be called many times for an Optimizable while optimizing a query - it will typically be called every time the Optimizable is placed in a potential join order.

Specified by:
startOptimizing in interface Optimizable
Overrides:
startOptimizing in class FromTable
See Also:
Optimizable.startOptimizing(org.apache.derby.iapi.sql.compile.Optimizer, org.apache.derby.iapi.sql.compile.RowOrdering)

convertAbsoluteToRelativeColumnPosition

public int convertAbsoluteToRelativeColumnPosition(int absolutePosition)
Description copied from interface: Optimizable
Convert an absolute to a relative 0-based column position. This is useful when generating qualifiers for partial rows from the store.

Specified by:
convertAbsoluteToRelativeColumnPosition in interface Optimizable
Overrides:
convertAbsoluteToRelativeColumnPosition in class FromTable
See Also:
Optimizable.convertAbsoluteToRelativeColumnPosition(int)

estimateCost

public CostEstimate estimateCost(OptimizablePredicateList predList,
                                 ConglomerateDescriptor cd,
                                 CostEstimate outerCost,
                                 Optimizer optimizer,
                                 RowOrdering rowOrdering)
                          throws StandardException
Description copied from interface: Optimizable
Estimate the cost of scanning this Optimizable using the given predicate list with the given conglomerate. It is assumed that the predicate list has already been classified. This cost estimate is just for one scan, not for the life of the query.

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

scanCostAfterSelectivity

private double scanCostAfterSelectivity(double originalScanCost,
                                        double initialPositionCost,
                                        double selectivity,
                                        boolean anotherIndexUnique)
                                 throws StandardException
Throws:
StandardException

setLockingBasedOnThreshold

private void setLockingBasedOnThreshold(Optimizer optimizer,
                                        double rowsTouched)

isBaseTable

public boolean isBaseTable()
Description copied from interface: Optimizable
Tell whether this Optimizable represents a base table

Specified by:
isBaseTable in interface Optimizable
Overrides:
isBaseTable in class FromTable
See Also:
Optimizable.isBaseTable()

forUpdate

public boolean forUpdate()
Description copied from interface: Optimizable
Return true if this is the target table of an update

Specified by:
forUpdate in interface Optimizable
Overrides:
forUpdate in class FromTable
See Also:
Optimizable.forUpdate()

initialCapacity

public int initialCapacity()
Description copied from interface: Optimizable
Return the initial capacity of the hash table, for hash join strategy

Specified by:
initialCapacity in interface Optimizable
Overrides:
initialCapacity in class FromTable
See Also:
Optimizable.initialCapacity()

loadFactor

public float loadFactor()
Description copied from interface: Optimizable
Return the load factor of the hash table, for hash join strategy

Specified by:
loadFactor in interface Optimizable
Overrides:
loadFactor in class FromTable
See Also:
Optimizable.loadFactor()

memoryUsageOK

public boolean memoryUsageOK(double rowCount,
                             int maxMemoryPerTable)
                      throws StandardException
Specified by:
memoryUsageOK in interface Optimizable
Overrides:
memoryUsageOK in class FromTable
Throws:
StandardException
See Also:
Optimizable.memoryUsageOK(double, int)

isTargetTable

public boolean isTargetTable()
Description copied from interface: Optimizable
Is the optimizable the target table of an update or delete?

Specified by:
isTargetTable in interface Optimizable
Overrides:
isTargetTable in class FromTable
See Also:
Optimizable.isTargetTable()

uniqueJoin

public double uniqueJoin(OptimizablePredicateList predList)
                  throws StandardException
Description copied from interface: Optimizable
Does this optimizable have a uniqueness condition on the given predicate list, and if so, how many unique keys will be returned per scan.

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

isOneRowScan

public boolean isOneRowScan()
                     throws StandardException
Description copied from interface: Optimizable
Will the optimizable return at most 1 row per scan?

Specified by:
isOneRowScan in interface Optimizable
Overrides:
isOneRowScan in class FromTable
Throws:
StandardException - Thrown on error
See Also:
Optimizable.isOneRowScan()

legalJoinOrder

public boolean legalJoinOrder(JBitSet assignedTableMap)
Description copied from interface: Optimizable
Can this Optimizable appear at the current location in the join order. In other words, have the Optimizable's dependencies been satisfied?

Specified by:
legalJoinOrder in interface Optimizable
Overrides:
legalJoinOrder in class FromTable
See Also:
Optimizable.legalJoinOrder(org.apache.derby.iapi.util.JBitSet)

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 FromTable
Returns:
This object as a String

getExistsBaseTable

boolean getExistsBaseTable()
Does this FBT represent an EXISTS FBT.

Returns:
Whether or not this FBT represents an EXISTS FBT.

setExistsBaseTable

void setExistsBaseTable(boolean existsBaseTable,
                        JBitSet dependencyMap,
                        boolean isNotExists)
Set whether or not this FBT represents an EXISTS FBT.

Parameters:
existsBaseTable - Whether or not an EXISTS FBT.
dependencyMap - The dependency map for the EXISTS FBT.
isNotExists - Whether or not for NOT EXISTS, more specifically.
Returns:
Nothing.

clearDependency

void clearDependency(java.util.Vector locations)
Clear the bits from the dependency map when join nodes are flattened

Returns:
Nothing.

setTableProperties

public void setTableProperties(java.util.Properties tableProperties)
Set the table properties for this table.

Parameters:
tableProperties - The new table properties.
Returns:
Nothing.

bindNonVTITables

public ResultSetNode bindNonVTITables(DataDictionary dataDictionary,
                                      FromList fromListParam)
                               throws StandardException
Bind the table in this FromBaseTable. This is where view resolution occurs

Overrides:
bindNonVTITables in class ResultSetNode
Parameters:
dataDictionary - The DataDictionary to use for binding
fromListParam - FromList to use/append to.
Returns:
ResultSetNode The FromTable for the table or resolved view.
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 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

bindTableDescriptor

private TableDescriptor bindTableDescriptor()
                                     throws StandardException
Bind the table descriptor for this table.

Throws:
StandardException - Thrown on error

bindExpressions

public void bindExpressions(FromList fromListParam)
                     throws StandardException
Bind the expressions in this FromBaseTable. 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.
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 ResultSetNode
Parameters:
fromListParam - FromList to use/append to.
Returns:
Nothing
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

genProjectRestrict

protected ResultSetNode genProjectRestrict(int numTables)
                                    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:
genProjectRestrict in class ResultSetNode
Parameters:
numTables - Number of tables in the DML Statement
Returns:
The generated ProjectRestrictNode atop the original FromTable.
Throws:
StandardException - Thrown on error

changeAccessPath

public ResultSetNode changeAccessPath()
                               throws StandardException
Description copied from class: ResultSetNode
The optimizer's decision on the access path for a result set may require the generation of extra result sets. For example, if it chooses an index for a FromBaseTable, we need an IndexToBaseRowNode above the FromBaseTable (and the FromBaseTable has to change its column list to match the index. This method in the parent class does not generate any extra result sets. It may be overridden in child classes.

Overrides:
changeAccessPath in class ResultSetNode
Returns:
A ResultSetNode tree modified to do any extra processing for the chosen access path
Throws:
StandardException - Thrown on error
See Also:
ResultSetNode.changeAccessPath()

newResultColumns

private ResultColumnList newResultColumns(ResultColumnList oldColumns,
                                          ConglomerateDescriptor idxCD,
                                          ConglomerateDescriptor heapCD,
                                          boolean cloneRCs)
                                   throws StandardException
Create a new ResultColumnList to reflect the columns in the index described by the given ConglomerateDescriptor. The columns in the new ResultColumnList are based on the columns in the given ResultColumnList, which reflects the columns in the base table.

Parameters:
oldColumns - The original list of columns, which reflects the columns in the base table.
idxCD - The ConglomerateDescriptor, which describes the index that the new ResultColumnList will reflect.
heapCD - The ConglomerateDescriptor for the base heap
cloneRCs - Whether or not to clone the RCs
Returns:
A new ResultColumnList that reflects the columns in the index.
Throws:
StandardException - Thrown on error

generate

public void generate(ActivationClassBuilder acb,
                     MethodBuilder mb)
              throws StandardException
Generation on a FromBaseTable creates a scan on the optimizer-selected conglomerate.

Overrides:
generate in class QueryTreeNode
Parameters:
acb - The ActivationClassBuilder for the class being built
mb - the execute() method to be built
Returns:
A compiled Expression that returns a ResultSet that scans the table.
Throws:
StandardException - Thrown on error

generateResultSet

public void generateResultSet(ExpressionClassBuilder acb,
                              MethodBuilder mb)
                       throws StandardException
Generation on a FromBaseTable for a SELECT. This logic was separated out so that it could be shared with PREPARE SELECT FILTER.

Overrides:
generateResultSet in class ResultSetNode
Parameters:
acb - The ExpressionClassBuilder for the class being built
mb - The execute() method to be built
Returns:
A compiled Expression that returns a ResultSet that scans the table.
Throws:
StandardException - Thrown on error

getFinalCostEstimate

public CostEstimate getFinalCostEstimate()
Get the final CostEstimate for this ResultSetNode.

Overrides:
getFinalCostEstimate in class ResultSetNode
Returns:
The final CostEstimate for this ResultSetNode.

generateMaxSpecialResultSet

private void generateMaxSpecialResultSet(ExpressionClassBuilder acb,
                                         MethodBuilder mb)
                                  throws StandardException
Throws:
StandardException

generateDistinctScan

private void generateDistinctScan(ExpressionClassBuilder acb,
                                  MethodBuilder mb)
                           throws StandardException
Throws:
StandardException

generateRefActionDependentTableScan

private void generateRefActionDependentTableScan(ExpressionClassBuilder acb,
                                                 MethodBuilder mb)
                                          throws StandardException
Generation on a FromBaseTable for a referential action dependent table.

Parameters:
acb - The ExpressionClassBuilder for the class being built
mb - The execute() method to be built
Returns:
A compiled Expression that returns a ResultSet that scans the referential action dependent table.
Throws:
StandardException - Thrown on error

getScanArguments

private int getScanArguments(ExpressionClassBuilder acb,
                             MethodBuilder mb)
                      throws StandardException
Throws:
StandardException

mapAbsoluteToRelativeColumnPosition

private int mapAbsoluteToRelativeColumnPosition(int absolutePosition)
Convert an absolute to a relative 0-based column position.

Parameters:
absolutePosition - The absolute 0-based column position.
Returns:
The relative 0-based column position.

getExposedName

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

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

getTableNameField

public TableName getTableNameField()
Return the table name for this table.

Returns:
The table name for this table.

getAllResultColumns

public ResultColumnList getAllResultColumns(TableName allTableName)
                                     throws StandardException
Return a ResultColumnList with all of the columns in this table. (Used in expanding '*'s.) NOTE: Since this method is for expanding a "*" in the SELECT list, ResultColumn.expression will be a ColumnReference.

Overrides:
getAllResultColumns in class ResultSetNode
Parameters:
allTableName - The qualifier on the "*"
Returns:
ResultColumnList List of result columns from this table.
Throws:
StandardException - Thrown on error

genResultColList

public ResultColumnList genResultColList()
                                  throws StandardException
Build a ResultColumnList based on all of the columns in this FromBaseTable. NOTE - Since the ResultColumnList generated is for the FromBaseTable, ResultColumn.expression will be a BaseColumnNode.

Returns:
ResultColumnList representing all referenced columns
Throws:
StandardException - Thrown on error

addColsToList

public ResultColumnList addColsToList(ResultColumnList inputRcl,
                                      FormatableBitSet colsWeWant)
                               throws StandardException
Augment the RCL to include the columns in the FormatableBitSet. If the column is already there, don't add it twice. Column is added as a ResultColumn pointing to a ColumnReference.

Parameters:
inputRcl - The original list
colsWeWant - bit set of cols we want
Returns:
ResultColumnList the rcl
Throws:
StandardException - Thrown on error

getTableName

public TableName getTableName()
                       throws StandardException
Return a TableName node representing this FromTable.

Overrides:
getTableName in class FromTable
Returns:
a TableName node representing this FromTable.
Throws:
StandardException - Thrown on error

markAsCursorTargetTable

public boolean markAsCursorTargetTable()
Mark this ResultSetNode as the target table of an updatable cursor.

Overrides:
markAsCursorTargetTable in class ResultSetNode
Returns:
true if the target table supports positioned updates.

cursorTargetTable

protected boolean cursorTargetTable()
Is this a table that has a FOR UPDATE clause?

Overrides:
cursorTargetTable in class FromTable
Returns:
true/false

markUpdated

void markUpdated(ResultColumnList updateColumns)
Mark as updatable all the columns in the result column list of this FromBaseTable that match the columns in the given update column list.

Parameters:
updateColumns - A ResultColumnList representing the columns to be updated.

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

isOneRowResultSet

public boolean isOneRowResultSet()
                          throws StandardException
Return whether or not the underlying ResultSet tree will return a single row, at most. This method is intended to be used during generation, after the "truly" best conglomerate has been chosen. This is important for join nodes where we can save the extra next on the right side if we know that it will return at most 1 row.

Overrides:
isOneRowResultSet in class ResultSetNode
Returns:
Whether or not the underlying ResultSet tree will return a single row.
Throws:
StandardException - Thrown on error

isNotExists

public boolean isNotExists()
Return whether or not this is actually a EBT for NOT EXISTS.

Overrides:
isNotExists in class ResultSetNode
Returns:
Whether or not the underlying ResultSet tree if for NOT EXISTS.

isOneRowResultSet

public boolean isOneRowResultSet(OptimizablePredicateList predList)
                          throws StandardException
Throws:
StandardException

supersetOfUniqueIndex

protected boolean supersetOfUniqueIndex(boolean[] eqCols)
                                 throws StandardException
Determine whether or not the columns marked as true in the passed in array are a superset of any unique index on this table. This is useful for subquery flattening and distinct elimination based on a uniqueness condition.

Parameters:
eqCols - The columns to consider
Returns:
Whether or not the columns marked as true are a superset
Throws:
StandardException

supersetOfUniqueIndex

protected boolean supersetOfUniqueIndex(JBitSet[] tableColMap)
                                 throws StandardException
Determine whether or not the columns marked as true in the passed in join table matrix are a superset of any single column unique index on this table. This is useful for distinct elimination based on a uniqueness condition.

Parameters:
tableColMap - The columns to consider
Returns:
Whether or not the columns marked as true for one at least one table are a superset
Throws:
StandardException

updateTargetLockMode

public int updateTargetLockMode()
Get the lock mode for the target table heap of an update or delete statement. It is not always MODE_RECORD. We want the lock on the heap to be consistent with optimizer and eventually system's decision. This is to avoid deadlock (beetle 4318). During update/delete's execution, it will first use this lock mode we return to lock heap to open a RowChanger, then use the lock mode that is the optimizer and system's combined decision to open the actual source conglomerate. We've got to make sure they are consistent. This is the lock chart (for detail reason, see comments below): BEST ACCESS PATH LOCK MODE ON HEAP ---------------------- ----------------------------------------- index row lock heap row lock if READ_COMMITTED, REPEATBLE_READ, or READ_UNCOMMITTED && not specified table lock otherwise, use optimizer decided best acess path's lock mode

Overrides:
updateTargetLockMode in class ResultSetNode
Returns:
The lock mode
See Also:
TransactionController

isOrderedOn

boolean isOrderedOn(ColumnReference[] crs,
                    boolean permuteOrdering,
                    java.util.Vector fbtVector)
              throws StandardException
Return whether or not the underlying ResultSet tree is ordered on the specified columns. RESOLVE - This method currently only considers the outermost table of the query block. RESOLVE - We do not currently push method calls down, so we don't worry about whether the equals comparisons can be against a variant method.

Overrides:
isOrderedOn in class ResultSetNode
Parameters:
crs - The specified ColumnReference[]
permuteOrdering - Whether or not the order of the CRs in the array can be permuted
fbtVector - Vector that is to be filled with the FromBaseTable
Returns:
Whether the underlying ResultSet tree is ordered on the specified column.
Throws:
StandardException - Thrown on error

disableBulkFetch

void disableBulkFetch()
Turn off bulk fetch


doSpecialMaxScan

void doSpecialMaxScan()
Do a special scan for max.


isPossibleDistinctScan

boolean isPossibleDistinctScan()
Is it possible to do a distinct scan on this ResultSet tree. (See SelectNode for the criteria.)

Overrides:
isPossibleDistinctScan in class ResultSetNode
Returns:
Whether or not it is possible to do a distinct scan on this ResultSet tree.

markForDistinctScan

void markForDistinctScan()
Mark the underlying scan as a distinct scan.

Overrides:
markForDistinctScan in class ResultSetNode
Returns:
Nothing.

markOrderingDependent

void markOrderingDependent()
Notify the underlying result set tree that the result is ordering dependent. (For example, no bulk fetch on an index if under an IndexRowToBaseRow.)

Overrides:
markOrderingDependent in class ResultSetNode
Returns:
Nothing.

isOrdered

private boolean isOrdered(ColumnReference[] crs,
                          ConglomerateDescriptor cd)
                   throws StandardException
Return whether or not this index is ordered on a permutation of the specified columns.

Parameters:
crs - The specified ColumnReference[]
cd - The ConglomerateDescriptor for the chosen index.
Returns:
Whether or not this index is ordered exactly on the specified columns.
Throws:
StandardException - Thrown on error

isStrictlyOrdered

private boolean isStrictlyOrdered(ColumnReference[] crs,
                                  ConglomerateDescriptor cd)
                           throws StandardException
Return whether or not this index is ordered on a permutation of the specified columns.

Parameters:
crs - The specified ColumnReference[]
cd - The ConglomerateDescriptor for the chosen index.
Returns:
Whether or not this index is ordered exactly on the specified columns.
Throws:
StandardException - Thrown on error

isOneRowResultSet

private boolean isOneRowResultSet(ConglomerateDescriptor cd,
                                  OptimizablePredicateList predList)
                           throws StandardException
Is this a one-row result set with the given conglomerate descriptor?

Throws:
StandardException

getDefaultBulkFetch

private int getDefaultBulkFetch()
                         throws StandardException
Throws:
StandardException

getUserSpecifiedIndexName

private java.lang.String getUserSpecifiedIndexName()

getStoreCostController

private StoreCostController getStoreCostController(ConglomerateDescriptor cd)
                                            throws StandardException
Throws:
StandardException

getBaseCostController

private StoreCostController getBaseCostController()
                                           throws StandardException
Throws:
StandardException

baseRowCount

private long baseRowCount()
                   throws StandardException
Throws:
StandardException

getRowTemplate

private DataValueDescriptor[] getRowTemplate(ConglomerateDescriptor cd,
                                             StoreCostController scc)
                                      throws StandardException
Throws:
StandardException

getFirstConglom

private ConglomerateDescriptor getFirstConglom()
                                        throws StandardException
Throws:
StandardException

getNextConglom

private ConglomerateDescriptor getNextConglom(ConglomerateDescriptor currCD)
                                       throws StandardException
Throws:
StandardException

getConglomDescs

private void getConglomDescs()
                      throws StandardException
Throws:
StandardException

setRefActionInfo

public void setRefActionInfo(long fkIndexConglomId,
                             int[] fkColArray,
                             java.lang.String parentResultSetId,
                             boolean dependentScan)
set the Information gathered from the parent table that is required to peform a referential action on dependent table.

Overrides:
setRefActionInfo in class QueryTreeNode
Returns:
Nothing.

Built on Tue 2006-10-10 19:23:47+0200, from revision exported

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