org.apache.calcite.sql.SqlOperatorTable Java Examples

The following examples show how to use org.apache.calcite.sql.SqlOperatorTable. 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: SqlTestFactory.java    From calcite with Apache License 2.0 6 votes vote down vote up
protected SqlTestFactory(ImmutableMap<String, Object> options,
    MockCatalogReaderFactory catalogReaderFactory,
    ValidatorFactory validatorFactory) {
  this.options = options;
  this.catalogReaderFactory = catalogReaderFactory;
  this.validatorFactory = validatorFactory;
  this.operatorTable = Suppliers.memoize(
      () -> createOperatorTable((SqlOperatorTable) options.get("operatorTable")));
  this.typeFactory = Suppliers.memoize(
      () -> createTypeFactory((SqlConformance) options.get("conformance")));
  Boolean caseSensitive = (Boolean) options.get("caseSensitive");
  this.catalogReader = Suppliers.memoize(
      () -> catalogReaderFactory.create(typeFactory.get(), caseSensitive).init());
  this.parserConfig = Suppliers.memoize(
      () -> createParserConfig(options));
}
 
Example #2
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a validator.
 *
 * @param opTab         Operator table
 * @param catalogReader Catalog reader
 * @param typeFactory   Type factory
 * @param conformance   Compatibility mode
 */
protected SqlValidatorImpl(
	SqlOperatorTable opTab,
	SqlValidatorCatalogReader catalogReader,
	RelDataTypeFactory typeFactory,
	SqlConformance conformance) {
	this.opTab = Objects.requireNonNull(opTab);
	this.catalogReader = Objects.requireNonNull(catalogReader);
	this.typeFactory = Objects.requireNonNull(typeFactory);
	this.conformance = Objects.requireNonNull(conformance);

	unknownType = typeFactory.createUnknownType();
	booleanType = typeFactory.createSqlType(SqlTypeName.BOOLEAN);

	rewriteCalls = true;
	expandColumnReferences = true;
	aggFinder = new AggFinder(opTab, false, true, false, null);
	aggOrOverFinder = new AggFinder(opTab, true, true, false, null);
	overFinder = new AggFinder(opTab, true, false, false, aggOrOverFinder);
	groupFinder = new AggFinder(opTab, false, false, true, null);
	aggOrOverOrGroupFinder = new AggFinder(opTab, true, true, true, null);
}
 
Example #3
Source File: PlanningConfigurationBuilder.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the operator table for this environment including a custom Calcite configuration.
 */
private SqlOperatorTable getSqlOperatorTable(CalciteConfig calciteConfig, FunctionCatalog functionCatalog) {
	SqlOperatorTable baseOperatorTable = ChainedSqlOperatorTable.of(
		new BasicOperatorTable(),
		new FunctionCatalogOperatorTable(functionCatalog, typeFactory)
	);

	return JavaScalaConversionUtil.toJava(calciteConfig.sqlOperatorTable()).map(operatorTable -> {
			if (calciteConfig.replacesSqlOperatorTable()) {
				return operatorTable;
			} else {
				return ChainedSqlOperatorTable.of(baseOperatorTable, operatorTable);
			}
		}
	).orElse(baseOperatorTable);
}
 
Example #4
Source File: CalciteConnectionConfigImpl.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static void operatorTable(String s,
      Collection<SqlOperatorTable> tables) {
  switch (s) {
  case "standard":
    tables.add(SqlStdOperatorTable.instance());
    return;
  case "oracle":
    tables.add(OracleSqlOperatorTable.instance());
    return;
  case "spatial":
    tables.add(
        CalciteCatalogReader.operatorTable(GeoFunctions.class.getName()));
    return;
  default:
    throw new IllegalArgumentException("Unknown operator table: " + s);
  }
}
 
Example #5
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a validator.
 *
 * @param opTab         Operator table
 * @param catalogReader Catalog reader
 * @param typeFactory   Type factory
 * @param conformance   Compatibility mode
 */
