org.apache.calcite.schema.SchemaPlus Java Examples

The following examples show how to use org.apache.calcite.schema.SchemaPlus. 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: calcite   Author: apache   File: TableFunctionTest.java    License: 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 #2
Source Project: dk-fitting   Author: dkhadoop   File: ElasticsearchSchemaFactory.java    License: Apache License 2.0 6 votes vote down vote up
public Schema create(SchemaPlus parentSchema, String name, Map<String, Object> operand) {
    final Map map = (Map) operand;
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    try {
        final Map<String, Integer> esAddresses =
                mapper.readValue((String) map.get("esAddresses"),
                        new TypeReference<Map<String, Integer>>() { });
        final Map<String, String> esClusterConfig =
                mapper.readValue((String) map.get("esClusterConfig"),
                        new TypeReference<Map<String, String>>() { });
        final String esIndexName = (String) map.get("esIndexName");
        return new ElasticsearchSchema(esAddresses, esClusterConfig, esIndexName);
    } catch (IOException e) {
        throw new RuntimeException("Cannot parse values from json", e);
    }
}
 
Example #3
Source Project: calcite   Author: apache   File: PigRelBuilderStyleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test @Disabled("CALCITE-1751")
public void testImplWithGroupByAndCount() {
  final SchemaPlus schema = createTestSchema();
  final RelBuilder builder = createRelBuilder(schema);
  final RelNode node = builder.scan("t")
      .aggregate(builder.groupKey("tc0"), builder.count(false, "c", builder.field("tc1")))
      .build();
  final RelNode optimized = optimizeWithVolcano(node);
  assertScriptAndResults("t", getPigScript(optimized, schema),
      "t = LOAD 'target/data.txt"
          + "' USING PigStorage() AS (tc0:chararray, tc1:chararray);\n"
          + "t = GROUP t BY (tc0);\n"
          + "t = FOREACH t {\n"
          + "  GENERATE group AS tc0, COUNT(t.tc1) AS c;\n"
          + "};",
      new String[] { "(a,1)", "(b,1)", "(c,1)" });
}
 
Example #4
Source Project: marble   Author: 51nb   File: TableDataContexImpl.java    License: Apache License 2.0 6 votes vote down vote up
public TableDataContexImpl(QueryProvider queryProvider,
    SchemaPlus rootSchema,
    JavaTypeFactory typeFactory, TableConfig tableConfig) {
  this.queryProvider = queryProvider;
  this.typeFactory = typeFactory;
  this.rootSchema = rootSchema;

  final long time = System.currentTimeMillis();
  final TimeZone timeZone = tableConfig.getTimeZone();
  final long localOffset = timeZone.getOffset(time);
  final long currentOffset = localOffset;
  ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
  builder.put(Variable.UTC_TIMESTAMP.camelName, time)
      .put(Variable.CURRENT_TIMESTAMP.camelName, time + currentOffset)
      .put(Variable.LOCAL_TIMESTAMP.camelName, time + localOffset)
      .put(Variable.TIME_ZONE.camelName, timeZone);

  map = builder.build();
}
 
Example #5
Source Project: calcite   Author: apache   File: GeodeSchemaFactory.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized Schema create(SchemaPlus parentSchema, String name,
    Map<String, Object> operand) {
  Map map = (Map) operand;
  String locatorHost = (String) map.get(LOCATOR_HOST);
  int locatorPort = Integer.valueOf((String) map.get(LOCATOR_PORT));
  String[] regionNames = ((String) map.get(REGIONS)).split(COMMA_DELIMITER);
  String pbxSerializablePackagePath = (String) map.get(PDX_SERIALIZABLE_PACKAGE_PATH);

  boolean allowSpatialFunctions = true;
  if (map.containsKey(ALLOW_SPATIAL_FUNCTIONS)) {
    allowSpatialFunctions = Boolean.valueOf((String) map.get(ALLOW_SPATIAL_FUNCTIONS));
  }

  if (allowSpatialFunctions) {
    ModelHandler.addFunctions(parentSchema, null, ImmutableList.of(),
        GeoFunctions.class.getName(), "*", true);
  }

  return new GeodeSchema(
      createClientCache(locatorHost, locatorPort, pbxSerializablePackagePath, true),
      Arrays.asList(regionNames));
}
 
