org.apache.calcite.sql.validate.SqlNameMatcher Java Examples

The following examples show how to use org.apache.calcite.sql.validate.SqlNameMatcher. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SqlTypeUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether two struct types are equal, ignoring nullability.
 *
 * <p>They do not need to come from the same factory.
 *
 * @param factory       Type factory
 * @param type1         First type
 * @param type2         Second type
 * @param nameMatcher   Name matcher used to compare the field names, if null,
 *                      the field names are also ignored
 *
 * @return Whether types are equal, ignoring nullability
 */
public static boolean equalAsStructSansNullability(
    RelDataTypeFactory factory,
    RelDataType type1,
    RelDataType type2,
    SqlNameMatcher nameMatcher) {
  assert type1.isStruct();
  assert type2.isStruct();

  if (type1.getFieldCount() != type2.getFieldCount()) {
    return false;
  }

  for (Pair<RelDataTypeField, RelDataTypeField> pair
      : Pair.zip(type1.getFieldList(), type2.getFieldList())) {
    if (nameMatcher != null
        && !nameMatcher.matches(pair.left.getName(), pair.right.getName())) {
      return false;
    }
    if (!equalSansNullability(factory, pair.left.getType(), pair.right.getType())) {
      return false;
    }
  }

  return true;
}
 
Example #2
Source File: FunctionCatalogOperatorTable.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void lookupOperatorOverloads(
		SqlIdentifier opName,
		SqlFunctionCategory category,
		SqlSyntax syntax,
		List<SqlOperator> operatorList,
		SqlNameMatcher nameMatcher) {
	if (!opName.isSimple()) {
		return;
	}

	// We lookup only user functions via CatalogOperatorTable. Built in functions should
	// go through BasicOperatorTable
	if (isNotUserFunction(category)) {
		return;
	}

	String name = opName.getSimple();
	Optional<FunctionLookup.Result> candidateFunction = functionCatalog.lookupFunction(name);

	candidateFunction.flatMap(lookupResult ->
		convertToSqlFunction(category, name, lookupResult.getFunctionDefinition())
	).ifPresent(operatorList::add);
}
 
Example #3
Source File: FunctionCatalogOperatorTable.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void lookupOperatorOverloads(
		SqlIdentifier opName,
		SqlFunctionCategory category,
		SqlSyntax syntax,
		List<SqlOperator> operatorList,
		SqlNameMatcher nameMatcher) {
	if (!opName.isSimple()) {
		return;
	}

	// We lookup only user functions via CatalogOperatorTable. Built in functions should
	// go through BasicOperatorTable
	if (isNotUserFunction(category)) {
		return;
	}

	String name = opName.getSimple();
	Optional<FunctionLookup.Result> candidateFunction = functionCatalog.lookupFunction(name);

	candidateFunction.flatMap(lookupResult ->
		convertToSqlFunction(category, name, lookupResult.getFunctionDefinition())
	).ifPresent(operatorList::add);
}
 
Example #4
Source File: SqlUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Looks up a (possibly overloaded) routine based on name and argument
 * types.
 *
 * @param opTab         operator table to search
 * @param funcName      name of function being invoked
 * @param argTypes      argument types
 * @param argNames      argument names, or null if call by position
 * @param category      whether a function or a procedure. (If a procedure is
 *                      being invoked, the overload rules are simpler.)
 * @param nameMatcher   Whether to look up the function case-sensitively
 * @param coerce        Whether to allow type coercion when do filter routines
 *                      by parameter types
 * @return matching routine, or null if none found
 *
 * @see Glossary#SQL99 SQL:1999 Part 2 Section 10.4
 */
public static SqlOperator lookupRoutine(SqlOperatorTable opTab,
    SqlIdentifier funcName, List<RelDataType> argTypes,
    List<String> argNames, SqlFunctionCategory category,
    SqlSyntax syntax, SqlKind sqlKind, SqlNameMatcher nameMatcher,
    boolean coerce) {
  Iterator<SqlOperator> list =
      lookupSubjectRoutines(
          opTab,
          funcName,
          argTypes,
          argNames,
          syntax,
          sqlKind,
          category,
          nameMatcher,
          coerce);
  if (list.hasNext()) {
    // return first on schema path
    return list.next();
  }
  return null;
}
 
