Java Code Examples for org.apache.calcite.util.Pair

The following examples show how to use org.apache.calcite.util.Pair. These examples are extracted from open source projects. 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: marble   Source File: TableEnv.java    License: 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 2
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: 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 3
Source Project: Bats   Source File: VisitorDataContext.java    License: 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 4
Source Project: calcite   Source File: SqlValidatorUtil.java    License: 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 5
Source Project: Bats   Source File: DrillSemiJoinRel.java    License: 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 6
Source Project: calcite   Source File: WithItemNamespace.java    License: 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 7
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: 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 8
Source Project: calcite   Source File: SqlLineTest.java    License: 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 9
Source Project: dremio-oss   Source File: JoinPrel.java    License: 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 10
Source Project: attic-apex-malhar   Source File: ApexRelNode.java    License: 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 11
Source Project: calcite   Source File: ScannableTableTest.java    License: 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 12
Source Project: flink   Source File: HiveTableSqlFunction.java    License: 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 13
Source Project: calcite   Source File: SqlValidatorUtil.java    License: 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 14
Source Project: calcite   Source File: DruidJsonFilter.java    License: 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 15
Source Project: calcite   Source File: ScannableTableTest.java    License: 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 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 16
Source Project: calcite   Source File: SqlRowTypeNameSpec.java    License: 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 17
Source Project: Bats   Source File: LatticeSuggester.java    License: Apache License 2.0 5 votes vote down vote up
private java.util.function.Function<Lattice.Column, Lattice.Column> mapper(
    final Lattice lattice, final Lattice.Builder builder) {
  return (Lattice.Column c) -> {
    if (c instanceof Lattice.BaseColumn) {
      Lattice.BaseColumn baseColumn = (Lattice.BaseColumn) c;
      Pair<Path, Integer> p = lattice.columnToPathOffset(baseColumn);
      return builder.pathOffsetToColumn(p.left, p.right);
    } else {
      final Lattice.DerivedColumn derivedColumn = (Lattice.DerivedColumn) c;
      return builder.expression(derivedColumn.e, derivedColumn.alias,
          derivedColumn.tables);
    }
  };
}
 
Example 18
Source Project: Bats   Source File: Lattice.java    License: Apache License 2.0 5 votes vote down vote up
Pair<Path, Integer> columnToPathOffset(BaseColumn c) {
  for (Pair<LatticeNode, Path> p
      : Pair.zip(rootNode.descendants, rootNode.paths)) {
    if (p.left.alias.equals(c.table)) {
      return Pair.of(p.right, c.ordinal - p.left.startCol);
    }
  }
  throw new AssertionError("lattice column not found: " + c);
}
 
Example 19
Source Project: calcite   Source File: ServerDdlExecutor.java    License: Apache License 2.0 5 votes vote down vote up
/** Executes a {@code CREATE MATERIALIZED VIEW} command. */
public void execute(SqlCreateMaterializedView create,
    CalcitePrepare.Context context) {
  final Pair<CalciteSchema, String> pair = schema(context, true, create.name);
  if (pair.left.plus().getTable(pair.right) != null) {
    // Materialized view exists.
    if (!create.ifNotExists) {
      // They did not specify IF NOT EXISTS, so give error.
      throw SqlUtil.newContextException(create.name.getParserPosition(),
          RESOURCE.tableExists(pair.right));
    }
    return;
  }
  final SqlNode q = renameColumns(create.columnList, create.query);
  final String sql = q.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
  final List<String> schemaPath = pair.left.path(null);
  final ViewTableMacro viewTableMacro =
      ViewTable.viewMacro(pair.left.plus(), sql, schemaPath,
          context.getObjectPath(), false);
  final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
  final RelDataType rowType = x.getRowType(context.getTypeFactory());

  // Table does not exist. Create it.
  final MaterializedViewTable table =
      new MaterializedViewTable(pair.right, RelDataTypeImpl.proto(rowType));
  pair.left.add(pair.right, table);
  populate(create.name, create.query, context);
  table.key =
      MaterializationService.instance().defineMaterialization(pair.left, null,
          sql, schemaPath, pair.right, true, true);
}
 
