Java Code Examples for org.apache.calcite.jdbc.CalciteSchema#from()

The following examples show how to use org.apache.calcite.jdbc.CalciteSchema#from() . 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: PlannerContext.java    From flink with Apache License 2.0 6 votes vote down vote up
private FlinkCalciteCatalogReader createCatalogReader(
		boolean lenientCaseSensitivity,
		String currentCatalog,
		String currentDatabase) {
	SqlParser.Config sqlParserConfig = getSqlParserConfig();
	final boolean caseSensitive;
	if (lenientCaseSensitivity) {
		caseSensitive = false;
	} else {
		caseSensitive = sqlParserConfig.caseSensitive();
	}

	SqlParser.Config newSqlParserConfig = SqlParser.configBuilder(sqlParserConfig)
			.setCaseSensitive(caseSensitive)
			.build();

	SchemaPlus rootSchema = getRootSchema(this.rootSchema.plus());
	return new FlinkCalciteCatalogReader(
			CalciteSchema.from(rootSchema),
			asList(
					asList(currentCatalog, currentDatabase),
					singletonList(currentCatalog)
			),
			typeFactory,
			CalciteConfig$.MODULE$.connectionConfig(newSqlParserConfig));
}
 
Example 2
Source File: PlannerContext.java    From flink with Apache License 2.0 6 votes vote down vote up
private FlinkCalciteCatalogReader createCatalogReader(
		boolean lenientCaseSensitivity,
		String currentCatalog,
		String currentDatabase) {
	SqlParser.Config sqlParserConfig = getSqlParserConfig();
	final boolean caseSensitive;
	if (lenientCaseSensitivity) {
		caseSensitive = false;
	} else {
		caseSensitive = sqlParserConfig.caseSensitive();
	}

	SqlParser.Config newSqlParserConfig = SqlParser.configBuilder(sqlParserConfig)
			.setCaseSensitive(caseSensitive)
			.build();

	SchemaPlus rootSchema = getRootSchema(this.rootSchema.plus());
	return new FlinkCalciteCatalogReader(
			CalciteSchema.from(rootSchema),
			asList(
					asList(currentCatalog, currentDatabase),
					singletonList(currentCatalog)
			),
			typeFactory,
			CalciteConfig$.MODULE$.connectionConfig(newSqlParserConfig));
}
 
Example 3
Source File: ModelHandler.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void visit(JsonLattice jsonLattice) {
  try {
    checkRequiredAttributes(jsonLattice, "name", "sql");
    final SchemaPlus schema = currentSchema();
    if (!schema.isMutable()) {
      throw new RuntimeException("Cannot define lattice; parent schema '"
          + currentSchemaName()
          + "' is not a SemiMutableSchema");
    }
    CalciteSchema calciteSchema = CalciteSchema.from(schema);
    Lattice.Builder latticeBuilder =
        Lattice.builder(calciteSchema, jsonLattice.getSql())
            .auto(jsonLattice.auto)
            .algorithm(jsonLattice.algorithm);
    if (jsonLattice.rowCountEstimate != null) {
      latticeBuilder.rowCountEstimate(jsonLattice.rowCountEstimate);
    }
    if (jsonLattice.statisticProvider != null) {
      latticeBuilder.statisticProvider(jsonLattice.statisticProvider);
    }
    populateLattice(jsonLattice, latticeBuilder);
    schema.add(jsonLattice.name, latticeBuilder.build());
  } catch (Exception e) {
    throw new RuntimeException("Error instantiating " + jsonLattice, e);
  }
}
 
Example 4
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Executes a prepare action. */
public <R> R perform(CalciteServerStatement statement,
    FrameworkConfig config, Frameworks.BasePrepareAction<R> action) {
  final CalcitePrepare.Context prepareContext =
      statement.createPrepareContext();
  final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
  final CalciteSchema schema =
      config.getDefaultSchema() != null
          ? CalciteSchema.from(config.getDefaultSchema())
          : prepareContext.getRootSchema();
  CalciteCatalogReader catalogReader =
      new CalciteCatalogReader(schema.root(),
          schema.path(null),
          typeFactory,
          prepareContext.config());
  final RexBuilder rexBuilder = new RexBuilder(typeFactory);
  final RelOptPlanner planner =
      createPlanner(prepareContext,
          config.getContext(),
          config.getCostFactory());
  final RelOptCluster cluster = createCluster(planner, rexBuilder);
  return action.apply(cluster, catalogReader,
      prepareContext.getRootSchema().plus(), statement);
}
 
