org.apache.calcite.tools.RelConversionException Java Examples

The following examples show how to use org.apache.calcite.tools.RelConversionException. 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: CreateTableHandler.java    From Bats with Apache License 2.0 6 votes vote down vote up
private DrillRel convertToDrel(RelNode relNode,
                               AbstractSchema schema,
                               String tableName,
                               List<String> partitionColumns,
                               RelDataType queryRowType,
                               StorageStrategy storageStrategy)
    throws RelConversionException, SqlUnsupportedException {
  final DrillRel convertedRelNode = convertToRawDrel(relNode);

  // Put a non-trivial topProject to ensure the final output field name is preserved, when necessary.
  // Only insert project when the field count from the child is same as that of the queryRowType.
  final DrillRel topPreservedNameProj = queryRowType.getFieldCount() == convertedRelNode.getRowType().getFieldCount() ?
      addRenamedProject(convertedRelNode, queryRowType) : convertedRelNode;

  final RelTraitSet traits = convertedRelNode.getCluster().traitSet().plus(DrillRel.DRILL_LOGICAL);
  final DrillWriterRel writerRel = new DrillWriterRel(convertedRelNode.getCluster(),
      traits, topPreservedNameProj, schema.createNewTable(tableName, partitionColumns, storageStrategy));
  return new DrillScreenRel(writerRel.getCluster(), writerRel.getTraitSet(), writerRel);
}
 
Example #2
Source File: DrillSqlWorker.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Converts sql query string into query physical plan.
 * In case of any errors (that might occur due to missing function implementation),
 * checks if local function registry should be synchronized with remote function registry.
 * If sync took place, reloads drill operator table
 * (since functions were added to / removed from local function registry)
 * and attempts to converts sql query string into query physical plan one more time.
 *
 * @param context query context
 * @param sql sql query
 * @param textPlan text plan
 * @return query physical plan
 */
private static PhysicalPlan convertPlan(QueryContext context, String sql, Pointer<String> textPlan)
    throws ForemanSetupException, RelConversionException, IOException, ValidationException {
  Pointer<String> textPlanCopy = textPlan == null ? null : new Pointer<>(textPlan.value);
  try {
    return getQueryPlan(context, sql, textPlan);
  } catch (Exception e) {
    logger.trace("There was an error during conversion into physical plan. " +
        "Will sync remote and local function registries if needed and retry " +
        "in case if issue was due to missing function implementation.", e);
    if (context.getFunctionRegistry().syncWithRemoteRegistry(
        context.getDrillOperatorTable().getFunctionRegistryVersion())) {
      context.reloadDrillOperatorTable();
      logger.trace("Local function registry was synchronized with remote. Trying to find function one more time.");
      return getQueryPlan(context, sql, textPlanCopy);
    }
    throw e;
  }
}
 
Example #3
Source File: LexEscapeTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static void runProjectQueryWithLex(Lex lex, String sql)
    throws SqlParseException, ValidationException, RelConversionException {
  Config javaLex = SqlParser.configBuilder().setLex(lex).build();
  Planner planner = getPlanner(null, javaLex, Programs.ofRules(Programs.RULE_SET));
  SqlNode parse = planner.parse(sql);
  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).rel;
  assertThat(convert, instanceOf(LogicalProject.class));
  List<RelDataTypeField> fields = convert.getRowType().getFieldList();
  // Get field type from sql text and validate we parsed it after validation.
  assertThat(fields.size(), is(4));
  assertThat(fields.get(0).getType().getSqlTypeName(), is(SqlTypeName.VARCHAR));
  assertThat(fields.get(1).getType().getSqlTypeName(), is(SqlTypeName.TIME));
  assertThat(fields.get(2).getType().getSqlTypeName(), is(SqlTypeName.INTEGER));
  assertThat(fields.get(3).getType().getSqlTypeName(), is(SqlTypeName.TIMESTAMP));
}
 
