org.apache.calcite.runtime.Utilities Java Examples

The following examples show how to use org.apache.calcite.runtime.Utilities. 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: ImmutableBitSetTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testCompare() {
  final List<ImmutableBitSet> sorted = getSortedList();
  for (int i = 0; i < sorted.size(); i++) {
    for (int j = 0; j < sorted.size(); j++) {
      final ImmutableBitSet set0 = sorted.get(i);
      final ImmutableBitSet set1 = sorted.get(j);
      int c = set0.compareTo(set1);
      if (c == 0) {
        assertTrue(i == j || i == 3 && j == 4 || i == 4 && j == 3);
      } else {
        assertEquals(c, Utilities.compare(i, j));
      }
      assertEquals(c == 0, set0.equals(set1));
      assertEquals(c == 0, set1.equals(set0));
    }
  }
}
 
Example #2
Source File: RexExecutable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static Function1<DataContext, Object[]> compile(String code,
    Object reason) {
  try {
    final ClassBodyEvaluator cbe = new ClassBodyEvaluator();
    cbe.setClassName(GENERATED_CLASS_NAME);
    cbe.setExtendedClass(Utilities.class);
    cbe.setImplementedInterfaces(new Class[] {Function1.class, Serializable.class});
    cbe.setParentClassLoader(RexExecutable.class.getClassLoader());
    cbe.cook(new Scanner(null, new StringReader(code)));
    Class c = cbe.getClazz();
    //noinspection unchecked
    final Constructor<Function1<DataContext, Object[]>> constructor =
        c.getConstructor();
    return constructor.newInstance();
  } catch (CompileException | IOException | InstantiationException
      | IllegalAccessException | InvocationTargetException
      | NoSuchMethodException e) {
    throw new RuntimeException("While compiling " + reason, e);
  }
}
 
Example #3
Source File: RelCollationImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
public int compareTo(@Nonnull RelMultipleTrait o) {
  final RelCollationImpl that = (RelCollationImpl) o;
  final UnmodifiableIterator<RelFieldCollation> iterator =
      that.fieldCollations.iterator();
  for (RelFieldCollation f : fieldCollations) {
    if (!iterator.hasNext()) {
      return 1;
    }
    final RelFieldCollation f2 = iterator.next();
    int c = Utilities.compare(f.getFieldIndex(), f2.getFieldIndex());
    if (c != 0) {
      return c;
    }
  }
  return iterator.hasNext() ? -1 : 0;
}
 
Example #4
Source File: HiveEnumerableInterpretable.java    From marble with Apache License 2.0 6 votes vote down vote up
static Bindable getBindable(ClassDeclaration expr, String s, int fieldCount)
    throws CompileException, IOException {
  ICompilerFactory compilerFactory;
  try {
    compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory();
  } catch (Exception e) {
    throw new IllegalStateException(
        "Unable to instantiate java compiler", e);
  }
  IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator();
  cbe.setClassName(expr.name);
  cbe.setExtendedClass(Utilities.class);
  cbe.setImplementedInterfaces(
      fieldCount == 1
          ? new Class[]{Bindable.class, Typed.class}
          : new Class[]{ArrayBindable.class});
  cbe.setParentClassLoader(EnumerableInterpretable.class.getClassLoader());
  if (CalcitePrepareImpl.DEBUG) {
    // Add line numbers to the generated janino class
    cbe.setDebuggingInformation(true, true, true);
  }
  return (Bindable) cbe.createInstance(new StringReader(s));
}
 
Example #5
Source File: EnumUtils.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static Expression generateCollatorExpression(SqlCollation collation) {
  if (collation == null || collation.getCollator() == null) {
    return null;
  }

  // Utilities.generateCollator(
  //      new Locale(
  //          collation.getLocale().getLanguage(),
  //          collation.getLocale().getCountry(),
  //          collation.getLocale().getVariant()),
  //      collation.getCollator().getStrength());
  final Locale locale = collation.getLocale();
  final int strength = collation.getCollator().getStrength();
  return Expressions.call(
      Utilities.class,
      "generateCollator",
      Expressions.new_(
          Locale.class,
          Expressions.constant(locale.getLanguage()),
          Expressions.constant(locale.getCountry()),
          Expressions.constant(locale.getVariant())),
      Expressions.constant(strength));
}
 
