org.apache.calcite.tools.Frameworks Java Examples

The following examples show how to use org.apache.calcite.tools.Frameworks. 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: 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 #2
Source File: NormalizationTrimFieldTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static Frameworks.ConfigBuilder config() {
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  rootSchema.add("mv0", new AbstractTable() {
    @Override public RelDataType getRowType(RelDataTypeFactory typeFactory) {
      return typeFactory.builder()
          .add("deptno", SqlTypeName.INTEGER)
          .add("count_sal", SqlTypeName.BIGINT)
          .build();
    }
  });
  return Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.Config.DEFAULT)
      .defaultSchema(
          CalciteAssert.addSchema(rootSchema, CalciteAssert.SchemaSpec.SCOTT_WITH_TEMPORAL))
      .traitDefs((List<RelTraitDef>) null);
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Unit test for {@link org.apache.calcite.rel.externalize.RelJsonReader}.
 */
@Test void testReader() {
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        SchemaPlus schema =
            rootSchema.add("hr",
                new ReflectiveSchema(new JdbcTest.HrSchema()));
        final RelJsonReader reader =
            new RelJsonReader(cluster, relOptSchema, schema);
        RelNode node;
        try {
          node = reader.read(XX);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });

  assertThat(s,
      isLinux("LogicalAggregate(group=[{0}], c=[COUNT(DISTINCT $1)], d=[COUNT()])\n"
          + "  LogicalFilter(condition=[=($1, 10)])\n"
          + "    LogicalTableScan(table=[[hr, emps]])\n"));
}
 
Example #9
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 #10
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 #11
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Creates a config builder that will contain a view, "MYVIEW", and also
 * the SCOTT JDBC schema, whose tables implement
 * {@link org.apache.calcite.schema.TranslatableTable}. */
static Frameworks.ConfigBuilder expandingConfig(Connection connection)
    throws SQLException {
  final CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  final SchemaPlus root = calciteConnection.getRootSchema();
  CalciteAssert.SchemaSpec spec = CalciteAssert.SchemaSpec.SCOTT;
  CalciteAssert.addSchema(root, spec);
  final String viewSql =
      String.format(Locale.ROOT, "select * from \"%s\".\"%s\" where 1=1",
          spec.schemaName, "EMP");

  // create view
  ViewTableMacro macro = ViewTable.viewMacro(root, viewSql,
      Collections.singletonList("test"), Arrays.asList("test", "view"), false);

  // register view (in root schema)
  root.add("MYVIEW", macro);

  return Frameworks.newConfigBuilder().defaultSchema(root);
}
 
Example #12
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Unit test for {@link org.apache.calcite.rel.externalize.RelJsonReader}.
 */
@Test void testReaderNull() {
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        SchemaPlus schema =
            rootSchema.add("hr",
                new ReflectiveSchema(new JdbcTest.HrSchema()));
        final RelJsonReader reader =
            new RelJsonReader(cluster, relOptSchema, schema);
        RelNode node;
        try {
          node = reader.read(XXNULL);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });

  assertThat(s,
      isLinux("LogicalAggregate(group=[{0}], agg#0=[COUNT(DISTINCT $1)], agg#1=[COUNT()])\n"
          + "  LogicalFilter(condition=[=($1, null:INTEGER)])\n"
          + "    LogicalTableScan(table=[[hr, emps]])\n"));
}
 
Example #13
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 #14
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Deserialize a relnode from the json string by {@link RelJsonReader},
 * and dump it to text format.
 */
private String deserializeAndDumpToTextFormat(RelOptSchema schema, String relJson) {
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        final RelJsonReader reader = new RelJsonReader(
            cluster, schema, rootSchema);
        RelNode node;
        try {
          node = reader.read(relJson);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });
  return s;
}
 
Example #15
Source File: GremlinCompiler.java    From sql-gremlin with Apache License 2.0 6 votes vote down vote up
public GremlinCompiler(Graph graph, SchemaConfig schemaConfig) {
    this.graph = graph;
    this.schemaConfig = schemaConfig;

    final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
    final List<RelTraitDef> traitDefs = new ArrayList<>();
    traitDefs.add(ConventionTraitDef.INSTANCE);
    traitDefs.add(RelCollationTraitDef.INSTANCE);
    final SqlParser.Config parserConfig =
            SqlParser.configBuilder().setLex(Lex.MYSQL).build();

    frameworkConfig = Frameworks.newConfigBuilder()
            .parserConfig(parserConfig)
            .defaultSchema(rootSchema.add("gremlin", new GremlinSchema(graph, schemaConfig)))
            .traitDefs(traitDefs)
            .programs(Programs.sequence(Programs.ofRules(Programs.RULE_SET), Programs.CALC_PROGRAM))
            .build();
}
 
