Java Code Examples for org.apache.calcite.linq4j.Ord#zip()

The following examples show how to use org.apache.calcite.linq4j.Ord#zip() . 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: SqlWindow.java    From calcite with Apache License 2.0 6 votes vote down vote up
public <R> void acceptCall(
    SqlVisitor<R> visitor,
    SqlCall call,
    boolean onlyExpressions,
    SqlBasicVisitor.ArgHandler<R> argHandler) {
  if (onlyExpressions) {
    for (Ord<SqlNode> operand : Ord.zip(call.getOperandList())) {
      // if the second param is an Identifier then it's supposed to
      // be a name from a window clause and isn't part of the
      // group by check
      if (operand.e == null) {
        continue;
      }
      if (operand.i == 1 && operand.e instanceof SqlIdentifier) {
        // skip refName
        continue;
      }
      argHandler.visitChild(visitor, call, operand.i, operand.e);
    }
  } else {
    super.acceptCall(visitor, call, onlyExpressions, argHandler);
  }
}
 
Example 2
Source File: EnumerableMatch.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Generates code for a pattern.
 *
 * <p>For example, for the pattern {@code (A B)}, generates
 * {@code patternBuilder.symbol("A").symbol("B").seq()}. */
private Expression implementPattern(Expression patternBuilder_,
    RexNode pattern) {
  switch (pattern.getKind()) {
  case LITERAL:
    final String symbol = ((RexLiteral) pattern).getValueAs(String.class);
    return Expressions.call(patternBuilder_,
        BuiltInMethod.PATTERN_BUILDER_SYMBOL.method,
        Expressions.constant(symbol));

  case PATTERN_CONCAT:
    final RexCall concat = (RexCall) pattern;
    for (Ord<RexNode> operand : Ord.zip(concat.operands)) {
      patternBuilder_ = implementPattern(patternBuilder_, operand.e);
      if (operand.i > 0) {
        patternBuilder_ = Expressions.call(patternBuilder_,
            BuiltInMethod.PATTERN_BUILDER_SEQ.method);
      }
    }
    return patternBuilder_;

  default:
    throw new AssertionError("unknown kind: " + pattern);
  }
}
 
