org.apache.calcite.util.Pair Java Examples

The following examples show how to use org.apache.calcite.util.Pair. 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: SqlLineTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to execute a simple script file with the -f option to SqlLine.
 * Tests for presence of an expected pattern in the output (stdout or stderr).
 *
 * @param scriptText Script text
 * @param flag Command flag (--run or -f)
 * @param statusMatcher Checks whether status is as expected
 * @param outputMatcher Checks whether output is as expected
 * @throws Exception on command execution error
 */
private void checkScriptFile(String scriptText, boolean flag,
    Matcher<SqlLine.Status> statusMatcher,
    Matcher<String> outputMatcher) throws Throwable {
  // Put the script content in a temp file
  File scriptFile = File.createTempFile("foo", "temp");
  scriptFile.deleteOnExit();
  try (PrintWriter w = Util.printWriter(scriptFile)) {
    w.print(scriptText);
  }

  Pair<SqlLine.Status, String> pair = runScript(scriptFile, flag);

  // Check output before status. It gives a better clue what went wrong.
  assertThat(pair.right, outputMatcher);
  assertThat(pair.left, statusMatcher);
  final boolean delete = scriptFile.delete();
  assertThat(delete, is(true));
}
 
Example #2
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a list of extended columns with field indices to the underlying table.
 */
public static List<RelDataTypeField> getExtendedColumns(
    SqlValidator validator, SqlValidatorTable table, SqlNodeList extendedColumns) {
  final ImmutableList.Builder<RelDataTypeField> extendedFields =
      ImmutableList.builder();
  final ExtensibleTable extTable = table.unwrap(ExtensibleTable.class);
  int extendedFieldOffset =
      extTable == null
          ? table.getRowType().getFieldCount()
          : extTable.getExtendedColumnOffset();
  for (final Pair<SqlIdentifier, SqlDataTypeSpec> pair : pairs(extendedColumns)) {
    final SqlIdentifier identifier = pair.left;
    final SqlDataTypeSpec type = pair.right;
    extendedFields.add(
        new RelDataTypeFieldImpl(identifier.toString(),
            extendedFieldOffset++,
            type.deriveType(validator)));
  }
  return extendedFields.build();
}
 
Example #3
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Adds an expression to a select list, ensuring that its alias does not
 * clash with any existing expressions on the list.
 */
protected void addToSelectList(
	List<SqlNode> list,
	Set<String> aliases,
	List<Map.Entry<String, RelDataType>> fieldList,
	SqlNode exp,
	SqlValidatorScope scope,
	final boolean includeSystemVars) {
	String alias = SqlValidatorUtil.getAlias(exp, -1);
	String uniqueAlias =
		SqlValidatorUtil.uniquify(
			alias, aliases, SqlValidatorUtil.EXPR_SUGGESTER);
	if (!alias.equals(uniqueAlias)) {
		exp = SqlValidatorUtil.addAlias(exp, uniqueAlias);
	}
	fieldList.add(Pair.of(uniqueAlias, deriveType(scope, exp)));
	list.add(exp);
}
 
Example #4
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve a target column name in the target table.
 *
 * @return the target field or null if the name cannot be resolved
 * @param rowType the target row type
 * @param id      the target column identifier
 * @param table   the target table or null if it is not a RelOptTable instance
 */
public static RelDataTypeField getTargetField(
    RelDataType rowType, RelDataTypeFactory typeFactory,
    SqlIdentifier id, SqlValidatorCatalogReader catalogReader,
    RelOptTable table) {
  final Table t = table == null ? null : table.unwrap(Table.class);
  if (!(t instanceof CustomColumnResolvingTable)) {
    final SqlNameMatcher nameMatcher = catalogReader.nameMatcher();
    return nameMatcher.field(rowType, id.getSimple());
  }

  final List<Pair<RelDataTypeField, List<String>>> entries =
      ((CustomColumnResolvingTable) t).resolveColumn(
          rowType, typeFactory, id.names);
  switch (entries.size()) {
  case 1:
    if (!entries.get(0).getValue().isEmpty()) {
      return null;
    }
    return entries.get(0).getKey();
  default:
    return null;
  }
}
 