protected SqlValidatorImpl(
	SqlOperatorTable opTab,
	SqlValidatorCatalogReader catalogReader,
	RelDataTypeFactory typeFactory,
	SqlConformance conformance) {
	this.opTab = Objects.requireNonNull(opTab);
	this.catalogReader = Objects.requireNonNull(catalogReader);
	this.typeFactory = Objects.requireNonNull(typeFactory);
	this.conformance = Objects.requireNonNull(conformance);

	unknownType = typeFactory.createUnknownType();
	booleanType = typeFactory.createSqlType(SqlTypeName.BOOLEAN);

	rewriteCalls = true;
	expandColumnReferences = true;
	final SqlNameMatcher nameMatcher = catalogReader.nameMatcher();
	aggFinder = new AggFinder(opTab, false, true, false, null, nameMatcher);
	aggOrOverFinder = new AggFinder(opTab, true, true, false, null, nameMatcher);
	overFinder = new AggFinder(opTab, true, false, false, aggOrOverFinder, nameMatcher);
	groupFinder = new AggFinder(opTab, false, false, true, null, nameMatcher);
	aggOrOverOrGroupFinder = new AggFinder(opTab, true, true, true, null, nameMatcher);
}
 
Example #6
Source File: CalciteCatalogReader.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Creates an operator table that contains functions in the given class.
 *
 * @see ModelHandler#addFunctions */
public static SqlOperatorTable operatorTable(String className) {
  // Dummy schema to collect the functions
  final CalciteSchema schema =
      CalciteSchema.createRootSchema(false, false);
  ModelHandler.addFunctions(schema.plus(), null, ImmutableList.of(),
      className, "*", true);

  // The following is technical debt; see [CALCITE-2082] Remove
  // RelDataTypeFactory argument from SqlUserDefinedAggFunction constructor
  final SqlTypeFactoryImpl typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);

  final ListSqlOperatorTable table = new ListSqlOperatorTable();
  for (String name : schema.getFunctionNames()) {
    for (Function function : schema.getFunctions(name, true)) {
      final SqlIdentifier id = new SqlIdentifier(name, SqlParserPos.ZERO);
      table.add(
          toOp(typeFactory, id, function));
    }
  }
  return table;
}
 
Example #7
Source File: PlanningConfigurationBuilder.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the operator table for this environment including a custom Calcite configuration.
 */
private SqlOperatorTable getSqlOperatorTable(CalciteConfig calciteConfig, FunctionCatalog functionCatalog) {
	SqlOperatorTable baseOperatorTable = ChainedSqlOperatorTable.of(
		new BasicOperatorTable(),
		new FunctionCatalogOperatorTable(functionCatalog, typeFactory)
	);

	return JavaScalaConversionUtil.toJava(calciteConfig.sqlOperatorTable()).map(operatorTable -> {
			if (calciteConfig.replacesSqlOperatorTable()) {
				return operatorTable;
			} else {
				return ChainedSqlOperatorTable.of(baseOperatorTable, operatorTable);
			}
		}
	).orElse(baseOperatorTable);
}
 
Example #8
Source File: TableEnv.java    From marble with Apache License 2.0 6 votes vote down vote up
private FrameworkConfig createFrameworkConfig(
    SqlParser.Config sqlParserConfig, SqlOperatorTable sqlOperatorTable,
    SqlRexConvertletTable convertletTable,
    CalciteConnectionConfig calciteConnectionConfig,
    RelDataTypeSystem relDataTypeSystem, RexExecutor rexExecutor) {
  return Frameworks
      .newConfigBuilder()
      .defaultSchema(rootSchema)
      .parserConfig(sqlParserConfig)
      .operatorTable(sqlOperatorTable)
      .convertletTable(convertletTable)
      .typeSystem(relDataTypeSystem)
      .executor(rexExecutor)
      .context(Contexts.of(calciteConnectionConfig))
      .build();
}
 
