org.apache.calcite.schema.impl.AbstractSchema Java Examples

The following examples show how to use org.apache.calcite.schema.impl.AbstractSchema. 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: ReflectiveSchemaTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a view.
 */
@Test void testView() throws SQLException, ClassNotFoundException {
  Connection connection =
      DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  schema.add("emps_view",
      ViewTable.viewMacro(schema,
          "select * from \"hr\".\"emps\" where \"deptno\" = 10",
          null, Arrays.asList("s", "emps_view"), null));
  rootSchema.add("hr", new ReflectiveSchema(new JdbcTest.HrSchema()));
  ResultSet resultSet = connection.createStatement().executeQuery(
      "select *\n"
      + "from \"s\".\"emps_view\"\n"
      + "where \"empid\" < 120");
  assertEquals(
      "empid=100; deptno=10; name=Bill; salary=10000.0; commission=1000\n"
      + "empid=110; deptno=10; name=Theodore; salary=11500.0; commission=250\n",
      CalciteAssert.toString(resultSet));
}
 
Example #2
Source File: TableFunctionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testTableFunctionWithMapParameter() throws SQLException {
  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
    final TableFunction table =
        TableFunctionImpl.create(Smalls.GENERATE_STRINGS_OF_INPUT_MAP_SIZE_METHOD);
    schema.add("GenerateStringsOfInputMapSize", table);
    final String sql = "select *\n"
        + "from table(\"s\".\"GenerateStringsOfInputMapSize\"(Map[5,4,3,1])) as t(n, c)\n"
        + "where char_length(c) > 0";
    ResultSet resultSet = connection.createStatement().executeQuery(sql);
    assertThat(CalciteAssert.toString(resultSet),
        equalTo("N=1; C=a\n"));
  }
}
 
Example #3
Source File: TableFunctionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testTableFunctionWithArrayParameter() throws SQLException {
  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
    final TableFunction table =
        TableFunctionImpl.create(Smalls.GENERATE_STRINGS_OF_INPUT_SIZE_METHOD);
    schema.add("GenerateStringsOfInputSize", table);
    final String sql = "select *\n"
        + "from table(\"s\".\"GenerateStringsOfInputSize\"(ARRAY[5,4,3,1,2])) as t(n, c)\n"
        + "where char_length(c) > 3";
    ResultSet resultSet = connection.createStatement().executeQuery(sql);
    assertThat(CalciteAssert.toString(resultSet),
        equalTo("N=4; C=abcd\n"));
  }
}
 
Example #4
Source File: TableFunctionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a table function with literal arguments.
 */
@Test void testTableFunction() throws SQLException {
  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
    final TableFunction table =
        TableFunctionImpl.create(Smalls.GENERATE_STRINGS_METHOD);
    schema.add("GenerateStrings", table);
    final String sql = "select *\n"
        + "from table(\"s\".\"GenerateStrings\"(5)) as t(n, c)\n"
        + "where char_length(c) > 3";
    ResultSet resultSet = connection.createStatement().executeQuery(sql);
    assertThat(CalciteAssert.toString(resultSet),
        equalTo("N=4; C=abcd\n"));
  }
}
 
Example #5
Source File: TableFunctionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a table function that implements {@link ScannableTable} and returns
 * a single column.
 */
@Test void testScannableTableFunction()
    throws SQLException, ClassNotFoundException {
  Connection connection = DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  final TableFunction table = TableFunctionImpl.create(Smalls.MAZE_METHOD);
  schema.add("Maze", table);
  final String sql = "select *\n"
      + "from table(\"s\".\"Maze\"(5, 3, 1))";
  ResultSet resultSet = connection.createStatement().executeQuery(sql);
  final String result = "S=abcde\n"
      + "S=xyz\n"
      + "S=generate(w=5, h=3, s=1)\n";
  assertThat(CalciteAssert.toString(resultSet), is(result));
}
 
Example #6
Source File: TableFunctionTest.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-2382">[CALCITE-2382]
 * Sub-query lateral joined to table function</a>. */