Example #5
Source File: SqlUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static Iterator<SqlOperator> lookupSubjectRoutinesByName(
    SqlOperatorTable opTab,
    SqlIdentifier funcName,
    final SqlSyntax syntax,
    SqlFunctionCategory category,
    SqlNameMatcher nameMatcher) {
  final List<SqlOperator> sqlOperators = new ArrayList<>();
  opTab.lookupOperatorOverloads(funcName, category, syntax, sqlOperators,
      nameMatcher);
  switch (syntax) {
  case FUNCTION:
    return Iterators.filter(sqlOperators.iterator(),
        Predicates.instanceOf(SqlFunction.class));
  default:
    return Iterators.filter(sqlOperators.iterator(),
        operator -> Objects.requireNonNull(operator).getSyntax() == syntax);
  }
}
 
Example #6
Source File: SqlUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether there is a routine matching the given name and number
 * of arguments.
 *
 * @param opTab         operator table to search
 * @param funcName      name of function being invoked
 * @param argTypes      argument types
 * @param category      category of routine to look up
 * @param nameMatcher   Whether to look up the function case-sensitively
 * @return true if match found
 */
public static boolean matchRoutinesByParameterCount(
    SqlOperatorTable opTab,
    SqlIdentifier funcName,
    List<RelDataType> argTypes,
    SqlFunctionCategory category,
    SqlNameMatcher nameMatcher) {
  // start with all routines matching by name
  Iterator<SqlOperator> routines =
      lookupSubjectRoutinesByName(opTab, funcName, SqlSyntax.FUNCTION,
          category, nameMatcher);

  // first pass:  eliminate routines which don't accept the given
  // number of arguments
  routines = filterRoutinesByParameterCount(routines, argTypes);

  return routines.hasNext();
}
 
Example #7
Source File: FunctionCatalogOperatorTable.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void lookupOperatorOverloads(
		SqlIdentifier opName,
		SqlFunctionCategory category,
		SqlSyntax syntax,
		List<SqlOperator> operatorList,
		SqlNameMatcher nameMatcher) {
	if (!opName.isSimple()) {
		return;
	}

	// We lookup only user functions via CatalogOperatorTable. Built in functions should
	// go through BasicOperatorTable
	if (isNotUserFunction(category)) {
		return;
	}

	String name = opName.getSimple();
	Optional<FunctionLookup.Result> candidateFunction = functionCatalog.lookupFunction(
		UnresolvedIdentifier.of(name));

	candidateFunction.flatMap(lookupResult ->
		convertToSqlFunction(category, name, lookupResult.getFunctionDefinition())
	).ifPresent(operatorList::add);
}
 
Example #8
Source File: FunctionCatalogOperatorTable.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void lookupOperatorOverloads(
		SqlIdentifier opName,
		SqlFunctionCategory category,
		SqlSyntax syntax,
		List<SqlOperator> operatorList,
		SqlNameMatcher nameMatcher) {
	if (opName.isStar()) {
		return;
	}

	final UnresolvedIdentifier identifier = UnresolvedIdentifier.of(opName.names);

	functionCatalog.lookupFunction(identifier)
		.flatMap(lookupResult ->
			convertToSqlFunction(
				category,
				lookupResult.getFunctionIdentifier(),
				lookupResult.getFunctionDefinition()))
		.ifPresent(operatorList::add);
}
 
Example #9
Source File: ListSqlOperatorTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void lookupOperatorOverloads(SqlIdentifier opName,
    SqlFunctionCategory category,
    SqlSyntax syntax,
    List<SqlOperator> operatorList,
    SqlNameMatcher nameMatcher) {
  for (SqlOperator operator : this.operatorList) {
    if (operator.getSyntax() != syntax) {
      continue;
    }
    if (!opName.isSimple()
        || !nameMatcher.matches(operator.getName(), opName.getSimple())) {
      continue;
    }
    if (category != null
        && category != category(operator)
        && !category.isUserDefinedNotSpecificFunction()) {
      continue;
    }
    operatorList.add(operator);
  }
}
 
