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
Nested ClassesModifier and TypeClassDescriptionstatic classHandles particularDatabaseMetaDatamethods; invocations of other methods will fall through to the base class,BarfingInvocationHandler, which will throw an error. -
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic SqlNodeandExpressions(@Nullable SqlNode node1, SqlNode node2) Returns the AND of two expressions.static RelNodeattachRelHint(HintStrategyTable hintStrategies, List<RelHint> hints, Hintable rel) Attach thehintstorelwith specified hint strategies.static SqlLiteralconcatenateLiterals(List<SqlLiteral> lits) Concatenates string literals.static booleancontainsAgg(SqlNode node) Returns whether an AST tree contains a call to an aggregate function.static booleancontainsCall(SqlNode node, Predicate<SqlCall> callPredicate) Returns whether an AST tree contains a call that matches a given predicate.static booleancontainsDefault(SqlNode node) Returns whether a given node contains aSqlKind.DEFAULTexpression.static booleancontainsIn(SqlNode node) Returns whether a given node contains aSqlInOperator.static SqlNodecreateCall(SqlOperator op, SqlParserPos pos, List<SqlNode> operands) Creates a call to an operator.static RelDataTypecreateNlsStringType(RelDataTypeFactory typeFactory, NlsString str) Creates the type of anNlsString.static StringderiveAliasFromOrdinal(int ordinal) static StringgetAliasedSignature(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 ofpredicatewithin a givenSqlNodetree.static CharsetgetCharset(String charsetName) Returns the Java-levelCharsetbased on given SQL-level name.static SqlNodegetFromNode(SqlSelect query, int ordinal) Returns thenth (0-based) input to a join expression.static StringgetOperatorSignature(SqlOperator op, List<?> typeList) Constructs an operator signature from a type list.getRelHint(HintStrategyTable hintStrategies, @Nullable SqlNodeList sqlHints) Returns an immutable list ofRelHintfrom sql hints, with a given inherit path from the root node.static SqlNodegetSelectListItem(SqlNode query, int i) Returns theith select-list item of a query.static intindexOfDeep(List<? extends SqlNode> list, SqlNode e, Litmus litmus) Finds the index of an expression in a list, comparing usingSqlNode.equalsDeep(SqlNode, Litmus).static booleanisCallTo(SqlNode node, SqlOperator operator) static booleanisGeneratedAlias(String alias) Whether the alias is generated by calcite.static booleanReturns whether a node is a literal.static booleanReturns whether a node is a literal.static booleanisLiteralChain(SqlNode node) Returns whether a node is a literal chain which is used to represent a continued string literal.static booleanReturns whether a node represents the NULL value or a series of nestedCAST(NULL AS type)calls.static booleanisNullLiteral(@Nullable SqlNode node, boolean allowCast) Returns whether a node represents the NULL value.static @Nullable SqlOperatorlookupRoutine(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 booleanmatchRoutinesByParameterCount(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 CalciteContextExceptionnewContextException(int line, int col, int endLine, int endCol, org.apache.calcite.runtime.Resources.ExInst<?> e) Wraps an exception with context.static CalciteContextExceptionnewContextException(SqlParserPos pos, org.apache.calcite.runtime.Resources.ExInst<?> e) Wraps an exception with context.static CalciteExceptionnewContextException(SqlParserPos pos, org.apache.calcite.runtime.Resources.ExInst<?> e, String inputText) Wraps an exception with context.static @PolyNull SqlNodeIf a node is "AS", returns the underlying expression; otherwise returns the node.static SqlNodeListstripListAs(SqlNodeList nodeList) Modifies a list of nodes, removing AS from each if present.static SqlNodeListtoNodeList(SqlNode[] operands) Converts a SqlNode array to a SqlNodeList.static @Nullable StringTranslates a character set name from a SQL-level name into a Java-level name.static voidunparseBinarySyntax(SqlOperator operator, SqlCall call, SqlWriter writer, int leftPrec, int rightPrec) static voidunparseFunctionSyntax(SqlOperator operator, SqlWriter writer, SqlCall call) Deprecated.static voidunparseFunctionSyntax(SqlOperator operator, SqlWriter writer, SqlCall call, boolean ordered) Unparses a call to an operator that has function syntax.static voidunparseSqlIdentifierSyntax(SqlWriter writer, SqlIdentifier identifier, boolean asFunctionID) Unparse a SqlIdentifier syntax.static voidvalidateCharset(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
node1is null, returnsnode2. Flattens if either node is an AND. -
getFromNode
Returns thenth (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
SqlLiteralUnknown, returns false. - For
CAST(NULL AS type), returns true ifallowCastis 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 ifallowCastis 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 theith 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 ofSqlTypeNameorStringto 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
CharsetandSqlCollation, 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-levelCharsetbased 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 ofpredicatewithin a givenSqlNodetree.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 ofRelHintfrom 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
RelHintlist
-
attachRelHint
public static RelNode attachRelHint(HintStrategyTable hintStrategies, List<RelHint> hints, Hintable rel) Attach thehintstorelwith specified hint strategies.- Parameters:
hintStrategies- The strategies to filter the hintshints- The original hints to be attached- Returns:
- A copy of
relif 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.DEFAULTexpression.- 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.
-