Example #4
Source File: CompactRefreshHandler.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private RelNode getPlan(SqlHandlerConfig sqlHandlerConfig, List<String> refreshTablePath, PlanNormalizer planNormalizer) {
  SqlSelect select = new SqlSelect(
    SqlParserPos.ZERO,
    new SqlNodeList(SqlParserPos.ZERO),
    new SqlNodeList(ImmutableList.<SqlNode>of(SqlIdentifier.star(SqlParserPos.ZERO)), SqlParserPos.ZERO),
    new SqlIdentifier(refreshTablePath, SqlParserPos.ZERO),
    null,
    null,
    null,
    null,
    null,
    null,
    null
  );

  try {
    ConvertedRelNode converted = PrelTransformer.validateAndConvert(sqlHandlerConfig, select, planNormalizer);

    return converted.getConvertedNode();
  } catch (ForemanSetupException | RelConversionException | ValidationException e) {
    throw Throwables.propagate(SqlExceptionHelper.coerceException(logger, select.toString(), e, false));
  }
}
 
Example #5
Source File: ExplainHandler.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public SqlNode rewrite(SqlNode sqlNode) throws RelConversionException, ForemanSetupException {
  SqlExplain node = unwrap(sqlNode, SqlExplain.class);
  SqlLiteral op = node.operand(2);
  SqlExplain.Depth depth = (SqlExplain.Depth) op.getValue();
  if (node.getDetailLevel() != null) {
    level = node.getDetailLevel();
  }
  switch (depth) {
  case LOGICAL:
    mode = ResultMode.LOGICAL;
    break;
  case PHYSICAL:
    mode = ResultMode.PHYSICAL;
    break;
  default:
    throw new UnsupportedOperationException("Unknown depth " + depth);
  }

  return node.operand(0);
}
 
Example #6
Source File: ExplainHandler.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) throws ValidationException, RelConversionException, IOException, ForemanSetupException {
  final ConvertedRelNode convertedRelNode = validateAndConvert(sqlNode);
  final RelDataType validatedRowType = convertedRelNode.getValidatedRowType();
  final RelNode queryRelNode = convertedRelNode.getConvertedNode();

  log("Calcite", queryRelNode, logger, null);
  DrillRel drel = convertToDrel(queryRelNode);

  if (mode == ResultMode.LOGICAL) {
    LogicalExplain logicalResult = new LogicalExplain(drel, level, context);
    return DirectPlan.createDirectPlan(context, logicalResult);
  }

  Prel prel = convertToPrel(drel, validatedRowType);
  logAndSetTextPlan("Drill Physical", prel, logger);
  PhysicalOperator pop = convertToPop(prel);
  PhysicalPlan plan = convertToPlan(pop);
  log("Drill Plan", plan, logger);
  PhysicalExplain physicalResult = new PhysicalExplain(prel, plan, level, context);
  return DirectPlan.createDirectPlan(context, physicalResult);
}
 
Example #7
Source File: SqlExceptionHelper.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public static Exception coerceException(Logger logger, String sql, Exception e, boolean coerceToPlan){
  if(e instanceof UserException){
    return e;
  } else if(e instanceof ValidationException){
    throw validationError(sql, (ValidationException) e).build(logger);
  } else if (e instanceof AccessControlException){
  throw UserException.permissionError(e)
      .addContext(SQL_QUERY_CONTEXT, sql)
      .build(logger);
  } else if (e instanceof SqlUnsupportedException){
  throw UserException.unsupportedError(e)
      .addContext(SQL_QUERY_CONTEXT, sql)
      .build(logger);
  } else if (e instanceof IOException || e instanceof RelConversionException){
    return new QueryInputException("Failure handling SQL.", e);
  } else if (coerceToPlan){
    throw planError(sql, e).build(logger);
  }
  return e;
}
 
