org.apache.calcite.sql2rel.SqlToRelConverter Java Examples

The following examples show how to use org.apache.calcite.sql2rel.SqlToRelConverter. 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: SqlToRelTestBase.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a TesterImpl.
 *
 * @param diffRepos Diff repository
 * @param enableDecorrelate Whether to decorrelate
 * @param enableTrim Whether to trim unused fields
 * @param enableExpand Whether to expand sub-queries
 * @param catalogReaderFactory Function to create catalog reader, or null
 * @param clusterFactory Called after a cluster has been created
 */
protected TesterImpl(DiffRepository diffRepos, boolean enableDecorrelate,
    boolean enableTrim, boolean enableExpand,
    boolean enableLateDecorrelate,
    boolean enableTypeCoercion,
    SqlTestFactory.MockCatalogReaderFactory
        catalogReaderFactory,
    Function<RelOptCluster, RelOptCluster> clusterFactory) {
  this(diffRepos, enableDecorrelate, enableTrim, enableExpand,
      enableLateDecorrelate,
      enableTypeCoercion,
      catalogReaderFactory,
      clusterFactory,
      SqlToRelConverter.Config.DEFAULT,
      SqlConformanceEnum.DEFAULT,
      Contexts.empty());
}
 
Example #2
Source File: SqlToRelTestBase.java    From calcite with Apache License 2.0 6 votes vote down vote up
protected TesterImpl(DiffRepository diffRepos, boolean enableDecorrelate,
    boolean enableTrim, boolean enableExpand, boolean enableLateDecorrelate,
    boolean enableTypeCoercion,
    SqlTestFactory.MockCatalogReaderFactory catalogReaderFactory,
    Function<RelOptCluster, RelOptCluster> clusterFactory,
    SqlToRelConverter.Config config, SqlConformance conformance,
    Context context) {
  this.diffRepos = diffRepos;
  this.enableDecorrelate = enableDecorrelate;
  this.enableTrim = enableTrim;
  this.enableExpand = enableExpand;
  this.enableLateDecorrelate = enableLateDecorrelate;
  this.enableTypeCoercion = enableTypeCoercion;
  this.catalogReaderFactory = catalogReaderFactory;
  this.clusterFactory = clusterFactory;
  this.config = config;
  this.conformance = conformance;
  this.context = context;
}
 
Example #3
Source File: SqlToRelTestBase.java    From calcite with Apache License 2.0 6 votes vote down vote up
protected SqlToRelConverter createSqlToRelConverter(
    final SqlValidator validator,
    final Prepare.CatalogReader catalogReader,
    final RelDataTypeFactory typeFactory,
    final SqlToRelConverter.Config config) {
  final RexBuilder rexBuilder = new RexBuilder(typeFactory);
  RelOptCluster cluster =
      RelOptCluster.create(getPlanner(), rexBuilder);
  if (clusterFactory != null) {
    cluster = clusterFactory.apply(cluster);
  }
  RelOptTable.ViewExpander viewExpander =
      new MockViewExpander(validator, catalogReader, cluster, config);
  return new SqlToRelConverter(viewExpander, validator, catalogReader, cluster,
      StandardConvertletTable.INSTANCE, config);
}
 
Example #4
Source File: AbstractMaterializedViewTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private RelNode toRel(RelOptCluster cluster, SchemaPlus rootSchema,
    SchemaPlus defaultSchema, String sql) throws SqlParseException {
  final SqlParser parser = SqlParser.create(sql, SqlParser.Config.DEFAULT);
  final SqlNode parsed = parser.parseStmt();

  final CalciteCatalogReader catalogReader = new CalciteCatalogReader(
      CalciteSchema.from(rootSchema),
      CalciteSchema.from(defaultSchema).path(null),
      new JavaTypeFactoryImpl(), new CalciteConnectionConfigImpl(new Properties()));

  final SqlValidator validator = new ValidatorForTest(SqlStdOperatorTable.instance(),
      catalogReader, new JavaTypeFactoryImpl(), SqlConformanceEnum.DEFAULT);
  final SqlNode validated = validator.validate(parsed);
  final SqlToRelConverter.Config config = SqlToRelConverter.configBuilder()
      .withTrimUnusedFields(true)
      .withExpand(true)
      .withDecorrelationEnabled(true)
      .build();
  final SqlToRelConverter converter = new SqlToRelConverter(
      (rowType, queryString, schemaPath, viewPath) -> {
        throw new UnsupportedOperationException("cannot expand view");
      }, validator, catalogReader, cluster, StandardConvertletTable.INSTANCE, config);
  return converter.convertQuery(validated, false, true).rel;
}
 