@Test void testInlineViewLateralTableFunction() throws SQLException {
  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
    final TableFunction table =
        TableFunctionImpl.create(Smalls.GENERATE_STRINGS_METHOD);
    schema.add("GenerateStrings", table);
    Table tbl = new ScannableTableTest.SimpleTable();
    schema.add("t", tbl);

    final String sql = "select *\n"
        + "from (select 5 as f0 from \"s\".\"t\") \"a\",\n"
        + "  lateral table(\"s\".\"GenerateStrings\"(f0)) as t(n, c)\n"
        + "where char_length(c) > 3";
    ResultSet resultSet = connection.createStatement().executeQuery(sql);
    final String expected = "F0=5; N=4; C=abcd\n"
        + "F0=5; N=4; C=abcd\n"
        + "F0=5; N=4; C=abcd\n"
        + "F0=5; N=4; C=abcd\n";
    assertThat(CalciteAssert.toString(resultSet), equalTo(expected));
  }
}
 
Example #7
Source File: FrameworksTest.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-2039">[CALCITE-2039]
 * AssertionError when pushing project to ProjectableFilterableTable</a>
 * using UPDATE via {@link Frameworks}. */
@Test void testUpdate() throws Exception {
  Table table = new TableImpl();
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  SchemaPlus schema = rootSchema.add("x", new AbstractSchema());
  schema.add("MYTABLE", table);
  List<RelTraitDef> traitDefs = new ArrayList<>();
  traitDefs.add(ConventionTraitDef.INSTANCE);
  traitDefs.add(RelDistributionTraitDef.INSTANCE);
  SqlParser.Config parserConfig =
      SqlParser.configBuilder(SqlParser.Config.DEFAULT)
          .setCaseSensitive(false)
          .build();

  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .parserConfig(parserConfig)
      .defaultSchema(schema)
      .traitDefs(traitDefs)
      // define the rules you want to apply
      .ruleSets(
          RuleSets.ofList(AbstractConverter.ExpandConversionRule.INSTANCE))
      .programs(Programs.ofRules(Programs.RULE_SET))
      .build();
  executeQuery(config, " UPDATE MYTABLE set id=7 where id=1",
      CalciteSystemProperty.DEBUG.value());
}
 
Example #8
Source File: ReflectiveSchemaTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a relation that is accessed via method syntax.
 * The function returns a {@link org.apache.calcite.linq4j.Queryable}.
 */
@Disabled
@Test void testOperator() throws SQLException, ClassNotFoundException {
  Connection connection =
      DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  schema.add("GenerateStrings",
      TableMacroImpl.create(Smalls.GENERATE_STRINGS_METHOD));
  schema.add("StringUnion",
      TableMacroImpl.create(Smalls.STRING_UNION_METHOD));
  rootSchema.add("hr", new ReflectiveSchema(new JdbcTest.HrSchema()));
  ResultSet resultSet = connection.createStatement().executeQuery(
      "select *\n"
      + "from table(s.StringUnion(\n"
      + "  GenerateStrings(5),\n"
      + "  cursor (select name from emps)))\n"
      + "where char_length(s) > 3");
  assertTrue(resultSet.next());
}
 
Example #9
Source File: ExampleFunctionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void checkMazeTableFunction(Boolean solution, String maze)
    throws SQLException, ClassNotFoundException {
  Connection connection = DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  final TableFunction table = TableFunctionImpl.create(MAZE_METHOD);
  schema.add("Maze", table);
  final TableFunction table2 = TableFunctionImpl.create(SOLVE_METHOD);
  schema.add("Solve", table2);
  final String sql;
  if (solution) {
    sql = "select *\n"
        + "from table(\"s\".\"Solve\"(5, 3, 1)) as t(s)";
  } else {
    sql = "select *\n"
        + "from table(\"s\".\"Maze\"(5, 3, 1)) as t(s)";
  }
  ResultSet resultSet = connection.createStatement().executeQuery(sql);
  final StringBuilder b = new StringBuilder();
  while (resultSet.next()) {
    b.append(resultSet.getString(1)).append("\n");
  }
  assertThat(b.toString(), is(maze));
}
 