Example #16
Source File: CalcitePlanner.java    From herddb with Apache License 2.0 6 votes vote down vote up
private SchemaPlus getRootSchema() throws MetadataStorageManagerException {
    if (rootSchema != null) {
        return rootSchema;
    }
    final SchemaPlus _rootSchema = Frameworks.createRootSchema(true);
    for (String tableSpace : manager.getLocalTableSpaces()) {
        TableSpaceManager tableSpaceManager = manager.getTableSpaceManager(tableSpace);
        SchemaPlus schema = _rootSchema.add(tableSpace, new AbstractSchema());
        List<Table> tables = tableSpaceManager.getAllTablesForPlanner();
        for (Table table : tables) {
            AbstractTableManager tableManager = tableSpaceManager.getTableManager(table.name);
            TableImpl tableDef = new TableImpl(tableManager);
            schema.add(table.name, tableDef);
        }
    }
    rootSchema = _rootSchema;
    return _rootSchema;
}
 
Example #17
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 #18
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 #19
Source File: RexExecutorTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures that for a given context operator,
 * the correct value is retrieved from the {@link DataContext}.
 *
 * @param operator The Operator to check
 * @param variable The DataContext variable this operator should be bound to
 * @param value The expected value to retrieve.
 */
private void testContextLiteral(
    final SqlOperator operator,
    final DataContext.Variable variable,
    final Object value) {
  Frameworks.withPrepare((cluster, relOptSchema, rootSchema, statement) -> {
    final RexBuilder rexBuilder = cluster.getRexBuilder();
    final RexExecutorImpl executor =
        new RexExecutorImpl(
            new SingleValueDataContext(variable.camelName, value));
    try {
      checkConstant(value, builder -> {
        final List<RexNode> output = new ArrayList<>();
        executor.reduce(rexBuilder,
            ImmutableList.of(rexBuilder.makeCall(operator)), output);
        return output.get(0);
      });
    } catch (Exception e) {
      throw TestUtil.rethrow(e);
    }
    return null;
  });
}
 
Example #20
Source File: TableEnv.java    From marble with Apache License 2.0 6 votes vote down vote up
protected RelRoot getSqlPlanRel(String sql) throws Throwable {
  try (Planner planner = Frameworks.getPlanner(frameworkConfig)) {
    RelRoot root;
    final SqlNode parsedSqlNode = planner.parse(sql);
    final Pair<SqlNode, RelDataType> validatedSqlNodeAndType = planner
        .validateAndGetType(
            parsedSqlNode);
    root = planner.rel(validatedSqlNodeAndType.getKey());
    final Program program = createProgram();
    //getDesiredTraits
    final RelTraitSet desiredTraits = root.rel.getTraitSet()
        .replace(EnumerableConvention.INSTANCE)
        .replace(root.collation)
        .simplify();

    RelNode logicalRelNode = root.rel;
    final RelNode optimizedRelNode = program.run(
        root.rel.getCluster().getPlanner(), logicalRelNode, desiredTraits,
        Collections.emptyList(), Collections.emptyList());
    root = root.withRel(optimizedRelNode);
    return root;
  }

}
 
Example #21
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 #22
Source File: SqlStatisticProviderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a config based on the "foodmart" schema. */
public static Frameworks.ConfigBuilder config() {
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  return Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.Config.DEFAULT)
      .defaultSchema(
          CalciteAssert.addSchema(rootSchema,
              CalciteAssert.SchemaSpec.JDBC_FOODMART))
      .traitDefs((List<RelTraitDef>) null)
      .programs(Programs.heuristicJoinOrder(Programs.RULE_SET, true, 2));
}
 
