org.apache.calcite.plan.Contexts Java Examples

The following examples show how to use org.apache.calcite.plan.Contexts. 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: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testExpandViewShouldKeepAlias() throws SQLException {
  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    final Frameworks.ConfigBuilder configBuilder =
        expandingConfig(connection);
    final RelOptTable.ViewExpander viewExpander =
        (RelOptTable.ViewExpander) Frameworks.getPlanner(configBuilder.build());
    configBuilder.context(Contexts.of(viewExpander));
    final RelBuilder builder = RelBuilder.create(configBuilder.build());
    RelNode node =
        builder.scan("MYVIEW")
            .project(
                builder.field(1, "MYVIEW", "EMPNO"),
                builder.field(1, "MYVIEW", "ENAME"))
            .build();
    String expected =
        "LogicalProject(EMPNO=[$0], ENAME=[$1])\n"
            + "  LogicalFilter(condition=[=(1, 1)])\n"
                + "    LogicalTableScan(table=[[scott, EMP]])\n";
    assertThat(node, hasTree(expected));
  }
}
 
Example #2
Source File: PlanningConfigurationBuilder.java    From flink with Apache License 2.0 6 votes vote down vote up
public PlanningConfigurationBuilder(
		TableConfig tableConfig,
		FunctionCatalog functionCatalog,
		CalciteSchema rootSchema,
		ExpressionBridge<PlannerExpression> expressionBridge) {
	this.tableConfig = tableConfig;
	this.functionCatalog = functionCatalog;

	// the converter is needed when calling temporal table functions from SQL, because
	// they reference a history table represented with a tree of table operations.
	this.context = Contexts.of(expressionBridge, tableConfig);

	this.planner = new VolcanoPlanner(costFactory, context);
	planner.setExecutor(new ExpressionReducer(tableConfig));
	planner.addRelTraitDef(ConventionTraitDef.INSTANCE);

	this.expressionBridge = expressionBridge;

	this.rootSchema = rootSchema;
}
 
Example #3
Source File: PlanningConfigurationBuilder.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a configured {@link FlinkRelBuilder} for a planning session.
 *
 * @param currentCatalog the current default catalog to look for first during planning.
 * @param currentDatabase the current default database to look for first during planning.
 * @return configured rel builder
 */
public FlinkRelBuilder createRelBuilder(String currentCatalog, String currentDatabase) {
	RelOptCluster cluster = FlinkRelOptClusterFactory.create(
		planner,
		new RexBuilder(typeFactory));
	RelOptSchema relOptSchema = createCatalogReader(false, currentCatalog, currentDatabase);
	Context chain = Contexts.chain(
		context,
		// We need to overwrite the default scan factory, which does not
		// expand views. The expandingScanFactory uses the FlinkPlanner to translate a view
		// into a rel tree, before applying any subsequent rules.
		Contexts.of(RelFactories.expandingScanFactory(
			createFlinkPlanner(currentCatalog, currentDatabase),
			RelFactories.DEFAULT_TABLE_SCAN_FACTORY))
	);

	return new FlinkRelBuilder(chain, cluster, relOptSchema, expressionBridge);
}
 
Example #4
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 #5
Source File: PlanningConfigurationBuilder.java    From flink with Apache License 2.0 6 votes vote down vote up
public PlanningConfigurationBuilder(
		TableConfig tableConfig,
		FunctionCatalog functionCatalog,
		CalciteSchema rootSchema,
		ExpressionBridge<PlannerExpression> expressionBridge) {
	this.tableConfig = tableConfig;
	this.functionCatalog = functionCatalog;

	// the converter is needed when calling temporal table functions from SQL, because
	// they reference a history table represented with a tree of table operations
	this.context = Contexts.of(expressionBridge);

	this.planner = new VolcanoPlanner(costFactory, context);
	planner.setExecutor(new ExpressionReducer(tableConfig));
	planner.addRelTraitDef(ConventionTraitDef.INSTANCE);

	this.expressionBridge = expressionBridge;

	this.rootSchema = rootSchema;
}
 
Example #6
Source File: TpcdsLatticeSuggesterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
Tester tpcds() {
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  final double scaleFactor = 0.01d;
  final SchemaPlus schema =
      rootSchema.add("tpcds", new TpcdsSchema(scaleFactor));
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.Config.DEFAULT)
      .context(
          Contexts.of(
              new CalciteConnectionConfigImpl(new Properties())
                  .set(CalciteConnectionProperty.CONFORMANCE,
                      SqlConformanceEnum.LENIENT.name())))
      .defaultSchema(schema)
      .build();
  return withConfig(config);
}
 