Example #10
Source File: QueryPlanner.java    From samza with Apache License 2.0 6 votes vote down vote up
private void registerSourceSchemas(SchemaPlus rootSchema) {
  RelSchemaConverter relSchemaConverter = new RelSchemaConverter();

  for (SqlIOConfig ssc : systemStreamConfigBySource.values()) {
    SchemaPlus previousLevelSchema = rootSchema;
    List<String> sourceParts = ssc.getSourceParts();
    RelSchemaProvider relSchemaProvider = relSchemaProviders.get(ssc.getSource());

    for (int sourcePartIndex = 0; sourcePartIndex < sourceParts.size(); sourcePartIndex++) {
      String sourcePart = sourceParts.get(sourcePartIndex);
      if (sourcePartIndex < sourceParts.size() - 1) {
        SchemaPlus sourcePartSchema = previousLevelSchema.getSubSchema(sourcePart);
        if (sourcePartSchema == null) {
          sourcePartSchema = previousLevelSchema.add(sourcePart, new AbstractSchema());
        }
        previousLevelSchema = sourcePartSchema;
      } else {
        // If the source part is the last one, then fetch the schema corresponding to the stream and register.
        RelDataType relationalSchema = getSourceRelSchema(relSchemaProvider, relSchemaConverter);
        previousLevelSchema.add(sourcePart, createTableFromRelSchema(relationalSchema));
        break;
      }
    }
  }
}
 
Example #11
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 #12
Source File: ReflectiveSchemaTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Tests a view with a path.
 */
@Test void testViewPath() throws SQLException, ClassNotFoundException {
  Connection connection =
      DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  // create a view s.emps based on hr.emps. uses explicit schema path "hr".
  schema.add("emps",
      ViewTable.viewMacro(schema,
          "select * from \"emps\" where \"deptno\" = 10",
          ImmutableList.of("hr"), ImmutableList.of("s", "emps"), null));
  schema.add("hr_emps",
      ViewTable.viewMacro(schema,
          "select * from \"emps\"",
          ImmutableList.of("hr"), ImmutableList.of("s", "hr_emps"), null));
  schema.add("s_emps",
      ViewTable.viewMacro(schema,
          "select * from \"emps\"",
          ImmutableList.of("s"), ImmutableList.of("s", "s_emps"), null));
  schema.add("null_emps",
      ViewTable.viewMacro(schema, "select * from \"emps\"", null,
          ImmutableList.of("s", "null_emps"), null));
  rootSchema.add("hr", new ReflectiveSchema(new JdbcTest.HrSchema()));
  final Statement statement = connection.createStatement();
  ResultSet resultSet;
  resultSet = statement.executeQuery(
      "select * from \"s\".\"hr_emps\"");
  assertEquals(4, count(resultSet)); // "hr_emps" -> "hr"."emps", 4 rows
  resultSet = statement.executeQuery(
      "select * from \"s\".\"s_emps\""); // "s_emps" -> "s"."emps", 3 rows
  assertEquals(3, count(resultSet));
  resultSet = statement.executeQuery(
      "select * from \"s\".\"null_emps\""); // "null_emps" -> "s"."emps", 3
  assertEquals(3, count(resultSet));
  statement.close();
}
 
Example #13
Source File: ScannableTableTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected ConnectionPostProcessor newSchema(final String schemaName,
    Pair<String, Table>... tables) {
  return connection -> {
    CalciteConnection con = connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = con.getRootSchema();
    SchemaPlus schema = rootSchema.add(schemaName, new AbstractSchema());
    for (Pair<String, Table> t : tables) {
      schema.add(t.left, t.right);
    }
    connection.setSchema(schemaName);
    return connection;
  };
}
 
Example #14
Source File: UdfTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-937">[CALCITE-937]
 * User-defined function within view</a>. */