Example 20
Source Project: calcite   Source File: EnumerableMatch.java    License: Apache License 2.0 5 votes vote down vote up
PrevInputGetter(ParameterExpression row, PhysType physType) {
  this.row = row;
  generator = e -> new RexToLixTranslator.InputGetterImpl(
      Collections.singletonList(
          Pair.of(e, physType)));
  this.physType = physType;
}
 
Example 21
Source Project: calcite   Source File: JoinToMultiJoinRule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Copies outer join data from a source MultiJoin to a new set of arrays.
 * Also adjusts the conditions to reflect the new position of an input if
 * that input ends up being shifted to the right.
 *
 * @param multiJoin     the source MultiJoin
 * @param destJoinSpecs    the list where the join types and conditions will
 *                         be copied
 * @param adjustmentAmount if &gt; 0, the amount the RexInputRefs in the join
 *                         conditions need to be adjusted by
 * @param srcFields        the source fields that the original join conditions
 *                         are referencing
 * @param destFields       the destination fields that the new join conditions
 */
private void copyOuterJoinInfo(
    MultiJoin multiJoin,
    List<Pair<JoinRelType, RexNode>> destJoinSpecs,
    int adjustmentAmount,
    List<RelDataTypeField> srcFields,
    List<RelDataTypeField> destFields) {
  final List<Pair<JoinRelType, RexNode>> srcJoinSpecs =
      Pair.zip(
          multiJoin.getJoinTypes(),
          multiJoin.getOuterJoinConditions());

  if (adjustmentAmount == 0) {
    destJoinSpecs.addAll(srcJoinSpecs);
  } else {
    assert srcFields != null;
    assert destFields != null;
    int nFields = srcFields.size();
    int[] adjustments = new int[nFields];
    for (int idx = 0; idx < nFields; idx++) {
      adjustments[idx] = adjustmentAmount;
    }
    for (Pair<JoinRelType, RexNode> src
        : srcJoinSpecs) {
      destJoinSpecs.add(
          Pair.of(
              src.left,
              src.right == null
                  ? null
                  : src.right.accept(
                      new RelOptUtil.RexInputConverter(
                          multiJoin.getCluster().getRexBuilder(),
                          srcFields, destFields, adjustments))));
    }
  }
}
 
Example 22
Source Project: calcite   Source File: ScannableTableTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testPFPushDownProjectFilterInAggregateNoGroup() {
  final StringBuilder buf = new StringBuilder();
  final Table table = new BeatlesProjectableFilterableTable(buf, false);
  final String explain = "PLAN=EnumerableAggregate(group=[{}], M=[MAX($0)])\n"
      + "  EnumerableInterpreter\n"
      + "    BindableTableScan(table=[[s, beatles]], filters=[[>($0, 1)]], projects=[[2]])";
  CalciteAssert.that()
      .with(newSchema("s", Pair.of("beatles", table)))
      .query("select max(\"k\") as m from \"s\".\"beatles\" where \"i\" > 1")
      .explainContains(explain)
      .returnsUnordered("M=1943");
}
 
Example 23
Source Project: Bats   Source File: RexBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static List<Integer> nullableArgs(List<Integer> list0,
    List<RelDataType> types) {
  final List<Integer> list = new ArrayList<>();
  for (Pair<Integer, RelDataType> pair : Pair.zip(list0, types)) {
    if (pair.right.isNullable()) {
      list.add(pair.left);
    }
  }
  return list;
}
 
Example 24
Source Project: Bats   Source File: AbstractMaterializedViewRule.java    License: 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 25
Source Project: calcite   Source File: ScannableTableTest.java    License: 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 26
Source Project: calcite   Source File: RelStructuredTypeFlattener.java    License: 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 Project: sql-gremlin   Source File: GremlinTable.java    License: 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 28
Source Project: Bats   Source File: RexAnalyzer.java    License: 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 29
Source Project: calcite   Source File: RelStructuredTypeFlattener.java    License: 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);
  }
}
 
Example 30
Source Project: Bats   Source File: NumberingRelWriter.java    License: 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();
}