Example #5
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public RelRoot expandView(RelDataType rowType, String queryString,
    List<String> schemaPath, List<String> viewPath) {
  expansionDepth++;

  SqlParser parser = prepare.createParser(queryString);
  SqlNode sqlNode;
  try {
    sqlNode = parser.parseQuery();
  } catch (SqlParseException e) {
    throw new RuntimeException("parse failed", e);
  }
  // View may have different schema path than current connection.
  final CatalogReader catalogReader =
      this.catalogReader.withSchemaPath(schemaPath);
  SqlValidator validator = createSqlValidator(catalogReader);
  final SqlToRelConverter.Config config = SqlToRelConverter.configBuilder()
          .withTrimUnusedFields(true).build();
  SqlToRelConverter sqlToRelConverter =
      getSqlToRelConverter(validator, catalogReader, config);
  RelRoot root =
      sqlToRelConverter.convertQuery(sqlNode, true, false);

  --expansionDepth;
  return root;
}
 
Example #6
Source File: SqlToRelConverterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-2323">[CALCITE-2323]
 * Validator should allow alternative nullCollations for ORDER BY in
 * OVER</a>. */
@Test void testUserDefinedOrderByOver() {
  String sql = "select deptno,\n"
      + "  rank() over(partition by empno order by deptno)\n"
      + "from emp\n"
      + "order by row_number() over(partition by empno order by deptno)";
  Properties properties = new Properties();
  properties.setProperty(
      CalciteConnectionProperty.DEFAULT_NULL_COLLATION.camelName(),
      NullCollation.LOW.name());
  CalciteConnectionConfigImpl connectionConfig =
      new CalciteConnectionConfigImpl(properties);
  TesterImpl tester = new TesterImpl(getDiffRepos(), false, false, true, false, true,
      null, null, SqlToRelConverter.Config.DEFAULT,
      SqlConformanceEnum.DEFAULT, Contexts.of(connectionConfig));
  sql(sql).with(tester).ok();
}
 
Example #7
Source File: CalciteMaterializer.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Populates a materialization record, converting a table path
 * (essentially a list of strings, like ["hr", "sales"]) into a table object
 * that can be used in the planning process. */
void populate(Materialization materialization) {
  SqlParser parser = SqlParser.create(materialization.sql);
  SqlNode node;
  try {
    node = parser.parseStmt();
  } catch (SqlParseException e) {
    throw new RuntimeException("parse failed", e);
  }
  final SqlToRelConverter.Config config = SqlToRelConverter.configBuilder()
      .withTrimUnusedFields(true).build();
  SqlToRelConverter sqlToRelConverter2 =
      getSqlToRelConverter(getSqlValidator(), catalogReader, config);

  RelRoot root = sqlToRelConverter2.convertQuery(node, true, true);
  materialization.queryRel = trimUnusedFields(root).rel;

  // Identify and substitute a StarTable in queryRel.
  //
  // It is possible that no StarTables match. That is OK, but the
  // materialization patterns that are recognized will not be as rich.
  //
  // It is possible that more than one StarTable matches. TBD: should we
  // take the best (whatever that means), or all of them?
  useStar(schema, materialization);

  RelOptTable table =
      this.catalogReader.getTable(materialization.materializedTable.path());
  materialization.tableRel = sqlToRelConverter2.toRel(table, ImmutableList.of());
}
 
Example #8
Source File: SqlToRelTestBase.java    From calcite with Apache License 2.0 5 votes vote down vote up
public TesterImpl withConfig(SqlToRelConverter.Config config) {
  return this.config == config
      ? this
      : new TesterImpl(diffRepos, enableDecorrelate, enableTrim,
          enableExpand, enableLateDecorrelate, enableTypeCoercion, catalogReaderFactory,
          clusterFactory, config, conformance, context);
}
 
Example #9
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 #10
Source File: Frameworks.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a ConfigBuilder, initializing to defaults. */
private ConfigBuilder() {
  convertletTable = StandardConvertletTable.INSTANCE;
  operatorTable = SqlStdOperatorTable.instance();
  programs = ImmutableList.of();
  context = Contexts.empty();
  parserConfig = SqlParser.Config.DEFAULT;
  sqlValidatorConfig = SqlValidator.Config.DEFAULT;
  sqlToRelConverterConfig = SqlToRelConverter.Config.DEFAULT;
  typeSystem = RelDataTypeSystem.DEFAULT;
  evolveLattice = false;
  statisticProvider = QuerySqlStatisticProvider.SILENT_CACHING_INSTANCE;
}
 