@Test void testUserDefinedFunctionInView() throws Exception {
  Class.forName("org.apache.calcite.jdbc.Driver");
  Connection connection = DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  rootSchema.add("hr", new ReflectiveSchema(new JdbcTest.HrSchema()));

  SchemaPlus post = rootSchema.add("POST", new AbstractSchema());
  post.add("MY_INCREMENT",
      ScalarFunctionImpl.create(Smalls.MyIncrement.class, "eval"));

  final String viewSql = "select \"empid\" as EMPLOYEE_ID,\n"
      + "  \"name\" || ' ' || \"name\" as EMPLOYEE_NAME,\n"
      + "  \"salary\" as EMPLOYEE_SALARY,\n"
      + "  POST.MY_INCREMENT(\"empid\", 10) as INCREMENTED_SALARY\n"
      + "from \"hr\".\"emps\"";
  post.add("V_EMP",
      ViewTable.viewMacro(post, viewSql, ImmutableList.of(),
          ImmutableList.of("POST", "V_EMP"), null));

  final String result = ""
      + "EMPLOYEE_ID=100; EMPLOYEE_NAME=Bill Bill; EMPLOYEE_SALARY=10000.0; INCREMENTED_SALARY=110.0\n"
      + "EMPLOYEE_ID=200; EMPLOYEE_NAME=Eric Eric; EMPLOYEE_SALARY=8000.0; INCREMENTED_SALARY=220.0\n"
      + "EMPLOYEE_ID=150; EMPLOYEE_NAME=Sebastian Sebastian; EMPLOYEE_SALARY=7000.0; INCREMENTED_SALARY=165.0\n"
      + "EMPLOYEE_ID=110; EMPLOYEE_NAME=Theodore Theodore; EMPLOYEE_SALARY=11500.0; INCREMENTED_SALARY=121.0\n";

  Statement statement = connection.createStatement();
  ResultSet resultSet = statement.executeQuery(viewSql);
  assertThat(CalciteAssert.toString(resultSet), is(result));
  resultSet.close();

  ResultSet viewResultSet =
      statement.executeQuery("select * from \"POST\".\"V_EMP\"");
  assertThat(CalciteAssert.toString(viewResultSet), is(result));
  statement.close();
  connection.close();
}
 
Example #15
Source File: UdfTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-1834">[CALCITE-1834]
 * User-defined function for Arrays</a>.
 */
@Test void testArrayUserDefinedFunction() throws Exception {
  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    rootSchema.add("hr", new ReflectiveSchema(new JdbcTest.HrSchema()));

    SchemaPlus post = rootSchema.add("POST", new AbstractSchema());
    post.add("ARRAY_APPEND", new ArrayAppendDoubleFunction());
    post.add("ARRAY_APPEND", new ArrayAppendIntegerFunction());
    final String sql = "select \"empid\" as EMPLOYEE_ID,\n"
        + "  \"name\" || ' ' || \"name\" as EMPLOYEE_NAME,\n"
        + "  \"salary\" as EMPLOYEE_SALARY,\n"
        + "  POST.ARRAY_APPEND(ARRAY[1,2,3], \"deptno\") as DEPARTMENTS\n"
        + "from \"hr\".\"emps\"";

    final String result = ""
        + "EMPLOYEE_ID=100; EMPLOYEE_NAME=Bill Bill;"
        + " EMPLOYEE_SALARY=10000.0; DEPARTMENTS=[1, 2, 3, 10]\n"
        + "EMPLOYEE_ID=200; EMPLOYEE_NAME=Eric Eric;"
        + " EMPLOYEE_SALARY=8000.0; DEPARTMENTS=[1, 2, 3, 20]\n"
        + "EMPLOYEE_ID=150; EMPLOYEE_NAME=Sebastian Sebastian;"
        + " EMPLOYEE_SALARY=7000.0; DEPARTMENTS=[1, 2, 3, 10]\n"
        + "EMPLOYEE_ID=110; EMPLOYEE_NAME=Theodore Theodore;"
        + " EMPLOYEE_SALARY=11500.0; DEPARTMENTS=[1, 2, 3, 10]\n";

    try (Statement statement = connection.createStatement();
         ResultSet resultSet = statement.executeQuery(sql)) {
      assertThat(CalciteAssert.toString(resultSet), is(result));
    }
    connection.close();
  }
}
 
Example #16
Source File: TableFunctionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Connection getConnectionWithMultiplyFunction() throws SQLException {
  Connection connection =
      DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  final TableFunction table =
      TableFunctionImpl.create(Smalls.MULTIPLICATION_TABLE_METHOD);
  schema.add("multiplication", table);
  return connection;
}
 
