Class SqlUtil

java.lang.Object
org.apache.calcite.sql.SqlUtil

public abstract class SqlUtil extends Object
Contains utility functions related to SQL parsing, all static.
  • Field Details

    • GENERATED_EXPR_ALIAS_PREFIX

      public static final String 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

      public static SqlNode andExpressions(@Nullable SqlNode node1, SqlNode node2)
      Returns the AND of two expressions.

      If node1 is null, returns node2. Flattens if either node is an AND.

    • getFromNode

      public static SqlNode getFromNode(SqlSelect query, int ordinal)
      Returns the nth (0-based) input to a join expression.
    • toNodeList

      public static SqlNodeList toNodeList(SqlNode[] operands)
      Converts a SqlNode array to a SqlNodeList.
    • indexOfDeep

      public static int indexOfDeep(List<? extends SqlNode> list, SqlNode e, Litmus litmus)
      Finds the index of an expression in a list, comparing using SqlNode.equalsDeep(SqlNode, Litmus).
    • isNullLiteral

      public static boolean isNullLiteral(@Nullable SqlNode node, boolean allowCast)
      Returns whether a node represents the NULL value.

      Examples:

      • For SqlLiteral Unknown, returns false.
      • For CAST(NULL AS type), returns true if allowCast is true, false otherwise.
      • For CAST(CAST(NULL AS type) AS type)), returns false.
    • isNull

      public static boolean isNull(SqlNode node)
      Returns whether a node represents the NULL value or a series of nested CAST(NULL AS type) calls. For example: isNull(CAST(CAST(NULL as INTEGER) AS VARCHAR(1))) returns true.
    • isLiteral

      public static boolean isLiteral(SqlNode node, boolean allowCast)
      Returns whether a node is a literal.

      Examples:

      • For CAST(literal AS type), returns true if allowCast 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
    • isLiteral

      public static boolean isLiteral(SqlNode node)
      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 call isNullLiteral(org.apache.calcite.sql.SqlNode, boolean) first.

      Parameters:
      node - The node, never null.
      Returns:
      Whether the node is a literal
    • isLiteralChain

      public static boolean isLiteralChain(SqlNode node)
      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 operator
      writer - Writer
      call - List of 0 or more operands
      ordered - 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 - Writer
      identifier - SqlIdentifier
      asFunctionID - Whether this identifier comes from a SqlFunction
    • unparseBinarySyntax

      public static void unparseBinarySyntax(SqlOperator operator, SqlCall call, SqlWriter writer, int leftPrec, int rightPrec)
    • concatenateLiterals

      public static SqlLiteral concatenateLiterals(List<SqlLiteral> lits)
      Concatenates string literals.

      This method takes an array of arguments, since pairwise concatenation means too much string copying.

      Parameters:
      lits - an array of SqlLiteral, 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 search
      typeFactory - Type factory
      funcName - name of function being invoked
      argTypes - argument types
      argNames - argument names, or null if call by position
      category - 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-sensitively
      coerce - 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 search
      typeFactory - Type factory
      funcName - name of function being invoked
      argTypes - argument types
      argNames - argument names, or null if call by position
      sqlSyntax - the SqlSyntax of the SqlOperator being looked up
      sqlKind - the SqlKind of the SqlOperator being looked up
      category - Category of routine to look up
      nameMatcher - Whether to look up the function case-sensitively
      coerce - 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 search
      funcName - name of function being invoked
      argTypes - argument types
      category - category of routine to look up
      nameMatcher - Whether to look up the function case-sensitively
      Returns:
      true if match found
    • getSelectListItem

      public static SqlNode getSelectListItem(SqlNode query, int i)
      Returns the ith select-list item of a query.
    • deriveAliasFromOrdinal

      public static String deriveAliasFromOrdinal(int ordinal)
    • isGeneratedAlias

      public static boolean isGeneratedAlias(String alias)
      Whether the alias is generated by calcite.
      Parameters:
      alias - not null
      Returns:
      true if alias is generated by calcite, otherwise false
    • getOperatorSignature

      public static String getOperatorSignature(SqlOperator op, List<?> typeList)
      Constructs an operator signature from a type list.
      Parameters:
      op - operator
      typeList - list of types to use for operands. Types may be represented as String, SqlTypeFamily, or any object with a valid Object.toString() method.
      Returns:
      constructed signature
    • getAliasedSignature

      public static String getAliasedSignature(SqlOperator op, String opName, List<?> typeList)
      Constructs an operator signature from a type list, substituting an alias for the operator name.
      Parameters:
      op - operator
      opName - name to use for operator
      typeList - list of SqlTypeName or String 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

      public static boolean isCallTo(SqlNode node, SqlOperator operator)
      Returns whether a node is a call to a given operator.
    • createNlsStringType

      public static RelDataType createNlsStringType(RelDataTypeFactory typeFactory, NlsString str)
      Creates the type of an NlsString.

      The type inherits the NlsString's Charset and SqlCollation, if they are set, otherwise it gets the system defaults.

      Parameters:
      typeFactory - Type factory
      str - String
      Returns:
      Type, including collation and charset
    • translateCharacterSetName

      public static @Nullable String translateCharacterSetName(String name)
      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

      public static Charset getCharset(String charsetName)
      Returns the Java-level Charset 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 array
      charset - charset
      Throws:
      RuntimeException - If the given value cannot be represented in the given charset
    • stripAs

      public static @PolyNull SqlNode stripAs(@PolyNull SqlNode node)
      If a node is "AS", returns the underlying expression; otherwise returns the node. Returns null if and only if the node is null.
    • stripListAs

      public static SqlNodeList stripListAs(SqlNodeList nodeList)
      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 of predicate within a given SqlNode tree.

      The first element of the list is root, and the last is the node that matched predicate. Throws if no node matches.

    • getRelHint

      public static List<RelHint> getRelHint(HintStrategyTable hintStrategies, @Nullable SqlNodeList sqlHints)
      Returns an immutable list of RelHint 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 hints
      sqlHints - The sql hints nodes
      Returns:
      the RelHint list
    • attachRelHint

      public static RelNode attachRelHint(HintStrategyTable hintStrategies, List<RelHint> hints, Hintable rel)
      Attach the hints to rel with specified hint strategies.
      Parameters:
      hintStrategies - The strategies to filter the hints
      hints - 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

      public static SqlNode createCall(SqlOperator op, SqlParserPos pos, List<SqlNode> operands)
      Creates a call to an operator.

      Deals with the fact the AND and OR are binary.

    • containsIn

      public static boolean containsIn(SqlNode node)
      Returns whether a given node contains a SqlInOperator.
      Parameters:
      node - AST tree
    • containsDefault

      public static boolean containsDefault(SqlNode node)
      Returns whether a given node contains a SqlKind.DEFAULT expression.
      Parameters:
      node - AST tree
    • containsAgg

      public static boolean containsAgg(SqlNode node)
      Returns whether an AST tree contains a call to an aggregate function.
      Parameters:
      node - AST tree
    • containsCall

      public static boolean containsCall(SqlNode node, Predicate<SqlCall> callPredicate)
      Returns whether an AST tree contains a call that matches a given predicate.