Example #5
Source File: TableEnv.java    From marble with Apache License 2.0 6 votes vote down vote up
protected RelRoot getSqlPlanRel(String sql) throws Throwable {
  try (Planner planner = Frameworks.getPlanner(frameworkConfig)) {
    RelRoot root;
    final SqlNode parsedSqlNode = planner.parse(sql);
    final Pair<SqlNode, RelDataType> validatedSqlNodeAndType = planner
        .validateAndGetType(
            parsedSqlNode);
    root = planner.rel(validatedSqlNodeAndType.getKey());
    final Program program = createProgram();
    //getDesiredTraits
    final RelTraitSet desiredTraits = root.rel.getTraitSet()
        .replace(EnumerableConvention.INSTANCE)
        .replace(root.collation)
        .simplify();

    RelNode logicalRelNode = root.rel;
    final RelNode optimizedRelNode = program.run(
        root.rel.getCluster().getPlanner(), logicalRelNode, desiredTraits,
        Collections.emptyList(), Collections.emptyList());
    root = root.withRel(optimizedRelNode);
    return root;
  }

}
 
Example #6
Source File: DruidJsonFilter.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Nullable
private static DruidJsonFilter toIsNullKindDruidFilter(RexNode rexNode, RelDataType rowType,
    DruidQuery druidQuery) {
  if (rexNode.getKind() != SqlKind.IS_NULL && rexNode.getKind() != SqlKind.IS_NOT_NULL) {
    throw new AssertionError(
        DruidQuery.format("Expecting IS_NULL or IS_NOT_NULL but got [%s]", rexNode.getKind()));
  }
  final RexCall rexCall = (RexCall) rexNode;
  final RexNode refNode = rexCall.getOperands().get(0);
  Pair<String, ExtractionFunction> druidColumn = DruidQuery
      .toDruidColumn(refNode, rowType, druidQuery);
  final String columnName = druidColumn.left;
  final ExtractionFunction extractionFunction = druidColumn.right;
  if (columnName == null) {
    return null;
  }
  if (rexNode.getKind() == SqlKind.IS_NOT_NULL) {
    return toNotDruidFilter(new JsonSelector(columnName, null, extractionFunction));
  }
  return new JsonSelector(columnName, null, extractionFunction);
}
 
Example #7
Source File: VisitorDataContext.java    From Bats with Apache License 2.0 6 votes vote down vote up
public static DataContext of(RelDataType rowType,
    List<Pair<RexInputRef, RexNode>> usageList) {
  final int size = rowType.getFieldList().size();
  final Object[] values = new Object[size];
  for (Pair<RexInputRef, RexNode> elem : usageList) {
    Pair<Integer, ?> value = getValue(elem.getKey(), elem.getValue());
    if (value == null) {
      LOGGER.warn("{} is not handled for {} for checking implication",
          elem.getKey(), elem.getValue());
      return null;
    }
    int index = value.getKey();
    values[index] = value.getValue();
  }
  return new VisitorDataContext(values);
}
 
Example #8
Source File: HiveTableSqlFunction.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * This method is copied from calcite, and modify it to not rely on Function.
 * TODO FlinkTableFunction need implement getElementType.
 */
private static Object[] convertArguments(
		List<RelDataType> operandTypes,
		List<SqlNode> operandList) {
	List<Object> arguments = new ArrayList<>(operandList.size());
	// Construct a list of arguments, if they are all constants.
	for (Pair<RelDataType, SqlNode> pair
			: Pair.zip(operandTypes, operandList)) {
		try {
			final Object o = getValue(pair.right);
			final Object o2 = coerce(o, pair.left);
			arguments.add(o2);
		} catch (NonLiteralException e) {
			arguments.add(null);
		}
	}
	return arguments.toArray();
}
 
Example #9
Source File: ScannableTableTest.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-3405">[CALCITE-3405]
 * Prune columns for ProjectableFilterable when project is not simple mapping</a>. */
@Test void testPushNonSimpleMappingProject() throws Exception {
  final StringBuilder buf = new StringBuilder();
  final Table table = new BeatlesProjectableFilterableTable(buf, true);
  final String explain = "PLAN="
      + "EnumerableCalc(expr#0..1=[{inputs}], expr#2=[+($t1, $t1)], expr#3=[3],"
      + " proj#0..1=[{exprs}], k0=[$t0], $f3=[$t2], $f4=[$t3])\n"
      + "  EnumerableInterpreter\n"
      + "    BindableTableScan(table=[[s, beatles]], projects=[[2, 0]])";
  CalciteAssert.that()
      .with(newSchema("s", Pair.of("beatles", table)))
      .query("select \"k\", \"i\", \"k\", \"i\"+\"i\" \"ii\", 3 from \"s\".\"beatles\"")
      .explainContains(explain)
      .returnsUnordered(
          "k=1940; i=4; k=1940; ii=8; EXPR$3=3",
          "k=1940; i=5; k=1940; ii=10; EXPR$3=3",
          "k=1942; i=4; k=1942; ii=8; EXPR$3=3",
          "k=1943; i=6; k=1943; ii=12; EXPR$3=3");
  assertThat(buf.toString(), is("returnCount=4, projects=[2, 0]"));
}
 