Example #17
Source File: TableFunctionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** As {@link #testScannableTableFunction()} but with named parameters. */
@Test void testScannableTableFunctionWithNamedParameters()
    throws SQLException, ClassNotFoundException {
  Connection connection = DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  final TableFunction table = TableFunctionImpl.create(Smalls.MAZE2_METHOD);
  schema.add("Maze", table);
  final String sql = "select *\n"
      + "from table(\"s\".\"Maze\"(5, 3, 1))";
  final Statement statement = connection.createStatement();
  ResultSet resultSet = statement.executeQuery(sql);
  final String result = "S=abcde\n"
      + "S=xyz\n";
  assertThat(CalciteAssert.toString(resultSet),
      is(result + "S=generate2(w=5, h=3, s=1)\n"));

  final String sql2 = "select *\n"
      + "from table(\"s\".\"Maze\"(WIDTH => 5, HEIGHT => 3, SEED => 1))";
  resultSet = statement.executeQuery(sql2);
  assertThat(CalciteAssert.toString(resultSet),
      is(result + "S=generate2(w=5, h=3, s=1)\n"));

  final String sql3 = "select *\n"
      + "from table(\"s\".\"Maze\"(HEIGHT => 3, WIDTH => 5))";
  resultSet = statement.executeQuery(sql3);
  assertThat(CalciteAssert.toString(resultSet),
      is(result + "S=generate2(w=5, h=3, s=null)\n"));
  connection.close();
}
 
Example #18
Source File: CollectionTypeTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Connection setupConnectionWithNestedTable() throws SQLException {
  Connection connection =
      DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  schema.add("nested", new NestedCollectionTable());
  return connection;
}
 
Example #19
Source File: CollectionTypeTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Connection setupConnectionWithNestedAnyTypeTable() throws SQLException {
  Connection connection =
      DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  schema.add("nested", new NestedCollectionWithAnyTypeTable());
  return connection;
}
 
Example #20
Source File: JdbcFrontLinqBackTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the post processor routine to be applied against a Connection.
 *
 * <p>Table schema is based on JdbcTest#Employee
 * (refer to {@link JdbcFrontLinqBackTest#mutable}).
 *
 * @param initialData records to be presented in table
 * @return a connection post-processor
 */
private static CalciteAssert.ConnectionPostProcessor makePostProcessor(
    final List<JdbcTest.Employee> initialData) {
  return connection -> {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus mapSchema = rootSchema.add("foo", new AbstractSchema());
    final String tableName = "bar";
    final JdbcTest.AbstractModifiableTable table =
        mutable(tableName, initialData);
    mapSchema.add(tableName, table);
    return calciteConnection;
  };
}
 
Example #21
Source File: SqlAdvisorJdbcTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void adviseSql(int apiVersion, String sql, Consumer<ResultSet> checker)
    throws SQLException {
  Properties info = new Properties();
  if (apiVersion == 1) {
    info.put("lex", "JAVA");
    info.put("quoting", "DOUBLE_QUOTE");
  } else if (apiVersion == 2) {
    info.put("lex", "SQL_SERVER");
    info.put("quoting", "BRACKET");
  }
  Connection connection =
      DriverManager.getConnection("jdbc:calcite:", info);
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  rootSchema.add("hr", new ReflectiveSchema(new JdbcTest.HrSchema()));
  SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
  calciteConnection.setSchema("hr");
  final TableFunction getHints =
      apiVersion == 1 ? new SqlAdvisorGetHintsFunction() : new SqlAdvisorGetHintsFunction2();
  schema.add("get_hints", getHints);
  String getHintsSql;
  if (apiVersion == 1) {
    getHintsSql = "select id, names, type from table(\"s\".\"get_hints\"(?, ?)) as t";
  } else {
    getHintsSql = "select id, names, type, replacement from table([s].[get_hints](?, ?)) as t";
  }

  PreparedStatement ps = connection.prepareStatement(getHintsSql);
  SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql);
  ps.setString(1, sap.sql);
  ps.setInt(2, sap.cursor);
  final ResultSet resultSet = ps.executeQuery();
  checker.accept(resultSet);
  resultSet.close();
  connection.close();
}
 
Example #22
Source File: FrameworksTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-3228">[CALCITE-3228]
 * Error while applying rule ProjectScanRule:interpreter</a>
 *
 * <p>This bug appears under the following conditions:
 * 1) have an aggregate with group by and multi aggregate calls.
 * 2) the aggregate can be removed during optimization.
 * 3) all aggregate calls are simplified to the same reference.
 * */