Example #6
Source File: SqlFunctionsTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Unit test for
 * {@link Utilities#compare(java.util.List, java.util.List)}. */
@Test void testCompare() {
  final List<String> ac = Arrays.asList("a", "c");
  final List<String> abc = Arrays.asList("a", "b", "c");
  final List<String> a = Collections.singletonList("a");
  final List<String> empty = Collections.emptyList();
  assertThat(Utilities.compare(ac, ac), is(0));
  assertThat(Utilities.compare(ac, new ArrayList<>(ac)), is(0));
  assertThat(Utilities.compare(a, ac), is(-1));
  assertThat(Utilities.compare(empty, ac), is(-1));
  assertThat(Utilities.compare(ac, a), is(1));
  assertThat(Utilities.compare(ac, abc), is(1));
  assertThat(Utilities.compare(ac, empty), is(1));
  assertThat(Utilities.compare(empty, empty), is(0));
}
 
Example #7
Source File: UtilTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public void checkHash(double v) {
  assertThat(Double.valueOf(v).hashCode(), is(Utilities.hashCode(v)));
  final long long_ = (long) v;
  assertThat(Long.valueOf(long_).hashCode(), is(Utilities.hashCode(long_)));
  final float float_ = (float) v;
  assertThat(Float.valueOf(float_).hashCode(),
      is(Utilities.hashCode(float_)));
  final boolean boolean_ = v != 0;
  assertThat(Boolean.valueOf(boolean_).hashCode(),
      is(Utilities.hashCode(boolean_)));
}
 
Example #8
Source File: Lattice.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static int compare(List<Column> list0, List<Column> list1) {
  final int size = Math.min(list0.size(), list1.size());
  for (int i = 0; i < size; i++) {
    final int o0 = list0.get(i).ordinal;
    final int o1 = list1.get(i).ordinal;
    final int c = Utilities.compare(o0, o1);
    if (c != 0) {
      return c;
    }
  }
  return Utilities.compare(list0.size(), list1.size());
}
 
Example #9
Source File: RelNodes.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Compares arrays of {@link RelNode}. */
public static int compareRels(RelNode[] rels0, RelNode[] rels1) {
  int c = Utilities.compare(rels0.length, rels1.length);
  if (c != 0) {
    return c;
  }
  for (int i = 0; i < rels0.length; i++) {
    c = COMPARATOR.compare(rels0[i], rels1[i]);
    if (c != 0) {
      return c;
    }
  }
  return 0;
}
 
Example #10
Source File: RelNodes.java    From calcite with Apache License 2.0 5 votes vote down vote up
public int compare(RelNode o1, RelNode o2) {
  // Compare on field count first. It is more stable than id (when rules
  // are added to the set of active rules).
  final int c = Utilities.compare(o1.getRowType().getFieldCount(),
      o2.getRowType().getFieldCount());
  if (c != 0) {
    return -c;
  }
  return Utilities.compare(o1.getId(), o2.getId());
}
 
Example #11
Source File: EnumerableInterpretable.java    From calcite with Apache License 2.0 5 votes vote down vote up
static Bindable getBindable(ClassDeclaration expr, String s, int fieldCount)
    throws CompileException, IOException, ExecutionException {
  ICompilerFactory compilerFactory;
  try {
    compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory();
  } catch (Exception e) {
    throw new IllegalStateException(
        "Unable to instantiate java compiler", e);
  }
  final IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator();
  cbe.setClassName(expr.name);
  cbe.setExtendedClass(Utilities.class);
  cbe.setImplementedInterfaces(
      fieldCount == 1
          ? new Class[] {Bindable.class, Typed.class}
          : new Class[] {ArrayBindable.class});
  cbe.setParentClassLoader(EnumerableInterpretable.class.getClassLoader());
  if (CalciteSystemProperty.DEBUG.value()) {
    // Add line numbers to the generated janino class
    cbe.setDebuggingInformation(true, true, true);
  }

  if (CalciteSystemProperty.BINDABLE_CACHE_MAX_SIZE.value() != 0) {
    StaticFieldDetector detector = new StaticFieldDetector();
    expr.accept(detector);
    if (!detector.containsStaticField) {
      return BINDABLE_CACHE.get(s, () -> (Bindable) cbe.createInstance(new StringReader(s)));
    }
  }
  return (Bindable) cbe.createInstance(new StringReader(s));
}
 
Example #12
Source File: ImmutableBitSet.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Compares this ImmutableBitSet with another, using a lexicographic
 * ordering.
 *
 * <p>Bit sets {@code (), (0), (0, 1), (0, 1, 3), (1), (2, 3)} are in sorted
 * order.</p>
 */
public int compareTo(@Nonnull ImmutableBitSet o) {
  int i = 0;
  for (;;) {
    int n0 = nextSetBit(i);
    int n1 = o.nextSetBit(i);
    int c = Utilities.compare(n0, n1);
    if (c != 0 || n0 < 0) {
      return c;
    }
    i = n0 + 1;
  }
}
 
Example #13
Source File: PhysTypeImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Expression generateComparator(RelCollation collation) {
  // int c;
  // c = Utilities.compare(v0, v1);
  // if (c != 0) return c; // or -c if descending
  // ...
  // return 0;
  BlockBuilder body = new BlockBuilder();
  final Type javaRowClass = Primitive.box(this.javaRowClass);
  final ParameterExpression parameterV0 =
      Expressions.parameter(javaRowClass, "v0");
  final ParameterExpression parameterV1 =
      Expressions.parameter(javaRowClass, "v1");
  final ParameterExpression parameterC =
      Expressions.parameter(int.class, "c");
  final int mod =
      collation.getFieldCollations().size() == 1 ? Modifier.FINAL : 0;
  body.add(Expressions.declare(mod, parameterC, null));
  for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
    final int index = fieldCollation.getFieldIndex();
    final RelDataType fieldType = rowType.getFieldList().get(index).getType();
    final Expression fieldComparator = generateCollatorExpression(fieldType.getCollation());
    Expression arg0 = fieldReference(parameterV0, index);
    Expression arg1 = fieldReference(parameterV1, index);
    switch (Primitive.flavor(fieldClass(index))) {
    case OBJECT:
      arg0 = EnumUtils.convert(arg0, Comparable.class);
      arg1 = EnumUtils.convert(arg1, Comparable.class);
    }
    final boolean nullsFirst =
        fieldCollation.nullDirection
            == RelFieldCollation.NullDirection.FIRST;
    final boolean descending =
        fieldCollation.getDirection()
            == RelFieldCollation.Direction.DESCENDING;
    body.add(
        Expressions.statement(
            Expressions.assign(
                parameterC,
                Expressions.call(
                    Utilities.class,
                    fieldNullable(index)
                        ? (nullsFirst != descending
                        ? "compareNullsFirst"
                        : "compareNullsLast")
                        : "compare",
                    Expressions.list(
                        arg0,
                        arg1)
                        .appendIfNotNull(fieldComparator)))));
    body.add(
        Expressions.ifThen(
            Expressions.notEqual(
                parameterC, Expressions.constant(0)),
            Expressions.return_(
                null,
                descending
                    ? Expressions.negate(parameterC)
                    : parameterC)));
  }
  body.add(
      Expressions.return_(null, Expressions.constant(0)));

  final List<MemberDeclaration> memberDeclarations =
      Expressions.list(
          Expressions.methodDecl(
              Modifier.PUBLIC,
              int.class,
              "compare",
              ImmutableList.of(parameterV0, parameterV1),
              body.toBlock()));

  if (EnumerableRules.BRIDGE_METHODS) {
    final ParameterExpression parameterO0 =
        Expressions.parameter(Object.class, "o0");
    final ParameterExpression parameterO1 =
        Expressions.parameter(Object.class, "o1");
    BlockBuilder bridgeBody = new BlockBuilder();
    bridgeBody.add(
        Expressions.return_(
            null,
            Expressions.call(
                Expressions.parameter(
                    Comparable.class, "this"),
                BuiltInMethod.COMPARATOR_COMPARE.method,
                Expressions.convert_(
                    parameterO0,
                    javaRowClass),
                Expressions.convert_(
                    parameterO1,
                    javaRowClass))));
    memberDeclarations.add(
        overridingMethodDecl(
            BuiltInMethod.COMPARATOR_COMPARE.method,
            ImmutableList.of(parameterO0, parameterO1),
            bridgeBody.toBlock()));
  }
  return Expressions.new_(
      Comparator.class,
      ImmutableList.of(),
      memberDeclarations);
}
 