Example #9
Source File: SqlValidatorImpl.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected SqlValidatorImpl(
    FlattenOpCounter flattenCount,
    SqlOperatorTable opTab,
    SqlValidatorCatalogReader catalogReader,
    RelDataTypeFactory typeFactory,
    SqlConformance conformance) {
  super(opTab, catalogReader, typeFactory, conformance);
  this.flattenCount = flattenCount;
}
 
Example #10
Source File: PlannerTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testValidateUserDefinedAggregate() throws Exception {
  final SqlStdOperatorTable stdOpTab = SqlStdOperatorTable.instance();
  SqlOperatorTable opTab =
      ChainedSqlOperatorTable.of(stdOpTab,
          new ListSqlOperatorTable(
              ImmutableList.of(new MyCountAggFunction())));
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .defaultSchema(
          CalciteAssert.addSchema(rootSchema, CalciteAssert.SchemaSpec.HR))
      .operatorTable(opTab)
      .build();
  final Planner planner = Frameworks.getPlanner(config);
  SqlNode parse =
      planner.parse("select \"deptno\", my_count(\"empid\") from \"emps\"\n"
          + "group by \"deptno\"");
  assertThat(Util.toLinux(parse.toString()),
      equalTo("SELECT `deptno`, `MY_COUNT`(`empid`)\n"
          + "FROM `emps`\n"
          + "GROUP BY `deptno`"));

  // MY_COUNT is recognized as an aggregate function, and therefore it is OK
  // that its argument empid is not in the GROUP BY clause.
  SqlNode validate = planner.validate(parse);
  assertThat(validate, notNullValue());

  // The presence of an aggregate function in the SELECT clause causes it
  // to become an aggregate query. Non-aggregate expressions become illegal.
  planner.close();
  planner.reset();
  parse = planner.parse("select \"deptno\", count(1) from \"emps\"");
  try {
    validate = planner.validate(parse);
    fail("expected exception, got " + validate);
  } catch (ValidationException e) {
    assertThat(e.getCause().getCause().getMessage(),
        containsString("Expression 'deptno' is not being grouped"));
  }
}
 
Example #11
Source File: PlannerImpl.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private SqlValidator createSqlValidator(CalciteCatalogReader catalogReader) {
    final SqlOperatorTable opTab =
            ChainedSqlOperatorTable.of(operatorTable, catalogReader);
    return new CalciteSqlValidator(opTab,
            catalogReader,
            typeFactory,
            sqlValidatorConfig
                    .withDefaultNullCollation(connectionConfig.defaultNullCollation())
                    .withLenientOperatorLookup(connectionConfig.lenientOperatorLookup())
                    .withSqlConformance(connectionConfig.conformance())
                    .withIdentifierExpansion(true));
}
 
Example #12
Source File: SQLAnalyzerFactory.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method to create the SQLAnalyzer using the appropriate implementation of SqlValidatorWithHints.
 *
 * If createForSqlSuggestions is true, construct a SqlAdvisorValidator instance,
 * otherwise construct a SqlValidatorImpl instance. Inject this into the constructor
 * for a SQLAnalyzer object.
 *
 * @param username
 * @param sabotContext
 * @param context
 * @param createForSqlSuggestions
 * @return SQLAnalyzer instance
 */