@Test void testPushProjectToScan() throws Exception {
  Table table = new TableImpl();
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  SchemaPlus schema = rootSchema.add("x", new AbstractSchema());
  schema.add("MYTABLE", table);
  List<RelTraitDef> traitDefs = new ArrayList<>();
  traitDefs.add(ConventionTraitDef.INSTANCE);
  traitDefs.add(RelDistributionTraitDef.INSTANCE);
  SqlParser.Config parserConfig =
          SqlParser.configBuilder(SqlParser.Config.DEFAULT)
                  .setCaseSensitive(false)
                  .build();

  final FrameworkConfig config = Frameworks.newConfigBuilder()
          .parserConfig(parserConfig)
          .defaultSchema(schema)
          .traitDefs(traitDefs)
          // define the rules you want to apply
          .ruleSets(
                  RuleSets.ofList(AbstractConverter.ExpandConversionRule.INSTANCE,
                          ProjectTableScanRule.INSTANCE))
          .programs(Programs.ofRules(Programs.RULE_SET))
          .build();

  executeQuery(config, "select min(id) as mi, max(id) as ma from mytable where id=1 group by id",
          CalciteSystemProperty.DEBUG.value());
}
 
Example #23
Source File: ModelHandler.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void visit(JsonMapSchema jsonSchema) {
  checkRequiredAttributes(jsonSchema, "name");
  final SchemaPlus parentSchema = currentMutableSchema("schema");
  final SchemaPlus schema =
      parentSchema.add(jsonSchema.name, new AbstractSchema());
  if (jsonSchema.path != null) {
    schema.setPath(stringListList(jsonSchema.path));
  }
  populateSchema(jsonSchema, schema);
}
 
Example #24
Source File: ServerDdlExecutor.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Executes a {@code CREATE SCHEMA} command. */
public void execute(SqlCreateSchema create,
    CalcitePrepare.Context context) {
  final Pair<CalciteSchema, String> pair = schema(context, true, create.name);
  final SchemaPlus subSchema0 = pair.left.plus().getSubSchema(pair.right);
  if (subSchema0 != null) {
    if (!create.getReplace() && !create.ifNotExists) {
      throw SqlUtil.newContextException(create.name.getParserPosition(),
          RESOURCE.schemaExists(pair.right));
    }
  }
  final Schema subSchema = new AbstractSchema();
  pair.left.add(pair.right, subSchema);
}
 
Example #25
Source File: MycatCalciteDataContext.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static SchemaPlus getSchema(MycatDBClientBased based) {
    SchemaPlus plus = CalciteSchema.createRootSchema(true).plus();
    MycatDBClientBasedConfig config = based.config();
    for (Map.Entry<String, SchemaHandler> stringConcurrentHashMapEntry : config.getSchemaMap().entrySet()) {
        SchemaPlus schemaPlus = plus.add(stringConcurrentHashMapEntry.getKey(), new AbstractSchema());
        for (Map.Entry<String, TableHandler> entry : stringConcurrentHashMapEntry.getValue().logicTables().entrySet()) {
            TableHandler logicTable = entry.getValue();
            MycatLogicTable mycatLogicTable = new MycatLogicTable(logicTable);
            schemaPlus.add(entry.getKey(), mycatLogicTable);
        }
    }
    config.getReflectiveSchemas().forEach((key, value) -> plus.add(key, new MycatReflectiveSchema(value)));
    return plus;
}
 
Example #26
Source File: MockCatalogReader.java    From calcite with Apache License 2.0 4 votes vote down vote up
private void registerNestedSchema(MockSchema parentSchema, MockSchema schema) {
  rootSchema.getSubSchema(parentSchema.getName(), true)
      .add(schema.name, new AbstractSchema());
}
 
Example #27
Source File: MockCatalogReader.java    From calcite with Apache License 2.0 4 votes vote down vote up
protected void registerSchema(MockSchema schema) {
  rootSchema.add(schema.name, new AbstractSchema());
}
 
