org.eigenbase.sql.validate
Interface SqlValidator

All Known Subinterfaces:
SqlValidatorWithHints
All Known Implementing Classes:
FarragoSqlValidator, LucidDbSqlValidator, SqlAdvisorValidator, SqlToRelTestBase.FarragoTestValidator, SqlValidatorFeatureTest.FeatureValidator, SqlValidatorImpl

public interface SqlValidator

Validates the parse tree of a SQL statement, and provides semantic information about the parse tree.

To create an instance of the default validator implementation, call SqlValidatorUtil.newValidator(org.eigenbase.sql.SqlOperatorTable, org.eigenbase.sql.validate.SqlValidatorCatalogReader, org.eigenbase.reltype.RelDataTypeFactory).

Visitor pattern

The validator interface is an instance of the visitor pattern. Implementations of the SqlNode.validate(org.eigenbase.sql.validate.SqlValidator, org.eigenbase.sql.validate.SqlValidatorScope) method call the validateXxx method appropriate to the kind of node: SqlLiteral.validate(SqlValidator, SqlValidatorScope) calls validateLiteral(org.eigenbase.sql.SqlLiteral); SqlCall.validate(SqlValidator, SqlValidatorScope) calls validateCall(SqlCall,SqlValidatorScope); and so forth.

The SqlNode.validateExpr(SqlValidator, SqlValidatorScope) method is as SqlNode.validate(SqlValidator, SqlValidatorScope) but is called when the node is known to be a scalar expression.

Scopes and namespaces

In order to resolve names to objects, the validator builds a map of the structure of the query. This map consists of two types of objects. A SqlValidatorScope describes the tables and columns accessible at a particular point in the query; and a SqlValidatorNamespace is a description of a data source used in a query.

There are different kinds of namespace for different parts of the query. for example IdentifierNamespace for table names, SelectNamespace for SELECT queries, SetopNamespace for UNION, EXCEPT and INTERSECT. A validator is allowed to wrap namespaces in other objects which implement SqlValidatorNamespace, so don't try to cast your namespace or use instanceof; use SqlValidatorNamespace.unwrap(Class) and SqlValidatorNamespace.isWrapperFor(Class) instead.

The validator builds the map by making a quick scan over the query when the root SqlNode is first provided. Thereafter, it supplies the correct scope or namespace object when it calls validation methods.

The methods getSelectScope(org.eigenbase.sql.SqlSelect), getFromScope(org.eigenbase.sql.SqlSelect), getWhereScope(org.eigenbase.sql.SqlSelect), getGroupScope(org.eigenbase.sql.SqlSelect), getHavingScope(org.eigenbase.sql.SqlSelect), getOrderScope(org.eigenbase.sql.SqlSelect) and getJoinScope(org.eigenbase.sql.SqlNode) get the correct scope to resolve names in a particular clause of a SQL statement.

Since:
Oct 28, 2004
Version:
$Id: //open/dev/farrago/src/org/eigenbase/sql/validate/SqlValidator.java#36 $
Author:
jhyde

Nested Class Summary
static class SqlValidator.Compatible
          Deprecated. This class is for backwards-compatibility with the previous incarnation of SqlConformance.
 