public static SQLAnalyzer createSQLAnalyzer(final String username,
                                            final SabotContext sabotContext,
                                            final List<String> context,
                                            final boolean createForSqlSuggestions,
                                            ProjectOptionManager projectOptionManager) {
  final ViewExpansionContext viewExpansionContext = new ViewExpansionContext(username);
  final OptionManager optionManager = OptionManagerWrapper.Builder.newBuilder()
    .withOptionManager(new DefaultOptionManager(sabotContext.getOptionValidatorListing()))
    .withOptionManager(new EagerCachingOptionManager(projectOptionManager))
    .withOptionManager(new QueryOptionManager(sabotContext.getOptionValidatorListing()))
    .build();
  final NamespaceKey defaultSchemaPath = context == null ? null : new NamespaceKey(context);

  final SchemaConfig newSchemaConfig = SchemaConfig.newBuilder(username)
    .defaultSchema(defaultSchemaPath)
    .optionManager(optionManager)
    .setViewExpansionContext(viewExpansionContext)
    .build();

  Catalog catalog = sabotContext.getCatalogService()
      .getCatalog(MetadataRequestOptions.of(newSchemaConfig));
  JavaTypeFactory typeFactory = JavaTypeFactoryImpl.INSTANCE;
  DremioCatalogReader catalogReader = new DremioCatalogReader(catalog, typeFactory);

  FunctionImplementationRegistry functionImplementationRegistry = optionManager.getOption
    (PlannerSettings.ENABLE_DECIMAL_V2_KEY).getBoolVal() ? sabotContext.getDecimalFunctionImplementationRegistry()
      : sabotContext.getFunctionImplementationRegistry();
  OperatorTable opTable = new OperatorTable(functionImplementationRegistry);
  SqlOperatorTable chainedOpTable =  new ChainedSqlOperatorTable(ImmutableList.<SqlOperatorTable>of(opTable, catalogReader));

  // Create the appropriate implementation depending on intended use of the validator.
  SqlValidatorWithHints validator =
    createForSqlSuggestions ?
      new SqlAdvisorValidator(chainedOpTable, catalogReader, typeFactory, DremioSqlConformance.INSTANCE) :
      SqlValidatorUtil.newValidator(chainedOpTable, catalogReader, typeFactory, DremioSqlConformance.INSTANCE);

  return new SQLAnalyzer(validator);
}
 
Example #13
Source File: SqlToRelTestBase.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an operator table.
 *
 * @return New operator table
 */
protected SqlOperatorTable createOperatorTable() {
  final MockSqlOperatorTable opTab =
      new MockSqlOperatorTable(SqlStdOperatorTable.instance());
  MockSqlOperatorTable.addRamp(opTab);
  return opTab;
}
 
Example #14
Source File: SqlValidatorUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method for {@link SqlValidator}, with default conformance.
 */
@Deprecated // to be removed before 2.0
public static SqlValidatorWithHints newValidator(
    SqlOperatorTable opTab,
    SqlValidatorCatalogReader catalogReader,
    RelDataTypeFactory typeFactory) {
  return newValidator(opTab, catalogReader, typeFactory,
      SqlConformanceEnum.DEFAULT);
}
 
Example #15
Source File: SQLExecEnvironment.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
/**
 * Method method build a calcite framework configuration for calcite to parse SQL and generate relational tree
 * out of it.
 * @return FrameworkConfig
 */
private FrameworkConfig buildFrameWorkConfig()
{
  List<SqlOperatorTable> sqlOperatorTables = new ArrayList<>();
  sqlOperatorTables.add(SqlStdOperatorTable.instance());
  sqlOperatorTables
    .add(new CalciteCatalogReader(CalciteSchema.from(schema), false, Collections.<String>emptyList(), typeFactory));
  return Frameworks.newConfigBuilder().defaultSchema(schema)
    .parserConfig(SqlParser.configBuilder().setLex(Lex.MYSQL).build())
    .operatorTable(new ChainedSqlOperatorTable(sqlOperatorTables)).build();
}
 
Example #16
Source File: PlannerContext.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the operator table for this environment including a custom Calcite configuration.
 */
private SqlOperatorTable getSqlOperatorTable(CalciteConfig calciteConfig, FunctionCatalog functionCatalog) {
	return JavaScalaConversionUtil.toJava(calciteConfig.getSqlOperatorTable()).map(operatorTable -> {
				if (calciteConfig.replacesSqlOperatorTable()) {
					return operatorTable;
				} else {
					return ChainedSqlOperatorTable.of(getBuiltinSqlOperatorTable(functionCatalog), operatorTable);
				}
			}
	).orElseGet(() -> getBuiltinSqlOperatorTable(functionCatalog));
}
 