Example #10
Source File: FlinkSqlOperatorTable.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void lookupOperatorOverloads(
		SqlIdentifier opName,
		SqlFunctionCategory category,
		SqlSyntax syntax,
		List<SqlOperator> operatorList,
		SqlNameMatcher nameMatcher) {
	// set caseSensitive=false to make sure the behavior is same with before.
	super.lookupOperatorOverloads(opName, category, syntax, operatorList, SqlNameMatchers.withCaseSensitive(false));
}
 
Example #11
Source File: ReflectiveSqlOperatorTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Look up operators based on case-sensitiveness.
 */
private Collection<SqlOperator> lookUpOperators(String name, SqlSyntax syntax,
    SqlNameMatcher nameMatcher) {
  // Case sensitive only works for UDFs.
  // Always look up built-in operators case-insensitively. Even in sessions
  // with unquotedCasing=UNCHANGED and caseSensitive=true.
  if (nameMatcher.isCaseSensitive()
      && !(this instanceof SqlStdOperatorTable)) {
    return caseSensitiveOperators.get(new CaseSensitiveKey(name, syntax));
  } else {
    return caseInsensitiveOperators.get(new CaseInsensitiveKey(name, syntax));
  }
}
 
Example #12
Source File: ChainedSqlOperatorTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void lookupOperatorOverloads(SqlIdentifier opName,
    SqlFunctionCategory category, SqlSyntax syntax,
    List<SqlOperator> operatorList, SqlNameMatcher nameMatcher) {
  for (SqlOperatorTable table : tableList) {
    table.lookupOperatorOverloads(opName, category, syntax, operatorList,
        nameMatcher);
  }
}
 
Example #13
Source File: CalciteCatalogReader.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected CalciteCatalogReader(CalciteSchema rootSchema,
    SqlNameMatcher nameMatcher, List<List<String>> schemaPaths,
    RelDataTypeFactory typeFactory, CalciteConnectionConfig config) {
  this.rootSchema = Objects.requireNonNull(rootSchema);
  this.nameMatcher = nameMatcher;
  this.schemaPaths =
      Util.immutableCopy(Util.isDistinct(schemaPaths)
          ? schemaPaths
          : new LinkedHashSet<>(schemaPaths));
  this.typeFactory = typeFactory;
  this.config = config;
}
 
Example #14
Source File: CalciteCatalogReader.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void lookupOperatorOverloads(final SqlIdentifier opName,
    SqlFunctionCategory category,
    SqlSyntax syntax,
    List<SqlOperator> operatorList,
    SqlNameMatcher nameMatcher) {
  if (syntax != SqlSyntax.FUNCTION) {
    return;
  }

  final Predicate<Function> predicate;
  if (category == null) {
    predicate = function -> true;
  } else if (category.isTableFunction()) {
    predicate = function ->
        function instanceof TableMacro
            || function instanceof TableFunction;
  } else {
    predicate = function ->
        !(function instanceof TableMacro
            || function instanceof TableFunction);
  }
  getFunctionsFrom(opName.names)
      .stream()
      .filter(predicate)
      .map(function -> toOp(opName, function))
      .forEachOrdered(operatorList::add);
}
 
Example #15
Source File: CalciteCatalogReader.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected CalciteCatalogReader(CalciteSchema rootSchema,
    SqlNameMatcher nameMatcher, List<List<String>> schemaPaths,
    RelDataTypeFactory typeFactory, CalciteConnectionConfig config) {
  this.rootSchema = Objects.requireNonNull(rootSchema);
  this.nameMatcher = nameMatcher;
  this.schemaPaths =
      Util.immutableCopy(Util.isDistinct(schemaPaths)
          ? schemaPaths
          : new LinkedHashSet<>(schemaPaths));
  this.typeFactory = typeFactory;
  this.config = config;
}
 
Example #16
Source File: FlinkSqlOperatorTable.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void lookupOperatorOverloads(
		SqlIdentifier opName,
		SqlFunctionCategory category,
		SqlSyntax syntax,
		List<SqlOperator> operatorList,
		SqlNameMatcher nameMatcher) {
	// set caseSensitive=false to make sure the behavior is same with before.
	super.lookupOperatorOverloads(opName, category, syntax, operatorList, SqlNameMatchers.withCaseSensitive(false));
}
 