Example 3
Source File: Project.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a mapping of a set of project expressions.
 *
 * <p>The mapping is an inverse surjection.
 * Every target has a source field, but no
 * source has more than one target.
 * Thus you can safely call
 * {@link org.apache.calcite.util.mapping.Mappings.TargetMapping#getSourceOpt(int)}.
 *
 * @param inputFieldCount Number of input fields
 * @param projects Project expressions
 * @return Mapping of a set of project expressions, or null if projection is
 * not a mapping
 */
public static Mappings.TargetMapping getMapping(int inputFieldCount,
    List<? extends RexNode> projects) {
  if (inputFieldCount < projects.size()) {
    return null; // surjection is not possible
  }
  Mappings.TargetMapping mapping =
      Mappings.create(MappingType.INVERSE_SURJECTION,
          inputFieldCount, projects.size());
  for (Ord<RexNode> exp : Ord.<RexNode>zip(projects)) {
    if (!(exp.e instanceof RexInputRef)) {
      return null;
    }

    int source = ((RexInputRef) exp.e).getIndex();
    if (mapping.getTargetOpt(source) != -1) {
      return null;
    }
    mapping.set(source, exp.i);
  }
  return mapping;
}
 
Example 4
Source File: JavaTypeFactoryImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Type createSyntheticType(List<Type> types) {
  if (types.isEmpty()) {
    // Unit is a pre-defined synthetic type to be used when there are 0
    // fields. Because all instances are the same, we use a singleton.
    return Unit.class;
  }
  final String name =
      "Record" + types.size() + "_" + syntheticTypes.size();
  final SyntheticRecordType syntheticType =
      new SyntheticRecordType(null, name);
  for (final Ord<Type> ord : Ord.zip(types)) {
    syntheticType.fields.add(
        new RecordFieldImpl(
            syntheticType,
            "f" + ord.i,
            ord.e,
            !Primitive.is(ord.e),
            Modifier.PUBLIC));
  }
  return register(syntheticType);
}
 
Example 5
Source File: RelOptUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a permutation describing where output fields come from. In
 * the returned map, value of {@code map.getTargetOpt(i)} is {@code n} if
 * field {@code i} projects input field {@code n} or applies a cast on
 * {@code n}, -1 if it is another expression.
 */
public static Mappings.TargetMapping permutationIgnoreCast(
    List<RexNode> nodes,
    RelDataType inputRowType) {
  final Mappings.TargetMapping mapping =
      Mappings.create(
          MappingType.PARTIAL_FUNCTION,
          nodes.size(),
          inputRowType.getFieldCount());
  for (Ord<RexNode> node : Ord.zip(nodes)) {
    if (node.e instanceof RexInputRef) {
      mapping.set(
          node.i,
          ((RexInputRef) node.e).getIndex());
    } else if (node.e.isA(SqlKind.CAST)) {
      final RexNode operand = ((RexCall) node.e).getOperands().get(0);
      if (operand instanceof RexInputRef) {
        mapping.set(node.i, ((RexInputRef) operand).getIndex());
      }
    }
  }
  return mapping;
}
 
Example 6
Source File: RelOptUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a permutation describing where the Project's fields come from
 * after the Project is pushed down.
 */
public static Mappings.TargetMapping permutationPushDownProject(
    List<RexNode> nodes,
    RelDataType inputRowType,
    int sourceOffset,
    int targetOffset) {
  final Mappings.TargetMapping mapping =
      Mappings.create(MappingType.PARTIAL_FUNCTION,
          inputRowType.getFieldCount() + sourceOffset,
          nodes.size() + targetOffset);
  for (Ord<RexNode> node : Ord.zip(nodes)) {
    if (node.e instanceof RexInputRef) {
      mapping.set(
          ((RexInputRef) node.e).getIndex() + sourceOffset,
          node.i + targetOffset);
    }
  }
  return mapping;
}
 
Example 7
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static int lookupGroupExpr(GroupAnalyzer groupAnalyzer,
    SqlNode expr) {
  for (Ord<SqlNode> node : Ord.zip(groupAnalyzer.groupExprs)) {
    if (node.e.equalsDeep(expr, Litmus.IGNORE)) {
      return node.i;
    }
  }

  switch (expr.getKind()) {
  case HOP:
  case TUMBLE:
  case SESSION:
    groupAnalyzer.extraExprs.add(expr);
    break;
  }
  groupAnalyzer.groupExprs.add(expr);
  return groupAnalyzer.groupExprs.size() - 1;
}
 
Example 8
Source File: SqlSubstringFunction.java    From calcite with Apache License 2.0 6 votes vote down vote up
public String getAllowedSignatures(String opName) {
  StringBuilder ret = new StringBuilder();
  for (Ord<SqlTypeName> typeName : Ord.zip(SqlTypeName.STRING_TYPES)) {
    if (typeName.i > 0) {
      ret.append(NL);
    }
    ret.append(
        SqlUtil.getAliasedSignature(this, opName,
            ImmutableList.of(typeName.e, SqlTypeName.INTEGER)));
    ret.append(NL);
    ret.append(
        SqlUtil.getAliasedSignature(this, opName,
            ImmutableList.of(typeName.e, SqlTypeName.INTEGER,
                SqlTypeName.INTEGER)));
  }
  return ret.toString();
}
 
Example 9
Source File: RelDecorrelator.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Projects all {@code input} output fields plus the additional expressions.
 *
 * @param input        Input relational expression
 * @param additionalExprs Additional expressions and names
 * @return the new Project
 */
private RelNode createProjectWithAdditionalExprs(
    RelNode input,
    List<Pair<RexNode, String>> additionalExprs) {
  final List<RelDataTypeField> fieldList =
      input.getRowType().getFieldList();
  List<Pair<RexNode, String>> projects = new ArrayList<>();
  for (Ord<RelDataTypeField> field : Ord.zip(fieldList)) {
    projects.add(
        Pair.of(
            (RexNode) relBuilder.getRexBuilder().makeInputRef(
                field.e.getType(), field.i),
            field.e.getName()));
  }
  projects.addAll(additionalExprs);
  return relBuilder.push(input)
      .projectNamed(Pair.left(projects), Pair.right(projects), true)
      .build();
}
 
Example 10
Source File: RelDecorrelator.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Projects all {@code input} output fields plus the additional expressions.
 *
 * @param input        Input relational expression
 * @param additionalExprs Additional expressions and names
 * @return the new Project
 */
private RelNode createProjectWithAdditionalExprs(
    RelNode input,
    List<Pair<RexNode, String>> additionalExprs) {
  final List<RelDataTypeField> fieldList =
      input.getRowType().getFieldList();
  List<Pair<RexNode, String>> projects = new ArrayList<>();
  for (Ord<RelDataTypeField> field : Ord.zip(fieldList)) {
    projects.add(
        Pair.of(
            (RexNode) relBuilder.getRexBuilder().makeInputRef(
                field.e.getType(), field.i),
            field.e.getName()));
  }
  projects.addAll(additionalExprs);
  return relBuilder.push(input)
      .projectNamed(Pair.left(projects), Pair.right(projects), true)
      .build();
}
 
Example 11
Source File: RelRecordType.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected void generateTypeString(StringBuilder sb, boolean withDetail) {
  sb.append("RecordType");
  switch (kind) {
  case PEEK_FIELDS:
    sb.append(":peek");
    break;
  case PEEK_FIELDS_DEFAULT:
    sb.append(":peek_default");
    break;
  case PEEK_FIELDS_NO_EXPAND:
    sb.append(":peek_no_expand");
    break;
  }
  sb.append("(");
  for (Ord<RelDataTypeField> ord : Ord.zip(fieldList)) {
    if (ord.i > 0) {
      sb.append(", ");
    }
    RelDataTypeField field = ord.e;
    if (withDetail) {
      sb.append(field.getType().getFullTypeString());
    } else {
      sb.append(field.getType().toString());
    }
    sb.append(" ");
    sb.append(field.getName());
  }
  sb.append(")");
}
 
Example 12
Source File: NumberingRelWriter.java    From dremio-oss 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 13
Source File: SingleMergeExchangePrel.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public RelWriter explainTerms(RelWriter pw) {
  super.explainTerms(pw);
  if (pw.nest()) {
    pw.item("collation", collation);
  } else {
    for (Ord<RelFieldCollation> ord : Ord.zip(collation.getFieldCollations())) {
      pw.item("sort" + ord.i, ord.e);
    }
  }
  return pw;
}
 
Example 14
Source File: MutableMultiRel.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected MutableMultiRel(RelOptCluster cluster,
    RelDataType rowType, MutableRelType type, List<MutableRel> inputs) {
  super(cluster, rowType, type);
  this.inputs = new ArrayList<>(inputs);
  for (Ord<MutableRel> input : Ord.zip(inputs)) {
    input.e.parent = this;
    input.e.ordinalInParent = input.i;
  }
}
 
Example 15
Source File: CompoundNameColumnResolver.java    From calcite with Apache License 2.0 5 votes vote down vote up
CompoundNameColumnResolver(
    List<CompoundNameColumn> columns, String defaultColumnGroup) {
  this.defaultColumnGroup = defaultColumnGroup;
  for (Ord<CompoundNameColumn> column : Ord.zip(columns)) {
    nameMap.put(column.e.getName(), column.i);
    Map<String, Integer> subMap =
        groupMap.computeIfAbsent(column.e.first, k -> new HashMap<>());
    subMap.put(column.e.second, column.i);
  }
}
 
Example 16
Source File: KylinEnumerableUnion.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
    final BlockBuilder builder = new BlockBuilder();
    Expression unionExp = null;
    for (Ord<RelNode> ord : Ord.zip(inputs)) {
        EnumerableRel input = (EnumerableRel) ord.e;
        final Result result = implementor.visitChild(this, ord.i, input, pref);
        Expression childExp =
                builder.append(
                        "child" + ord.i,
                        result.block);

        if (unionExp == null) {
            unionExp = childExp;
        } else {
            unionExp = createUnionExpression(unionExp, childExp, result.format == JavaRowFormat.ARRAY);
        }
    }

    builder.add(unionExp);
    final PhysType physType =
            PhysTypeImpl.of(
                    implementor.getTypeFactory(),
                    getRowType(),
                    pref.prefer(JavaRowFormat.CUSTOM));
    return implementor.result(physType, builder.toBlock());
}
 