Example #17
Source File: BatsOptimizerTest.java    From Bats with Apache License 2.0 5 votes vote down vote up
static Pair<SqlNode, SqlValidator> testSqlValidator() throws Exception {
    String sql = "select * from my_schema.test where f1=1 or f2=2 order by f3 limit 2";
    sql = "select * from test";
    sql = "select * from my_schema2.test2";
    sql = "select sum(f1),max(f2) from test";

    sql = "select t1.f1,sum(Distinct f1) as sumf1 from test as t1 "
            + "where f2>20 group by f1 having f1>10 order by f1 limit 2";
    // sql = "insert into test(f1,f2,f3) values(1,2,3)";
    // sql = "update test set f1=100 where f2>10";
    // sql = "delete from test where f2>10";
    SqlNode sqlNode = parse(sql);

    SqlOperatorTable opTab = SqlStdOperatorTable.instance();
    RelDataTypeFactory typeFactory = createJavaTypeFactory();
    SqlValidatorCatalogReader catalogReader = createCalciteCatalogReader(typeFactory);
    SqlConformance conformance = SqlConformanceEnum.DEFAULT;

    List<String> names = new ArrayList<>();
    names.add("my_schema");
    names.add("test");
    catalogReader.getTable(names);

    SqlValidator sqlValidator = SqlValidatorUtil.newValidator(opTab, catalogReader, typeFactory, conformance);
    sqlNode = sqlValidator.validate(sqlNode);
    // System.out.println(sqlNode);

    sql = "insert into test(f1,f2,f3) values(1,2,3)";
    // sqlNode = parse(sql);
    // sqlNode = sqlValidator.validate(sqlNode);

    return new Pair<>(sqlNode, sqlValidator);
}
 
Example #18
Source File: StreamlineSqlImpl.java    From streamline with Apache License 2.0 5 votes vote down vote up
private FrameworkConfig buildFrameWorkConfig() {
  if (hasUdf) {
    List<SqlOperatorTable> sqlOperatorTables = new ArrayList<>();
    sqlOperatorTables.add(SqlStdOperatorTable.instance());
    sqlOperatorTables.add(new CalciteCatalogReader(CalciteSchema.from(schema),
                                                   false,
                                                   Collections.<String>emptyList(), typeFactory));
    return Frameworks.newConfigBuilder().defaultSchema(schema)
            .operatorTable(new ChainedSqlOperatorTable(sqlOperatorTables)).build();
  } else {
    return Frameworks.newConfigBuilder().defaultSchema(schema).build();
  }
}
 
Example #19
Source File: TestCompilerUtils.java    From streamline with Apache License 2.0 5 votes vote down vote up
public static CalciteState sqlOverDummyTable(String sql)
        throws RelConversionException, ValidationException, SqlParseException {
    SchemaPlus schema = Frameworks.createRootSchema(true);
    JavaTypeFactory typeFactory = new JavaTypeFactoryImpl
            (RelDataTypeSystem.DEFAULT);
    StreamableTable streamableTable = new CompilerUtil.TableBuilderInfo(typeFactory)
            .field("ID", SqlTypeName.INTEGER)
            .field("NAME", typeFactory.createType(String.class))
            .field("ADDR", typeFactory.createType(String.class))
            .build();
    Table table = streamableTable.stream();
    schema.add("FOO", table);
    schema.add("BAR", table);
    schema.add("MYPLUS", ScalarFunctionImpl.create(MyPlus.class, "eval"));

    List<SqlOperatorTable> sqlOperatorTables = new ArrayList<>();
    sqlOperatorTables.add(SqlStdOperatorTable.instance());
    sqlOperatorTables.add(new CalciteCatalogReader(CalciteSchema.from(schema),
            false,
            Collections.<String>emptyList(), typeFactory));
    SqlOperatorTable chainedSqlOperatorTable = new ChainedSqlOperatorTable(sqlOperatorTables);
    FrameworkConfig config = Frameworks.newConfigBuilder().defaultSchema(
            schema).operatorTable(chainedSqlOperatorTable).build();
    Planner planner = Frameworks.getPlanner(config);
    SqlNode parse = planner.parse(sql);
    SqlNode validate = planner.validate(parse);
    RelNode tree = planner.convert(validate);
    System.out.println(RelOptUtil.toString(tree, SqlExplainLevel.ALL_ATTRIBUTES));
    return new CalciteState(schema, tree);
}
 