Example #7
Source File: RelBuilder.java    From calcite with Apache License 2.0 6 votes vote down vote up
protected RelBuilder(Context context, RelOptCluster cluster,
    RelOptSchema relOptSchema) {
  this.cluster = cluster;
  this.relOptSchema = relOptSchema;
  if (context == null) {
    context = Contexts.EMPTY_CONTEXT;
  }
  this.config = getConfig(context);
  this.viewExpander = getViewExpander(cluster, context);
  this.struct =
      Objects.requireNonNull(RelFactories.Struct.fromContext(context));
  final RexExecutor executor =
      Util.first(context.unwrap(RexExecutor.class),
          Util.first(cluster.getPlanner().getExecutor(), RexUtil.EXECUTOR));
  final RelOptPredicateList predicates = RelOptPredicateList.EMPTY;
  this.simplifier =
      new RexSimplify(cluster.getRexBuilder(), predicates, executor);
}
 
Example #8
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 #9
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 #10
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures that relational algebra ({@link RelBuilder}) works with SQL views.
 *
 * <p>This test currently fails (thus ignored).
 */
@Test void testExpandViewInRelBuilder() throws SQLException {
  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    final Frameworks.ConfigBuilder configBuilder =
        expandingConfig(connection);
    final RelOptTable.ViewExpander viewExpander =
        (RelOptTable.ViewExpander) Frameworks.getPlanner(configBuilder.build());
    configBuilder.context(Contexts.of(viewExpander));
    final RelBuilder builder = RelBuilder.create(configBuilder.build());
    RelNode node = builder.scan("MYVIEW").build();

    int count = 0;
    try (PreparedStatement statement =
             connection.unwrap(RelRunner.class).prepare(node);
         ResultSet resultSet = statement.executeQuery()) {
      while (resultSet.next()) {
        count++;
      }
    }

    assertTrue(count > 1);
  }
}
 
Example #11
Source File: QuerySqlStatisticProvider.java    From calcite with Apache License 2.0 5 votes vote down vote up
private <R> R withBuilder(BuilderAction<R> action) {
  return Frameworks.withPlanner(
      (cluster, relOptSchema, rootSchema) -> {
        final RelBuilder relBuilder =
            RelBuilder.proto(Contexts.of()).create(cluster, relOptSchema);
        return action.apply(cluster, relOptSchema, relBuilder);
      });
}
 
Example #12
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 #13
Source File: FilterAggregateTransposeRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public FilterAggregateTransposeRule(
    Class<? extends Filter> filterClass,
    RelFactories.FilterFactory filterFactory,
    Class<? extends Aggregate> aggregateClass) {
  this(filterClass, RelBuilder.proto(Contexts.of(filterFactory)),
      aggregateClass);
}
 
Example #14
Source File: AggregateExpandDistinctAggregatesRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public AggregateExpandDistinctAggregatesRule(
    Class<? extends LogicalAggregate> clazz,
    boolean useGroupingSets,
    RelFactories.JoinFactory joinFactory) {
  this(clazz, useGroupingSets, RelBuilder.proto(Contexts.of(joinFactory)));
}
 
Example #15
Source File: JoinProjectTransposeRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public JoinProjectTransposeRule(RelOptRuleOperand operand,
    String description, boolean includeOuter,
    ProjectFactory projectFactory) {
  this(operand, description, includeOuter,
      RelBuilder.proto(Contexts.of(projectFactory)));
}
 
Example #16
Source File: PigRelBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
static PigRelBuilder createBuilder(
    UnaryOperator<RelBuilder.Config> transform) {
  final Frameworks.ConfigBuilder configBuilder = config();
  configBuilder.context(
      Contexts.of(transform.apply(RelBuilder.Config.DEFAULT)));
  return PigRelBuilder.create(configBuilder.build());
}
 
Example #17
Source File: PlannerContext.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a configured {@link FlinkRelBuilder} for a planning session.
 *
 * @param currentCatalog the current default catalog to look for first during planning.
 * @param currentDatabase the current default database to look for first during planning.
 * @return configured rel builder
 */