Method Summary
 void declareCursor(SqlSelect select, SqlValidatorScope scope)
          Declares a SELECT expression as a cursor.
 String deriveAlias(SqlNode node, int ordinal)
          Derives an alias for an expression.
 RelDataType deriveConstructorType(SqlValidatorScope scope, SqlCall call, SqlFunction unresolvedConstructor, SqlFunction resolvedConstructor, RelDataType[] argTypes)
          Derives the type of a constructor.
 RelDataType deriveType(SqlValidatorScope scope, SqlNode operand)
          Derives the type of a node in a given scope.
 SqlNode expand(SqlNode expr, SqlValidatorScope scope)
          Expands an expression.
 SqlNode expandOrderExpr(SqlSelect select, SqlNode orderExpr)
          Expands an expression in the ORDER BY clause into an expression with the same semantics as expressions in the SELECT clause.
 SqlNodeList expandStar(SqlNodeList selectList, SqlSelect query, boolean includeSystemVars)
          Returns a list of expressions, with every occurrence of "*" or "TABLE.*" expanded.
 SqlValidatorCatalogReader getCatalogReader()
          Returns the catalog reader used by this validator.
 SqlConformance getConformance()
          Returns the dialect of SQL (SQL:2003, etc.) this validator recognizes.
 SqlValidatorScope getFromScope(SqlSelect select)
          Returns a scope containing the objects visible from the FROM clause of a query.
 SqlValidatorScope getGroupScope(SqlSelect select)
          Returns a scope containing the objects visible from the GROUP BY clause of a query.
 SqlValidatorScope getHavingScope(SqlSelect select)
          Returns a scope containing the objects visible from the HAVING clause of a query.
 SqlValidatorScope getJoinScope(SqlNode node)
          Returns a scope containing the objects visible from the ON and USING sections of a JOIN clause.
 SqlValidatorNamespace getNamespace(SqlNode node)
          Finds the namespace corresponding to a given node.
 SqlOperatorTable getOperatorTable()
          Returns the operator table used by this validator.
 SqlValidatorScope getOrderScope(SqlSelect select)
          Returns the scope that expressions in the SELECT and HAVING clause of this query should use.
 String getParentCursor(String columnListParamName)
          Retrieves the name of the parent cursor referenced by a column list parameter.
 SelectScope getRawSelectScope(SqlSelect select)
          Returns the scope for resolving the SELECT, GROUP BY and HAVING clauses.
 SqlValidatorScope getSelectScope(SqlSelect select)
          Returns the appropriate scope for validating a particular clause of a SELECT statement.
 RelDataTypeFactory getTypeFactory()
          Returns the type factory used by this validator.
 RelDataType getUnknownType()
          Returns an object representing the "unknown" type.
 RelDataType getValidatedNodeType(SqlNode node)
          Returns the type assigned to a node by validation.
 RelDataType getValidatedNodeTypeIfKnown(SqlNode node)
          Returns the type assigned to a node by validation, or null if unknown.
 SqlValidatorScope getWhereScope(SqlSelect select)
          Returns the scope that expressions in the WHERE and GROUP BY clause of this query should use.
 void handleUnresolvedFunction(SqlCall call, SqlFunction unresolvedFunction, RelDataType[] argTypes)
          Handles a call to a function which cannot be resolved, throwing an appropriately descriptive error.
 boolean isAggregate(SqlNode selectNode)
          Returns whether a select list expression is an aggregate function.
 boolean isAggregate(SqlSelect select)
          Returns whether a SELECT statement is an aggregation.
 boolean isSystemField(RelDataTypeField field)
          Returns whether a field is a system field.
 EigenbaseException newValidationError(SqlNode node, SqlValidatorException e)
          Adds "line x, column y" context to a validator exception.
 void popFunctionCall()
          Removes the topmost entry from the function call stack.
 void pushFunctionCall()
          Pushes a new instance of a function call on to a function call stack.
 void removeValidatedNodeType(SqlNode node)
          Removes a node from the set of validated nodes
 SqlWindow resolveWindow(SqlNode windowOrRef, SqlValidatorScope scope, boolean populateBounds)
          Converts a window specification or window name into a fully-resolved window specification.
 void setCallRewrite(boolean rewriteCalls)
          Enables or disables rewrite of "macro-like" calls such as COALESCE.
 void setColumnReferenceExpansion(boolean expandColumnReferences)
          Enables or disables expansion of column references.
 void setIdentifierExpansion(boolean expandIdentifiers)
          Enables or disables expansion of identifiers other than column references.
 void setValidatedNodeType(SqlNode node, RelDataType type)
          Deprecated. This method should not be in the SqlValidator interface. The validator should drive the type-derivation process, and store nodes' types when they have been derived.
 boolean shouldExpandIdentifiers()
          Returns expansion of identifiers.
 SqlNode validate(SqlNode topNode)
          Validates an expression tree.
 void validateAggregateParams(SqlCall aggFunction, SqlValidatorScope scope)
          Validates parameters for aggregate function.
 void validateCall(SqlCall call, SqlValidatorScope scope)
          Validates a call to an operator.
 void validateColumnListParams(SqlFunction function, RelDataType[] argTypes, SqlNode[] operands)
          Validates a COLUMN_LIST parameter
 void validateDataType(SqlDataTypeSpec dataType)
          Validates a data type expression.
 void validateDelete(SqlDelete delete)
          Validates a DELETE statement.
 void validateDynamicParam(SqlDynamicParam dynamicParam)
          Validates a dynamic parameter.
 void validateIdentifier(SqlIdentifier id, SqlValidatorScope scope)
          Resolves an identifier to a fully-qualified name.
 void validateInsert(SqlInsert insert)
          Validates an INSERT statement.
 void validateIntervalQualifier(SqlIntervalQualifier qualifier)
          Validates a SqlIntervalQualifier
 void validateLiteral(SqlLiteral literal)
          Validates a literal.
 void validateMerge(SqlMerge merge)
          Validates a MERGE statement.
 SqlNode validateParameterizedExpression(SqlNode topNode, Map<String,RelDataType> nameToTypeMap)
          Validates an expression tree.
 void validateQuery(SqlNode node, SqlValidatorScope scope)
          Checks that a query is valid.
 void validateUpdate(SqlUpdate update)
          Validates an UPDATE statement.
 void validateWindow(SqlNode windowOrId, SqlValidatorScope scope, SqlCall call)
          Validates the right-hand side of an OVER expression.
 

