Class SQLSelectStatement

  • All Implemented Interfaces:
    Serializable, Cloneable

    public class SQLSelectStatement
    extends SQLStatement

    Purpose: Print SELECT statement.

    Responsibilities:

    • Print SELECT statement.
    Since:
    TOPLink/Java 1.0
    Author:
    Dorin Sandu
    See Also:
    Serialized Form
    • Field Detail

      • query

        protected ReadQuery query
        Query this statement is associated to (used for SQL query options).
      • useUniqueFieldAliases

        protected boolean useUniqueFieldAliases
        Flag used to indicate field names should use unique aliases
      • fieldCounter

        protected int fieldCounter
        Counter to generate unique alias names
      • fields

        protected Vector fields
        Fields being selected (can include expressions).
      • nonSelectFields

        protected List<Object> nonSelectFields
        Fields not being selected (can include expressions).
      • distinctState

        protected short distinctState
        Used for "Select Distinct" option.
      • orderByExpressions

        protected List<Expression> orderByExpressions
        Order by clause for read all queries.
      • groupByExpressions

        protected List<Expression> groupByExpressions
        Group by clause for report queries.
      • unionExpressions

        protected List<Expression> unionExpressions
        Union clause.
      • havingExpression

        protected Expression havingExpression
        Having clause for report queries.
      • forUpdateClause

        protected ForUpdateClause forUpdateClause
        Used for pessimistic locking ie. "For Update".
      • isAggregateSelect

        protected boolean isAggregateSelect
        Used for report query or counts so we know how to treat distincts.
      • startWithExpression

        protected Expression startWithExpression
        Used for Oracle Hierarchical Queries
      • connectByExpression

        protected Expression connectByExpression
      • orderSiblingsByExpressions

        protected List<Expression> orderSiblingsByExpressions
      • requiresAliases

        protected boolean requiresAliases
        Variables used for aliasing and normalizing.
      • currentAliasNumber

        protected int currentAliasNumber
      • optimizedClonedExpressions

        protected Map<Expression,​Expression> optimizedClonedExpressions
        It is used by subselect to re-normalize joins
      • fieldAliases

        protected Map<DatabaseField,​String> fieldAliases
        Used for caching the field alias written to the query
      • shouldCacheFieldAliases

        protected boolean shouldCacheFieldAliases
    • Constructor Detail

      • SQLSelectStatement

        public SQLSelectStatement()
    • Method Detail

      • addField

        public void addField​(Expression expression)
        INTERNAL: adds an expression to the fields. set a flag if the expression is for and aggregate function.
      • addOrderByExpressionToSelectForDistinct

        protected void addOrderByExpressionToSelectForDistinct()
        When distinct is used with order by the ordered fields must be in the select clause.
      • addTable

        public void addTable​(DatabaseTable table)
        Add a table to the statement. The table will be used in the FROM part of the SQL statement.
      • appendFromClauseForInformixOuterJoin

        public void appendFromClauseForInformixOuterJoin​(ExpressionSQLPrinter printer,
                                                         List<DatabaseTable> outerJoinedAliases)
                                                  throws IOException
        ADVANCED: If a platform is Informix, then the outer join must be in the FROM clause. This is used internally by EclipseLink for building Informix outer join syntax which differs from other platforms (Oracle,Sybase) that print the outer join in the WHERE clause and from DB2 which prints the OuterJoinedAliases passed in to keep track of tables used for outer join so no normal join is given. This syntax is old for Informix, so should probably be removed.
        Throws:
        IOException
      • appendFromClauseForOuterJoin

        public void appendFromClauseForOuterJoin​(ExpressionSQLPrinter printer,
                                                 List<DatabaseTable> outerJoinedAliases,
                                                 Collection aliasesOfTablesToBeLocked,
                                                 boolean shouldPrintUpdateClauseForAllTables)
                                          throws IOException
        ADVANCED: Appends the SQL standard outer join clause, and some variation per platform. Most platforms use this syntax, support is also offered for Oracle to join in the where clause (although it should use the FROM clause as the WHERE clause is obsolete). This is also used for inner joins when configured in the platform.
        Throws:
        IOException
      • printForUpdateClauseOnJoin

        protected void printForUpdateClauseOnJoin​(DatabaseTable alias,
                                                  ExpressionSQLPrinter printer,
                                                  boolean shouldPrintUpdateClauseForAllTables,
                                                  Collection aliasesOfTablesToBeLocked,
                                                  DatabasePlatform platform)
        Print the FOR UPDATE clause after each join if required.
      • appendFromClauseToWriter

        public void appendFromClauseToWriter​(ExpressionSQLPrinter printer)
                                      throws IOException
        Print the from clause. This includes outer joins, these must be printed before the normal join to ensure that the source tables are not joined again. Outer joins are not printed in the FROM clause on Oracle or Sybase.
        Throws:
        IOException
      • appendGroupByClauseToWriter

        public void appendGroupByClauseToWriter​(ExpressionSQLPrinter printer)
                                         throws IOException
        This method will append the group by clause to the end of the select statement.
        Throws:
        IOException
      • appendHierarchicalQueryClauseToWriter

        public void appendHierarchicalQueryClauseToWriter​(ExpressionSQLPrinter printer)
                                                   throws IOException
        This method will append the Hierarchical Query Clause to the end of the select statement
        Throws:
        IOException
      • appendOrderClauseToWriter

        public void appendOrderClauseToWriter​(ExpressionSQLPrinter printer)
                                       throws IOException
        This method will append the order clause to the end of the select statement.
        Throws:
        IOException
      • appendUnionClauseToWriter

        public void appendUnionClauseToWriter​(ExpressionSQLPrinter printer)
                                       throws IOException
        This method will append the union clause to the end of the select statement.
        Throws:
        IOException
      • appendForUpdateClause

        public void appendForUpdateClause​(ExpressionSQLPrinter printer)
        This method will append the for update clause to the end of the select statement.
      • assignAliases

        public void assignAliases​(Vector allExpressions)
        INTERNAL: Alias the tables in all of our nodes.
      • buildCall

        public DatabaseCall buildCall​(AbstractSession session,
                                      DatabaseQuery query)
        Build the call, setting the query first, this is required in some cases when the query info is required to print the SQL.
      • computeDistinct

        public void computeDistinct()
        INTERNAL: This is used by cursored stream to determine if an expression used distinct as the size must account for this.
      • isSubSelect

        public boolean isSubSelect()
      • getOptimizedClonedExpressions

        public Map<Expression,​Expression> getOptimizedClonedExpressions()
        INTERNAL: It is used by subqueries to avoid duplicate joins.
      • addOptimizedClonedExpressions

        public void addOptimizedClonedExpressions​(Expression originalKey,
                                                  Expression optimizedValue)
        INTERNAL: It is used by subqueries to avoid duplicate joins.
      • computeTables

        public void computeTables()
        INTERNAL: Computes all aliases which will appear in the FROM clause.
      • computeTablesFromTables

        public void computeTablesFromTables()
        If there is no where clause, alias the tables from the tables list directly. Assume there's no ambiguity
      • dontUseDistinct

        public void dontUseDistinct()
        ADVANCED: If a distinct has been set the DISTINCT clause will be printed. This is used internally by TopLink for batch reading but may also be used directly for advanced queries or report queries.
      • fieldsContainField

        protected boolean fieldsContainField​(List fields,
                                             Expression expression)
        Check if the field from the field expression is already contained in the select clause of the statement. This is used on order by expression when the field being ordered by must be in the select, but cannot be in the select twice.
      • getCurrentAliasNumber

        public int getCurrentAliasNumber()
        Gets a unique id that will be used to alias the next table. For sub-selects all must use this same aliasing information, maintained in the root enclosing statement. For CR#2627019
      • getFields

        public Vector getFields()
        INTERNAL: Return all the fields
      • getGroupByExpressions

        public List<Expression> getGroupByExpressions()
        INTERNAL: Return the group bys.
      • getHavingExpression

        public Expression getHavingExpression()
        INTERNAL: Return the having expression.
      • getQuery

        public ReadQuery getQuery()
        INTERNAL: Query held as it may store properties needed to generate the SQL
      • getStartWithExpression

        public Expression getStartWithExpression()
        INTERNAL: Return the StartWith expression
      • getConnectByExpression

        public Expression getConnectByExpression()
        INTERNAL: Return the CONNECT BY expression
      • getOrderSiblingsByExpressions

        public List<Expression> getOrderSiblingsByExpressions()
        INTERNAL: Return the ORDER SIBLINGS BY expression
      • getDirection

        public ReadAllQuery.Direction getDirection()
        INTERNAL:
        Returns:
        the position of the PRIOR keyword
      • getNextFieldCounterValue

        public int getNextFieldCounterValue()
        INTERNAL: Return the next value of fieldCounter
      • getNonSelectFields

        public List<Object> getNonSelectFields()
        Return the fields we don't want to select but want to join on.
      • getOrderByExpressions

        public List<Expression> getOrderByExpressions()
        INTERNAL: Return the order expressions for the query.
      • setUnionExpressions

        public void setUnionExpressions​(List<Expression> unionExpressions)
      • getOuterJoinExpressionsHolders

        public List<OuterJoinExpressionHolder> getOuterJoinExpressionsHolders()
        INTERNAL: returns outerJoinExpressionHolders representing outerjoin expressions.
        Returns:
      • addOuterJoinExpressionsHolders

        public Integer addOuterJoinExpressionsHolders​(ObjectExpression joinExpression,
                                                      Expression outerJoinedMappingCriteria,
                                                      Map<DatabaseTable,​Expression> outerJoinedAdditionalJoinCriteria,
                                                      ClassDescriptor descriptor)
        INTERNAL: Used by ExpressionBuilder and QueryKeyExpression normalization to create a standard outerjoin.
        Parameters:
        joinExpression - - expression resulting in the outerjoin. Null if it is for inheritance reading of subclasses
        outerJoinedMappingCriteria - - used for querykey mapping expressions
        outerJoinedAdditionalJoinCriteria - - additional tables/expressions to join. Usually for multitableInheritance join expressions
        descriptor - - descriptor to use if this is for reading in subclasses in one query.
        Returns:
      • addOuterJoinExpressionsHolders

        public Integer addOuterJoinExpressionsHolders​(Map<DatabaseTable,​Expression> outerJoinedAdditionalJoinCriteria,
                                                      ClassDescriptor descriptor)
        INTERNAL: used by TREAT to add in a join from the parent table to the child tables when the parent expression did not add an outer join of its own
      • getParentStatement

        public SQLSelectStatement getParentStatement()
        Return the parent statement if using subselects. This is used to normalize correctly with subselects.
      • getTables

        public List<DatabaseTable> getTables()
        INTERNAL: Return all the tables.
      • getUseUniqueFieldAliases

        public boolean getUseUniqueFieldAliases()
        INTERNAL: Return True if unique field aliases will be generated of the form "fieldname AS fieldnameX", False otherwise.
      • hasAliasForTable

        protected boolean hasAliasForTable​(DatabaseTable table)
      • hasGroupByExpressions

        public boolean hasGroupByExpressions()
      • hasHavingExpression

        public boolean hasHavingExpression()
      • hasStartWithExpression

        public boolean hasStartWithExpression()
      • hasConnectByExpression

        public boolean hasConnectByExpression()
      • hasOrderSiblingsByExpressions

        public boolean hasOrderSiblingsByExpressions()
      • hasHierarchicalQueryExpressions

        public boolean hasHierarchicalQueryExpressions()
      • hasOrderByExpressions

        public boolean hasOrderByExpressions()
      • hasUnionExpressions

        public boolean hasUnionExpressions()
      • hasNonSelectFields

        public boolean hasNonSelectFields()
      • hasOuterJoinExpressions

        public boolean hasOuterJoinExpressions()
      • isAggregateSelect

        public boolean isAggregateSelect()
        INTERNAL:
      • isDistinctComputed

        public boolean isDistinctComputed()
        INTERNAL: return true if this query has computed its distinct value already
      • normalize

        public final void normalize​(AbstractSession session,
                                    ClassDescriptor descriptor)
        INTERNAL: Normalize an expression into a printable structure. i.e. merge the expression with the join expressions. Also replace table names with corresponding aliases.
      • normalize

        public void normalize​(AbstractSession session,
                              ClassDescriptor descriptor,
                              Map clonedExpressions)
        INTERNAL: Normalize an expression into a printable structure. i.e. merge the expression with the join expressions. Also replace table names with corresponding aliases.
        Parameters:
        clonedExpressions - With 2612185 allows additional expressions from multiple bases to be rebuilt on the correct cloned base.
      • normalizeForView

        public void normalizeForView​(AbstractSession theSession,
                                     ClassDescriptor theDescriptor,
                                     Map clonedExpressions)
        INTERNAL: Normalize an expression mapping all of the descriptor's tables to the view. This is used to allow a descriptor to read from a view, but write to tables. This is used in the multiple table and subclasses read so all of the descriptor's possible tables must be mapped to the view.
      • rebuildAndAddExpressions

        public void rebuildAndAddExpressions​(List expressions,
                                             List allExpressions,
                                             ExpressionBuilder primaryBuilder,
                                             Map clonedExpressions)
        Rebuild the expressions with the correct expression builder if using a different one.
      • rebuildAndAddExpressions

        public void rebuildAndAddExpressions​(Map expressions,
                                             Vector allExpressions,
                                             ExpressionBuilder primaryBuilder,
                                             Map clonedExpressions)
        Rebuild the expressions with the correct expression builder if using a different one. Exact copy of the another rebuildAndAddExpressions adopted to a Map with Expression values as the first parameter (instead of Vector in the original method)
      • removeField

        public void removeField​(DatabaseField field)
        INTERNAL:
      • removeTable

        public void removeTable​(DatabaseTable table)
        Remove a table from the statement. The table will be dropped from the FROM part of the SQL statement.
      • requiresAliases

        public boolean requiresAliases()
        INTERNAL: Returns true if aliases are required, false otherwise. If requiresAliases is set then force aliasing, this is required for object-rel.
      • resetDistinct

        public void resetDistinct()
        ADVANCED: If a distinct has been set the DISTINCT clause will be printed. This is used internally by TopLink for batch reading but may also be used directly for advanced queries or report queries.
      • setCurrentAliasNumber

        public void setCurrentAliasNumber​(int currentAliasNumber)
        Sets a unique id that will be used to alias the next table. For sub-selects all must use this same aliasing information, maintained in the root enclosing statement. For CR#2627019
      • setNonSelectFields

        public void setNonSelectFields​(List nonSelectFields)
        Set the non select fields. The fields are used only on joining.
      • setNormalizedWhereClause

        public void setNormalizedWhereClause​(Expression whereClause)
        Set the where clause expression. This must be used during normalization as the normal setWhereClause has the side effect of setting the builder, which must not occur during normalize.
      • setDistinctState

        public void setDistinctState​(short distinctState)
        ADVANCED: If a distinct has been set the DISTINCT clause will be printed. This is used internally by TopLink for batch reading but may also be used directly for advanced queries or report queries.
      • setFields

        public void setFields​(Vector fields)
        INTERNAL: Set the fields, if any are aggregate selects then record this so that the distinct is not printed through anyOfs.
      • setGroupByExpressions

        public void setGroupByExpressions​(List<Expression> expressions)
      • setHavingExpression

        public void setHavingExpression​(Expression expressions)
      • setHierarchicalQueryExpressions

        public void setHierarchicalQueryExpressions​(Expression startWith,
                                                    Expression connectBy,
                                                    List<Expression> orderSiblingsExpressions)
        INTERNAL: takes the hierarchical query expression which have been set on the query and sets them here used to generate the Hierarchical Query Clause in the SQL
      • setHierarchicalQueryExpressions

        public void setHierarchicalQueryExpressions​(Expression startWith,
                                                    Expression connectBy,
                                                    List<Expression> orderSiblingsExpressions,
                                                    ReadAllQuery.Direction direction)
        INTERNAL: takes the hierarchical query expression which have been set on the query and sets them here used to generate the Hierarchical Query Clause in the SQL
      • setIsAggregateSelect

        public void setIsAggregateSelect​(boolean isAggregateSelect)
      • setForUpdateClause

        protected void setForUpdateClause​(ForUpdateClause clause)
      • setLockingClause

        public void setLockingClause​(ForUpdateClause lockingClause)
      • setOrderByExpressions

        public void setOrderByExpressions​(List<Expression> orderByExpressions)
      • setParentStatement

        public void setParentStatement​(SQLSelectStatement parentStatement)
        Set the parent statement if using subselects. This is used to normalize correctly with subselects.
      • setQuery

        public void setQuery​(ReadQuery query)
        Query held as it may store properties needed to generate the SQL
      • setRequiresAliases

        public void setRequiresAliases​(boolean requiresAliases)
      • setUseUniqueFieldAliases

        public void setUseUniqueFieldAliases​(boolean useUniqueFieldAliases)
        INTERNAL: If set unique field aliases will be generated of the form "fieldname AS fieldnameX" Where fieldname is the column name and X is an incremental value ensuring uniqueness
      • shouldDistinctBeUsed

        public boolean shouldDistinctBeUsed()
        INTERNAL: If a distinct has been set the DISTINCT clause will be printed. This is required for batch reading.
      • useDistinct

        public void useDistinct()
        ADVANCED: If a distinct has been set the DISTINCT clause will be printed. This is used internally by TopLink for batch reading but may also be used directly for advanced queries or report queries.
      • enableFieldAliasesCaching

        public void enableFieldAliasesCaching()
      • generatedAlias

        public String generatedAlias​(String fieldName)
        Returns a generated alias based on the column name. If the new alias will be too long The alias is automatically truncated
      • mapTableIndexToExpression

        public static SortedSet mapTableIndexToExpression​(Expression expression,
                                                          TreeMap map,
                                                          List<DatabaseTable> tablesInOrder)
        INTERNAL: The method searches for expressions that join two tables each in a given expression. Given expression and tablesInOrder and an empty SortedMap (TreeMap with no Comparator), this method populates the map with expressions corresponding to two tables keyed by an index (in tablesInOrder) of the table with the highest (of two) index; returns all the participating in at least one of the expressions. Example: expression (joining Employee to Project through m-m mapping "projects"): (employee.emp_id = proj_emp.emp_id) and (proj_emp.proj_id = project.proj_id) tablesInOrder: employee, proj_emp, project results: map: 1 -> (employee.emp_id = proj_emp.emp_id) 2 -> (proj_emp.proj_id = project.proj_id) returned SortedSet: {0, 1, 2}. Note that tablesInOrder must contain all tables used by expression
      • mapTableToExpression

        public static Map mapTableToExpression​(Expression expression,
                                               Vector tablesInOrder)
        INTERNAL: The method searches for expressions that join two tables each in a given expression. Given expression and tablesInOrder, this method returns the map with expressions corresponding to two tables keyed by tables (from tablesInOrder) with the highest (of two) index; Example: expression (joining Employee to Project through m-m mapping "projects"): (employee.emp_id = proj_emp.emp_id) and (proj_emp.proj_id = project.proj_id) tablesInOrder: employee, proj_emp, project results: returned map: proj_emp -> (employee.emp_id = proj_emp.emp_id) project -> (proj_emp.proj_id = project.proj_id) Note that tablesInOrder must contain all tables used by expression