Example #10
Source File: DrillSemiJoinRel.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public LogicalOperator implement(DrillImplementor implementor) {
  List<String> fields = new ArrayList<>();
  fields.addAll(getInput(0).getRowType().getFieldNames());
  fields.addAll(getInput(1).getRowType().getFieldNames());
  Preconditions.checkArgument(DrillJoinRel.isUnique(fields));
  final int leftCount = left.getRowType().getFieldCount();
  final List<String> leftFields = fields.subList(0, leftCount);
  final List<String> rightFields = fields.subList(leftCount, leftCount + right.getRowType().getFieldCount());

  final LogicalOperator leftOp = DrillJoinRel.implementInput(implementor, 0, 0, left, this, fields);
  final LogicalOperator rightOp = DrillJoinRel.implementInput(implementor, 1, leftCount, right, this, fields);

  Join.Builder builder = Join.builder();
  builder.type(joinType);
  builder.left(leftOp);
  builder.right(rightOp);
  List<JoinCondition> conditions = Lists.newArrayList();
  for (Pair<Integer, Integer> pair : Pair.zip(leftKeys, rightKeys)) {
    conditions.add(new JoinCondition(DrillJoinRel.EQUALITY_CONDITION,
            new FieldReference(leftFields.get(pair.left)), new FieldReference(rightFields.get(pair.right))));
  }

  return new LogicalSemiJoin(leftOp, rightOp, conditions, joinType);
}
 
Example #11
Source File: ApexRelNode.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Override
public RelInfo visit(RelContext context, RelNode node, List<RelInfo> inputStreams)
{
  Project project = (Project)node;
  if (inputStreams.size() == 0 || inputStreams.size() > 1) {
    throw new UnsupportedOperationException("Project is a SingleRel");
  }

  FilterTransformOperator operator = context.dag
      .addOperator(OperatorUtils.getUniqueOperatorName(project.getRelTypeName()), FilterTransformOperator.class);
  Map<String, String> expMap = new HashMap<>();
  ExpressionCompiler compiler = new ExpressionCompiler(new RexBuilder(project.getCluster().getTypeFactory()));

  for (Pair<RelDataTypeField, RexNode> pair : Pair.zip(project.getRowType().getFieldList(),
      project.getProjects())) {
    String fieldName = OperatorUtils.getFieldName(pair.left);
    String expression = compiler.getExpression(pair.right, project.getInput().getRowType(), project.getRowType());
    expMap.put(fieldName, expression);
  }
  operator.setExpressionMap(expMap);

  return new RelInfo("Project", Lists.<Operator.InputPort>newArrayList(operator.input), operator, operator.output,
      project.getRowType());
}
 
Example #12
Source File: WithItemNamespace.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override protected RelDataType validateImpl(RelDataType targetRowType) {
  final SqlValidatorNamespace childNs =
      validator.getNamespace(withItem.query);
  final RelDataType rowType = childNs.getRowTypeSansSystemColumns();
  if (withItem.columnList == null) {
    return rowType;
  }
  final RelDataTypeFactory.Builder builder =
      validator.getTypeFactory().builder();
  for (Pair<SqlNode, RelDataTypeField> pair
      : Pair.zip(withItem.columnList, rowType.getFieldList())) {
    builder.add(((SqlIdentifier) pair.left).getSimple(),
        pair.right.getType());
  }
  return builder.build();
}
 
Example #13
Source File: JoinPrel.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Build the list of join conditions for this join.
 * A join condition is built only for equality and IS NOT DISTINCT FROM comparisons. The difference is:
 * null == null is FALSE whereas null IS NOT DISTINCT FROM null is TRUE
 * For a use case of the IS NOT DISTINCT FROM comparison, see
 * {@link org.apache.calcite.rel.rules.RemoveDistinctAggregateRule}
 * @param conditions populated list of join conditions
 * @param leftFields join fields from the left input
 * @param rightFields join fields from the right input
 */