Example #11
Source File: SqlToRelTestBase.java    From calcite with Apache License 2.0 5 votes vote down vote up
MockViewExpander(
    SqlValidator validator,
    Prepare.CatalogReader catalogReader,
    RelOptCluster cluster,
    SqlToRelConverter.Config config) {
  this.validator = validator;
  this.catalogReader = catalogReader;
  this.cluster = cluster;
  this.config = config;
}
 
Example #12
Source File: Prepare.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Walks over a tree of relational expressions, replacing each
 * {@link org.apache.calcite.rel.RelNode} with a 'slimmed down' relational
 * expression that projects
 * only the columns required by its consumer.
 *
 * @param root Root of relational expression tree
 * @return Trimmed relational expression
 */
protected RelRoot trimUnusedFields(RelRoot root) {
  final SqlToRelConverter.Config config = SqlToRelConverter.configBuilder()
      .withTrimUnusedFields(shouldTrim(root.rel))
      .withExpand(THREAD_EXPAND.get())
      .build();
  final SqlToRelConverter converter =
      getSqlToRelConverter(getSqlValidator(), catalogReader, config);
  final boolean ordered = !root.collation.getFieldCollations().isEmpty();
  final boolean dml = SqlKind.DML.contains(root.kind);
  return root.withRel(converter.trimUnusedFields(dml || ordered, root.rel));
}
 
Example #13
Source File: BatsOptimizerTest.java    From Bats with Apache License 2.0 5 votes vote down vote up
static RelNode testSqlToRelConverter(RelOptPlanner planner) throws Exception {
    RexBuilder rexBuilder = createRexBuilder();
    RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder);
    RelOptTable.ViewExpander viewExpander = ViewExpanders.simpleContext(cluster);

    Pair<SqlNode, SqlValidator> pair = testSqlValidator();
    SqlNode sqlNode = pair.left;
    SqlValidator validator = pair.right;
    CatalogReader catalogReader = createCalciteCatalogReader();
    SqlRexConvertletTable convertletTable = StandardConvertletTable.INSTANCE;
    SqlToRelConverter.Config config = SqlToRelConverter.Config.DEFAULT;
    // 不转换成EnumerableTableScan,而是LogicalTableScan
    config = SqlToRelConverter.configBuilder().withConvertTableAccess(false).build();

    SqlToRelConverter converter = new SqlToRelConverter(viewExpander, validator, catalogReader, cluster,
            convertletTable, config);

    boolean needsValidation = false;
    boolean top = false;
    RelRoot root = converter.convertQuery(sqlNode, needsValidation, top);
    RelNode relNode = root.rel;

    String plan = RelOptUtil.toString(relNode);
    System.out.println("Logical Plan:");
    System.out.println("------------------------------------------------------------------");
    System.out.println(plan);
    System.out.println();

    // testPrograms(root.rel);

    return relNode;
}
 
Example #14
Source File: SqlToRelTestBase.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public RelRoot expandView(RelDataType rowType, String queryString,
    List<String> schemaPath, List<String> viewPath) {
  try {
    SqlNode parsedNode = SqlParser.create(queryString).parseStmt();
    SqlNode validatedNode = validator.validate(parsedNode);
    SqlToRelConverter converter = new SqlToRelConverter(
        this, validator, catalogReader, cluster,
        StandardConvertletTable.INSTANCE, config);
    return converter.convertQuery(validatedNode, false, true);
  } catch (SqlParseException e) {
    throw new RuntimeException("Error happened while expanding view.", e);
  }
}
 