Example #8
Source File: DefaultSqlHandler.java    From Bats with Apache License 2.0 6 votes vote down vote up
protected Pair<SqlNode, RelDataType> validateNode(SqlNode sqlNode) throws ValidationException, RelConversionException, ForemanSetupException {
  final SqlNode sqlNodeValidated = config.getConverter().validate(sqlNode);
  final Pair<SqlNode, RelDataType> typedSqlNode = new Pair<>(sqlNodeValidated, config.getConverter().getOutputType(
      sqlNodeValidated));

  // Check if the unsupported functionality is used
  UnsupportedOperatorsVisitor visitor = UnsupportedOperatorsVisitor.createVisitor(context);
  try {
    sqlNodeValidated.accept(visitor);
  } catch (UnsupportedOperationException ex) {
    // If the exception due to the unsupported functionalities
    visitor.convertException();

    // If it is not, let this exception move forward to higher logic
    throw ex;
  }

  return typedSqlNode;
}
 
Example #9
Source File: LexCaseSensitiveTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static void runProjectQueryWithLex(Lex lex, String sql)
    throws SqlParseException, ValidationException, RelConversionException {
  Config javaLex = SqlParser.configBuilder().setLex(lex).build();
  Planner planner = getPlanner(null, javaLex, Programs.ofRules(Programs.RULE_SET));
  SqlNode parse = planner.parse(sql);
  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).rel;
  RelTraitSet traitSet =
      convert.getTraitSet().replace(EnumerableConvention.INSTANCE);
  RelNode transform = planner.transform(0, traitSet, convert);
  assertThat(transform, instanceOf(EnumerableProject.class));
  List<String> fieldNames = transform.getRowType().getFieldNames();
  assertThat(fieldNames.size(), is(2));
  if (lex.caseSensitive) {
    assertThat(fieldNames.get(0), is("EMPID"));
    assertThat(fieldNames.get(1), is("empid"));
  } else {
    assertThat(fieldNames.get(0) + "-" + fieldNames.get(1),
        anyOf(is("EMPID-empid0"), is("EMPID0-empid")));
  }
}
 
Example #10
Source File: DropTableHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Function resolves the schema and invokes the drop method
 * (while IF EXISTS statement is used function invokes the drop method only if table exists).
 * Raises an exception if the schema is immutable.
 * @param sqlNode - SqlDropTable (SQL parse tree of drop table [if exists] query)
 * @return - Single row indicating drop succeeded or table is not found while IF EXISTS statement is used,
 * raise exception otherwise
 * @throws ValidationException
 * @throws RelConversionException
 * @throws IOException
 */
@Override
public List<SimpleCommandResult> toResult(String sql, SqlNode sqlNode) throws ValidationException, ForemanSetupException,
RelConversionException, IOException {
  SqlDropTable dropTableNode = SqlNodeUtil.unwrap(sqlNode, SqlDropTable.class);
  NamespaceKey path = catalog.resolveSingle(dropTableNode.getPath());
  DremioTable table = catalog.getTableNoColumnCount(path);

  if (!dropTableNode.checkTableExistence()) {
    if(table == null) {
      throw UserException.validationError()
        .message("Table [%s] not found.", path)
        .build(logger);
    } else if(table.getJdbcTableType() != TableType.TABLE) {
      throw UserException.validationError()
          .message("[%s] is not a TABLE", table.getPath())
          .build(logger);
    }
  } else if(table == null || (table.getJdbcTableType() != TableType.TABLE)) {
    return Collections.singletonList(new SimpleCommandResult(true, String.format("Table [%s] not found.", path)));
  }


  catalog.dropTable(path);
  return Collections.singletonList(SimpleCommandResult.successful("Table [%s] dropped", path));

}
 
Example #11
Source File: TpcdsLatticeSuggesterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
List<Lattice> addQuery(String q) throws SqlParseException,
    ValidationException, RelConversionException {
  final Planner planner = new PlannerImpl(config);
  final SqlNode node = planner.parse(q);
  final SqlNode node2 = planner.validate(node);
  final RelRoot root = planner.rel(node2);
  return suggester.addQuery(root.project());
}
 
