Java Code Examples for org.apache.calcite.sql.SqlOperatorTable

The following examples show how to use org.apache.calcite.sql.SqlOperatorTable. These examples are extracted from open source projects. 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 Project: Bats   Source File: CalciteConnectionConfigImpl.java    License: 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 2
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: 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 Project: flink   Source File: SqlValidatorImpl.java    License: 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 4
Source Project: flink   Source File: PlanningConfigurationBuilder.java    License: 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 5
Source Project: marble   Source File: TableEnv.java    License: 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 6
Source Project: flink   Source File: PlanningConfigurationBuilder.java    License: 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 7
Source Project: calcite   Source File: CalciteCatalogReader.java    License: 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 8
Source Project: calcite   Source File: SqlTestFactory.java    License: 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 9
Source Project: Bats   Source File: BatsOptimizerTest.java    License: 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 10
Source Project: Bats   Source File: SqlValidatorUtil.java    License: 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,
    SqlConformance conformance) {
  return new SqlValidatorImpl(opTab, catalogReader, typeFactory,
      conformance);
}
 
Example 11
Source Project: Bats   Source File: SqlValidatorUtil.java    License: 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 12
Source Project: Bats   Source File: ChainedSqlOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
public void lookupOperatorOverloads(SqlIdentifier opName,
    SqlFunctionCategory category, SqlSyntax syntax,
    List<SqlOperator> operatorList) {
  for (SqlOperatorTable table : tableList) {
    table.lookupOperatorOverloads(opName, category, syntax, operatorList);
  }
}
 
Example 13
Source Project: calcite   Source File: SqlValidatorFeatureTest.java    License: Apache License 2.0 5 votes vote down vote up
protected FeatureValidator(
    SqlOperatorTable opTab,
    SqlValidatorCatalogReader catalogReader,
    RelDataTypeFactory typeFactory,
    Config config) {
  super(opTab, catalogReader, typeFactory, config);
}
 
Example 14
Source Project: calcite   Source File: SqlToRelTestBase.java    License: 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 15
Source Project: flink   Source File: PlannerContext.java    License: 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 16
Source Project: Mycat2   Source File: PlannerImpl.java    License: 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 17
Source Project: dremio-oss   Source File: SqlValidatorImpl.java    License: 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 18
Source Project: dremio-oss   Source File: SQLAnalyzerFactory.java    License: 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 19
Source Project: attic-apex-malhar   Source File: SQLExecEnvironment.java    License: 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 20
Source Project: streamline   Source File: StreamlineSqlImpl.java    License: 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 21
Source Project: streamline   Source File: TestCompilerUtils.java    License: 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 22
Source Project: flink   Source File: PlannerContext.java    License: 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 23
Source Project: flink   Source File: PlannerContext.java    License: 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 24
Source Project: flink   Source File: FlinkDDLDataTypeTest.java    License: 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 25
Source Project: calcite   Source File: PlannerImpl.java    License: 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 26
Source Project: calcite   Source File: SqlValidatorUtil.java    License: 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 27
Source Project: calcite   Source File: SqlValidatorUtil.java    License: 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 28
Source Project: calcite   Source File: SqlValidatorUtil.java    License: 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 29
Source Project: calcite   Source File: SqlValidatorUtil.java    License: 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 30
Source Project: calcite   Source File: SqlLibraryOperatorTableFactory.java    License: 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);
  }
}