Example #6
Source Project: dremio-oss   Author: dremio   File: DatasetPath.java    License: Apache License 2.0 6 votes vote down vote up
public Table getTable(SchemaPlus rootSchema){
  List<FolderName> components = this.getFolderPath();
  SchemaPlus schema = rootSchema.getSubSchema(this.getRoot().getName());
  if(schema == null){
    throw new IllegalStateException(String.format("Failure finding schema path %s in position 0 of path %s", getRoot().getName(), toPathString()));
  }

  int i = 1;
  for(FolderName folder : components){
    schema = schema.getSubSchema(folder.getName());
    if(schema == null){
      throw new IllegalStateException(String.format("Failure finding schema path %s in position %d of path %s", folder.getName(), i, toPathString()));
    }
    i++;
  }
  Table table = schema.getTable(getLeaf().getName());
  if(table == null){
    throw new IllegalStateException(String.format("Failure finding table in path %s. The schema exists but no table in that schema matches %s", toPathString(), getLeaf().getName()));
  }

  return table;
}
 
Example #7
Source Project: calcite   Author: apache   File: ReflectiveSchemaTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-1919">[CALCITE-1919]
 * NPE when target in ReflectiveSchema belongs to the unnamed package</a>. */
@Test void testReflectiveSchemaInUnnamedPackage() throws Exception {
  final Driver driver = new Driver();
  try (CalciteConnection connection = (CalciteConnection)
      driver.connect("jdbc:calcite:", new Properties())) {
    SchemaPlus rootSchema = connection.getRootSchema();
    final Class<?> c = Class.forName("RootHr");
    final Object o = c.getDeclaredConstructor().newInstance();
    rootSchema.add("hr", new ReflectiveSchema(o));
    connection.setSchema("hr");
    final Statement statement = connection.createStatement();
    final String sql = "select * from \"emps\"";
    final ResultSet resultSet = statement.executeQuery(sql);
    final String expected = "empid=100; name=Bill\n"
        + "empid=200; name=Eric\n"
        + "empid=150; name=Sebastian\n";
    assertThat(CalciteAssert.toString(resultSet), is(expected));
  }
}
 
Example #8
Source Project: calcite   Author: apache   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 #9
Source Project: calcite   Author: apache   File: ReflectiveSchemaTest.java    License: 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 #10
Source Project: calcite   Author: apache   File: AbstractMaterializedViewTest.java    License: Apache License 2.0 6 votes vote down vote up
private RelNode toRel(RelOptCluster cluster, SchemaPlus rootSchema,
    SchemaPlus defaultSchema, String sql) throws SqlParseException {
  final SqlParser parser = SqlParser.create(sql, SqlParser.Config.DEFAULT);
  final SqlNode parsed = parser.parseStmt();

  final CalciteCatalogReader catalogReader = new CalciteCatalogReader(
      CalciteSchema.from(rootSchema),
      CalciteSchema.from(defaultSchema).path(null),
      new JavaTypeFactoryImpl(), new CalciteConnectionConfigImpl(new Properties()));

  final SqlValidator validator = new ValidatorForTest(SqlStdOperatorTable.instance(),
      catalogReader, new JavaTypeFactoryImpl(), SqlConformanceEnum.DEFAULT);
  final SqlNode validated = validator.validate(parsed);
  final SqlToRelConverter.Config config = SqlToRelConverter.configBuilder()
      .withTrimUnusedFields(true)
      .withExpand(true)
      .withDecorrelationEnabled(true)
      .build();
  final SqlToRelConverter converter = new SqlToRelConverter(
      (rowType, queryString, schemaPath, viewPath) -> {
        throw new UnsupportedOperationException("cannot expand view");
      }, validator, catalogReader, cluster, StandardConvertletTable.INSTANCE, config);
  return converter.convertQuery(validated, false, true).rel;
}
 
Example #11
Source Project: calcite   Author: apache   File: TableFunctionTest.java    License: 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 #12
Source Project: calcite   Author: apache   File: PigRelBuilderStyleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test @Disabled("CALCITE-1751")
public void testImplWithMultipleFilters() {
  final SchemaPlus schema = createTestSchema();
  final RelBuilder builder = createRelBuilder(schema);
  final RelNode node = builder.scan("t")
      .filter(
          builder.and(builder.call(GREATER_THAN, builder.field("tc0"), builder.literal("abc")),
              builder.call(EQUALS, builder.field("tc1"), builder.literal("3"))))
      .build();
  final RelNode optimized = optimizeWithVolcano(node);
  assertScriptAndResults("t", getPigScript(optimized, schema),
      "t = LOAD 'target/data.txt"
          + "' USING PigStorage() AS (tc0:chararray, tc1:chararray);\n"
          + "t = FILTER t BY (tc0 > 'abc') AND (tc1 == '3');",
      new String[] { "(c,3)" });
}
 