Method Detail

getConformance

SqlConformance getConformance()
Returns the dialect of SQL (SQL:2003, etc.) this validator recognizes. Default is SqlConformance.Default.

Returns:
dialect of SQL this validator recognizes

getCatalogReader

SqlValidatorCatalogReader getCatalogReader()
Returns the catalog reader used by this validator.

Returns:
catalog reader

getOperatorTable

SqlOperatorTable getOperatorTable()
Returns the operator table used by this validator.

Returns:
operator table

validate

SqlNode validate(SqlNode topNode)
Validates an expression tree. You can call this method multiple times, but not reentrantly.

Parameters:
topNode - top of expression tree to be validated
Returns:
validated tree (possibly rewritten)
"Precondition:"
outermostNode == null

validateParameterizedExpression

SqlNode validateParameterizedExpression(SqlNode topNode,
                                        Map<String,RelDataType> nameToTypeMap)
Validates an expression tree. You can call this method multiple times, but not reentrantly.

Parameters:
topNode - top of expression tree to be validated
nameToTypeMap - map of simple name to RelDataType; used to resolve SqlIdentifier references
Returns:
validated tree (possibly rewritten)
"Precondition:"
outermostNode == null

validateQuery

void validateQuery(SqlNode node,
                   SqlValidatorScope scope)
Checks that a query is valid.

Valid queries include:

Parameters:
node - Query node
scope - Scope in which the query occurs
Throws:
RuntimeException - if the query is not valid

getValidatedNodeType

RelDataType getValidatedNodeType(SqlNode node)
Returns the type assigned to a node by validation.

Parameters:
node - the node of interest
Returns:
validated type, never null

getValidatedNodeTypeIfKnown

RelDataType getValidatedNodeTypeIfKnown(SqlNode node)
Returns the type assigned to a node by validation, or null if unknown. This allows for queries against nodes such as aliases, which have no type of their own. If you want to assert that the node of interest must have a type, use getValidatedNodeType(org.eigenbase.sql.SqlNode) instead.

Parameters:
node - the node of interest
Returns:
validated type, or null if unknown or not applicable

validateIdentifier

void validateIdentifier(SqlIdentifier id,
                        SqlValidatorScope scope)
Resolves an identifier to a fully-qualified name.

Parameters:
id - Identifier
scope - Naming scope

validateLiteral

void validateLiteral(SqlLiteral literal)
Validates a literal.