Example 17
Source File: Project.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RelWriter explainTerms(RelWriter pw) {
  super.explainTerms(pw);
  // Skip writing field names so the optimizer can reuse the projects that differ in
  // field names only
  if (pw.getDetailLevel() == SqlExplainLevel.DIGEST_ATTRIBUTES) {
    final int firstNonTrivial = countTrivial(exps);
    if (firstNonTrivial == 1) {
      pw.item("inputs", "0");
    } else if (firstNonTrivial != 0) {
      pw.item("inputs", "0.." + (firstNonTrivial - 1));
    }
    if (firstNonTrivial != exps.size()) {
      pw.item("exprs", exps.subList(firstNonTrivial, exps.size()));
    }
    return pw;
  }

  if (pw.nest()) {
    pw.item("fields", rowType.getFieldNames());
    pw.item("exprs", exps);
  } else {
    for (Ord<RelDataTypeField> field : Ord.zip(rowType.getFieldList())) {
      String fieldName = field.e.getName();
      if (fieldName == null) {
        fieldName = "field#" + field.i;
      }
      pw.item(fieldName, exps.get(field.i));
    }
  }

  return pw;
}
 
Example 18
Source File: SqlLiteralChainOperator.java    From calcite with Apache License 2.0 4 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  final SqlWriter.Frame frame = writer.startList("", "");
  SqlCollation collation = null;
  for (Ord<SqlNode> operand : Ord.zip(call.getOperandList())) {
    SqlLiteral rand = (SqlLiteral) operand.e;
    if (operand.i > 0) {
      // SQL:2003 says there must be a newline between string
      // fragments.
      writer.newlineAndIndent();
    }
    if (rand instanceof SqlCharStringLiteral) {
      NlsString nls = ((SqlCharStringLiteral) rand).getNlsString();
      if (operand.i == 0) {
        collation = nls.getCollation();

        // print with prefix
        writer.literal(nls.asSql(true, false, writer.getDialect()));
      } else {
        // print without prefix
        writer.literal(nls.asSql(false, false, writer.getDialect()));
      }
    } else if (operand.i == 0) {
      // print with prefix
      rand.unparse(writer, leftPrec, rightPrec);
    } else {
      // print without prefix
      if (rand.getTypeName() == SqlTypeName.BINARY) {
        BitString bs = (BitString) rand.getValue();
        writer.literal("'" + bs.toHexString() + "'");
      } else {
        writer.literal("'" + rand.toValue() + "'");
      }
    }
  }
  if (collation != null) {
    collation.unparse(writer);
  }
  writer.endList(frame);
}
 
