Java Code Examples for org.apache.calcite.tools.Frameworks

The following examples show how to use org.apache.calcite.tools.Frameworks. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: marble   Source File: TableEnv.java    License: Apache License 2.0 6 votes vote down vote up
private FrameworkConfig createFrameworkConfig(
    SqlParser.Config sqlParserConfig, SqlOperatorTable sqlOperatorTable,
    SqlRexConvertletTable convertletTable,
    CalciteConnectionConfig calciteConnectionConfig,
    RelDataTypeSystem relDataTypeSystem, RexExecutor rexExecutor) {
  return Frameworks
      .newConfigBuilder()
      .defaultSchema(rootSchema)
      .parserConfig(sqlParserConfig)
      .operatorTable(sqlOperatorTable)
      .convertletTable(convertletTable)
      .typeSystem(relDataTypeSystem)
      .executor(rexExecutor)
      .context(Contexts.of(calciteConnectionConfig))
      .build();
}
 
Example 2
Source Project: marble   Source File: TableEnv.java    License: 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 3
Source Project: herddb   Source File: CalcitePlanner.java    License: 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 4
Source Project: sql-gremlin   Source File: GremlinCompiler.java    License: 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 5
Source Project: attic-apex-malhar   Source File: SQLExecEnvironment.java    License: 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 Project: streamline   Source File: RuleParser.java    License: 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 7
Source Project: streamline   Source File: StreamlineSqlImpl.java    License: 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 8
Source Project: quark   Source File: SqlWorker.java    License: 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 9
Source Project: calcite   Source File: TpcdsLatticeSuggesterTest.java    License: 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 10
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: 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 11
Source Project: calcite   Source File: NormalizationTrimFieldTest.java    License: 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 12
Source Project: calcite   Source File: LatticeSuggesterTest.java    License: 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 13
Source Project: calcite   Source File: SortRemoveRuleTest.java    License: 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 14
Source Project: calcite   Source File: LexEscapeTest.java    License: 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 15
Source Project: calcite   Source File: RelBuilderTest.java    License: 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 16
Source Project: calcite   Source File: RelBuilderTest.java    License: 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 17
Source Project: calcite   Source File: RelBuilderTest.java    License: 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 18
Source Project: calcite   Source File: RelWriterTest.java    License: 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 19
Source Project: calcite   Source File: RelWriterTest.java    License: 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 20
Source Project: calcite   Source File: RelWriterTest.java    License: 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 21
Source Project: calcite   Source File: RexExecutorTest.java    License: 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 22
Source Project: flink   Source File: PlanningConfigurationBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private FrameworkConfig createFrameworkConfig() {
	return Frameworks
		.newConfigBuilder()
		.parserConfig(getSqlParserConfig())
		.costFactory(costFactory)
		.typeSystem(typeSystem)
		.operatorTable(getSqlOperatorTable(calciteConfig(tableConfig), functionCatalog))
		.sqlToRelConverterConfig(
			getSqlToRelConverterConfig(
				calciteConfig(tableConfig),
				expressionBridge))
		// set the executor to evaluate constant expressions
		.executor(new ExpressionReducer(tableConfig))
		.build();
}
 
Example 23
Source Project: flink   Source File: PlannerContext.java    License: 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 24
Source Project: samza   Source File: SamzaSqlQueryParser.java    License: 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 Project: attic-apex-malhar   Source File: SQLExecEnvironment.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method method build a calcite framework configuration for calcite to parse SQL and generate relational tree
 * out of it.
 * @return FrameworkConfig
 */
private FrameworkConfig buildFrameWorkConfig()
{
  List<SqlOperatorTable> sqlOperatorTables = new ArrayList<>();
  sqlOperatorTables.add(SqlStdOperatorTable.instance());
  sqlOperatorTables
    .add(new CalciteCatalogReader(CalciteSchema.from(schema), false, Collections.<String>emptyList(), typeFactory));
  return Frameworks.newConfigBuilder().defaultSchema(schema)
    .parserConfig(SqlParser.configBuilder().setLex(Lex.MYSQL).build())
    .operatorTable(new ChainedSqlOperatorTable(sqlOperatorTables)).build();
}
 