Example #20
Source File: PlannerContext.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the operator table for this environment including a custom Calcite configuration.
 */
private SqlOperatorTable getSqlOperatorTable(CalciteConfig calciteConfig) {
	return JavaScalaConversionUtil.<SqlOperatorTable>toJava(calciteConfig.getSqlOperatorTable()).map(operatorTable -> {
				if (calciteConfig.replacesSqlOperatorTable()) {
					return operatorTable;
				} else {
					return ChainedSqlOperatorTable.of(getBuiltinSqlOperatorTable(), operatorTable);
				}
			}
	).orElseGet(this::getBuiltinSqlOperatorTable);
}
 
Example #21
Source File: PlannerContext.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns builtin the operator table and external the operator for this environment.
 */
private SqlOperatorTable getBuiltinSqlOperatorTable() {
	return ChainedSqlOperatorTable.of(
			new FunctionCatalogOperatorTable(
					context.getFunctionCatalog(),
					context.getCatalogManager().getDataTypeFactory(),
					typeFactory),
			FlinkSqlOperatorTable.instance());
}
 
Example #22
Source File: FlinkDDLDataTypeTest.java    From flink with Apache License 2.0 5 votes vote down vote up
TestFactory(
		Map<String, Object> options,
		SqlTestFactory.MockCatalogReaderFactory catalogReaderFactory,
		SqlTestFactory.ValidatorFactory validatorFactory) {
	this.options = options;
	this.validatorFactory = validatorFactory;
	this.operatorTable =
		createOperatorTable((SqlOperatorTable) options.get("operatorTable"));
	this.typeFactory = createTypeFactory((SqlConformance) options.get("conformance"));
	Boolean caseSensitive = (Boolean) options.get("caseSensitive");
	this.catalogReader = catalogReaderFactory.create(typeFactory, caseSensitive).init();
	this.parserConfig = createParserConfig(options);
}
 
Example #23
Source File: PlannerImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
private SqlValidator createSqlValidator(CalciteCatalogReader catalogReader) {
  final SqlOperatorTable opTab =
      ChainedSqlOperatorTable.of(operatorTable, catalogReader);
  return new CalciteSqlValidator(opTab,
      catalogReader,
      typeFactory,
      sqlValidatorConfig
          .withDefaultNullCollation(connectionConfig.defaultNullCollation())
          .withLenientOperatorLookup(connectionConfig.lenientOperatorLookup())
          .withSqlConformance(connectionConfig.conformance())
          .withIdentifierExpansion(true));
}
 
Example #24
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method for {@link SqlValidator}.
 */
public static SqlValidatorWithHints newValidator(
    SqlOperatorTable opTab,
    SqlValidatorCatalogReader catalogReader,
    RelDataTypeFactory typeFactory,
    SqlValidator.Config config) {
  return new SqlValidatorImpl(opTab, catalogReader, typeFactory,
      config);
}
 
Example #25
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method for {@link SqlValidator}, with default conformance.
 */
@Deprecated // to be removed before 2.0
public static SqlValidatorWithHints newValidator(
    SqlOperatorTable opTab,
    SqlValidatorCatalogReader catalogReader,
    RelDataTypeFactory typeFactory) {
  return newValidator(opTab, catalogReader, typeFactory,
      SqlValidator.Config.DEFAULT);
}
 
Example #26
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Lookup sql function by sql identifier and function category.
 *
 * @param opTab    operator table to look up
 * @param funName  function name
 * @param funcType function category
 * @return A sql function if and only if there is one operator matches, else null
 */