Example #17
Source File: SqlUtil.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Looks up all subject routines matching the given name and argument types.
 *
 * @param opTab       operator table to search
 * @param funcName    name of function being invoked
 * @param argTypes    argument types
 * @param argNames    argument names, or null if call by position
 * @param sqlSyntax   the SqlSyntax of the SqlOperator being looked up
 * @param sqlKind     the SqlKind of the SqlOperator being looked up
 * @param category    Category of routine to look up
 * @param nameMatcher Whether to look up the function case-sensitively
 * @param coerce      Whether to allow type coercion when do filter routine
 *                    by parameter types
 * @return list of matching routines
 * @see Glossary#SQL99 SQL:1999 Part 2 Section 10.4
 */
public static Iterator<SqlOperator> lookupSubjectRoutines(
    SqlOperatorTable opTab,
    SqlIdentifier funcName,
    List<RelDataType> argTypes,
    List<String> argNames,
    SqlSyntax sqlSyntax,
    SqlKind sqlKind,
    SqlFunctionCategory category,
    SqlNameMatcher nameMatcher,
    boolean coerce) {
  // start with all routines matching by name
  Iterator<SqlOperator> routines =
      lookupSubjectRoutinesByName(opTab, funcName, sqlSyntax, category,
          nameMatcher);

  // first pass:  eliminate routines which don't accept the given
  // number of arguments
  routines = filterRoutinesByParameterCount(routines, argTypes);

  // NOTE: according to SQL99, procedures are NOT overloaded on type,
  // only on number of arguments.
  if (category == SqlFunctionCategory.USER_DEFINED_PROCEDURE) {
    return routines;
  }

  // second pass:  eliminate routines which don't accept the given
  // argument types and parameter names if specified
  routines =
      filterRoutinesByParameterTypeAndName(sqlSyntax, routines, argTypes, argNames, coerce);

  // see if we can stop now; this is necessary for the case
  // of builtin functions where we don't have param type info,
  // or UDF whose operands can make type coercion.
  final List<SqlOperator> list = Lists.newArrayList(routines);
  routines = list.iterator();
  if (list.size() < 2 || coerce) {
    return routines;
  }

  // third pass:  for each parameter from left to right, eliminate
  // all routines except those with the best precedence match for
  // the given arguments
  routines = filterRoutinesByTypePrecedence(sqlSyntax, routines, argTypes, argNames);

  // fourth pass: eliminate routines which do not have the same
  // SqlKind as requested
  return filterOperatorRoutinesByKind(routines, sqlKind);
}
 
Example #18
Source File: CalciteCatalogReader.java    From calcite with Apache License 2.0 4 votes vote down vote up
public SqlNameMatcher nameMatcher() {
  return nameMatcher;
}
 
Example #19
Source File: LookupOperatorOverloadsTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
private void checkInternal(boolean caseSensitive) throws SQLException {
  final SqlNameMatcher nameMatcher =
      SqlNameMatchers.withCaseSensitive(caseSensitive);
  final String schemaName = "MySchema";
  final String funcName = "MyFUNC";
  final String anotherName = "AnotherFunc";

  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus schema = rootSchema.add(schemaName, new AbstractSchema());
    final TableFunction table = TableFunctionImpl.create(Smalls.MAZE_METHOD);
    schema.add(funcName, table);
    schema.add(anotherName, table);
    final TableFunction table2 =
        TableFunctionImpl.create(Smalls.MAZE3_METHOD);
    schema.add(funcName, table2);

    final CalciteServerStatement statement =
        connection.createStatement().unwrap(CalciteServerStatement.class);
    final CalcitePrepare.Context prepareContext =
        statement.createPrepareContext();
    final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
    CalciteCatalogReader reader =
        new CalciteCatalogReader(prepareContext.getRootSchema(),
            ImmutableList.of(), typeFactory, prepareContext.config());

    final List<SqlOperator> operatorList = new ArrayList<>();
    SqlIdentifier myFuncIdentifier =
        new SqlIdentifier(Lists.newArrayList(schemaName, funcName), null,
            SqlParserPos.ZERO, null);
    reader.lookupOperatorOverloads(myFuncIdentifier,
        SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION, SqlSyntax.FUNCTION,
        operatorList, nameMatcher);
    checkFunctionType(2, funcName, operatorList);

    operatorList.clear();
    reader.lookupOperatorOverloads(myFuncIdentifier,
        SqlFunctionCategory.USER_DEFINED_FUNCTION, SqlSyntax.FUNCTION,
        operatorList, nameMatcher);
    checkFunctionType(0, null, operatorList);

    operatorList.clear();
    SqlIdentifier anotherFuncIdentifier =
        new SqlIdentifier(Lists.newArrayList(schemaName, anotherName), null,
            SqlParserPos.ZERO, null);
    reader.lookupOperatorOverloads(anotherFuncIdentifier,
        SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION, SqlSyntax.FUNCTION,
        operatorList, nameMatcher);
    checkFunctionType(1, anotherName, operatorList);
  }
}
 
