Package org.apache.calcite.sql
Class SqlUtil
java.lang.Object
org.apache.calcite.sql.SqlUtil
Contains utility functions related to SQL parsing, all static.
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
Handles particularDatabaseMetaData
methods; invocations of other methods will fall through to the base class,BarfingInvocationHandler
, which will throw an error. -
Field Summary
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic SqlNode
andExpressions
(@Nullable SqlNode node1, SqlNode node2) Returns the AND of two expressions.static RelNode
attachRelHint
(HintStrategyTable hintStrategies, List<RelHint> hints, Hintable rel) Attach thehints
torel
with specified hint strategies.static SqlLiteral
concatenateLiterals
(List<SqlLiteral> lits) Concatenates string literals.static boolean
containsAgg
(SqlNode node) Returns whether an AST tree contains a call to an aggregate function.static boolean
containsCall
(SqlNode node, Predicate<SqlCall> callPredicate) Returns whether an AST tree contains a call that matches a given predicate.static boolean
containsDefault
(SqlNode node) Returns whether a given node contains aSqlKind.DEFAULT
expression.static boolean
containsIn
(SqlNode node) Returns whether a given node contains aSqlInOperator
.static SqlNode
createCall
(SqlOperator op, SqlParserPos pos, List<SqlNode> operands) Creates a call to an operator.static RelDataType
createNlsStringType
(RelDataTypeFactory typeFactory, NlsString str) Creates the type of anNlsString
.static String
deriveAliasFromOrdinal
(int ordinal) static String
getAliasedSignature
(SqlOperator op, String opName, List<?> typeList) Constructs an operator signature from a type list, substituting an alias for the operator name.static com.google.common.collect.ImmutableList<SqlNode>
Returns a list of ancestors ofpredicate
within a givenSqlNode
tree.static Charset
getCharset
(String charsetName) Returns the Java-levelCharset
based on given SQL-level name.static SqlNode
getFromNode
(SqlSelect query, int ordinal) Returns then
th (0-based) input to a join expression.static String
getOperatorSignature
(SqlOperator op, List<?> typeList) Constructs an operator signature from a type list.getRelHint
(HintStrategyTable hintStrategies, @Nullable SqlNodeList sqlHints) Returns an immutable list ofRelHint
from sql hints, with a given inherit path from the root node.static SqlNode
getSelectListItem
(SqlNode query, int i) Returns thei
th select-list item of a query.static int
indexOfDeep
(List<? extends SqlNode> list, SqlNode e, Litmus litmus) Finds the index of an expression in a list, comparing usingSqlNode.equalsDeep(SqlNode, Litmus)
.static boolean
isCallTo
(SqlNode node, SqlOperator operator) static boolean
isGeneratedAlias
(String alias) Whether the alias is generated by calcite.static boolean
Returns whether a node is a literal.static boolean
Returns whether a node is a literal.static boolean
isLiteralChain
(SqlNode node) Returns whether a node is a literal chain which is used to represent a continued string literal.static boolean
Returns whether a node represents the NULL value or a series of nestedCAST(NULL AS type)
calls.static boolean
isNullLiteral
(@Nullable SqlNode node, boolean allowCast) Returns whether a node represents the NULL value.static @Nullable SqlOperator
lookupRoutine
(SqlOperatorTable opTab, RelDataTypeFactory typeFactory, SqlIdentifier funcName, List<RelDataType> argTypes, @Nullable List<String> argNames, @Nullable SqlFunctionCategory category, SqlSyntax syntax, SqlKind sqlKind, SqlNameMatcher nameMatcher, boolean coerce) Looks up a (possibly overloaded) routine based on name and argument types.static Iterator<SqlOperator>
lookupSubjectRoutines
(SqlOperatorTable opTab, RelDataTypeFactory typeFactory, SqlIdentifier funcName, List<RelDataType> argTypes, @Nullable List<String> argNames, SqlSyntax sqlSyntax, SqlKind sqlKind, @Nullable SqlFunctionCategory category, SqlNameMatcher nameMatcher, boolean coerce) Looks up all subject routines matching the given name and argument types.static boolean
matchRoutinesByParameterCount
(SqlOperatorTable opTab, SqlIdentifier funcName, List<RelDataType> argTypes, SqlFunctionCategory category, SqlNameMatcher nameMatcher) Determines whether there is a routine matching the given name and number of arguments.static CalciteContextException
newContextException
(int line, int col, int endLine, int endCol, org.apache.calcite.runtime.Resources.ExInst<?> e) Wraps an exception with context.static CalciteContextException
newContextException
(SqlParserPos pos, org.apache.calcite.runtime.Resources.ExInst<?> e) Wraps an exception with context.static CalciteException
newContextException
(SqlParserPos pos, org.apache.calcite.runtime.Resources.ExInst<?> e, String inputText) Wraps an exception with context.static @PolyNull SqlNode
If a node is "AS", returns the underlying expression; otherwise returns the node.static SqlNodeList
stripListAs
(SqlNodeList nodeList) Modifies a list of nodes, removing AS from each if present.static SqlNodeList
toNodeList
(SqlNode[] operands) Converts a SqlNode array to a SqlNodeList.static @Nullable String
Translates a character set name from a SQL-level name into a Java-level name.static void
unparseBinarySyntax
(SqlOperator operator, SqlCall call, SqlWriter writer, int leftPrec, int rightPrec) static void
unparseFunctionSyntax
(SqlOperator operator, SqlWriter writer, SqlCall call) Deprecated.static void
unparseFunctionSyntax
(SqlOperator operator, SqlWriter writer, SqlCall call, boolean ordered) Unparses a call to an operator that has function syntax.static void
unparseSqlIdentifierSyntax
(SqlWriter writer, SqlIdentifier identifier, boolean asFunctionID) Unparse a SqlIdentifier syntax.static void
validateCharset
(org.apache.calcite.avatica.util.ByteString value, Charset charset) Validate if value can be decoded by given charset.
-
Field Details
-
GENERATED_EXPR_ALIAS_PREFIX
Prefix for generated column aliases. Ends with '$' so that human-written queries are unlikely to accidentally reference the generated name.- See Also:
-
-
Constructor Details
-
SqlUtil
public SqlUtil()
-
-
Method Details
-
andExpressions
Returns the AND of two expressions.If
node1
is null, returnsnode2
. Flattens if either node is an AND. -
getFromNode
Returns then
th (0-based) input to a join expression. -
toNodeList
Converts a SqlNode array to a SqlNodeList. -
indexOfDeep
Finds the index of an expression in a list, comparing usingSqlNode.equalsDeep(SqlNode, Litmus)
. -
isNullLiteral
Returns whether a node represents the NULL value.Examples:
- For
SqlLiteral
Unknown, returns false. - For
CAST(NULL AS type)
, returns true ifallowCast
is true, false otherwise. - For
CAST(CAST(NULL AS type) AS type))
, returns false.
- For
-
isNull
Returns whether a node represents the NULL value or a series of nestedCAST(NULL AS type)
calls. For example:isNull(CAST(CAST(NULL as INTEGER) AS VARCHAR(1)))
returnstrue
. -
isLiteral
Returns whether a node is a literal.Examples:
- For
CAST(literal AS type)
, returns true ifallowCast
is true, false otherwise. - For
CAST(CAST(literal AS type) AS type))
, returns false.
- Parameters:
node
- The node, never null.allowCast
- whether to regard CAST(literal) as a literal- Returns:
- Whether the node is a literal
- For
-
isLiteral
Returns whether a node is a literal.Many constructs which require literals also accept
CAST(NULL AS type)
. This method does not accept casts, so you should callisNullLiteral(org.apache.calcite.sql.SqlNode, boolean)
first.- Parameters:
node
- The node, never null.- Returns:
- Whether the node is a literal
-
isLiteralChain
Returns whether a node is a literal chain which is used to represent a continued string literal.- Parameters:
node
- The node, never null.- Returns:
- Whether the node is a literal chain
-
unparseFunctionSyntax
@Deprecated public static void unparseFunctionSyntax(SqlOperator operator, SqlWriter writer, SqlCall call) Deprecated. -
unparseFunctionSyntax
public static void unparseFunctionSyntax(SqlOperator operator, SqlWriter writer, SqlCall call, boolean ordered) Unparses a call to an operator that has function syntax.- Parameters:
operator
- The operatorwriter
- Writercall
- List of 0 or more operandsordered
- Whether argument list may end with ORDER BY
-
unparseSqlIdentifierSyntax
public static void unparseSqlIdentifierSyntax(SqlWriter writer, SqlIdentifier identifier, boolean asFunctionID) Unparse a SqlIdentifier syntax.- Parameters:
writer
- Writeridentifier
- SqlIdentifierasFunctionID
- Whether this identifier comes from a SqlFunction
-
unparseBinarySyntax
public static void unparseBinarySyntax(SqlOperator operator, SqlCall call, SqlWriter writer, int leftPrec, int rightPrec) -
concatenateLiterals
Concatenates string literals.This method takes an array of arguments, since pairwise concatenation means too much string copying.
- Parameters:
lits
- an array ofSqlLiteral
, not empty, all of the same class- Returns:
- a new
SqlLiteral
, of that same class, whose value is the string concatenation of the values of the literals - Throws:
ClassCastException
- if the lits are not homogeneous.ArrayIndexOutOfBoundsException
- if lits is an empty array.
-
lookupRoutine
public static @Nullable SqlOperator lookupRoutine(SqlOperatorTable opTab, RelDataTypeFactory typeFactory, SqlIdentifier funcName, List<RelDataType> argTypes, @Nullable List<String> argNames, @Nullable SqlFunctionCategory category, SqlSyntax syntax, SqlKind sqlKind, SqlNameMatcher nameMatcher, boolean coerce) Looks up a (possibly overloaded) routine based on name and argument types.- Parameters:
opTab
- operator table to searchtypeFactory
- Type factoryfuncName
- name of function being invokedargTypes
- argument typesargNames
- argument names, or null if call by positioncategory
- whether a function or a procedure. (If a procedure is being invoked, the overload rules are simpler.)nameMatcher
- Whether to look up the function case-sensitivelycoerce
- Whether to allow type coercion when do filter routines by parameter types- Returns:
- matching routine, or null if none found
- See Also:
-
lookupSubjectRoutines
public static Iterator<SqlOperator> lookupSubjectRoutines(SqlOperatorTable opTab, RelDataTypeFactory typeFactory, SqlIdentifier funcName, List<RelDataType> argTypes, @Nullable List<String> argNames, SqlSyntax sqlSyntax, SqlKind sqlKind, @Nullable SqlFunctionCategory category, SqlNameMatcher nameMatcher, boolean coerce) Looks up all subject routines matching the given name and argument types.- Parameters:
opTab
- operator table to searchtypeFactory
- Type factoryfuncName
- name of function being invokedargTypes
- argument typesargNames
- argument names, or null if call by positionsqlSyntax
- the SqlSyntax of the SqlOperator being looked upsqlKind
- the SqlKind of the SqlOperator being looked upcategory
- Category of routine to look upnameMatcher
- Whether to look up the function case-sensitivelycoerce
- Whether to allow type coercion when do filter routine by parameter types- Returns:
- list of matching routines
- See Also:
-
matchRoutinesByParameterCount
public static boolean matchRoutinesByParameterCount(SqlOperatorTable opTab, SqlIdentifier funcName, List<RelDataType> argTypes, SqlFunctionCategory category, SqlNameMatcher nameMatcher) Determines whether there is a routine matching the given name and number of arguments.- Parameters:
opTab
- operator table to searchfuncName
- name of function being invokedargTypes
- argument typescategory
- category of routine to look upnameMatcher
- Whether to look up the function case-sensitively- Returns:
- true if match found
-
getSelectListItem
Returns thei
th select-list item of a query. -
deriveAliasFromOrdinal
-
isGeneratedAlias
Whether the alias is generated by calcite.- Parameters:
alias
- not null- Returns:
- true if alias is generated by calcite, otherwise false
-
getOperatorSignature
Constructs an operator signature from a type list.- Parameters:
op
- operatortypeList
- list of types to use for operands. Types may be represented asString
,SqlTypeFamily
, or any object with a validObject.toString()
method.- Returns:
- constructed signature
-
getAliasedSignature
Constructs an operator signature from a type list, substituting an alias for the operator name.- Parameters:
op
- operatoropName
- name to use for operatortypeList
- list ofSqlTypeName
orString
to use for operands- Returns:
- constructed signature
-
newContextException
public static CalciteException newContextException(SqlParserPos pos, org.apache.calcite.runtime.Resources.ExInst<?> e, String inputText) Wraps an exception with context. -
newContextException
public static CalciteContextException newContextException(SqlParserPos pos, org.apache.calcite.runtime.Resources.ExInst<?> e) Wraps an exception with context. -
newContextException
public static CalciteContextException newContextException(int line, int col, int endLine, int endCol, org.apache.calcite.runtime.Resources.ExInst<?> e) Wraps an exception with context. -
isCallTo
-
createNlsStringType
Creates the type of anNlsString
.The type inherits the NlsString's
Charset
andSqlCollation
, if they are set, otherwise it gets the system defaults.- Parameters:
typeFactory
- Type factorystr
- String- Returns:
- Type, including collation and charset
-
translateCharacterSetName
Translates a character set name from a SQL-level name into a Java-level name.- Parameters:
name
- SQL-level name- Returns:
- Java-level name, or null if SQL-level name is unknown
-
getCharset
Returns the Java-levelCharset
based on given SQL-level name.- Parameters:
charsetName
- Sql charset name, must not be null.- Returns:
- charset, or default charset if charsetName is null.
- Throws:
UnsupportedCharsetException
- If no support for the named charset is available in this instance of the Java virtual machine
-
validateCharset
public static void validateCharset(org.apache.calcite.avatica.util.ByteString value, Charset charset) Validate if value can be decoded by given charset.- Parameters:
value
- nls string in byte arraycharset
- charset- Throws:
RuntimeException
- If the given value cannot be represented in the given charset
-
stripAs
If a node is "AS", returns the underlying expression; otherwise returns the node. Returns null if and only if the node is null. -
stripListAs
Modifies a list of nodes, removing AS from each if present.- See Also:
-
getAncestry
public static com.google.common.collect.ImmutableList<SqlNode> getAncestry(SqlNode root, Predicate<SqlNode> predicate, Predicate<SqlNode> postPredicate) Returns a list of ancestors ofpredicate
within a givenSqlNode
tree.The first element of the list is
root
, and the last is the node that matchedpredicate
. Throws if no node matches. -
getRelHint
public static List<RelHint> getRelHint(HintStrategyTable hintStrategies, @Nullable SqlNodeList sqlHints) Returns an immutable list ofRelHint
from sql hints, with a given inherit path from the root node.The inherit path would be empty list.
- Parameters:
hintStrategies
- The hint strategies to validate the sql hintssqlHints
- The sql hints nodes- Returns:
- the
RelHint
list
-
attachRelHint
public static RelNode attachRelHint(HintStrategyTable hintStrategies, List<RelHint> hints, Hintable rel) Attach thehints
torel
with specified hint strategies.- Parameters:
hintStrategies
- The strategies to filter the hintshints
- The original hints to be attached- Returns:
- A copy of
rel
if there are any hints can be attached given the hint strategies, or the original node if such hints don't exist
-
createCall
Creates a call to an operator.Deals with the fact the AND and OR are binary.
-
containsIn
Returns whether a given node contains aSqlInOperator
.- Parameters:
node
- AST tree
-
containsDefault
Returns whether a given node contains aSqlKind.DEFAULT
expression.- Parameters:
node
- AST tree
-
containsAgg
Returns whether an AST tree contains a call to an aggregate function.- Parameters:
node
- AST tree
-
containsCall
Returns whether an AST tree contains a call that matches a given predicate.
-