Example 19
Source File: EnumerableTraitsUtils.java    From calcite with Apache License 2.0 4 votes vote down vote up
static Pair<RelTraitSet, List<RelTraitSet>> deriveTraitsForProject(
    RelTraitSet childTraits, int childId, List<RexNode> exps,
    RelDataType inputRowType, RelDataTypeFactory typeFactory, RelTraitSet currentTraits) {
  final RelCollation collation = childTraits.getCollation();
  if (collation == null || collation == RelCollations.EMPTY) {
    return null;
  }

  final int maxField = Math.max(exps.size(),
      inputRowType.getFieldCount());
  Mappings.TargetMapping mapping = Mappings
      .create(MappingType.FUNCTION, maxField, maxField);
  for (Ord<RexNode> node : Ord.zip(exps)) {
    if (node.e instanceof RexInputRef) {
      mapping.set(((RexInputRef) node.e).getIndex(), node.i);
    } else if (node.e.isA(SqlKind.CAST)) {
      final RexNode operand = ((RexCall) node.e).getOperands().get(0);
      if (operand instanceof RexInputRef) {
        mapping.set(((RexInputRef) operand).getIndex(), node.i);
      }
    }
  }

  List<RelFieldCollation> collationFieldsToDerive = new ArrayList<>();
  for (RelFieldCollation rc : collation.getFieldCollations()) {
    if (isCollationOnTrivialExpr(exps, typeFactory, mapping, rc, false)) {
      collationFieldsToDerive.add(rc);
    } else {
      break;
    }
  }

  if (collationFieldsToDerive.size() > 0) {
    final RelCollation newCollation = RelCollations
        .of(collationFieldsToDerive).apply(mapping);
    return Pair.of(currentTraits.replace(newCollation),
        ImmutableList.of(currentTraits.replace(collation)));
  } else {
    return null;
  }
}
 
Example 20
Source File: Project.java    From calcite with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a partial mapping of a set of project expressions.
 *
 * <p>The mapping is an inverse function.
 * Every target has a source field, but
 * a source might have 0, 1 or more targets.
 * Project expressions that do not consist of
 * a mapping are ignored.
 *
 * @param inputFieldCount Number of input fields
 * @param projects Project expressions
 * @return Mapping of a set of project expressions, never null
 */
public static Mappings.TargetMapping getPartialMapping(int inputFieldCount,
    List<? extends RexNode> projects) {
  Mappings.TargetMapping mapping =
      Mappings.create(MappingType.INVERSE_FUNCTION,
          inputFieldCount, projects.size());
  for (Ord<RexNode> exp : Ord.<RexNode>zip(projects)) {
    if (exp.e instanceof RexInputRef) {
      mapping.set(((RexInputRef) exp.e).getIndex(), exp.i);
    }
  }
  return mapping;
}