Example #12
Source File: TestCompilerUtils.java    From streamline with 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 #13
Source File: LatticeSuggesterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
List<Lattice> addQuery(String q) throws SqlParseException,
    ValidationException, RelConversionException {
  final Planner planner = new PlannerImpl(config);
  final SqlNode node = planner.parse(q);
  final SqlNode node2 = planner.validate(node);
  final RelRoot root = planner.rel(node2);
  return s.addQuery(root.project());
}
 
Example #14
Source File: PrelTransformer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static RelNode convertToRel(SqlHandlerConfig config, SqlNode node, RelTransformer relTransformer) throws RelConversionException {
  RelNode rel;
  if(config.getContext().getPlannerSettings().isRelPlanningEnabled()) {
    rel = convertToRelRoot(config, node, relTransformer);
  } else {
    rel = convertToRelRootAndJdbc(config, node, relTransformer);
  }
  log("INITIAL", rel, logger, null);
  return transform(config, PlannerType.HEP, PlannerPhase.WINDOW_REWRITE, rel, rel.getTraitSet(), true);
}
 
Example #15
Source File: PrelTransformer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static RelNode convertToRelRoot(SqlHandlerConfig config, SqlNode node, RelTransformer relTransformer) throws RelConversionException {
  final boolean leafLimitEnabled = config.getContext().getPlannerSettings().isLeafLimitsEnabled();

  // First try and convert without "expanding" exists/in/subqueries
  final RelNode convertible = toConvertibleRelRoot(config, node, false, relTransformer);

  // Check for RexSubQuery in the converted rel tree, and make sure that the table scans underlying
  // rel node with RexSubQuery have the same JDBC convention.
  final RelNode convertedNodeNotExpanded = convertible;
  RexSubQueryUtils.RexSubQueryPushdownChecker checker = new RexSubQueryUtils.RexSubQueryPushdownChecker(null);
  checker.visit(convertedNodeNotExpanded);

  final RelNode convertedNodeWithoutRexSubquery;
  if (!checker.foundRexSubQuery()) {
    convertedNodeWithoutRexSubquery = convertedNodeNotExpanded;
  } else {
    convertedNodeWithoutRexSubquery = toConvertibleRelRoot(config, node, true, relTransformer);
  }

  // Convert with "expanding" exists/in subqueries (if applicable)
  // if we are having a RexSubQuery, this expanded tree will
  // have LogicalCorrelate rel nodes.
  final DremioVolcanoPlanner volcanoPlanner = (DremioVolcanoPlanner) convertedNodeWithoutRexSubquery.getCluster().getPlanner();
  final RelNode originalRoot = convertedNodeWithoutRexSubquery.accept(new InjectSample(leafLimitEnabled));
  volcanoPlanner.setOriginalRoot(originalRoot);
  return ExpansionNode.removeFromTree(convertedNodeWithoutRexSubquery.accept(new InjectSample(leafLimitEnabled)));
}
 
Example #16
Source File: PrelTransformer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Return Dremio Logical RelNode tree for a SELECT statement, when it is executed / explained directly.
 *
 * @param relNode : root RelNode corresponds to Calcite Logical RelNode.
 * @param validatedRowType : the rowType for the final field names. A rename project may be placed on top of the root.
 * @return
 * @throws RelConversionException
 * @throws SqlUnsupportedException
 */
public static Rel convertToDrel(SqlHandlerConfig config, RelNode relNode, RelDataType validatedRowType) throws RelConversionException, SqlUnsupportedException {

  Rel convertedRelNode = convertToDrel(config, relNode);

  final DremioFieldTrimmer trimmer = DremioFieldTrimmer.of(DremioRelFactories.LOGICAL_BUILDER.create(convertedRelNode.getCluster(), null));
  Rel trimmedRelNode = (Rel) trimmer.trim(convertedRelNode);

  // Put a non-trivial topProject to ensure the final output field name is preserved, when necessary.
  trimmedRelNode = addRenamedProject(config, trimmedRelNode, validatedRowType);

  trimmedRelNode = SqlHandlerUtil.storeQueryResultsIfNeeded(config.getConverter().getParserConfig(),
      config.getContext(), trimmedRelNode);
  return new ScreenRel(trimmedRelNode.getCluster(), trimmedRelNode.getTraitSet(), trimmedRelNode);
}
 