Example #13
Source Project: calcite   Author: apache   File: MultiJdbcSchemaJoinTest.java    License: Apache License 2.0 6 votes vote down vote up
private Connection setup() throws SQLException {
  // Create a jdbc database & table
  final String db = TempDb.INSTANCE.getUrl();
  Connection c1 = DriverManager.getConnection(db, "", "");
  Statement stmt1 = c1.createStatement();
  // This is a table we can join with the emps from the hr schema
  stmt1.execute("create table table1(id integer not null primary key, "
      + "field1 varchar(10))");
  stmt1.execute("insert into table1 values(100, 'foo')");
  stmt1.execute("insert into table1 values(200, 'bar')");
  c1.close();

  // Make a Calcite schema with both a jdbc schema and a non-jdbc schema
  Connection connection = DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  SchemaPlus rootSchema = calciteConnection.getRootSchema();
  rootSchema.add("DB",
      JdbcSchema.create(rootSchema, "DB",
          JdbcSchema.dataSource(db, "org.hsqldb.jdbcDriver", "", ""),
          null, null));
  rootSchema.add("hr", new ReflectiveSchema(new JdbcTest.HrSchema()));
  return connection;
}
 
Example #14
Source Project: calcite   Author: apache   File: PlannerTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-3547">[CALCITE-3547]
 * SqlValidatorException because Planner cannot find UDFs added to schema</a>. */
@Test void testValidateUserDefinedFunctionInSchema() throws Exception {
  SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  rootSchema.add("my_plus",
      ScalarFunctionImpl.create(Smalls.MyPlusFunction.class, "eval"));
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .defaultSchema(
          CalciteAssert.addSchema(rootSchema, CalciteAssert.SchemaSpec.HR))
      .build();
  final Planner planner = Frameworks.getPlanner(config);
  final String sql = "select \"my_plus\"(\"deptno\", 100) as \"p\"\n"
      + "from \"hr\".\"emps\"";
  SqlNode parse = planner.parse(sql);
  SqlNode validate = planner.validate(parse);
  assertThat(Util.toLinux(validate.toString()),
      equalTo("SELECT `my_plus`(`emps`.`deptno`, 100) AS `p`\n"
          + "FROM `hr`.`emps` AS `emps`"));
}
 
Example #15
Source Project: herddb   Author: diennea   File: CalcitePlanner.java    License: Apache License 2.0 6 votes vote down vote up
private SchemaPlus getSchemaForTableSpace(String defaultTableSpace) throws MetadataStorageManagerException {
    long startTs = System.currentTimeMillis();
    while (true) {
        SchemaPlus schema = getRootSchema();
        SchemaPlus result = schema.getSubSchema(defaultTableSpace);
        if (result != null) {
            return result;
        }
        long delta = System.currentTimeMillis() - startTs;
        LOG.log(Level.FINE, "schema {0} not available yet, after waiting {1}/{2} ms",
                new Object[]{defaultTableSpace, delta, WAIT_FOR_SCHEMA_UP_TIMEOUT});
        if (delta >= WAIT_FOR_SCHEMA_UP_TIMEOUT) {
            return null;
        }
        clearCache();
        try {
            Thread.sleep(100);
        } catch (InterruptedException err) {
            Thread.currentThread().interrupt();
        }
    }
}
 
Example #16
Source Project: nifi   Author: apache   File: QueryRecord.java    License: Apache License 2.0 6 votes vote down vote up
private CachedStatement buildCachedStatement(final String sql, final ProcessSession session,  final FlowFile flowFile, final RecordSchema schema,
                                             final RecordReaderFactory recordReaderFactory) {

    final CalciteConnection connection = createConnection();
    final SchemaPlus rootSchema = createRootSchema(connection);

    final FlowFileTable flowFileTable = new FlowFileTable(session, flowFile, schema, recordReaderFactory, getLogger());
    rootSchema.add("FLOWFILE", flowFileTable);
    rootSchema.setCacheEnabled(false);

    try {
        final PreparedStatement stmt = connection.prepareStatement(sql);
        return new CachedStatement(stmt, flowFileTable, connection);
    } catch (final SQLException e) {
        throw new ProcessException(e);
    }
}
 