public FlinkRelBuilder createRelBuilder(String currentCatalog, String currentDatabase) {
	FlinkCalciteCatalogReader relOptSchema = createCatalogReader(
			false,
			currentCatalog,
			currentDatabase);

	Context chain = Contexts.of(
		context,
		// Sets up the ViewExpander explicitly for FlinkRelBuilder.
		createFlinkPlanner(currentCatalog, currentDatabase).createToRelContext()
	);
	return new FlinkRelBuilder(chain, cluster, relOptSchema);
}
 
Example #18
Source File: FlinkAggregateExpandDistinctAggregatesRule.java    From flink with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public FlinkAggregateExpandDistinctAggregatesRule(
		Class<? extends LogicalAggregate> clazz,
		boolean useGroupingSets,
		RelFactories.JoinFactory joinFactory) {
	this(clazz, useGroupingSets, RelBuilder.proto(Contexts.of(joinFactory)));
}
 
Example #19
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a RelBuilder with transformed config. */
static RelBuilder createBuilder(UnaryOperator<RelBuilder.Config> transform) {
  final Frameworks.ConfigBuilder configBuilder = config();
  configBuilder.context(
      Contexts.of(transform.apply(RelBuilder.Config.DEFAULT)));
  return RelBuilder.create(configBuilder.build());
}
 
Example #20
Source File: CalciteAssert.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a {@link FrameworkConfig} that does not decorrelate. */
private FrameworkConfig forceDecorrelate(FrameworkConfig config) {
  return Frameworks.newConfigBuilder(config)
      .context(
          Contexts.of(new CalciteConnectionConfigImpl(new Properties())
              .set(CalciteConnectionProperty.FORCE_DECORRELATE,
                  Boolean.toString(false))))
      .build();
}
 
Example #21
Source File: JoinProjectTransposeRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public JoinProjectTransposeRule(RelOptRuleOperand operand,
    String description, boolean includeOuter,
    ProjectFactory projectFactory) {
  this(operand, description, includeOuter,
      RelBuilder.proto(Contexts.of(projectFactory)));
}
 
Example #22
Source File: FilterAggregateTransposeRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public FilterAggregateTransposeRule(
    Class<? extends Filter> filterClass,
    RelFactories.FilterFactory filterFactory,
    Class<? extends Aggregate> aggregateClass) {
  this(filterClass, RelBuilder.proto(Contexts.of(filterFactory)),
      aggregateClass);
}
 
Example #23
Source File: FlinkAggregateExpandDistinctAggregatesRule.java    From flink with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public FlinkAggregateExpandDistinctAggregatesRule(
		Class<? extends LogicalAggregate> clazz,
		boolean useGroupingSets,
		RelFactories.JoinFactory joinFactory) {
	this(clazz, useGroupingSets, RelBuilder.proto(Contexts.of(joinFactory)));
}
 
Example #24
Source File: SamzaSqlQueryParser.java    From samza with Apache License 2.0 5 votes vote down vote up
private static Planner createPlanner() {
  Connection connection;
  SchemaPlus rootSchema;
  try {
    JavaTypeFactory typeFactory = new SamzaSqlJavaTypeFactoryImpl();
    SamzaSqlDriver driver = new SamzaSqlDriver(typeFactory);
    DriverManager.deregisterDriver(DriverManager.getDriver("jdbc:calcite:"));
    DriverManager.registerDriver(driver);
    connection = driver.connect("jdbc:calcite:", new Properties());
    CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
    rootSchema = calciteConnection.getRootSchema();
  } catch (SQLException e) {
    throw new SamzaException(e);
  }

  final List<RelTraitDef> traitDefs = new ArrayList<>();

  traitDefs.add(ConventionTraitDef.INSTANCE);
  traitDefs.add(RelCollationTraitDef.INSTANCE);

  FrameworkConfig frameworkConfig = Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.configBuilder().setLex(Lex.JAVA).build())
      .defaultSchema(rootSchema)
      .operatorTable(SqlStdOperatorTable.instance())
      .traitDefs(traitDefs)
      .context(Contexts.EMPTY_CONTEXT)
      .costFactory(null)
      .build();
  return Frameworks.getPlanner(frameworkConfig);
}
 