Example 26
Source Project: streamline   Source File: StreamlineSqlImpl.java    License: Apache License 2.0 5 votes vote down vote up
private FrameworkConfig buildFrameWorkConfig() {
  if (hasUdf) {
    List<SqlOperatorTable> sqlOperatorTables = new ArrayList<>();
    sqlOperatorTables.add(SqlStdOperatorTable.instance());
    sqlOperatorTables.add(new CalciteCatalogReader(CalciteSchema.from(schema),
                                                   false,
                                                   Collections.<String>emptyList(), typeFactory));
    return Frameworks.newConfigBuilder().defaultSchema(schema)
            .operatorTable(new ChainedSqlOperatorTable(sqlOperatorTables)).build();
  } else {
    return Frameworks.newConfigBuilder().defaultSchema(schema).build();
  }
}
 
Example 27
Source Project: streamline   Source File: TestCompilerUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static CalciteState sqlOverDummyTable(String sql)
        throws RelConversionException, ValidationException, SqlParseException {
    SchemaPlus schema = Frameworks.createRootSchema(true);
    JavaTypeFactory typeFactory = new JavaTypeFactoryImpl
            (RelDataTypeSystem.DEFAULT);
    StreamableTable streamableTable = new CompilerUtil.TableBuilderInfo(typeFactory)
            .field("ID", SqlTypeName.INTEGER)
            .field("NAME", typeFactory.createType(String.class))
            .field("ADDR", typeFactory.createType(String.class))
            .build();
    Table table = streamableTable.stream();
    schema.add("FOO", table);
    schema.add("BAR", table);
    schema.add("MYPLUS", ScalarFunctionImpl.create(MyPlus.class, "eval"));

    List<SqlOperatorTable> sqlOperatorTables = new ArrayList<>();
    sqlOperatorTables.add(SqlStdOperatorTable.instance());
    sqlOperatorTables.add(new CalciteCatalogReader(CalciteSchema.from(schema),
            false,
            Collections.<String>emptyList(), typeFactory));
    SqlOperatorTable chainedSqlOperatorTable = new ChainedSqlOperatorTable(sqlOperatorTables);
    FrameworkConfig config = Frameworks.newConfigBuilder().defaultSchema(
            schema).operatorTable(chainedSqlOperatorTable).build();
    Planner planner = Frameworks.getPlanner(config);
    SqlNode parse = planner.parse(sql);
    SqlNode validate = planner.validate(parse);
    RelNode tree = planner.convert(validate);
    System.out.println(RelOptUtil.toString(tree, SqlExplainLevel.ALL_ATTRIBUTES));
    return new CalciteState(schema, tree);
}
 
Example 28
Source Project: flink   Source File: PlanningConfigurationBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private FrameworkConfig createFrameworkConfig() {
	return Frameworks
		.newConfigBuilder()
		.parserConfig(getSqlParserConfig())
		.costFactory(costFactory)
		.typeSystem(typeSystem)
		.operatorTable(getSqlOperatorTable(calciteConfig(tableConfig), functionCatalog))
		.sqlToRelConverterConfig(
			getSqlToRelConverterConfig(
				calciteConfig(tableConfig),
				expressionBridge))
		// set the executor to evaluate constant expressions
		.executor(new ExpressionReducer(tableConfig))
		.build();
}
 
Example 29
Source Project: flink   Source File: PlannerContext.java    License: 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)))
		// set the executor to evaluate constant expressions
		.executor(new ExpressionReducer(tableConfig, false))
		.context(context)
		.traitDefs(traitDefs)
		.build();
}
 
Example 30
Source Project: calcite   Source File: TpcdsLatticeSuggesterTest.java    License: Apache License 2.0 5 votes vote down vote up
static Frameworks.ConfigBuilder config(CalciteAssert.SchemaSpec spec) {
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  final SchemaPlus schema = CalciteAssert.addSchema(rootSchema, spec);
  return Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.Config.DEFAULT)
      .defaultSchema(schema);
}