public static SqlOperator lookupSqlFunctionByID(SqlOperatorTable opTab,
    SqlIdentifier funName,
    SqlFunctionCategory funcType) {
  if (funName.isSimple()) {
    final List<SqlOperator> list = new ArrayList<>();
    opTab.lookupOperatorOverloads(funName, funcType, SqlSyntax.FUNCTION, list,
        SqlNameMatchers.withCaseSensitive(funName.isComponentQuoted(0)));
    if (list.size() == 1) {
      return list.get(0);
    }
  }
  return null;
}
 
Example #27
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
 *
 * @param caseSensitive whether to match the catalog case-sensitively
 * @param operatorTable operator table
 * @param typeFactory   type factory
 * @param rowType       the table row type that has fields referenced by the expression
 * @param expr          the expression to validate
 * @return pair of a validated expression sql node and its data type,
 * usually a SqlUnresolvedFunction is converted to a resolved function
 */
public static Pair<SqlNode, RelDataType> validateExprWithRowType(
    boolean caseSensitive,
    SqlOperatorTable operatorTable,
    RelDataTypeFactory typeFactory,
    RelDataType rowType,
    SqlNode expr) {
  final String tableName = "_table_";
  final SqlSelect select0 = new SqlSelect(SqlParserPos.ZERO, null,
      new SqlNodeList(Collections.singletonList(expr), SqlParserPos.ZERO),
      new SqlIdentifier(tableName, SqlParserPos.ZERO),
      null, null, null, null, null, null, null, null);
  Prepare.CatalogReader catalogReader = createSingleTableCatalogReader(
      caseSensitive,
      tableName,
      typeFactory,
      rowType);
  SqlValidator validator = newValidator(operatorTable,
      catalogReader,
      typeFactory,
      SqlValidator.Config.DEFAULT);
  final SqlSelect select = (SqlSelect) validator.validate(select0);
  assert select.getSelectList().size() == 1
      : "Expression " + expr + " should be atom expression";
  final SqlNode node = select.getSelectList().get(0);
  final RelDataType nodeType = validator
      .getValidatedNodeType(select)
      .getFieldList()
      .get(0).getType();
  return Pair.of(node, nodeType);
}
 
Example #28
Source File: SqlLibraryOperatorTableFactory.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns a SQL operator table that contains operators in the given set of
 * libraries. */
public SqlOperatorTable getOperatorTable(Iterable<SqlLibrary> librarySet) {
  try {
    return cache.get(ImmutableSet.copyOf(librarySet));
  } catch (ExecutionException e) {
    Util.throwIfUnchecked(e.getCause());
    throw new RuntimeException("populating SqlOperatorTable for library "
        + librarySet, e);
  }
}
 
Example #29
Source File: Frameworks.java    From calcite with Apache License 2.0 5 votes vote down vote up
StdFrameworkConfig(Context context,
    SqlRexConvertletTable convertletTable,
    SqlOperatorTable operatorTable,
    ImmutableList<Program> programs,
    ImmutableList<RelTraitDef> traitDefs,
    SqlParser.Config parserConfig,
    SqlValidator.Config sqlValidatorConfig,
    SqlToRelConverter.Config sqlToRelConverterConfig,
    SchemaPlus defaultSchema,
    RelOptCostFactory costFactory,
    RelDataTypeSystem typeSystem,
    RexExecutor executor,
    boolean evolveLattice,
    SqlStatisticProvider statisticProvider,
    RelOptTable.ViewExpander viewExpander) {
  this.context = context;
  this.convertletTable = convertletTable;
  this.operatorTable = operatorTable;
  this.programs = programs;
  this.traitDefs = traitDefs;
  this.parserConfig = parserConfig;
  this.sqlValidatorConfig = sqlValidatorConfig;
  this.sqlToRelConverterConfig = sqlToRelConverterConfig;
  this.defaultSchema = defaultSchema;
  this.costFactory = costFactory;
  this.typeSystem = typeSystem;
  this.executor = executor;
  this.evolveLattice = evolveLattice;
  this.statisticProvider = statisticProvider;
  this.viewExpander = viewExpander;
}
 
Example #30
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);
  }
}