Example #15
Source File: PlannerImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public RelRoot expandView(RelDataType rowType, String queryString,
    List<String> schemaPath, List<String> viewPath) {
  if (planner == null) {
    ready();
  }
  SqlParser parser = SqlParser.create(queryString, parserConfig);
  SqlNode sqlNode;
  try {
    sqlNode = parser.parseQuery();
  } catch (SqlParseException e) {
    throw new RuntimeException("parse failed", e);
  }

  final CalciteCatalogReader catalogReader =
      createCatalogReader().withSchemaPath(schemaPath);
  final SqlValidator validator = createSqlValidator(catalogReader);

  final RexBuilder rexBuilder = createRexBuilder();
  final RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder);
  final SqlToRelConverter.Config config = SqlToRelConverter
      .configBuilder()
      .withConfig(sqlToRelConverterConfig)
      .withTrimUnusedFields(false)
      .build();
  final SqlToRelConverter sqlToRelConverter =
      new SqlToRelConverter(this, validator,
          catalogReader, cluster, convertletTable, config);

  final RelRoot root =
      sqlToRelConverter.convertQuery(sqlNode, true, false);
  final RelRoot root2 =
      root.withRel(sqlToRelConverter.flattenTypes(root.rel, true));
  final RelBuilder relBuilder =
      config.getRelBuilderFactory().create(cluster, null);
  return root2.withRel(
      RelDecorrelator.decorrelateQuery(root.rel, relBuilder));
}
 
Example #16
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override protected SqlToRelConverter getSqlToRelConverter(
    SqlValidator validator,
    CatalogReader catalogReader,
    SqlToRelConverter.Config config) {
  return new SqlToRelConverter(this, validator, catalogReader, cluster,
      convertletTable, config);
}
 
Example #17
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
private ParseResult convert_(Context context, String sql, boolean analyze,
    boolean fail, CalciteCatalogReader catalogReader, SqlValidator validator,
    SqlNode sqlNode1) {
  final JavaTypeFactory typeFactory = context.getTypeFactory();
  final Convention resultConvention =
      enableBindable ? BindableConvention.INSTANCE
          : EnumerableConvention.INSTANCE;
  // Use the Volcano because it can handle the traits.
  final VolcanoPlanner planner = new VolcanoPlanner();
  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);

  final SqlToRelConverter.ConfigBuilder configBuilder =
      SqlToRelConverter.configBuilder().withTrimUnusedFields(true);

  final CalcitePreparingStmt preparingStmt =
      new CalcitePreparingStmt(this, context, catalogReader, typeFactory,
          context.getRootSchema(), null, createCluster(planner, new RexBuilder(typeFactory)),
          resultConvention, createConvertletTable());
  final SqlToRelConverter converter =
      preparingStmt.getSqlToRelConverter(validator, catalogReader,
          configBuilder.build());

  final RelRoot root = converter.convertQuery(sqlNode1, false, true);
  if (analyze) {
    return analyze_(validator, sql, sqlNode1, root, fail);
  }
  return new ConvertResult(this, validator, sql, sqlNode1,
      validator.getValidatedNodeType(sqlNode1), root);
}
 
Example #18
Source File: CsvTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-1051">[CALCITE-1051]
 * Underflow exception due to scaling IN clause literals</a>. */
@Test void testInToSemiJoinWithoutCast() throws SQLException {
  final String sql = "SELECT e.name\n"
      + "FROM emps AS e\n"
      + "WHERE e.empno in "
      + range(130, SqlToRelConverter.DEFAULT_IN_SUB_QUERY_THRESHOLD);
  sql("smart", sql).returns("NAME=Alice").ok();
}
 
Example #19
Source File: CsvTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-824">[CALCITE-824]
 * Type inference when converting IN clause to semijoin</a>. */
@Test void testInToSemiJoinWithCast() throws SQLException {
  // Note that the IN list needs at least 20 values to trigger the rewrite
  // to a semijoin. Try it both ways.
  final String sql = "SELECT e.name\n"
      + "FROM emps AS e\n"
      + "WHERE cast(e.empno as bigint) in ";
  final int threshold = SqlToRelConverter.DEFAULT_IN_SUB_QUERY_THRESHOLD;
  sql("smart", sql + range(130, threshold - 5))
      .returns("NAME=Alice").ok();
  sql("smart", sql + range(130, threshold))
      .returns("NAME=Alice").ok();
  sql("smart", sql + range(130, threshold + 1000))
      .returns("NAME=Alice").ok();
}
 
Example #20
Source File: PlannerContext.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link SqlToRelConverter} config.
 *
 * <p>`expand` is set as false, and each sub-query becomes a [[org.apache.calcite.rex.RexSubQuery]].
 */
private SqlToRelConverter.Config getSqlToRelConverterConfig(CalciteConfig calciteConfig) {
	return JavaScalaConversionUtil.<SqlToRelConverter.Config>toJava(calciteConfig.getSqlToRelConverterConfig()).orElseGet(
			() -> SqlToRelConverter.configBuilder()
					.withTrimUnusedFields(false)
					.withHintStrategyTable(FlinkHintStrategies.createHintStrategyTable())
					.withInSubQueryThreshold(Integer.MAX_VALUE)
					.withExpand(false)
					.withRelBuilderFactory(FlinkRelFactories.FLINK_REL_BUILDER())
					.build()
	);
}
 