Example 5
Source File: AbstractMaterializedViewTest.java    From calcite with 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 6
Source File: FlinkCalciteCatalogReaderTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
	rootSchemaPlus = CalciteSchema.createRootSchema(true, false).plus();
	Properties prop = new Properties();
	prop.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), "false");
	CalciteConnectionConfigImpl calciteConnConfig = new CalciteConnectionConfigImpl(prop);
	catalogReader = new FlinkCalciteCatalogReader(
		CalciteSchema.from(rootSchemaPlus),
		Collections.emptyList(),
		typeFactory,
		calciteConnConfig);
}
 
Example 7
Source File: QueryContext.java    From quark with Apache License 2.0 5 votes vote down vote up
public CalcitePrepare.Context getPrepareContext() {
  return new CalcitePrepare.Context() {

    @Override
    public JavaTypeFactory getTypeFactory() {
      return typeFactory;
    }

    @Override
    public CalciteSchema getRootSchema() {
      return CalciteSchema.from(rootSchema);
    }

    @Override
    public List<String> getDefaultSchemaPath() {
      return defaultSchema;
    }

    @Override
    public CalciteConnectionConfig config() {
      return cfg;
    }

    @Override
    public CalcitePrepare.SparkHandler spark() {
      return CalcitePrepare.Dummy.getSparkHandler(false);
    }

    @Override
    public DataContext getDataContext() {
      return null;
    }
  };
}
 
Example 8
Source File: SqlWorker.java    From quark with Apache License 2.0 5 votes vote down vote up
private CalciteCatalogReader createCatalogReader(QueryContext context) {
  return new CalciteCatalogReader(
      CalciteSchema.from(context.getRootSchema()),
      false,
      context.getDefaultSchemaPath(),
      context.getTypeFactory());
}
 
Example 9
Source File: SqlWorker.java    From quark with Apache License 2.0 5 votes vote down vote up
public RelNode run(RelOptPlanner planner, RelNode rel,
                   RelTraitSet requiredOutputTraits,
                   List<RelOptMaterialization> materializations,
                   List<RelOptLattice> lattices) {
  planner.clear();

  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);

  planner.addRelTraitDef(RelCollationTraitDef.INSTANCE);
  //((VolcanoPlanner) planner).registerAbstractRelationalRules();

  RelOptUtil.registerAbstractRels(planner);
  for (RelOptRule rule : ruleSet) {
    planner.addRule(rule);
  }

  planner.addRule(Bindables.BINDABLE_TABLE_SCAN_RULE);
  planner.addRule(ProjectTableScanRule.INSTANCE);
  planner.addRule(ProjectTableScanRule.INTERPRETER);
  planner.addRule(EnumerableInterpreterRule.INSTANCE);

  final CalciteSchema rootSchema = CalciteSchema.from(context.getRootSchema());
  planner.setExecutor(new RexExecutorImpl(null));
  planner.setRoot(rel);

  MaterializationService.setThreadLocal(materializationService);
  plannerHolder.setPlanner(planner);
  populateMaterializationsAndLattice(plannerHolder, rootSchema);
  if (!rel.getTraitSet().equals(requiredOutputTraits)) {
    rel = planner.changeTraits(rel, requiredOutputTraits);
    planner.setRoot(rel);
  }

  RelOptPlanner planner2 = planner.chooseDelegate();
  return planner2.findBestExp();
}
 
Example 10
Source File: FlinkCalciteCatalogReaderTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
	rootSchemaPlus = CalciteSchema.createRootSchema(true, false).plus();
	Properties prop = new Properties();
	prop.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), "false");
	CalciteConnectionConfigImpl calciteConnConfig = new CalciteConnectionConfigImpl(prop);
	catalogReader = new FlinkCalciteCatalogReader(
		CalciteSchema.from(rootSchemaPlus),
		Collections.emptyList(),
		typeFactory,
		calciteConnConfig);
}
 