Example #17
Source File: SplitUpComplexExpressions.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public Prel visitPrel(Prel prel, Object value) throws RelConversionException {
  List<RelNode> children = Lists.newArrayList();
  for(Prel child : prel){
    child = child.accept(this, null);
    children.add(child);
  }
  return (Prel) prel.copy(prel.getTraitSet(), children);
}
 
Example #18
Source File: CreateTableHandler.java    From Bats with Apache License 2.0 5 votes vote down vote up
private Prel convertToPrel(RelNode drel, RelDataType inputRowType, List<String> partitionColumns)
    throws RelConversionException, SqlUnsupportedException {
  Prel prel = convertToPrel(drel, inputRowType);

  prel = prel.accept(new ProjectForWriterVisitor(inputRowType, partitionColumns), null);

  return prel;
}
 
Example #19
Source File: ViewHandler.java    From Bats with 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);
}
 
Example #20
Source File: TpcdsLatticeSuggesterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Parses a query returns its graph. */
LatticeRootNode node(String q) throws SqlParseException,
    ValidationException, RelConversionException {
  final List<Lattice> list = addQuery(q);
  assertThat(list.size(), is(1));
  return list.get(0).rootNode;
}
 
Example #21
Source File: ServerDdlExecutor.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Populates the table called {@code name} by executing {@code query}. */
static void populate(SqlIdentifier name, SqlNode query,
    CalcitePrepare.Context context) {
  // Generate, prepare and execute an "INSERT INTO table query" statement.
  // (It's a bit inefficient that we convert from SqlNode to SQL and back
  // again.)
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .defaultSchema(context.getRootSchema().plus())
      .build();
  final Planner planner = Frameworks.getPlanner(config);
  try {
    final StringBuilder buf = new StringBuilder();
    final SqlWriterConfig writerConfig =
        SqlPrettyWriter.config().withAlwaysUseParentheses(false);
    final SqlPrettyWriter w = new SqlPrettyWriter(writerConfig, buf);
    buf.append("INSERT INTO ");
    name.unparse(w, 0, 0);
    buf.append(' ');
    query.unparse(w, 0, 0);
    final String sql = buf.toString();
    final SqlNode query1 = planner.parse(sql);
    final SqlNode query2 = planner.validate(query1);
    final RelRoot r = planner.rel(query2);
    final PreparedStatement prepare = context.getRelRunner().prepare(r.rel);
    int rowCount = prepare.executeUpdate();
    Util.discard(rowCount);
    prepare.close();
  } catch (SqlParseException | ValidationException
      | RelConversionException | SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #22
Source File: RexSqlStandardConvertletTableTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private RelNode convertSqlToRel(String sql, boolean simplifyRex) {
  final FrameworkConfig config = Frameworks.newConfigBuilder()
          .defaultSchema(CalciteSchema.createRootSchema(false).plus())
          .parserConfig(SqlParser.configBuilder().build())
          .build();
  final Planner planner = Frameworks.getPlanner(config);
  try (Closer closer = new Closer()) {
    closer.add(Hook.REL_BUILDER_SIMPLIFY.addThread(Hook.propertyJ(simplifyRex)));
    final SqlNode parsed = planner.parse(sql);
    final SqlNode validated = planner.validate(parsed);
    return planner.rel(validated).rel;
  } catch (SqlParseException | RelConversionException | ValidationException e) {
    throw TestUtil.rethrow(e);
  }
}
 
Example #23
Source File: LatticeSuggesterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Parses a query returns its graph. */
LatticeRootNode node(String q) throws SqlParseException,
    ValidationException, RelConversionException {
  final List<Lattice> list = addQuery(q);
  assertThat(list.size(), is(1));
  return list.get(0).rootNode;
}
 
Example #24
Source File: LexCaseSensitiveTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testCalciteCaseJoinOracle()
    throws SqlParseException, ValidationException, RelConversionException {
  String sql = "select t.\"empid\" as EMPID, s.\"empid\" from\n"
      + "(select * from \"emps\" where \"emps\".\"deptno\" > 100) t join\n"
      + "(select * from \"emps\" where \"emps\".\"deptno\" < 200) s\n"
      + "on t.\"empid\" = s.\"empid\"";
  runProjectQueryWithLex(Lex.ORACLE, sql);
}
 
Example #25
Source File: LexCaseSensitiveTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testCalciteCaseJoinMySql()
    throws SqlParseException, ValidationException, RelConversionException {
  String sql = "select t.empid as EMPID, s.empid from\n"
      + "(select * from emps where emps.deptno > 100) t join\n"
      + "(select * from emps where emps.deptno < 200) s on t.empid = s.empid";
  runProjectQueryWithLex(Lex.MYSQL, sql);
}
 
Example #26
Source File: LexCaseSensitiveTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testCalciteCaseJoinMySqlAnsi()
    throws SqlParseException, ValidationException, RelConversionException {
  String sql = "select t.empid as EMPID, s.empid from\n"
      + "(select * from emps where emps.deptno > 100) t join\n"
      + "(select * from emps where emps.deptno < 200) s on t.empid = s.empid";
  runProjectQueryWithLex(Lex.MYSQL_ANSI, sql);
}
 
Example #27
Source File: LexCaseSensitiveTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testCalciteCaseJoinSqlServer()
    throws SqlParseException, ValidationException, RelConversionException {
  String sql = "select t.empid as EMPID, s.empid from\n"
      + "(select * from emps where emps.deptno > 100) t join\n"
      + "(select * from emps where emps.deptno < 200) s on t.empid = s.empid";
  runProjectQueryWithLex(Lex.SQL_SERVER, sql);
}
 
Example #28
Source File: LexCaseSensitiveTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testCalciteCaseJoinJava()
    throws SqlParseException, ValidationException, RelConversionException {
  String sql = "select t.empid as EMPID, s.empid from\n"
      + "(select * from emps where emps.deptno > 100) t join\n"
      + "(select * from emps where emps.deptno < 200) s on t.empid = s.empid";
  runProjectQueryWithLex(Lex.JAVA, sql);
}
 
Example #29
Source File: ExtensionDdlExecutor.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Populates the table called {@code name} by executing {@code query}. */
protected static void populate(SqlIdentifier name, SqlNode query,
    CalcitePrepare.Context context) {
  // Generate, prepare and execute an "INSERT INTO table query" statement.
  // (It's a bit inefficient that we convert from SqlNode to SQL and back
  // again.)
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .defaultSchema(
          Objects.requireNonNull(
              Schemas.subSchema(context.getRootSchema(),
                  context.getDefaultSchemaPath())).plus())
      .build();
  final Planner planner = Frameworks.getPlanner(config);
  try {
    final StringBuilder buf = new StringBuilder();
    final SqlPrettyWriter w =
        new SqlPrettyWriter(
            SqlPrettyWriter.config()
                .withDialect(CalciteSqlDialect.DEFAULT)
                .withAlwaysUseParentheses(false),
            buf);
    buf.append("INSERT INTO ");
    name.unparse(w, 0, 0);
    buf.append(" ");
    query.unparse(w, 0, 0);
    final String sql = buf.toString();
    final SqlNode query1 = planner.parse(sql);
    final SqlNode query2 = planner.validate(query1);
    final RelRoot r = planner.rel(query2);
    final PreparedStatement prepare = context.getRelRunner().prepare(r.rel);
    int rowCount = prepare.executeUpdate();
    Util.discard(rowCount);
    prepare.close();
  } catch (SqlParseException | ValidationException
      | RelConversionException | SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #30
Source File: SplitUpComplexExpressions.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public Prel visitPrel(Prel prel, Object value) throws RelConversionException {
  List<RelNode> children = Lists.newArrayList();
  for(Prel child : prel){
    child = child.accept(this, null);
    children.add(child);
  }
  return (Prel) prel.copy(prel.getTraitSet(), children);
}