Example #21
Source File: PlanningConfigurationBuilder.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link SqlToRelConverter} config.
 */
private SqlToRelConverter.Config getSqlToRelConverterConfig(
		CalciteConfig calciteConfig,
		ExpressionBridge<PlannerExpression> expressionBridge) {
	return JavaScalaConversionUtil.toJava(calciteConfig.sqlToRelConverterConfig()).orElseGet(
		() -> SqlToRelConverter.configBuilder()
			.withTrimUnusedFields(false)
			.withConvertTableAccess(true)
			.withInSubQueryThreshold(Integer.MAX_VALUE)
			.withRelBuilderFactory(new FlinkRelBuilderFactory(expressionBridge))
			.build()
	);
}
 
Example #22
Source File: SqlToRelConverterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
Sql(String sql, boolean decorrelate, Tester tester,
    boolean trim, UnaryOperator<SqlToRelConverter.ConfigBuilder> config,
    SqlConformance conformance) {
  this.sql = sql;
  this.decorrelate = decorrelate;
  this.tester = tester;
  this.trim = trim;
  this.config = config;
  this.conformance = conformance;
}
 
Example #23
Source File: SqlConverter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a rel root that defers materialization of scans via {@link com.dremio.exec.planner.logical.ConvertibleScan}
 *
 * Used for serialization.
 */
public RelRootPlus toConvertibleRelRoot(final SqlNode validatedNode, boolean expand) {

  final OptionManager o = settings.getOptions();
  final long inSubQueryThreshold =  o.getOption(ExecConstants.FAST_OR_ENABLE) ? o.getOption(ExecConstants.FAST_OR_MAX_THRESHOLD) : settings.getOptions().getOption(ExecConstants.PLANNER_IN_SUBQUERY_THRESHOLD);
  final SqlToRelConverter.Config config = SqlToRelConverter.configBuilder()
    .withInSubQueryThreshold((int) inSubQueryThreshold)
    .withTrimUnusedFields(true)
    .withConvertTableAccess(false)
    .withExpand(expand)
    .build();
  final ReflectionAllowedMonitoringConvertletTable convertletTable = new ReflectionAllowedMonitoringConvertletTable(new ConvertletTable(functionContext.getContextInformation()));
  final SqlToRelConverter sqlToRelConverter = new DremioSqlToRelConverter(this, validator, convertletTable, config);
  // Previously we had "top" = !innerQuery, but calcite only adds project if it is not a top query.
  final RelRoot rel = sqlToRelConverter.convertQuery(validatedNode, false /* needs validate */, false /* top */);
  final RelNode rel2 = sqlToRelConverter.flattenTypes(rel.rel, true);
  RelNode converted;
  final RelNode rel3 = expand ? rel2 : rel2.accept(new RelsWithRexSubQueryFlattener(sqlToRelConverter));
  if (settings.isRelPlanningEnabled()) {
    converted = rel3;
  } else {
    converted = DremioRelDecorrelator.decorrelateQuery(rel3, DremioRelFactories.CALCITE_LOGICAL_BUILDER.create(rel3.getCluster(), null), false, false);
  }

  if (logger.isDebugEnabled()) {
    logger.debug("ConvertQuery with expand = {}:\n{}", expand, RelOptUtil.toString(converted, SqlExplainLevel.ALL_ATTRIBUTES));
  }
  return RelRootPlus.of(converted, rel.validatedRowType, rel.kind, convertletTable.isReflectionDisallowed());
}
 
Example #24
Source File: SqlToRelConverterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void convertsTo(String plan) {
  final SqlToRelConverter.ConfigBuilder configBuilder =
      SqlToRelConverter.configBuilder().withTrimUnusedFields(true);
  tester.withDecorrelation(decorrelate)
      .withConformance(conformance)
      .withConfig(config.apply(configBuilder).build())
      .assertConvertsTo(sql, plan, trim);
}
 