Example #17
Source Project: calcite   Author: apache   File: ElasticSearchAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
private CalciteAssert.ConnectionFactory newConnectionFactory() {
  return new CalciteAssert.ConnectionFactory() {
    @Override public Connection createConnection() throws SQLException {
      final Connection connection = DriverManager.getConnection("jdbc:calcite:lex=JAVA");
      final SchemaPlus root = connection.unwrap(CalciteConnection.class).getRootSchema();

      root.add("elastic", new ElasticsearchSchema(NODE.restClient(), NODE.mapper(), ZIPS));

      // add calcite view programmatically
      final String viewSql = "select cast(_MAP['city'] AS varchar(20)) AS \"city\", "
          + " cast(_MAP['loc'][0] AS float) AS \"longitude\",\n"
          + " cast(_MAP['loc'][1] AS float) AS \"latitude\",\n"
          + " cast(_MAP['pop'] AS integer) AS \"pop\", "
          +  " cast(_MAP['state'] AS varchar(2)) AS \"state\", "
          +  " cast(_MAP['id'] AS varchar(5)) AS \"id\" "
          +  "from \"elastic\".\"zips\"";

      ViewTableMacro macro = ViewTable.viewMacro(root, viewSql,
          Collections.singletonList("elastic"), Arrays.asList("elastic", "view"), false);
      root.add("zips", macro);

      return connection;
    }
  };
}
 
Example #18
Source Project: calcite   Author: apache   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 #19
Source Project: calcite   Author: apache   File: PigRelBuilderStyleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Disabled("CALCITE-3660")
@Test void testImplWithJoin() throws Exception {
  final SchemaPlus schema = createTestSchema();
  final RelBuilder builder = createRelBuilder(schema);
  final RelNode node = builder.scan("t").scan("s")
      .join(JoinRelType.INNER,
          builder.equals(builder.field(2, 0, "tc1"), builder.field(2, 1, "sc0")))
      .filter(builder.call(GREATER_THAN, builder.field("tc0"), builder.literal("a"))).build();
  final RelNode optimized = optimizeWithVolcano(node);
  assertScriptAndResults("t", getPigScript(optimized, schema),
      "t = LOAD 'target/data.txt"
          + "' USING PigStorage() AS (tc0:chararray, tc1:chararray);\n"
          + "t = FILTER t BY (tc0 > 'a');\n"
          + "s = LOAD 'target/data2.txt"
          + "' USING PigStorage() AS (sc0:chararray, sc1:chararray);\n"
          + "t = JOIN t BY tc1 , s BY sc0;",
      new String[] { "(b,2,2,label2)" });
}
 
Example #20
Source Project: calcite   Author: apache   File: SqlAdvisorJdbcTest.java    License: 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 #21
Source Project: calcite   Author: apache   File: AbstractTableQueryable.java    License: Apache License 2.0 5 votes vote down vote up
public AbstractTableQueryable(QueryProvider queryProvider,
    SchemaPlus schema, QueryableTable table, String tableName) {
  this.queryProvider = queryProvider;
  this.schema = schema;
  this.table = table;
  this.tableName = tableName;
}
 
Example #22
Source Project: calcite   Author: apache   File: PlannerTest.java    License: Apache License 2.0 5 votes vote down vote up
private 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);
}
 
Example #23
Source Project: Bats   Author: lealone   File: SchemaTreeProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws Exception {
  List<AutoCloseable> toClose = Lists.newArrayList();
  for(SchemaPlus tree : schemaTreesToClose) {
    addSchemasToCloseList(tree, toClose);
  }

  AutoCloseables.close(toClose);
}
 
Example #24
Source Project: calcite   Author: apache   File: CsvTableFactory.java    License: Apache License 2.0 5 votes vote down vote up
public CsvTable create(SchemaPlus schema, String name,
    Map<String, Object> operand, RelDataType rowType) {
  String fileName = (String) operand.get("file");
  final File base =
      (File) operand.get(ModelHandler.ExtraOperand.BASE_DIRECTORY.camelName);
  final Source source = Sources.file(base, fileName);
  final RelProtoDataType protoRowType =
      rowType != null ? RelDataTypeImpl.proto(rowType) : null;
  return new CsvScannableTable(source, protoRowType);
}
 
Example #25
Source Project: calcite   Author: apache   File: Smalls.java    License: Apache License 2.0 5 votes vote down vote up
/** A function that generates multiplication table of {@code ncol} columns x
 * {@code nrow} rows. */