Example 11
Source File: ModelHandler.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void visit(JsonMaterialization jsonMaterialization) {
  try {
    checkRequiredAttributes(jsonMaterialization, "sql");
    final SchemaPlus schema = currentSchema();
    if (!schema.isMutable()) {
      throw new RuntimeException(
          "Cannot define materialization; parent schema '"
              + currentSchemaName()
              + "' is not a SemiMutableSchema");
    }
    CalciteSchema calciteSchema = CalciteSchema.from(schema);

    final String viewName;
    final boolean existing;
    if (jsonMaterialization.view == null) {
      // If the user did not supply a view name, that means the materialized
      // view is pre-populated. Generate a synthetic view name.
      viewName = "$" + schema.getTableNames().size();
      existing = true;
    } else {
      viewName = jsonMaterialization.view;
      existing = false;
    }
    List<String> viewPath = calciteSchema.path(viewName);
    schema.add(viewName,
        MaterializedViewTable.create(calciteSchema,
            jsonMaterialization.getSql(), jsonMaterialization.viewSchemaPath, viewPath,
            jsonMaterialization.table, existing));
  } catch (Exception e) {
    throw new RuntimeException("Error instantiating " + jsonMaterialization,
        e);
  }
}
 
Example 12
Source File: PlannerImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
private CalciteCatalogReader createCatalogReader() {
  final SchemaPlus rootSchema = rootSchema(defaultSchema);

  return new CalciteCatalogReader(
      CalciteSchema.from(rootSchema),
      CalciteSchema.from(defaultSchema).path(null),
      typeFactory, connectionConfig);
}
 
Example 13
Source File: TableEnv.java    From marble with Apache License 2.0 4 votes vote down vote up
public TableEnv(TableConfig tableConfig) {
  try {
    this.tableConfig = tableConfig;
    SqlParser.Config sqlParserConfig = tableConfig.getSqlParserConfig()
        != null ? tableConfig.getSqlParserConfig() : SqlParser
        .configBuilder().setCaseSensitive(false)
        .build();
    SqlOperatorTable sqlStdOperatorTable = tableConfig
        .getSqlOperatorTable()
        != null
        ? tableConfig.getSqlOperatorTable()
        : ChainedSqlOperatorTable.of(SqlStdOperatorTable.instance());
    CalciteConnectionConfig calciteConnectionConfig = tableConfig
        .getCalciteConnectionConfig()
        != null
        ? tableConfig.getCalciteConnectionConfig()
        : createDefaultConnectionConfig(sqlParserConfig);
    RelDataTypeSystem typeSystem = tableConfig.getRelDataTypeSystem() != null
        ? tableConfig.getRelDataTypeSystem()
        : calciteConnectionConfig.typeSystem(RelDataTypeSystem.class,
            RelDataTypeSystem.DEFAULT);
    SqlRexConvertletTable convertletTable = tableConfig
        .getConvertletTable()
        != null
        ? tableConfig
        .getConvertletTable()
        : StandardConvertletTable.INSTANCE;
    RexExecutor rexExecutor = tableConfig.getRexExecutor() != null
        ? tableConfig.getRexExecutor()
        : RexUtil.EXECUTOR;
    this.calciteCatalogReader = new CalciteCatalogReader(
        CalciteSchema.from(rootSchema),
        CalciteSchema.from(rootSchema).path(null),
        new JavaTypeFactoryImpl(typeSystem),
        calciteConnectionConfig);
    this.frameworkConfig = createFrameworkConfig(sqlParserConfig,
        ChainedSqlOperatorTable.of(sqlStdOperatorTable,
            calciteCatalogReader), convertletTable,
        calciteConnectionConfig, typeSystem, rexExecutor);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 14
Source File: ViewTable.java    From calcite with Apache License 2.0 2 votes vote down vote up
/** Table macro that returns a view.
 *
 * @param schema Schema the view will belong to
 * @param viewSql SQL query
 * @param schemaPath Path of schema
 * @param modifiable Whether view is modifiable, or null to deduce it
 */
public static ViewTableMacro viewMacro(SchemaPlus schema, String viewSql,
    List<String> schemaPath, List<String> viewPath, Boolean modifiable) {
  return new ViewTableMacro(CalciteSchema.from(schema), viewSql, schemaPath,
      viewPath, modifiable);
}