Example #25
Source File: PlannerImpl.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public RelRoot expandView(RelDataType rowType, String queryString,
                          List<String> schemaPath, List<String> viewPath) {
    if (planner == null) {
        ready();
    }
    SqlParser parser = SqlParser.create(queryString, parserConfig);
    SqlNode sqlNode;
    try {
        sqlNode = parser.parseQuery();
    } catch (SqlParseException e) {
        throw new RuntimeException("parse failed", e);
    }

    final CalciteCatalogReader catalogReader =
            createCatalogReader().withSchemaPath(schemaPath);
    final SqlValidator validator = createSqlValidator(catalogReader);

    final RexBuilder rexBuilder = createRexBuilder();
    final RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder);
    final SqlToRelConverter.Config config = SqlToRelConverter
            .configBuilder()
            .withConfig(sqlToRelConverterConfig)
            .withTrimUnusedFields(false)
            .build();
    final SqlToRelConverter sqlToRelConverter =
            new SqlToRelConverter(this, validator,
                    catalogReader, cluster, convertletTable, config);

    final RelRoot root =
            sqlToRelConverter.convertQuery(sqlNode, true, false);
    final RelRoot root2 =
            root.withRel(sqlToRelConverter.flattenTypes(root.rel, true));
    final RelBuilder relBuilder =
            config.getRelBuilderFactory().create(cluster, null);
    return root2.withRel(
            RelDecorrelator.decorrelateQuery(root.rel, relBuilder));
}
 
Example #26
Source File: SqlHintsConverterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testInvalidQueryHint() {
  final String sql = "select /*+ weird_hint */ empno\n"
      + "from (select /*+ resource(mem='20Mb')*/ empno, ename\n"
      + "from emp left join dept on emp.deptno = dept.deptno)";
  sql(sql).warns("Hint: WEIRD_HINT should be registered in the HintStrategyTable");

  final String sql1 = "select /*+ resource(mem='20Mb')*/ empno\n"
      + "from (select /*+ weird_kv_hint(k1='v1') */ empno, ename\n"
      + "from emp left join dept on emp.deptno = dept.deptno)";
  sql(sql1).warns("Hint: WEIRD_KV_HINT should be registered in the HintStrategyTable");

  final String sql2 = "select /*+ AGG_STRATEGY(OPTION1) */\n"
      + "ename, avg(sal)\n"
      + "from emp group by ename";
  final String error2 = "Hint AGG_STRATEGY only allows single option, "
      + "allowed options: [ONE_PHASE, TWO_PHASE]";
  sql(sql2).warns(error2);
  // Change the error handler to validate again.
  sql(sql2).withTester(
      tester -> tester.withConfig(
      SqlToRelConverter.configBuilder()
          .withHintStrategyTable(
              HintTools.createHintStrategies(
              HintStrategyTable.builder().errorHandler(Litmus.THROW)))
          .build()))
      .fails(error2);
}
 
Example #27
Source File: PlannerContext.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link SqlToRelConverter} config.
 *
 * <p>`expand` is set as false, and each sub-query becomes a [[org.apache.calcite.rex.RexSubQuery]].
 */
private SqlToRelConverter.Config getSqlToRelConverterConfig(CalciteConfig calciteConfig) {
	return JavaScalaConversionUtil.toJava(calciteConfig.getSqlToRelConverterConfig()).orElseGet(
			() -> SqlToRelConverter.configBuilder()
					.withTrimUnusedFields(false)
					.withConvertTableAccess(false)
					.withInSubQueryThreshold(Integer.MAX_VALUE)
					.withExpand(false)
					.build()
	);
}
 
Example #28
Source File: PlanningConfigurationBuilder.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link SqlToRelConverter} config.
 */
private SqlToRelConverter.Config getSqlToRelConverterConfig(
		CalciteConfig calciteConfig,
		ExpressionBridge<PlannerExpression> expressionBridge) {
	return JavaScalaConversionUtil.toJava(calciteConfig.sqlToRelConverterConfig()).orElseGet(
		() -> SqlToRelConverter.configBuilder()
			.withTrimUnusedFields(false)
			.withConvertTableAccess(false)
			.withInSubQueryThreshold(Integer.MAX_VALUE)
			.withRelBuilderFactory(new FlinkRelBuilderFactory(expressionBridge))
			.build()
	);
}
 
Example #29
Source File: SqlHintsConverterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override protected Tester createTester() {
  return super.createTester()
      .withConfig(SqlToRelConverter
        .configBuilder()
        .withHintStrategyTable(HintTools.HINT_STRATEGY_TABLE)
        .build());
}
 
Example #30
Source File: Prepare.java    From calcite with Apache License 2.0 4 votes vote down vote up
protected abstract RelNode decorrelate(SqlToRelConverter sqlToRelConverter,
SqlNode query, RelNode rootRel);