Parameters:
literal - Literal

validateIntervalQualifier

void validateIntervalQualifier(SqlIntervalQualifier qualifier)
Validates a SqlIntervalQualifier

Parameters:
qualifier - Interval qualifier

validateInsert

void validateInsert(SqlInsert insert)
Validates an INSERT statement.

Parameters:
insert - INSERT statement

validateUpdate

void validateUpdate(SqlUpdate update)
Validates an UPDATE statement.

Parameters:
update - UPDATE statement

validateDelete

void validateDelete(SqlDelete delete)
Validates a DELETE statement.

Parameters:
delete - DELETE statement

validateMerge

void validateMerge(SqlMerge merge)
Validates a MERGE statement.

Parameters:
merge - MERGE statement

validateDataType

void validateDataType(SqlDataTypeSpec dataType)
Validates a data type expression.

Parameters:
dataType - Data type

validateDynamicParam

void validateDynamicParam(SqlDynamicParam dynamicParam)
Validates a dynamic parameter.

Parameters:
dynamicParam - Dynamic parameter

validateWindow

void validateWindow(SqlNode windowOrId,
                    SqlValidatorScope scope,
                    SqlCall call)
Validates the right-hand side of an OVER expression. It might be either an identifier referencing a window, or an inline window specification.

Parameters:
windowOrId - SqlNode that can be either SqlWindow with all the components of a window spec or a SqlIdentifier with the name of a window spec.
scope - Naming scope
call - is the SqlNode if a function call if the window is attached to one.

validateCall

void validateCall(SqlCall call,
                  SqlValidatorScope scope)
Validates a call to an operator.

Parameters:
call - Operator call
scope - Naming scope

validateAggregateParams

void validateAggregateParams(SqlCall aggFunction,
                             SqlValidatorScope scope)
Validates parameters for aggregate function.

Parameters:
aggFunction - function containing COLUMN_LIST parameter
scope - Syntactic scope

validateColumnListParams

void validateColumnListParams(SqlFunction function,
                              RelDataType[] argTypes,
                              SqlNode[] operands)
Validates a COLUMN_LIST parameter

Parameters:
function - function containing COLUMN_LIST parameter
argTypes - function arguments
operands - operands passed into the function call

deriveType

RelDataType deriveType(SqlValidatorScope scope,
                       SqlNode operand)
Derives the type of a node in a given scope. If the type has already been inferred, returns the previous type.

Parameters:
scope - Syntactic scope
operand - Parse tree node
Returns:
Type of the SqlNode. Should never return NULL

newValidationError

EigenbaseException newValidationError(SqlNode node,
                                      SqlValidatorException e)
Adds "line x, column y" context to a validator exception.

Note that the input exception is checked (it derives from Exception) and the output exception is unchecked (it derives from RuntimeException). This is intentional -- it should remind code authors to provide context for their validation errors.

Parameters:
e - The validation error
node - The place where the exception occurred
Returns:
Exception containing positional information
"Precondition:"
node != null
"Postcondition:"
return != null

isAggregate