protected void buildJoinConditions(List<JoinCondition> conditions,
    List<String> leftFields,
    List<String> rightFields,
    List<Integer> leftKeys,
    List<Integer> rightKeys) {
  List<RexNode> conjuncts = RelOptUtil.conjunctions(this.getCondition());
  short i=0;

  for (Pair<Integer, Integer> pair : Pair.zip(leftKeys, rightKeys)) {
    final RexNode conditionExpr = conjuncts.get(i++);
    final SqlKind kind  = conditionExpr.getKind();
    if (kind != SqlKind.EQUALS && kind != SqlKind.IS_NOT_DISTINCT_FROM) {
      throw UserException.unsupportedError()
          .message("Unsupported comparator in join condition %s", conditionExpr)
          .build(logger);
    }

    conditions.add(new JoinCondition(kind.toString(),
        FieldReference.getWithQuotedRef(leftFields.get(pair.left)),
        FieldReference.getWithQuotedRef(rightFields.get(pair.right))));
  }
}
 
Example #14
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private boolean isRolledUpColumnAllowedInAgg(SqlIdentifier identifier, SqlValidatorScope scope,
	SqlCall aggCall, SqlNode parent) {
	Pair<String, String> pair = findTableColumnPair(identifier, scope);

	if (pair == null) {
		return true;
	}

	String tableAlias = pair.left;
	String columnName = pair.right;

	Table table = findTable(tableAlias);
	if (table != null) {
		return table.rolledUpColumnValidInsideAgg(columnName, aggCall, parent,
			catalogReader.getConfig());
	}
	return true;
}
 
Example #15
Source File: NumberingRelWriter.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the collected terms and values to a string. Does not write to
 * the parent writer.
 */
public String simple() {
  final StringBuilder buf = new StringBuilder("(");
  for (Ord<Pair<String, Object>> ord : Ord.zip(values)) {
    if (ord.i > 0) {
      buf.append(", ");
    }
    buf.append(ord.e.left).append("=[").append(ord.e.right).append("]");
  }
  buf.append(")");
  return buf.toString();
}
 
Example #16
Source File: ProjectAllowDupPrel.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
protected List<NamedExpression> getProjectExpressions(DrillParseContext context) {
  List<NamedExpression> expressions = Lists.newArrayList();
  for (Pair<RexNode, String> pair : Pair.zip(exps, getRowType().getFieldNames())) {
    LogicalExpression expr = DrillOptiq.toDrill(context, getInput(), pair.left);
    expressions.add(new NamedExpression(expr, FieldReference.getWithQuotedRef(pair.right)));
  }
  return expressions;
}
 
Example #17
Source File: SubstitutionVisitor.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static boolean allMatch(SubstitutionVisitor visitor, List<Operand> operands, List<MutableRel> rels) {
    if (operands.size() != rels.size()) {
        return false;
    }
    for (Pair<Operand, MutableRel> pair : Pair.zip(operands, rels)) {
        if (!pair.left.matches(visitor, pair.right)) {
            return false;
        }
    }
    return true;
}
 
Example #18
Source File: ScannableTableTest.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-458">[CALCITE-458]
 * ArrayIndexOutOfBoundsException when using just a single column in
 * interpreter</a>. */
@Test void testPFTableRefusesFilterSingleColumn() throws Exception {
  final StringBuilder buf = new StringBuilder();
  final Table table = new BeatlesProjectableFilterableTable(buf, false);
  final String explain = "PLAN="
      + "EnumerableInterpreter\n"
      + "  BindableTableScan(table=[[s, beatles2]], filters=[[>($2, 1941)]], projects=[[2]])";
  CalciteAssert.that()
      .with(newSchema("s", Pair.of("beatles2", table)))
      .query("select \"k\" from \"s\".\"beatles2\" where \"k\" > 1941")
      .explainContains(explain)
      .returnsUnordered("k=1942",
          "k=1943");
  assertThat(buf.toString(), is("returnCount=4, projects=[2]"));
}
 
Example #19
Source File: SqlRowTypeNameSpec.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
  writer.print(getTypeName().getSimple());
  SqlWriter.Frame frame = writer.startList(SqlWriter.FrameTypeEnum.FUN_CALL, "(", ")");
  for (Pair<SqlIdentifier, SqlDataTypeSpec> p : Pair.zip(this.fieldNames, this.fieldTypes)) {
    writer.sep(",", false);
    p.left.unparse(writer, 0, 0);
    p.right.unparse(writer, leftPrec, rightPrec);
    if (p.right.getNullable() != null && p.right.getNullable()) {
      // Row fields default is not nullable.
      writer.print("NULL");
    }
  }
  writer.endList(frame);
}
 
