org.apache.calcite.tools.FrameworkConfig Java Examples

The following examples show how to use org.apache.calcite.tools.FrameworkConfig. 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: SortRemoveRuleTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * The default schema that is used in these tests provides tables sorted on the primary key. Due
 * to this scan operators always come with a {@link org.apache.calcite.rel.RelCollation} trait.
 */
private RelNode transform(String sql, RuleSet prepareRules) throws Exception {
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  final SchemaPlus defSchema = rootSchema.add("hr", new HrClusteredSchema());
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.Config.DEFAULT)
      .defaultSchema(defSchema)
      .traitDefs(ConventionTraitDef.INSTANCE, RelCollationTraitDef.INSTANCE)
      .programs(
          Programs.of(prepareRules),
          Programs.ofRules(SortRemoveRule.INSTANCE))
      .build();
  Planner planner = Frameworks.getPlanner(config);
  SqlNode parse = planner.parse(sql);
  SqlNode validate = planner.validate(parse);
  RelRoot planRoot = planner.rel(validate);
  RelNode planBefore = planRoot.rel;
  RelTraitSet desiredTraits = planBefore.getTraitSet()
      .replace(EnumerableConvention.INSTANCE);
  RelNode planAfter = planner.transform(0, desiredTraits, planBefore);
  return planner.transform(1, desiredTraits, planAfter);
}
 