Example #14
Source File: IntPair.java    From calcite with Apache License 2.0 4 votes vote down vote up
public int hashCode() {
  return Utilities.hash(source, target);
}
 
Example #15
Source File: Lattice.java    From calcite with Apache License 2.0 4 votes vote down vote up
public int compareTo(Column column) {
  return Utilities.compare(ordinal, column.ordinal);
}
 
Example #16
Source File: CodeGenerationBenchmark.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Setup(Level.Trial)
public void setup() {
  planInfos = new PlanInfo[queries];
  VolcanoPlanner planner = new VolcanoPlanner();
  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);
  planner.addRule(FilterToCalcRule.INSTANCE);
  planner.addRule(ProjectToCalcRule.INSTANCE);
  planner.addRule(EnumerableRules.ENUMERABLE_CALC_RULE);
  planner.addRule(EnumerableRules.ENUMERABLE_JOIN_RULE);
  planner.addRule(EnumerableRules.ENUMERABLE_VALUES_RULE);

  RelDataTypeFactory typeFactory =
      new JavaTypeFactoryImpl(org.apache.calcite.rel.type.RelDataTypeSystem.DEFAULT);
  RelOptCluster cluster = RelOptCluster.create(planner, new RexBuilder(typeFactory));
  RelTraitSet desiredTraits =
      cluster.traitSet().replace(EnumerableConvention.INSTANCE);

  RelBuilder relBuilder = RelFactories.LOGICAL_BUILDER.create(cluster, null);
  // Generates queries of the following form depending on the configuration parameters.
  // SELECT `t`.`name`
  // FROM (VALUES  (1, 'Value0')) AS `t` (`id`, `name`)
  // INNER JOIN (VALUES  (1, 'Value1')) AS `t` (`id`, `name`) AS `t0` ON `t`.`id` = `t0`.`id`
  // INNER JOIN (VALUES  (2, 'Value2')) AS `t` (`id`, `name`) AS `t1` ON `t`.`id` = `t1`.`id`
  // INNER JOIN (VALUES  (3, 'Value3')) AS `t` (`id`, `name`) AS `t2` ON `t`.`id` = `t2`.`id`
  // INNER JOIN ...
  // WHERE
  //  `t`.`name` = 'name0' OR
  //  `t`.`name` = 'name1' OR
  //  `t`.`name` = 'name2' OR
  //  ...
  //  OR `t`.`id` = 0
  // The last disjunction (i.e, t.id = $i) is what makes the queries different from one another
  // by assigning a different constant literal.
  for (int i = 0; i < queries; i++) {
    relBuilder.values(new String[]{"id", "name"}, 1, "Value" + 0);
    for (int j = 1; j <= joins; j++) {
      relBuilder
          .values(new String[]{"id", "name"}, j, "Value" + j)
          .join(JoinRelType.INNER, "id");
    }

    List<RexNode> disjunctions = new ArrayList<>();
    for (int j = 0; j < whereClauseDisjunctions; j++) {
      disjunctions.add(
          relBuilder.equals(
              relBuilder.field("name"),
              relBuilder.literal("name" + j)));
    }
    disjunctions.add(
        relBuilder.equals(
            relBuilder.field("id"),
            relBuilder.literal(i)));
    RelNode query =
        relBuilder
            .filter(relBuilder.or(disjunctions))
            .project(relBuilder.field("name"))
            .build();

    RelNode query0 = planner.changeTraits(query, desiredTraits);
    planner.setRoot(query0);

    PlanInfo info = new PlanInfo();
    EnumerableRel plan = (EnumerableRel) planner.findBestExp();

    EnumerableRelImplementor relImplementor =
        new EnumerableRelImplementor(plan.getCluster().getRexBuilder(), new HashMap<>());
    info.classExpr = relImplementor.implementRoot(plan, EnumerableRel.Prefer.ARRAY);
    info.javaCode =
        Expressions.toString(info.classExpr.memberDeclarations, "\n", false);

    ICompilerFactory compilerFactory;
    try {
      compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory();
    } catch (Exception e) {
      throw new IllegalStateException(
          "Unable to instantiate java compiler", e);
    }
    IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator();
    cbe.setClassName(info.classExpr.name);
    cbe.setExtendedClass(Utilities.class);
    cbe.setImplementedInterfaces(
        plan.getRowType().getFieldCount() == 1
            ? new Class[]{Bindable.class, Typed.class}
            : new Class[]{ArrayBindable.class});
    cbe.setParentClassLoader(EnumerableInterpretable.class.getClassLoader());
    info.cbe = cbe;
    planInfos[i] = info;
  }

}
 
Example #17
Source File: QuarkCube.java    From quark with Apache License 2.0 4 votes vote down vote up
public int compareTo(Dimension dimension) {
  return Utilities.compare(this.cubeOrdinal, dimension.cubeOrdinal);
}
 
Example #18
Source File: QuarkTile.java    From quark with Apache License 2.0 4 votes vote down vote up
public int compareTo(Column column) {
  return Utilities.compare(ordinal, column.ordinal);
}