Example #20
Source File: RelStructuredTypeFlattener.java    From Bats with Apache License 2.0 5 votes vote down vote up
public void rewriteRel(TableScan rel) {
    RelNode newRel = rel.getTable().toRel(toRelContext);
    if (!SqlTypeUtil.isFlat(rel.getRowType())) {
        final List<Pair<RexNode, String>> flattenedExpList = new ArrayList<>();
        flattenInputs(rel.getRowType().getFieldList(), rexBuilder.makeRangeReference(newRel), flattenedExpList);
        newRel = relBuilder.push(newRel)
                .projectNamed(Pair.left(flattenedExpList), Pair.right(flattenedExpList), true).build();
    }
    setNewForOldRel(rel, newRel);
}
 
Example #21
Source File: AggregatingSelectScope.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the expressions that are in the GROUP BY clause (or the SELECT
 * DISTINCT clause, if distinct) and that can therefore be referenced
 * without being wrapped in aggregate functions.
 *
 * <p>The expressions are fully-qualified, and any "*" in select clauses are
 * expanded.
 *
 * @return list of grouping expressions
 */
private Pair<ImmutableList<SqlNode>, ImmutableList<SqlNode>> getGroupExprs() {
  if (distinct) {
    // Cannot compute this in the constructor: select list has not been
    // expanded yet.
    assert select.isDistinct();

    // Remove the AS operator so the expressions are consistent with
    // OrderExpressionExpander.
    ImmutableList.Builder<SqlNode> groupExprs = ImmutableList.builder();
    final SelectScope selectScope = (SelectScope) parent;
    for (SqlNode selectItem : selectScope.getExpandedSelectList()) {
      groupExprs.add(stripAs(selectItem));
    }
    return Pair.of(ImmutableList.of(), groupExprs.build());
  } else if (select.getGroup() != null) {
    if (temporaryGroupExprList != null) {
      // we are in the middle of resolving
      return Pair.of(ImmutableList.of(),
          ImmutableList.copyOf(temporaryGroupExprList));
    } else {
      final Resolved resolved = this.resolved.get();
      return Pair.of(resolved.extraExprList, resolved.groupExprList);
    }
  } else {
    return Pair.of(ImmutableList.of(), ImmutableList.of());
  }
}
 
Example #22
Source File: ScannableTableTest.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-3405">[CALCITE-3405]
 * Prune columns for ProjectableFilterable when project is not simple mapping</a>. */
@Test void testPushSimpleMappingProject() throws Exception {
  final StringBuilder buf = new StringBuilder();
  final Table table = new BeatlesProjectableFilterableTable(buf, true);
  // Note that no redundant Project on EnumerableInterpreter
  final String explain = "PLAN="
      + "EnumerableInterpreter\n"
      + "  BindableTableScan(table=[[s, beatles]], projects=[[2, 0]])";
  CalciteAssert.that()
      .with(newSchema("s", Pair.of("beatles", table)))
      .query("select \"k\", \"i\" from \"s\".\"beatles\"")
      .explainContains(explain)
      .returnsUnordered(
          "k=1940; i=4",
          "k=1940; i=5",
          "k=1942; i=4",
          "k=1943; i=6");
  assertThat(buf.toString(), is("returnCount=4, projects=[2, 0]"));
}
 
Example #23
Source File: RexAnalyzer.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Generates a map of variables and lists of values that could be assigned
 * to them. */
public Iterable<Map<RexNode, Comparable>> assignments() {
  final List<List<Comparable>> generators =
      variables.stream().map(RexAnalyzer::getComparables)
          .collect(Util.toImmutableList());
  final Iterable<List<Comparable>> product = EnumeratorUtils.product(generators);
  //noinspection StaticPseudoFunctionalStyleMethod
  return Iterables.transform(product,
      values -> ImmutableMap.copyOf(Pair.zip(variables, values)));
}
 
Example #24
Source File: GremlinTable.java    From sql-gremlin with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType getRowType(RelDataTypeFactory relDataTypeFactory) {
    List<String> names = new ArrayList<>();
    List<RelDataType> types = new ArrayList<>();

    for(Map.Entry<String, TableColumn> entry : tableDef.columns.entrySet()) {
        names.add(entry.getKey());
        types.add(relDataTypeFactory.createJavaType(
                getType(entry.getValue().getType())));
    }

    return relDataTypeFactory.createStructType(Pair.zip(names, types));
}
 