Example #20
Source File: MockCatalogReader.java    From calcite with Apache License 2.0 4 votes vote down vote up
public SqlNameMatcher nameMatcher() {
  return nameMatcher;
}
 
Example #21
Source File: ReflectiveSqlOperatorTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
public void lookupOperatorOverloads(SqlIdentifier opName,
    SqlFunctionCategory category, SqlSyntax syntax,
    List<SqlOperator> operatorList, SqlNameMatcher nameMatcher) {
  // NOTE jvs 3-Mar-2005:  ignore category until someone cares

  String simpleName;
  if (opName.names.size() > 1) {
    if (opName.names.get(opName.names.size() - 2).equals(IS_NAME)) {
      // per SQL99 Part 2 Section 10.4 Syntax Rule 7.b.ii.1
      simpleName = Util.last(opName.names);
    } else {
      return;
    }
  } else {
    simpleName = opName.getSimple();
  }

  final Collection<SqlOperator> list =
      lookUpOperators(simpleName, syntax, nameMatcher);
  if (list.isEmpty()) {
    return;
  }
  for (SqlOperator op : list) {
    if (op.getSyntax() == syntax) {
      operatorList.add(op);
    } else if (syntax == SqlSyntax.FUNCTION
        && op instanceof SqlFunction) {
      // this special case is needed for operators like CAST,
      // which are treated as functions but have special syntax
      operatorList.add(op);
    }
  }

  // REVIEW jvs 1-Jan-2005:  why is this extra lookup required?
  // Shouldn't it be covered by search above?
  switch (syntax) {
  case BINARY:
  case PREFIX:
  case POSTFIX:
    for (SqlOperator extra
        : lookUpOperators(simpleName, syntax, nameMatcher)) {
      // REVIEW: should only search operators added during this method?
      if (extra != null && !operatorList.contains(extra)) {
        operatorList.add(extra);
      }
    }
    break;
  }
}
 
Example #22
Source File: SamzaSqlUdfOperatorTable.java    From samza with Apache License 2.0 4 votes vote down vote up
@Override
public void lookupOperatorOverloads(SqlIdentifier opName, SqlFunctionCategory category, SqlSyntax syntax,
    List<SqlOperator> operatorList, SqlNameMatcher nameMatcher) {
  operatorTable.lookupOperatorOverloads(opName, category, syntax, operatorList, nameMatcher);
}
 
Example #23
Source File: TestSQLAnalyzer.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public SqlNameMatcher nameMatcher() {
  return SqlNameMatchers.withCaseSensitive(caseSensitive);
}
 
Example #24
Source File: DremioCatalogReader.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public SqlNameMatcher nameMatcher() {
  return SqlNameMatchers.withCaseSensitive(false);
}
 
Example #25
Source File: CalciteCatalogReader.java    From Bats with Apache License 2.0 4 votes vote down vote up
public SqlNameMatcher nameMatcher() {
  return nameMatcher;
}
 
Example #26
Source File: SqlOperatorTable.java    From calcite with Apache License 2.0 2 votes vote down vote up
/**
 * Retrieves a list of operators with a given name and syntax. For example,
 * by passing SqlSyntax.Function, the returned list is narrowed to only
 * matching SqlFunction objects.
 *
 * @param opName   name of operator
 * @param category function category to look up, or null for any matching
 *                 operator
 * @param syntax   syntax type of operator
 * @param operatorList mutable list to which to append matches
 * @param nameMatcher Name matcher
 */
void lookupOperatorOverloads(SqlIdentifier opName,
    SqlFunctionCategory category,
    SqlSyntax syntax,
    List<SqlOperator> operatorList,
    SqlNameMatcher nameMatcher);