Example #23
Source File: RelMetadataTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Unit test for
 * {@link org.apache.calcite.rel.metadata.RelMetadataQuery#getAverageColumnSizes(org.apache.calcite.rel.RelNode)},
 * {@link org.apache.calcite.rel.metadata.RelMetadataQuery#getAverageRowSize(org.apache.calcite.rel.RelNode)}. */
@Test void testAverageRowSize() {
  final Project rel = (Project) convertSql("select * from emp, dept");
  final Join join = (Join) rel.getInput();
  final RelOptTable empTable = join.getInput(0).getTable();
  final RelOptTable deptTable = join.getInput(1).getTable();
  Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
    checkAverageRowSize(cluster, empTable, deptTable);
    return null;
  });
}
 
Example #24
Source File: RelMetadataTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Unit test for
 * {@link org.apache.calcite.rel.metadata.RelMdCollation#project}
 * and other helper functions for deducing collations. */
@Test void testCollation() {
  final Project rel = (Project) convertSql("select * from emp, dept");
  final Join join = (Join) rel.getInput();
  final RelOptTable empTable = join.getInput(0).getTable();
  final RelOptTable deptTable = join.getInput(1).getTable();
  Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
    checkCollation(cluster, empTable, deptTable);
    return null;
  });
}
 
Example #25
Source File: ExtensionDdlExecutor.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Populates the table called {@code name} by executing {@code query}. */
protected static void populate(SqlIdentifier name, SqlNode query,
    CalcitePrepare.Context context) {
  // Generate, prepare and execute an "INSERT INTO table query" statement.
  // (It's a bit inefficient that we convert from SqlNode to SQL and back
  // again.)
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .defaultSchema(
          Objects.requireNonNull(
              Schemas.subSchema(context.getRootSchema(),
                  context.getDefaultSchemaPath())).plus())
      .build();
  final Planner planner = Frameworks.getPlanner(config);
  try {
    final StringBuilder buf = new StringBuilder();
    final SqlPrettyWriter w =
        new SqlPrettyWriter(
            SqlPrettyWriter.config()
                .withDialect(CalciteSqlDialect.DEFAULT)
                .withAlwaysUseParentheses(false),
            buf);
    buf.append("INSERT INTO ");
    name.unparse(w, 0, 0);
    buf.append(" ");
    query.unparse(w, 0, 0);
    final String sql = buf.toString();
    final SqlNode query1 = planner.parse(sql);
    final SqlNode query2 = planner.validate(query1);
    final RelRoot r = planner.rel(query2);
    final PreparedStatement prepare = context.getRelRunner().prepare(r.rel);
    int rowCount = prepare.executeUpdate();
    Util.discard(rowCount);
    prepare.close();
  } catch (SqlParseException | ValidationException
      | RelConversionException | SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #26
Source File: RelMetadataTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testAllPredicates() {
  final Project rel = (Project) convertSql("select * from emp, dept");
  final Join join = (Join) rel.getInput();
  final RelOptTable empTable = join.getInput(0).getTable();
  final RelOptTable deptTable = join.getInput(1).getTable();
  Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
    checkAllPredicates(cluster, empTable, deptTable);
    return null;
  });
}
 
Example #27
Source File: PlannerContext.java    From flink with Apache License 2.0 5 votes vote down vote up
private FrameworkConfig createFrameworkConfig() {
	return Frameworks.newConfigBuilder()
		.defaultSchema(rootSchema.plus())
		.parserConfig(getSqlParserConfig())
		.costFactory(new FlinkCostFactory())
		.typeSystem(typeSystem)
		.sqlToRelConverterConfig(getSqlToRelConverterConfig(getCalciteConfig(tableConfig)))
		.operatorTable(getSqlOperatorTable(getCalciteConfig(tableConfig), functionCatalog))
		// set the executor to evaluate constant expressions
		.executor(new ExpressionReducer(tableConfig, false))
		.context(context)
		.traitDefs(traitDefs)
		.build();
}
 
Example #28
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 #29
Source File: RelMetadataTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Unit test for
 * {@link org.apache.calcite.rel.metadata.RelMdPredicates#getPredicates(Join, RelMetadataQuery)}. */
@Test void testPredicates() {
  final Project rel = (Project) convertSql("select * from emp, dept");
  final Join join = (Join) rel.getInput();
  final RelOptTable empTable = join.getInput(0).getTable();
  final RelOptTable deptTable = join.getInput(1).getTable();
  Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
    checkPredicates(cluster, empTable, deptTable);
    return null;
  });
}
 
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);
}