Example #25
Source File: SqlMapValueConstructor.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  Pair<RelDataType, RelDataType> type =
      getComponentTypes(
          opBinding.getTypeFactory(), opBinding.collectOperandTypes());
  if (null == type) {
    return null;
  }
  return SqlTypeUtil.createMapType(
      opBinding.getTypeFactory(),
      type.left,
      type.right,
      false);
}
 
Example #26
Source File: RelStructuredTypeFlattener.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void flattenResultTypeOfRexCall(RexNode newExp,
    String fieldName,
    List<Pair<RexNode, String>> flattenedExps) {
  int nameIdx = 0;
  for (RelDataTypeField field : newExp.getType().getFieldList()) {
    RexNode fieldRef = rexBuilder.makeFieldAccess(newExp, field.getIndex());
    String fieldRefName = fieldName + "$" + (nameIdx++);
    if (fieldRef.getType().isStruct()) {
      flattenResultTypeOfRexCall(fieldRef, fieldRefName, flattenedExps);
    } else {
      flattenedExps.add(Pair.of(fieldRef, fieldRefName));
    }
  }
}
 
Example #27
Source File: ScannableTableTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** A table with one column. */
@Test void testSimple() throws Exception {
  CalciteAssert.that()
      .with(newSchema("s", Pair.of("simple", new SimpleTable())))
      .query("select * from \"s\".\"simple\"")
      .returnsUnordered("i=0", "i=10", "i=20", "i=30");
}
 
Example #28
Source File: AbstractMaterializedViewRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<RelNode, RelNode> pushFilterToOriginalViewPlan(RelBuilder builder, RelNode topViewProject,
        RelNode viewNode, RexNode cond) {
    // We add (and push) the filter to the view plan before triggering the rewriting.
    // This is useful in case some of the columns can be folded to same value after
    // filter is added.
    HepProgramBuilder pushFiltersProgram = new HepProgramBuilder();
    if (topViewProject != null) {
        pushFiltersProgram.addRuleInstance(filterProjectTransposeRule);
    }
    pushFiltersProgram.addRuleInstance(this.filterAggregateTransposeRule)
            .addRuleInstance(this.aggregateProjectPullUpConstantsRule).addRuleInstance(this.projectMergeRule);
    final HepPlanner tmpPlanner = new HepPlanner(pushFiltersProgram.build());
    // Now that the planner is created, push the node
    RelNode topNode = builder.push(topViewProject != null ? topViewProject : viewNode).filter(cond).build();
    tmpPlanner.setRoot(topNode);
    topNode = tmpPlanner.findBestExp();
    RelNode resultTopViewProject = null;
    RelNode resultViewNode = null;
    while (topNode != null) {
        if (topNode instanceof Project) {
            if (resultTopViewProject != null) {
                // Both projects could not be merged, we will bail out
                return Pair.of(topViewProject, viewNode);
            }
            resultTopViewProject = topNode;
            topNode = topNode.getInput(0);
        } else if (topNode instanceof Aggregate) {
            resultViewNode = topNode;
            topNode = null;
        } else {
            // We move to the child
            topNode = topNode.getInput(0);
        }
    }
    return Pair.of(resultTopViewProject, resultViewNode);
}
 
Example #29
Source File: CassandraProject.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void implement(Implementor implementor) {
  implementor.visitChild(0, getInput());
  final CassandraRules.RexToCassandraTranslator translator =
      new CassandraRules.RexToCassandraTranslator(
          (JavaTypeFactory) getCluster().getTypeFactory(),
          CassandraRules.cassandraFieldNames(getInput().getRowType()));
  final Map<String, String> fields = new LinkedHashMap<>();
  for (Pair<RexNode, String> pair : getNamedProjects()) {
    final String name = pair.right;
    final String originalName = pair.left.accept(translator);
    fields.put(originalName, name);
  }
  implementor.add(fields, null);
}
 
Example #30
Source File: RelStructuredTypeFlattener.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void flattenProjections(RewriteRexShuttle shuttle,
    List<? extends RexNode> exps,
    List<String> fieldNames,
    String prefix,
    List<Pair<RexNode, String>> flattenedExps) {
  for (int i = 0; i < exps.size(); ++i) {
    RexNode exp = exps.get(i);
    String fieldName = extractName(fieldNames, prefix, i);
    flattenProjection(shuttle, exp, fieldName, flattenedExps);
  }
}