public static QueryableTable multiplicationTable(final int ncol,
    final int nrow, Integer offset) {
  final int offs = offset == null ? 0 : offset;
  return new AbstractQueryableTable(Object[].class) {
    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
      final RelDataTypeFactory.Builder builder = typeFactory.builder();
      builder.add("row_name", typeFactory.createJavaType(String.class));
      final RelDataType int_ = typeFactory.createJavaType(int.class);
      for (int i = 1; i <= ncol; i++) {
        builder.add("c" + i, int_);
      }
      return builder.build();
    }

    public Queryable<Object[]> asQueryable(QueryProvider queryProvider,
        SchemaPlus schema, String tableName) {
      final List<Object[]> table = new AbstractList<Object[]>() {
        @Override public Object[] get(int index) {
          Object[] cur = new Object[ncol + 1];
          cur[0] = "row " + index;
          for (int j = 1; j <= ncol; j++) {
            cur[j] = j * (index + 1) + offs;
          }
          return cur;
        }

        @Override public int size() {
          return nrow;
        }
      };
      return Linq4j.asEnumerable(table).asQueryable();
    }
  };
}
 
Example #26
Source Project: calcite   Author: apache   File: StreamTest.java    License: Apache License 2.0 5 votes vote down vote up
public Table create(SchemaPlus schema, String name,
    Map<String, Object> operand, RelDataType rowType) {
  final Object[][] rows = {
      {"paint", 1},
      {"paper", 0},
      {"brush", 1}
  };
  return new ProductsTable(ImmutableList.copyOf(rows));
}
 
Example #27
Source Project: mat-calcite-plugin   Author: vlsi   File: TableFunctions.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> Queryable<T> asQueryable(QueryProvider queryProvider, SchemaPlus schemaPlus, String s) {
    BaseQueryable<RowType> queryable = new BaseQueryable<RowType>(null, getElementType(), null) {
        @Override
        public Enumerator<RowType> enumerator() {
            return Linq4j.enumerator(values);
        }
    };
    return (Queryable<T>) queryable;
}
 
Example #28
Source Project: quark   Author: qubole   File: QuarkConnectionImpl.java    License: Apache License 2.0 5 votes vote down vote up
public SchemaPlus getRootSchema() {
  try {
    return getSqlQueryParser().getRootSchma();
  } catch (SQLException e) {
    throw new RuntimeException("Resetting the connection failed: "
        + e.getMessage(), e);
  }
}
 
Example #29
Source Project: calcite   Author: apache   File: ReflectiveSchema.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns an expression for the object wrapped by this schema (not the
 * schema itself). */
Expression getTargetExpression(SchemaPlus parentSchema, String name) {
  return EnumUtils.convert(
      Expressions.call(
          Schemas.unwrap(
              getExpression(parentSchema, name),
              ReflectiveSchema.class),
          BuiltInMethod.REFLECTIVE_SCHEMA_GET_TARGET.method),
      target.getClass());
}
 
Example #30
Source Project: Bats   Author: lealone   File: ViewHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) throws ValidationException, RelConversionException, IOException, ForemanSetupException {
  SqlCreateView createView = unwrap(sqlNode, SqlCreateView.class);

  final String newViewName = FileSelection.removeLeadingSlash(createView.getName());

  // Disallow temporary tables usage in view definition
  config.getConverter().disallowTemporaryTables();
  // Store the viewSql as view def SqlNode is modified as part of the resolving the new table definition below.
  final String viewSql = createView.getQuery().toString();
  final ConvertedRelNode convertedRelNode = validateAndConvert(createView.getQuery());
  final RelDataType validatedRowType = convertedRelNode.getValidatedRowType();
  final RelNode queryRelNode = convertedRelNode.getConvertedNode();

  final RelNode newViewRelNode = SqlHandlerUtil.resolveNewTableRel(true, createView.getFieldNames(), validatedRowType, queryRelNode);

  final SchemaPlus defaultSchema = context.getNewDefaultSchema();
  final AbstractSchema drillSchema = SchemaUtilites.resolveToMutableDrillSchema(defaultSchema, createView.getSchemaPath());

  final View view = new View(newViewName, viewSql, newViewRelNode.getRowType(),
      SchemaUtilites.getSchemaPathAsList(defaultSchema));
  final String schemaPath = drillSchema.getFullSchemaName();

  // check view creation possibility
  if(!checkViewCreationPossibility(drillSchema, createView, context)) {
    return DirectPlan
      .createDirectPlan(context, false, String.format("A table or view with given name [%s] already exists in schema [%s]", view.getName(), schemaPath));
  }

  final boolean replaced = drillSchema.createView(view);
  final String summary = String.format("View '%s' %s successfully in '%s' schema",
      newViewName, replaced ? "replaced" : "created", drillSchema.getFullSchemaName());

  return DirectPlan.createDirectPlan(context, true, summary);
}