boolean isAggregate(SqlSelect select)
Returns whether a SELECT statement is an aggregation. Criteria are: (1) contains GROUP BY, or (2) contains HAVING, or (3) SELECT or ORDER BY clause contains aggregate functions. (Windowed aggregate functions, such as SUM(x) OVER w, don't count.)

Parameters:
select - SELECT statement
Returns:
whether SELECT statement is an aggregation

isAggregate

boolean isAggregate(SqlNode selectNode)
Returns whether a select list expression is an aggregate function.

Parameters:
selectNode - Expression in SELECT clause
Returns:
whether expression is an aggregate function

resolveWindow

SqlWindow resolveWindow(SqlNode windowOrRef,
                        SqlValidatorScope scope,
                        boolean populateBounds)
Converts a window specification or window name into a fully-resolved window specification. For example, in SELECT sum(x) OVER (PARTITION BY x ORDER BY y), sum(y) OVER w1, sum(z) OVER (w ORDER BY y) FROM t WINDOW w AS (PARTITION BY x) all aggregations have the same resolved window specification (PARTITION BY x ORDER BY y).

Parameters:
windowOrRef - Either the name of a window (a SqlIdentifier) or a window specification (a SqlWindow).
scope - Scope in which to resolve window names
populateBounds - Whether to populate bounds. Doing so may alter the definition of the window. It is recommended that populate bounds when translating to physical algebra, but not when validating.
Returns:
A window
Throws:
RuntimeException - Validation exception if window does not exist

getNamespace

SqlValidatorNamespace getNamespace(SqlNode node)
Finds the namespace corresponding to a given node.

For example, in the query SELECT * FROM (SELECT * FROM t), t1 AS alias, the both items in the FROM clause have a corresponding namespace.

Parameters:
node - Parse tree node
Returns:
namespace of node

deriveAlias

String deriveAlias(SqlNode node,
                   int ordinal)
Derives an alias for an expression. If no alias can be derived, returns null if ordinal is less than zero, otherwise generates an alias EXPR$ordinal.

Parameters:
node - Expression
ordinal - Ordinal of expression
Returns:
derived alias, or null if no alias can be derived and ordinal is less than zero

expandStar

SqlNodeList expandStar(SqlNodeList selectList,
                       SqlSelect query,
                       boolean includeSystemVars)
Returns a list of expressions, with every occurrence of "*" or "TABLE.*" expanded.

Parameters:
selectList - Select clause to be expanded
query - Query
includeSystemVars - Whether to include system variables
Returns:
expanded select clause

getWhereScope

SqlValidatorScope getWhereScope(SqlSelect select)
Returns the scope that expressions in the WHERE and GROUP BY clause of this query should use. This scope consists of the tables in the FROM clause, and the enclosing scope.

Parameters:
select - Query
Returns:
naming scope of WHERE clause

getTypeFactory

RelDataTypeFactory getTypeFactory()
Returns the type factory used by this validator.

Returns:
type factory

setValidatedNodeType

void setValidatedNodeType(SqlNode node,
                          RelDataType type)
Deprecated. This method should not be in the SqlValidator interface. The validator should drive the type-derivation process, and store nodes' types when they have been derived.

Saves the type of a SqlNode, now that it has been validated.

Parameters:
node - A SQL parse tree node
type - Its type; must not be null
"Precondition:"
type != null, node != null

removeValidatedNodeType

void removeValidatedNodeType(SqlNode node)
Removes a node from the set of validated nodes

Parameters:
node - node to be removed

getUnknownType

RelDataType getUnknownType()
Returns an object representing the "unknown" type.

Returns:
unknown type

getSelectScope

SqlValidatorScope getSelectScope(SqlSelect select)
Returns the appropriate scope for validating a particular clause of a SELECT statement.

Consider

SELECT *
 FROM foo
 WHERE EXISTS (
    SELECT deptno AS x
    FROM emp
       JOIN dept ON emp.deptno = dept.deptno
    WHERE emp.deptno = 5
    GROUP BY deptno
    ORDER BY x)
What objects can be seen in each part of the sub-query?

Parameters:
select - SELECT statement
Returns:
naming scope for SELECT statement

getRawSelectScope

SelectScope getRawSelectScope(SqlSelect select)
Returns the scope for resolving the SELECT, GROUP BY and HAVING clauses. Always a SelectScope; if this is an aggregation query, the AggregatingScope is stripped away.

Parameters:
select - SELECT statement
Returns:
naming scope for SELECT statement, sans any aggregating scope

getFromScope

SqlValidatorScope getFromScope(SqlSelect select)
Returns a scope containing the objects visible from the FROM clause of a query.

Parameters:
select - SELECT statement
Returns:
naming scope for FROM clause

getJoinScope

SqlValidatorScope getJoinScope(SqlNode node)
Returns a scope containing the objects visible from the ON and USING sections of a JOIN clause.

Parameters:
node - The item in the FROM clause which contains the ON or USING expression
Returns:
naming scope for JOIN clause
See Also:
getFromScope(org.eigenbase.sql.SqlSelect)

getGroupScope

SqlValidatorScope getGroupScope(SqlSelect select)
Returns a scope containing the objects visible from the GROUP BY clause of a query.

Parameters:
select - SELECT statement
Returns:
naming scope for GROUP BY clause

getHavingScope

SqlValidatorScope getHavingScope(SqlSelect select)
Returns a scope containing the objects visible from the HAVING clause of a query.

Parameters:
select - SELECT statement
Returns:
naming scope for HAVING clause

getOrderScope

SqlValidatorScope getOrderScope(SqlSelect select)
Returns the scope that expressions in the SELECT and HAVING clause of this query should use. This scope consists of the FROM clause and the enclosing scope. If the query is aggregating, only columns in the GROUP BY clause may be used.

Parameters:
select - SELECT statement
Returns:
naming scope for ORDER BY clause

declareCursor

void declareCursor(SqlSelect select,
                   SqlValidatorScope scope)
Declares a SELECT expression as a cursor.

Parameters:
select - select expression associated with the cursor
scope - scope of the parent query associated with the cursor

pushFunctionCall

void pushFunctionCall()
Pushes a new instance of a function call on to a function call stack.


popFunctionCall

void popFunctionCall()
Removes the topmost entry from the function call stack.


getParentCursor

String getParentCursor(String columnListParamName)
Retrieves the name of the parent cursor referenced by a column list parameter.

Parameters:
columnListParamName - name of the column list parameter
Returns:
name of the parent cursor

setIdentifierExpansion

void setIdentifierExpansion(boolean expandIdentifiers)
Enables or disables expansion of identifiers other than column references.

Parameters:
expandIdentifiers - new setting

setColumnReferenceExpansion

void setColumnReferenceExpansion(boolean expandColumnReferences)
Enables or disables expansion of column references. (Currently this does not apply to the ORDER BY clause; may be fixed in the future.)

Parameters:
expandColumnReferences - new setting

shouldExpandIdentifiers

boolean shouldExpandIdentifiers()
Returns expansion of identifiers.

Returns:
whether this validator should expand identifiers

setCallRewrite

void setCallRewrite(boolean rewriteCalls)
Enables or disables rewrite of "macro-like" calls such as COALESCE.

Parameters:
rewriteCalls - new setting

deriveConstructorType

RelDataType deriveConstructorType(SqlValidatorScope scope,
                                  SqlCall call,
                                  SqlFunction unresolvedConstructor,
                                  SqlFunction resolvedConstructor,
                                  RelDataType[] argTypes)
Derives the type of a constructor.

Parameters:
scope - Scope
call - Call
unresolvedConstructor - TODO
resolvedConstructor - TODO
argTypes - Types of arguments
Returns:
Resolved type of constructor

handleUnresolvedFunction

void handleUnresolvedFunction(SqlCall call,
                              SqlFunction unresolvedFunction,
                              RelDataType[] argTypes)
Handles a call to a function which cannot be resolved, throwing an appropriately descriptive error.

Parameters:
call - Call
unresolvedFunction - Overloaded function which is the target of the call
argTypes - Types of arguments

expandOrderExpr

SqlNode expandOrderExpr(SqlSelect select,
                        SqlNode orderExpr)
Expands an expression in the ORDER BY clause into an expression with the same semantics as expressions in the SELECT clause.

This is made necessary by a couple of dialect 'features':

Parameters:
select - Select statement which contains ORDER BY
orderExpr - Expression in the ORDER BY clause.
Returns:
Expression translated into SELECT clause semantics

expand

SqlNode expand(SqlNode expr,
               SqlValidatorScope scope)
Expands an expression.

Parameters:
expr - Expression
scope - Scope
Returns:
Expanded expression

isSystemField

boolean isSystemField(RelDataTypeField field)
Returns whether a field is a system field. Such fields may have particular properties such as sortedness and nullability.

In the default implementation, always returns false.

Parameters:
field - Field
Returns:
whether field is a system field