Example #25
Source File: RelBuilder.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected RelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
    this.cluster = cluster;
    this.relOptSchema = relOptSchema;
    if (context == null) {
        context = Contexts.EMPTY_CONTEXT;
    }
    this.simplify = Hook.REL_BUILDER_SIMPLIFY.get(true);
    this.aggregateFactory = Util.first(context.unwrap(RelFactories.AggregateFactory.class),
            RelFactories.DEFAULT_AGGREGATE_FACTORY);
    this.filterFactory = Util.first(context.unwrap(RelFactories.FilterFactory.class),
            RelFactories.DEFAULT_FILTER_FACTORY);
    this.projectFactory = Util.first(context.unwrap(RelFactories.ProjectFactory.class),
            RelFactories.DEFAULT_PROJECT_FACTORY);
    this.sortFactory = Util.first(context.unwrap(RelFactories.SortFactory.class),
            RelFactories.DEFAULT_SORT_FACTORY);
    this.exchangeFactory = Util.first(context.unwrap(RelFactories.ExchangeFactory.class),
            RelFactories.DEFAULT_EXCHANGE_FACTORY);
    this.sortExchangeFactory = Util.first(context.unwrap(RelFactories.SortExchangeFactory.class),
            RelFactories.DEFAULT_SORT_EXCHANGE_FACTORY);
    this.setOpFactory = Util.first(context.unwrap(RelFactories.SetOpFactory.class),
            RelFactories.DEFAULT_SET_OP_FACTORY);
    this.joinFactory = Util.first(context.unwrap(RelFactories.JoinFactory.class),
            RelFactories.DEFAULT_JOIN_FACTORY);
    this.semiJoinFactory = Util.first(context.unwrap(RelFactories.SemiJoinFactory.class),
            RelFactories.DEFAULT_SEMI_JOIN_FACTORY);
    this.correlateFactory = Util.first(context.unwrap(RelFactories.CorrelateFactory.class),
            RelFactories.DEFAULT_CORRELATE_FACTORY);
    this.valuesFactory = Util.first(context.unwrap(RelFactories.ValuesFactory.class),
            RelFactories.DEFAULT_VALUES_FACTORY);
    this.scanFactory = Util.first(context.unwrap(RelFactories.TableScanFactory.class),
            RelFactories.DEFAULT_TABLE_SCAN_FACTORY);
    this.snapshotFactory = Util.first(context.unwrap(RelFactories.SnapshotFactory.class),
            RelFactories.DEFAULT_SNAPSHOT_FACTORY);
    this.matchFactory = Util.first(context.unwrap(RelFactories.MatchFactory.class),
            RelFactories.DEFAULT_MATCH_FACTORY);
    final RexExecutor executor = Util.first(context.unwrap(RexExecutor.class),
            Util.first(cluster.getPlanner().getExecutor(), RexUtil.EXECUTOR));
    final RelOptPredicateList predicates = RelOptPredicateList.EMPTY;
    this.simplifier = new RexSimplify(cluster.getRexBuilder(), predicates, executor);
}
 
Example #26
Source File: JoinCommuteRule.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Deprecated // to be removed before 2.0
public JoinCommuteRule(Class<? extends Join> clazz, ProjectFactory projectFactory, boolean swapOuter) {
    this(clazz, RelBuilder.proto(Contexts.of(projectFactory)), swapOuter);
}
 
Example #27
Source File: RelBuilder.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Creates a {@link RelBuilderFactory} that uses a given set of factories. */
public static RelBuilderFactory proto(Object... factories) {
  return proto(Contexts.of(factories));
}
 
Example #28
Source File: FilterSetOpTransposeRule.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Deprecated // to  be removed before 2.0
public FilterSetOpTransposeRule(RelFactories.FilterFactory filterFactory) {
  this(RelBuilder.proto(Contexts.of(filterFactory)));
}
 
Example #29
Source File: JoinToCorrelateRule.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Deprecated // to be removed before 2.0
protected JoinToCorrelateRule(RelFactories.FilterFactory filterFactory) {
  this(RelBuilder.proto(Contexts.of(filterFactory)));
}
 
Example #30
Source File: SqlToRelTestBase.java    From calcite with Apache License 2.0 4 votes vote down vote up
protected Tester createTester() {
  return new TesterImpl(getDiffRepos(), false, false, true, false,
      true, null, null, SqlToRelConverter.Config.DEFAULT,
      SqlConformanceEnum.DEFAULT, Contexts.empty());
}