Class SqlValidatorUtil

java.lang.Object
org.apache.calcite.sql.validate.SqlValidatorUtil

public class SqlValidatorUtil extends Object
Utility methods related to validation.
  • Field Details

  • Method Details

    • getRelOptTable

      public static @Nullable RelOptTable getRelOptTable(SqlValidatorNamespace namespace, @Nullable Prepare.CatalogReader catalogReader, @Nullable String datasetName, boolean @Nullable [] usedDataset)
      Converts a SqlValidatorScope into a RelOptTable. This is only possible if the scope represents an identifier, such as "sales.emp". Otherwise, returns null.
      Parameters:
      namespace - Namespace
      catalogReader - Schema
      datasetName - Name of sample dataset to substitute, or null to use the regular table
      usedDataset - Output parameter which is set to true if a sample dataset is found; may be null
    • getExtendedColumns

      public static List<RelDataTypeField> getExtendedColumns(SqlValidator validator, SqlValidatorTable table, SqlNodeList extendedColumns)
      Gets a list of extended columns with field indices to the underlying table.
    • getIndexToFieldMap

      public static com.google.common.collect.ImmutableMap<Integer,RelDataTypeField> getIndexToFieldMap(List<RelDataTypeField> sourceFields, RelDataType targetFields)
      Gets a map of indexes from the source to fields in the target for the intersecting set of source and target fields.
      Parameters:
      sourceFields - The source of column names that determine indexes
      targetFields - The target fields to be indexed
    • getOrdinalBitSet

      public static ImmutableBitSet getOrdinalBitSet(RelDataType sourceRowType, RelDataType targetRowType)
      Gets the bit-set to the column ordinals in the source for columns that intersect in the target.
      Parameters:
      sourceRowType - The source upon which to ordinate the bit set.
      targetRowType - The target to overlay on the source to create the bit set.
    • getOrdinalBitSet

      public static ImmutableBitSet getOrdinalBitSet(RelDataType sourceRowType, Map<Integer,RelDataTypeField> indexToField)
      Gets the bit-set to the column ordinals in the source for columns that intersect in the target.
      Parameters:
      sourceRowType - The source upon which to ordinate the bit set.
      indexToField - The map of ordinals to target fields.
    • mapNameToIndex

      public static Map<String,Integer> mapNameToIndex(List<RelDataTypeField> fields)
      Returns a map from field names to indexes.
    • lookupField

      @Deprecated public static @Nullable RelDataTypeField lookupField(boolean caseSensitive, RelDataType rowType, String columnName)
      Deprecated.
    • checkCharsetAndCollateConsistentIfCharType

      public static void checkCharsetAndCollateConsistentIfCharType(RelDataType type)
    • addAlias

      public static SqlNode addAlias(SqlNode expr, String alias)
      Converts an expression "expr" into "expr AS alias".
    • alias

      public static String alias(SqlNode node, int ordinal)
      Derives an alias for a node, and invents a mangled identifier if it cannot.

      Examples:

      • Alias: "1 + 2 as foo" yields "foo"
      • Identifier: "foo.bar.baz" yields "baz"
      • Anything else yields "expr$ordinal"
      Parameters:
      node - Node
      ordinal - Ordinal in SELECT clause (must be ≥ 0)
      Returns:
      An alias, if one can be derived; or a synthetic alias "expr$ordinal"; never null
    • alias

      public static @Nullable String alias(SqlNode node)
    • getAlias

      @Deprecated public static @Nullable String getAlias(SqlNode node, int ordinal)
      Deprecated.
      Use alias(SqlNode) if ordinal is negative, or alias(SqlNode, int) if ordinal is non-negative.
      Derives an alias for a node, and invents a mangled identifier if it cannot.
    • newValidator

      public static SqlValidatorWithHints newValidator(SqlOperatorTable opTab, SqlValidatorCatalogReader catalogReader, RelDataTypeFactory typeFactory, SqlValidator.Config config)
      Factory method for SqlValidator.
    • newValidator

      @Deprecated public static SqlValidatorWithHints newValidator(SqlOperatorTable opTab, SqlValidatorCatalogReader catalogReader, RelDataTypeFactory typeFactory)
      Deprecated.
      Factory method for SqlValidator, with default conformance.
    • uniquify

      public static String uniquify(@Nullable String name, Set<String> usedNames, SqlValidatorUtil.Suggester suggester)
      Makes a name distinct from other names which have already been used, adds it to the list, and returns it.
      Parameters:
      name - Suggested name, may not be unique
      usedNames - Collection of names already used
      suggester - Base for name when input name is null
      Returns:
      Unique name
    • uniquify

      @Deprecated public static List<String> uniquify(List<? extends @Nullable String> nameList)
      Deprecated.
      Makes sure that the names in a list are unique.

      Does not modify the input list. Returns the input list if the strings are unique, otherwise allocates a new list. Deprecated in favor of caseSensitive aware version.

      Parameters:
      nameList - List of strings
      Returns:
      List of unique strings
    • uniquify

      @Deprecated public static List<String> uniquify(List<? extends @Nullable String> nameList, SqlValidatorUtil.Suggester suggester)
      Makes sure that the names in a list are unique.

      Does not modify the input list. Returns the input list if the strings are unique, otherwise allocates a new list.

      Parameters:
      nameList - List of strings
      suggester - How to generate new names if duplicate names are found
      Returns:
      List of unique strings
    • uniquify

      public static List<String> uniquify(List<? extends @Nullable String> nameList, boolean caseSensitive)
      Makes sure that the names in a list are unique.

      Does not modify the input list. Returns the input list if the strings are unique, otherwise allocates a new list.

      Parameters:
      nameList - List of strings
      caseSensitive - Whether upper and lower case names are considered distinct
      Returns:
      List of unique strings
    • uniquify

      public static List<String> uniquify(List<? extends @Nullable String> nameList, SqlValidatorUtil.Suggester suggester, boolean caseSensitive)
      Makes sure that the names in a list are unique.

      Does not modify the input list. Returns the input list if the strings are unique, otherwise allocates a new list.

      Parameters:
      nameList - List of strings
      suggester - How to generate new names if duplicate names are found
      caseSensitive - Whether upper and lower case names are considered distinct
      Returns:
      List of unique strings
    • deriveJoinRowType

      public static RelDataType deriveJoinRowType(RelDataType leftType, @Nullable RelDataType rightType, JoinRelType joinType, RelDataTypeFactory typeFactory, @Nullable List<String> fieldNameList, List<RelDataTypeField> systemFieldList)
      Derives the type of a join relational expression.
      Parameters:
      leftType - Row type of left input to join
      rightType - Row type of right input to join
      joinType - Type of join
      typeFactory - Type factory
      fieldNameList - List of names of fields; if null, field names are inherited and made unique
      systemFieldList - List of system fields that will be prefixed to output row type; typically empty but must not be null
      Returns:
      join type
    • createJoinType

      public static RelDataType createJoinType(RelDataTypeFactory typeFactory, RelDataType leftType, @Nullable RelDataType rightType, @Nullable List<String> fieldNameList, List<RelDataTypeField> systemFieldList)
      Returns the type the row which results when two relations are joined.

      The resulting row type consists of the system fields (if any), followed by the fields of the left type, followed by the fields of the right type. The field name list, if present, overrides the original names of the fields.

      Parameters:
      typeFactory - Type factory
      leftType - Type of left input to join
      rightType - Type of right input to join, or null for semi-join
      fieldNameList - If not null, overrides the original names of the fields
      systemFieldList - List of system fields that will be prefixed to output row type; typically empty but must not be null
      Returns:
      type of row which results when two relations are joined
    • getTargetField

      public static @Nullable RelDataTypeField getTargetField(RelDataType rowType, RelDataTypeFactory typeFactory, SqlIdentifier id, SqlValidatorCatalogReader catalogReader, @Nullable RelOptTable table)
      Resolve a target column name in the target table.
      Parameters:
      rowType - the target row type
      id - the target column identifier
      table - the target table or null if it is not a RelOptTable instance
      Returns:
      the target field or null if the name cannot be resolved
    • lookup

      public static SqlValidatorNamespace lookup(SqlValidatorScope scope, List<String> names)
      Resolves a multi-part identifier such as "SCHEMA.EMP.EMPNO" to a namespace. The returned namespace, never null, may represent a schema, table, column, etc.
    • getSchemaObjectMonikers

      public static void getSchemaObjectMonikers(SqlValidatorCatalogReader catalogReader, List<String> names, List<SqlMoniker> hints)
    • getEnclosingSelectScope

      public static @Nullable SelectScope getEnclosingSelectScope(SqlValidatorScope scope)
    • getEnclosingAggregateSelectScope

      public static @Nullable AggregatingSelectScope getEnclosingAggregateSelectScope(SqlValidatorScope scope)
    • deriveNaturalJoinColumnList

      public static List<String> deriveNaturalJoinColumnList(SqlNameMatcher nameMatcher, RelDataType leftRowType, RelDataType rightRowType)
      Derives the list of column names suitable for NATURAL JOIN. These are the columns that occur at least once each side of the join.
      Parameters:
      nameMatcher - Whether matches are case-sensitive
      leftRowType - Row type of left input to the join
      rightRowType - Row type of right input to the join
      Returns:
      List of columns that occur once on each side
    • createTypeFromProjection

      public static RelDataType createTypeFromProjection(RelDataType type, List<String> columnNameList, RelDataTypeFactory typeFactory, boolean caseSensitive)
    • analyzeGroupItem

      public static void analyzeGroupItem(SqlValidatorScope scope, org.apache.calcite.sql.validate.SqlValidatorUtil.GroupAnalyzer groupAnalyzer, com.google.common.collect.ImmutableList.Builder<com.google.common.collect.ImmutableList<ImmutableBitSet>> topBuilder, SqlNode groupExpr)
      Analyzes an expression in a GROUP BY clause.

      It may be an expression, an empty list (), or a call to GROUPING SETS, CUBE, ROLLUP, TUMBLE, HOP or SESSION.

      Each group item produces a list of group sets, which are written to topBuilder. To find the grouping sets of the query, we will take the cartesian product of the group sets.

    • rollup

      public static com.google.common.collect.ImmutableList<ImmutableBitSet> rollup(List<ImmutableBitSet> bitSets)
      Computes the rollup of bit sets.

      For example, rollup({0}, {1}) returns ({0, 1}, {0}, {}).

      Bit sets are not necessarily singletons: rollup({0, 2}, {3, 5}) returns ({0, 2, 3, 5}, {0, 2}, {}).

    • cube

      public static com.google.common.collect.ImmutableList<ImmutableBitSet> cube(List<ImmutableBitSet> bitSets)
      Computes the cube of bit sets.

      For example, rollup({0}, {1}) returns ({0, 1}, {0}, {}).

      Bit sets are not necessarily singletons: rollup({0, 2}, {3, 5}) returns ({0, 2, 3, 5}, {0, 2}, {}).

    • getTypeEntry

      public static @Nullable CalciteSchema.TypeEntry getTypeEntry(CalciteSchema rootSchema, SqlIdentifier typeName)
      Finds a CalciteSchema.TypeEntry in a given schema whose type has the given name, possibly qualified.
      Parameters:
      rootSchema - root schema
      typeName - name of the type, may be qualified or fully-qualified
      Returns:
      TypeEntry with a table with the given name, or null
    • getTableEntry

      public static @Nullable CalciteSchema.TableEntry getTableEntry(SqlValidatorCatalogReader catalogReader, List<String> names)
      Finds a CalciteSchema.TableEntry in a given catalog reader whose table has the given name, possibly qualified.

      Uses the case-sensitivity policy of the specified catalog reader.

      If not found, returns null.

      Parameters:
      catalogReader - accessor to the table metadata
      names - Name of table, may be qualified or fully-qualified
      Returns:
      TableEntry with a table with the given name, or null
    • getSchema

      public static @Nullable CalciteSchema getSchema(CalciteSchema rootSchema, Iterable<String> schemaPath, SqlNameMatcher nameMatcher)
      Finds and returns CalciteSchema nested to the given rootSchema with specified schemaPath.

      Uses the case-sensitivity policy of specified nameMatcher.

      If not found, returns null.

      Parameters:
      rootSchema - root schema
      schemaPath - full schema path of required schema
      nameMatcher - name matcher
      Returns:
      CalciteSchema that corresponds specified schemaPath
    • containsMonotonic

      public static boolean containsMonotonic(SqlValidatorScope scope)
      Returns whether there are any input columns that are sorted.

      If so, it can be the default ORDER BY clause for a WINDOW specification. (This is an extension to the SQL standard for streaming.)

    • lookupSqlFunctionByID

      public static @Nullable SqlOperator lookupSqlFunctionByID(SqlOperatorTable opTab, SqlIdentifier funName, @Nullable SqlFunctionCategory funcType)
      Lookup sql function by sql identifier and function category.
      Parameters:
      opTab - operator table to look up
      funName - function name
      funcType - function category
      Returns:
      A sql function if and only if there is one operator matches, else null
    • validateExprWithRowType

      public static Pair<SqlNode,RelDataType> validateExprWithRowType(boolean caseSensitive, SqlOperatorTable operatorTable, RelDataTypeFactory typeFactory, RelDataType rowType, SqlNode expr)
      Validate the sql node with specified base table row type. For "base table", we mean the table that the sql node expression references fields with.
      Parameters:
      caseSensitive - whether to match the catalog case-sensitively
      operatorTable - operator table
      typeFactory - type factory
      rowType - the table row type that has fields referenced by the expression
      expr - the expression to validate
      Returns:
      pair of a validated expression sql node and its data type, usually a SqlUnresolvedFunction is converted to a resolved function
    • createSingleTableCatalogReader

      public static CalciteCatalogReader createSingleTableCatalogReader(boolean caseSensitive, String tableName, RelDataTypeFactory typeFactory, RelDataType rowType)
      Creates a catalog reader that contains a single Table with temporary table name and specified rowType.

      Make this method public so that other systems can also use it.

      Parameters:
      caseSensitive - whether to match case sensitively
      tableName - table name to register with
      typeFactory - type factory
      rowType - table row type
      Returns:
      the CalciteCatalogReader instance
    • flatten

      public static SqlValidatorUtil.FlatAggregate flatten(SqlCall call)
      Flattens an aggregate call.
    • isMeasure

      public static boolean isMeasure(SqlNode selectItem)
      Returns whether a select item is a measure.
    • getMeasure

      public static @Nullable SqlNode getMeasure(SqlNode selectItem)
      Returns the measure expression if a select item is a measure, null otherwise.

      For a measure, selectItem will have the form AS(MEASURE(exp), alias) and this method returns exp.

    • adjustTypeForArrayConstructor

      public static void adjustTypeForArrayConstructor(RelDataType componentType, SqlOperatorBinding opBinding)
      When the array element does not equal the array component type, make explicit casting.
      Parameters:
      componentType - derived array component type
      opBinding - description of call
    • adjustTypeForMapConstructor

      public static void adjustTypeForMapConstructor(Pair<RelDataType,RelDataType> componentType, SqlOperatorBinding opBinding)
      When the map key or value does not equal the map component key type or value type, make explicit casting.
      Parameters:
      componentType - derived map pair component type
      opBinding - description of call