Example #28
Source File: TableFunctionTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** As {@link #testScannableTableFunction()} but with named parameters. */
@Test void testMultipleScannableTableFunctionWithNamedParameters()
    throws SQLException, ClassNotFoundException {
  try (Connection connection = DriverManager.getConnection("jdbc:calcite:");
       Statement statement = connection.createStatement()) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
    final TableFunction table1 = TableFunctionImpl.create(Smalls.MAZE_METHOD);
    schema.add("Maze", table1);
    final TableFunction table2 = TableFunctionImpl.create(Smalls.MAZE2_METHOD);
    schema.add("Maze", table2);
    final TableFunction table3 = TableFunctionImpl.create(Smalls.MAZE3_METHOD);
    schema.add("Maze", table3);
    final String sql = "select *\n"
        + "from table(\"s\".\"Maze\"(5, 3, 1))";
    ResultSet resultSet = statement.executeQuery(sql);
    final String result = "S=abcde\n"
        + "S=xyz\n";
    assertThat(CalciteAssert.toString(resultSet),
        is(result + "S=generate(w=5, h=3, s=1)\n"));

    final String sql2 = "select *\n"
        + "from table(\"s\".\"Maze\"(WIDTH => 5, HEIGHT => 3, SEED => 1))";
    resultSet = statement.executeQuery(sql2);
    assertThat(CalciteAssert.toString(resultSet),
        is(result + "S=generate2(w=5, h=3, s=1)\n"));

    final String sql3 = "select *\n"
        + "from table(\"s\".\"Maze\"(HEIGHT => 3, WIDTH => 5))";
    resultSet = statement.executeQuery(sql3);
    assertThat(CalciteAssert.toString(resultSet),
        is(result + "S=generate2(w=5, h=3, s=null)\n"));

    final String sql4 = "select *\n"
        + "from table(\"s\".\"Maze\"(FOO => 'a'))";
    resultSet = statement.executeQuery(sql4);
    assertThat(CalciteAssert.toString(resultSet),
        is(result + "S=generate3(foo=a)\n"));
  }
}
 
Example #29
Source File: LookupOperatorOverloadsTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
private void checkInternal(boolean caseSensitive) throws SQLException {
  final SqlNameMatcher nameMatcher =
      SqlNameMatchers.withCaseSensitive(caseSensitive);
  final String schemaName = "MySchema";
  final String funcName = "MyFUNC";
  final String anotherName = "AnotherFunc";

  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus schema = rootSchema.add(schemaName, new AbstractSchema());
    final TableFunction table = TableFunctionImpl.create(Smalls.MAZE_METHOD);
    schema.add(funcName, table);
    schema.add(anotherName, table);
    final TableFunction table2 =
        TableFunctionImpl.create(Smalls.MAZE3_METHOD);
    schema.add(funcName, table2);

    final CalciteServerStatement statement =
        connection.createStatement().unwrap(CalciteServerStatement.class);
    final CalcitePrepare.Context prepareContext =
        statement.createPrepareContext();
    final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
    CalciteCatalogReader reader =
        new CalciteCatalogReader(prepareContext.getRootSchema(),
            ImmutableList.of(), typeFactory, prepareContext.config());

    final List<SqlOperator> operatorList = new ArrayList<>();
    SqlIdentifier myFuncIdentifier =
        new SqlIdentifier(Lists.newArrayList(schemaName, funcName), null,
            SqlParserPos.ZERO, null);
    reader.lookupOperatorOverloads(myFuncIdentifier,
        SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION, SqlSyntax.FUNCTION,
        operatorList, nameMatcher);
    checkFunctionType(2, funcName, operatorList);

    operatorList.clear();
    reader.lookupOperatorOverloads(myFuncIdentifier,
        SqlFunctionCategory.USER_DEFINED_FUNCTION, SqlSyntax.FUNCTION,
        operatorList, nameMatcher);
    checkFunctionType(0, null, operatorList);

    operatorList.clear();
    SqlIdentifier anotherFuncIdentifier =
        new SqlIdentifier(Lists.newArrayList(schemaName, anotherName), null,
            SqlParserPos.ZERO, null);
    reader.lookupOperatorOverloads(anotherFuncIdentifier,
        SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION, SqlSyntax.FUNCTION,
        operatorList, nameMatcher);
    checkFunctionType(1, anotherName, operatorList);
  }
}
 
Example #30
Source File: DruidAdapter2IT.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Test to make sure that the mapping from a Table name to a Table returned from
 * {@link org.apache.calcite.adapter.druid.DruidSchema} is always the same Java object.
 * */
@Test void testTableMapReused() {
  AbstractSchema schema = new DruidSchema(
      "http://localhost:8082", "http://localhost:8081", true);
  assertSame(schema.getTable("wikiticker"), schema.getTable("wikiticker"));
}