Example #2
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testInterval() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  SqlIntervalQualifier sqlIntervalQualifier =
      new SqlIntervalQualifier(TimeUnit.DAY, TimeUnit.DAY, SqlParserPos.ZERO);
  BigDecimal value = new BigDecimal(86400000);
  RexLiteral intervalLiteral = builder.getRexBuilder()
      .makeIntervalLiteral(value, sqlIntervalQualifier);
  final RelNode rel = builder
      .scan("EMP")
      .project(
          builder.call(
              SqlStdOperatorTable.TUMBLE_END,
              builder.field("HIREDATE"),
              intervalLiteral))
      .build();
  RelJsonWriter jsonWriter = new RelJsonWriter();
  rel.explain(jsonWriter);
  String relJson = jsonWriter.asString();
  String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[TUMBLE_END($4, 86400000:INTERVAL DAY)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #3
Source File: RuleParser.java    From streamline with Apache License 2.0 6 votes vote down vote up
public void parse() {
    try {
        SchemaPlus schema = Frameworks.createRootSchema(true);
        FrameworkConfig config = Frameworks.newConfigBuilder().defaultSchema(schema).build();
        Planner planner = Frameworks.getPlanner(config);
        SqlSelect sqlSelect = (SqlSelect) planner.parse(sql);
        // FROM
        streams = parseStreams(sqlSelect);
        // SELECT
        projection = parseProjection(sqlSelect);
        // WHERE
        condition = parseCondition(sqlSelect);
        // GROUP BY
        groupBy = parseGroupBy(sqlSelect);
        // HAVING
        having = parseHaving(sqlSelect);
    } catch (Exception ex) {
        LOG.error("Got Exception while parsing rule {}", sql);
        throw new RuntimeException(ex);
    }
}
 
Example #4
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testUdf() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RelNode rel = builder
      .scan("EMP")
      .project(
          builder.call(new MockSqlOperatorTable.MyFunction(),
              builder.field("EMPNO")))
      .build();
  String relJson = RelOptUtil.dumpPlan("", rel,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[MYFUN($0)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #5
Source File: SQLExecEnvironment.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
/**
 * This is the main method takes SQL statement as input and contructs a DAG using contructs registered with this
 * {@link SQLExecEnvironment}.
 *
 * @param sql SQL statement that should be converted to a DAG.
 */
public void executeSQL(DAG dag, String sql)
{
  FrameworkConfig config = buildFrameWorkConfig();
  Planner planner = Frameworks.getPlanner(config);
  try {
    logger.info("Parsing SQL statement: {}", sql);
    SqlNode parsedTree = planner.parse(sql);
    SqlNode validatedTree = planner.validate(parsedTree);
    RelNode relationalTree = planner.rel(validatedTree).rel;
    logger.info("RelNode relationalTree generate from SQL statement is:\n {}",
        Util.toLinux(RelOptUtil.toString(relationalTree)));
    RelNodeVisitor visitor = new RelNodeVisitor(dag, typeFactory);
    visitor.traverse(relationalTree);
  } catch (Exception e) {
    throw Throwables.propagate(e);
  } finally {
    planner.close();
  }
}
 
Example #6
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testUDAF() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RelNode rel = builder
      .scan("EMP")
      .project(builder.field("ENAME"), builder.field("DEPTNO"))
      .aggregate(
          builder.groupKey("ENAME"),
          builder.aggregateCall(new MockSqlOperatorTable.MyAggFunc(),
              builder.field("DEPTNO")))
      .build();
  final String relJson = RelOptUtil.dumpPlan("", rel,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  final String result = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalAggregate(group=[{0}], agg#0=[myAggFunc($1)])\n"
      + "  LogicalProject(ENAME=[$1], DEPTNO=[$7])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(result, isLinux(expected));
}
 
Example #7
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testArrayType() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RelNode rel = builder
      .scan("EMP")
      .project(
          builder.call(new MockSqlOperatorTable.SplitFunction(),
              builder.field("ENAME"), builder.literal(",")))
      .build();
  final String relJson = RelOptUtil.dumpPlan("", rel,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  final String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[SPLIT($1, ',')])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #8
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testTableModifyInsert() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  RelNode project = builder
      .scan("EMP")
      .project(builder.fields(), ImmutableList.of(), true)
      .build();
  LogicalTableModify modify = LogicalTableModify.create(
      project.getInput(0).getTable(),
      (Prepare.CatalogReader) project.getInput(0).getTable().getRelOptSchema(),
      project,
      TableModify.Operation.INSERT,
      null,
      null,
      false);
  String relJson = RelOptUtil.dumpPlan("", modify,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s = deserializeAndDumpToTextFormat(getSchema(modify), relJson);
  final String expected = ""
      + "LogicalTableModify(table=[[scott, EMP]], operation=[INSERT], flattened=[false])\n"
      + "  LogicalProject(EMPNO=[$0], ENAME=[$1], JOB=[$2], MGR=[$3], HIREDATE=[$4], SAL=[$5], "
      + "COMM=[$6], DEPTNO=[$7])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #9
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 #10
Source File: PlannerContext.java    From flink with Apache License 2.0 6 votes vote down vote up
public PlannerContext(
		TableConfig tableConfig,
		FunctionCatalog functionCatalog,
		CalciteSchema rootSchema,
		List<RelTraitDef> traitDefs) {
	this.tableConfig = tableConfig;
	this.functionCatalog = functionCatalog;
	this.context = new FlinkContextImpl(tableConfig, functionCatalog);
	this.rootSchema = rootSchema;
	this.traitDefs = traitDefs;
	// Make a framework config to initialize the RelOptCluster instance,
	// caution that we can only use the attributes that can not be overwrite/configured
	// by user.
	final FrameworkConfig frameworkConfig = createFrameworkConfig();

	RelOptPlanner planner = new VolcanoPlanner(frameworkConfig.getCostFactory(), frameworkConfig.getContext());
	planner.setExecutor(frameworkConfig.getExecutor());
	for (RelTraitDef traitDef : frameworkConfig.getTraitDefs()) {
		planner.addRelTraitDef(traitDef);
	}
	this.cluster = FlinkRelOptClusterFactory.create(planner, new RexBuilder(typeFactory));
}
 
Example #11
Source File: StreamlineSqlImpl.java    From streamline with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(
    Iterable<String> statements, ChannelHandler result)
    throws Exception {
  Map<String, DataSource> dataSources = new HashMap<>();
  for (String sql : statements) {
    StreamlineParser parser = new StreamlineParser(sql);
    SqlNode node = parser.impl().parseSqlStmtEof();
    if (node instanceof SqlCreateTable) {
      handleCreateTable((SqlCreateTable) node, dataSources);
    } else if (node instanceof SqlCreateFunction) {
      handleCreateFunction((SqlCreateFunction) node);
    } else {
      FrameworkConfig config = buildFrameWorkConfig();
      Planner planner = Frameworks.getPlanner(config);
      SqlNode parse = planner.parse(sql);
      SqlNode validate = planner.validate(parse);
      RelNode tree = planner.convert(validate);
      PlanCompiler compiler = new PlanCompiler(typeFactory);
      AbstractValuesProcessor proc = compiler.compile(tree);
      proc.initialize(dataSources, result);
    }
  }
}
 
Example #12
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testCorrelateQuery() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final Holder<RexCorrelVariable> v = Holder.of(null);
  RelNode relNode = builder.scan("EMP")
      .variable(v)
      .scan("DEPT")
      .filter(
          builder.equals(builder.field(0), builder.field(v.get(), "DEPTNO")))
      .correlate(
          JoinRelType.INNER, v.get().id, builder.field(2, 0, "DEPTNO"))
      .build();
  RelJsonWriter jsonWriter = new RelJsonWriter();
  relNode.explain(jsonWriter);
  final String relJson = jsonWriter.asString();
  String s = deserializeAndDumpToTextFormat(getSchema(relNode), relJson);
  final String expected = ""
      + "LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{7}])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n"
      + "  LogicalFilter(condition=[=($0, $cor0.DEPTNO)])\n"
      + "    LogicalTableScan(table=[[scott, DEPT]])\n";

  assertThat(s, isLinux(expected));
}
 
Example #13
Source File: SqlWorker.java    From quark with Apache License 2.0 6 votes vote down vote up
private Planner buildPlanner(QueryContext context) {
  final List<RelTraitDef> traitDefs = new ArrayList<RelTraitDef>();
  traitDefs.add(ConventionTraitDef.INSTANCE);
  traitDefs.add(RelCollationTraitDef.INSTANCE);
  final ChainedSqlOperatorTable opTab =
      new ChainedSqlOperatorTable(
          ImmutableList.of(SqlStdOperatorTable.instance(),
              HiveSqlOperatorTable.instance(), catalogReader));
  FrameworkConfig config = Frameworks.newConfigBuilder() //
      .parserConfig(SqlParser.configBuilder()
          .setQuotedCasing(Casing.UNCHANGED)
          .setUnquotedCasing(Casing.TO_UPPER)
          .setQuoting(Quoting.DOUBLE_QUOTE)
          .build()) //
      .defaultSchema(context.getDefaultSchema()) //
      .operatorTable(opTab) //
      .traitDefs(traitDefs) //
      .convertletTable(StandardConvertletTable.INSTANCE)//
      .programs(getPrograms()) //
      .typeSystem(RelDataTypeSystem.DEFAULT) //
      .build();
  return Frameworks.getPlanner(config);
}
 
Example #14
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testTrim() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder b = RelBuilder.create(config);
  final RelNode rel =
      b.scan("EMP")
          .project(
              b.alias(
                  b.call(SqlStdOperatorTable.TRIM,
                      b.literal(SqlTrimFunction.Flag.BOTH),
                      b.literal(" "),
                      b.field("ENAME")),
                  "trimmed_ename"))
          .build();

  RelJsonWriter jsonWriter = new RelJsonWriter();
  rel.explain(jsonWriter);
  String relJson = jsonWriter.asString();
  final RelOptSchema schema = getSchema(rel);
  final String s = deserializeAndDumpToTextFormat(schema, relJson);
  final String expected = ""
      + "LogicalProject(trimmed_ename=[TRIM(FLAG(BOTH), ' ', $1)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #15
Source File: SqlExprToRexConverterImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a catalog reader that contains a single {@link Table} with temporary table name
 * and specified {@code rowType}.
 *
 * @param rowType     table row type
 * @return the {@link CalciteCatalogReader} instance
 */
private static CalciteCatalogReader createSingleTableCatalogReader(
		boolean lenientCaseSensitivity,
		FrameworkConfig config,
		FlinkTypeFactory typeFactory,
		RelDataType rowType) {

	// connection properties
	boolean caseSensitive = !lenientCaseSensitivity && config.getParserConfig().caseSensitive();
	Properties properties = new Properties();
	properties.put(
		CalciteConnectionProperty.CASE_SENSITIVE.camelName(),
		String.valueOf(caseSensitive));
	CalciteConnectionConfig connectionConfig = new CalciteConnectionConfigImpl(properties);

	// prepare root schema
	final RowTypeSpecifiedTable table = new RowTypeSpecifiedTable(rowType);
	final Map<String, Table> tableMap = Collections.singletonMap(TEMPORARY_TABLE_NAME, table);
	CalciteSchema schema = CalciteSchemaBuilder.asRootSchema(new TableSpecifiedSchema(tableMap));

	return new FlinkCalciteCatalogReader(
		schema,
		new ArrayList<>(new ArrayList<>()),
		typeFactory,
		connectionConfig);
}
 
Example #16
Source File: LexEscapeTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static Planner getPlanner(List<RelTraitDef> traitDefs,
    Config parserConfig, Program... programs) {
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  rootSchema.add("TMP", new AbstractTable() {
    @Override public RelDataType getRowType(RelDataTypeFactory typeFactory) {
      return typeFactory.createStructType(
          ImmutableList.of(typeFactory.createSqlType(SqlTypeName.VARCHAR),
              typeFactory.createSqlType(SqlTypeName.INTEGER)),
          ImmutableList.of("localtime", "current_timestamp"));
    }
  });
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .parserConfig(parserConfig)
      .defaultSchema(rootSchema)
      .traitDefs(traitDefs)
      .programs(programs)
      .operatorTable(SqlStdOperatorTable.instance())
      .build();
  return Frameworks.getPlanner(config);
}
 
Example #17
Source File: LatticeSuggesterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testDerivedColRef() throws Exception {
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .defaultSchema(Tester.schemaFrom(CalciteAssert.SchemaSpec.SCOTT))
      .statisticProvider(QuerySqlStatisticProvider.SILENT_CACHING_INSTANCE)
      .build();
  final Tester t = new Tester(config).foodmart().withEvolve(true);

  final String q0 = "select\n"
      + "  min(c.\"fname\") as \"customer.count\"\n"
      + "from \"customer\" as c\n"
      + "left join \"sales_fact_1997\" as s\n"
      + "on c.\"customer_id\" + 1 = s.\"customer_id\" + 2";
  t.addQuery(q0);
  assertThat(t.s.latticeMap.size(), is(1));
  assertThat(t.s.latticeMap.keySet().iterator().next(),
      is("sales_fact_1997 (customer:+($2, 2)):[MIN(customer.fname)]"));
  assertThat(t.s.space.g.toString(),
      is("graph(vertices: [[foodmart, customer],"
          + " [foodmart, sales_fact_1997]], "
          + "edges: [Step([foodmart, sales_fact_1997],"
          + " [foodmart, customer], +($2, 2):+($0, 1))])"));
}
 
Example #18
Source File: PlannerImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Creates a planner. Not a public API; call
 * {@link org.apache.calcite.tools.Frameworks#getPlanner} instead. */
public PlannerImpl(FrameworkConfig config) {
  this.costFactory = config.getCostFactory();
  this.defaultSchema = config.getDefaultSchema();
  this.operatorTable = config.getOperatorTable();
  this.programs = config.getPrograms();
  this.parserConfig = config.getParserConfig();
  this.sqlValidatorConfig = config.getSqlValidatorConfig();
  this.sqlToRelConverterConfig = config.getSqlToRelConverterConfig();
  this.state = State.STATE_0_CLOSED;
  this.traitDefs = config.getTraitDefs();
  this.convertletTable = config.getConvertletTable();
  this.executor = config.getExecutor();
  this.context = config.getContext();
  this.connectionConfig = connConfig();
  reset();
}
 
Example #19
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Executes a prepare action. */
public <R> R perform(CalciteServerStatement statement,
    FrameworkConfig config, Frameworks.BasePrepareAction<R> action) {
  final CalcitePrepare.Context prepareContext =
      statement.createPrepareContext();
  final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
  final CalciteSchema schema =
      config.getDefaultSchema() != null
          ? CalciteSchema.from(config.getDefaultSchema())
          : prepareContext.getRootSchema();
  CalciteCatalogReader catalogReader =
      new CalciteCatalogReader(schema.root(),
          schema.path(null),
          typeFactory,
          prepareContext.config());
  final RexBuilder rexBuilder = new RexBuilder(typeFactory);
  final RelOptPlanner planner =
      createPlanner(prepareContext,
          config.getContext(),
          config.getCostFactory());
  final RelOptCluster cluster = createCluster(planner, rexBuilder);
  return action.apply(cluster, catalogReader,
      prepareContext.getRootSchema().plus(), statement);
}
 
Example #20
Source File: RelMetadataTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testColumnUniquenessForCorrelateWithConstantColumns() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  RelNode rel0 = builder.scan("EMP")
      .project(builder.field("DEPTNO"), builder.field("SAL"))
      .distinct()
      .filter(builder.equals(builder.field("SAL"), builder.literal(1)))
      .build();
  final Holder<RexCorrelVariable> v = Holder.of(null);
  final RelNode rel1 = builder.scan("EMP")
      .variable(v)
      .project(builder.field("DEPTNO"), builder.field("SAL"))
      .filter(
          builder.equals(builder.field(0), builder.field(v.get(), "DEPTNO")))
      .build();
  final RelNode correl = builder.push(rel0)
      .variable(v)
      .push(rel1)
      .correlate(JoinRelType.SEMI, v.get().id, builder.field(2, 0, "DEPTNO"))
      .build();
  final RelMetadataQuery mq = correl.getCluster().getMetadataQuery();
  assertThat(mq.areColumnsUnique(correl, ImmutableBitSet.of(0)), is(true));
}
 
Example #21
Source File: RelMetadataTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testGetPredicatesForJoin() throws Exception {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  RelNode join = builder
      .scan("EMP")
      .scan("DEPT")
      .join(JoinRelType.INNER, builder.call(NONDETERMINISTIC_OP))
      .build();
  RelMetadataQuery mq = join.getCluster().getMetadataQuery();
  assertTrue(mq.getPulledUpPredicates(join).pulledUpPredicates.isEmpty());

  RelNode join1 = builder
      .scan("EMP")
      .scan("DEPT")
      .join(JoinRelType.INNER,
        builder.call(SqlStdOperatorTable.EQUALS,
          builder.field(2, 0, 0),
          builder.field(2, 1, 0)))
      .build();
  assertThat(mq.getPulledUpPredicates(join1)
      .pulledUpPredicates
      .get(0)
      .toString(),
      is("=($0, $8)"));
}
 
Example #22
Source File: RelMetadataTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testGetPredicatesForFilter() throws Exception {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  RelNode filter = builder
      .scan("EMP")
      .filter(builder.call(NONDETERMINISTIC_OP))
      .build();
  RelMetadataQuery mq = filter.getCluster().getMetadataQuery();
  assertTrue(mq.getPulledUpPredicates(filter).pulledUpPredicates.isEmpty());

  RelNode filter1 = builder
      .scan("EMP")
      .filter(
        builder.call(SqlStdOperatorTable.EQUALS,
          builder.field(1, 0, 0),
          builder.field(1, 0, 1)))
      .build();
  assertThat(mq.getPulledUpPredicates(filter1)
          .pulledUpPredicates
          .get(0)
          .toString(),
      is("=($0, $1)"));
}
 
Example #23
Source File: MutableRelTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Verifies equivalence of {@link MutableScan} */
@Test public void testMutableScanEquivalence() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);

  assertThat(mutableScanOf(builder, "EMP"),
      equalTo(mutableScanOf(builder, "EMP")));
  assertThat(mutableScanOf(builder, "EMP").hashCode(),
      equalTo(mutableScanOf(builder, "EMP").hashCode()));

  assertThat(mutableScanOf(builder, "scott", "EMP"),
      equalTo(mutableScanOf(builder, "scott", "EMP")));
  assertThat(mutableScanOf(builder, "scott", "EMP").hashCode(),
      equalTo(mutableScanOf(builder, "scott", "EMP").hashCode()));

  assertThat(mutableScanOf(builder, "scott", "EMP"),
      equalTo(mutableScanOf(builder, "EMP")));
  assertThat(mutableScanOf(builder, "scott", "EMP").hashCode(),
      equalTo(mutableScanOf(builder, "EMP").hashCode()));

  assertThat(mutableScanOf(builder, "EMP"),
      not(equalTo(mutableScanOf(builder, "DEPT"))));
}
 
Example #24
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 #25
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testPlusOperator() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RelNode rel = builder
      .scan("EMP")
      .project(
          builder.call(SqlStdOperatorTable.PLUS,
              builder.field("SAL"),
              builder.literal(10)))
      .build();
  RelJsonWriter jsonWriter = new RelJsonWriter();
  rel.explain(jsonWriter);
  String relJson = jsonWriter.asString();
  String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[+($5, 10)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #26
Source File: RelWriterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private RelNode createSortPlan(RelDistribution distribution) {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  return builder.scan("EMP")
          .sortExchange(distribution,
              RelCollations.of(0))
          .build();
}
 
Example #27
Source File: RelMetadataTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testColumnUniquenessForExchangeWithConstantColumns() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  RelNode exchange = builder.scan("EMP")
      .project(builder.field("DEPTNO"), builder.field("SAL"))
      .distinct()
      .filter(builder.equals(builder.field("SAL"), builder.literal(1)))
      .exchange(RelDistributions.hash(ImmutableList.of(1)))
      .build();
  final RelMetadataQuery mq = exchange.getCluster().getMetadataQuery();
  assertThat(mq.areColumnsUnique(exchange, ImmutableBitSet.of(0)), is(true));
}
 
Example #28
Source File: RelWriterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testTableModifyDelete() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  RelNode filter = builder
      .scan("EMP")
      .filter(
          builder.call(
              SqlStdOperatorTable.EQUALS,
              builder.field("JOB"),
              builder.literal("c")))
      .build();
  LogicalTableModify modify = LogicalTableModify.create(
      filter.getInput(0).getTable(),
      (Prepare.CatalogReader) filter.getInput(0).getTable().getRelOptSchema(),
      filter,
      TableModify.Operation.DELETE,
      null,
      null,
      false);
  String relJson = RelOptUtil.dumpPlan("", modify,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s = deserializeAndDumpToTextFormat(getSchema(modify), relJson);
  final String expected = ""
      + "LogicalTableModify(table=[[scott, EMP]], operation=[DELETE], flattened=[false])\n"
      + "  LogicalFilter(condition=[=($2, 'c')])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #29
Source File: RelWriterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testCalc() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RexBuilder rexBuilder = builder.getRexBuilder();
  final LogicalTableScan scan = (LogicalTableScan) builder.scan("EMP").build();
  final RexProgramBuilder programBuilder =
      new RexProgramBuilder(scan.getRowType(), rexBuilder);
  final RelDataTypeField field = scan.getRowType().getField("SAL", false, false);
  programBuilder.addIdentity();
  programBuilder.addCondition(
      rexBuilder.makeCall(SqlStdOperatorTable.GREATER_THAN,
          new RexInputRef(field.getIndex(), field.getType()),
          builder.literal(10)));
  final LogicalCalc calc = LogicalCalc.create(scan, programBuilder.getProgram());
  String relJson = RelOptUtil.dumpPlan("", calc,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        final RelJsonReader reader = new RelJsonReader(
            cluster, getSchema(calc), rootSchema);
        RelNode node;
        try {
          node = reader.read(relJson);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });
  final String expected =
      "LogicalCalc(expr#0..7=[{inputs}], expr#8=[10], expr#9=[>($t5, $t8)],"
          + " proj#0..7=[{exprs}], $condition=[$t9])\n"
          + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #30
Source File: LexCaseSensitiveTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static Planner getPlanner(List<RelTraitDef> traitDefs,
    SqlParser.Config parserConfig, Program... programs) {
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .parserConfig(parserConfig)
      .defaultSchema(CalciteAssert.addSchema(rootSchema, CalciteAssert.SchemaSpec.HR))
      .traitDefs(traitDefs)
      .programs(programs)
      .build();
  return Frameworks.getPlanner(config);
}