org.apache.calcite.linq4j.tree.Primitive Java Examples

The following examples show how to use org.apache.calcite.linq4j.tree.Primitive. 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: RelDataTypeFactoryImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
private RelDataType copySimpleType(
    RelDataType type,
    boolean nullable) {
  if (type instanceof JavaType) {
    JavaType javaType = (JavaType) type;
    if (SqlTypeUtil.inCharFamily(javaType)) {
      return new JavaType(
          javaType.clazz,
          nullable,
          javaType.charset,
          javaType.collation);
    } else {
      return new JavaType(
          nullable
              ? Primitive.box(javaType.clazz)
              : Primitive.unbox(javaType.clazz),
          nullable);
    }
  } else {
    // REVIEW: RelCrossType if it stays around; otherwise get rid of
    // this comment
    return type;
  }
}
 
Example #2
Source File: MongoEnumerator.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static Object convert(Object o, Class clazz) {
  if (o == null) {
    return null;
  }
  Primitive primitive = Primitive.of(clazz);
  if (primitive != null) {
    clazz = primitive.boxClass;
  } else {
    primitive = Primitive.ofBox(clazz);
  }
  if (clazz.isInstance(o)) {
    return o;
  }
  if (o instanceof Date && primitive != null) {
    o = ((Date) o).getTime() / DateTimeUtils.MILLIS_PER_DAY;
  }
  if (o instanceof Number && primitive != null) {
    return primitive.number((Number) o);
  }
  return o;
}
 
Example #3
Source File: EnumerableTableScan.java    From calcite with Apache License 2.0 6 votes vote down vote up
private JavaRowFormat format() {
  int fieldCount = getRowType().getFieldCount();
  if (fieldCount == 0) {
    return JavaRowFormat.LIST;
  }
  if (Object[].class.isAssignableFrom(elementType)) {
    return fieldCount == 1 ? JavaRowFormat.SCALAR : JavaRowFormat.ARRAY;
  }
  if (Row.class.isAssignableFrom(elementType)) {
    return JavaRowFormat.ROW;
  }
  if (fieldCount == 1 && (Object.class == elementType
        || Primitive.is(elementType)
        || Number.class.isAssignableFrom(elementType)
        || String.class == elementType)) {
    return JavaRowFormat.SCALAR;
  }
  return JavaRowFormat.CUSTOM;
}
 
Example #4
Source File: EnumUtils.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Match an argument expression to method parameter type with best effort
 * @param argument Argument Expression
 * @param parameter Parameter type
 * @return Converted argument expression that matches the parameter type.
 *         Returns null if it is impossible to match.
 */
private static Expression matchMethodParameterType(
    Expression argument, Class parameter) {
  Type argumentType = argument.getType();
  if (Types.isAssignableFrom(parameter, argumentType)) {
    return argument;
  }
  // Object.class is not assignable from primitive types,
  // but the method with Object parameters can accept primitive types.
  // E.g., "array(Object... args)" in SqlFunctions
  if (parameter == Object.class
      && Primitive.of(argumentType) != null) {
    return argument;
  }
  // Convert argument with Object.class type to parameter explicitly
  if (argumentType == Object.class
      && Primitive.of(argumentType) == null) {
    return convert(argument, parameter);
  }
  // assignable types that can be accepted with explicit conversion
  if (parameter == BigDecimal.class
      && Primitive.ofBoxOr(argumentType) != null) {
    return convert(argument, parameter);
  }
  return null;
}
 
Example #5
Source File: RexImpTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public Expression implement(RexToLixTranslator translator,
    Expression inputEnumerable,
    RexCall call, PhysType inputPhysType, PhysType outputPhysType) {
  // The table operand is removed from the RexCall because it
  // represents the input, see StandardConvertletTable#convertWindowFunction.
  Expression intervalExpression = translator.translate(call.getOperands().get(1));
  RexCall descriptor = (RexCall) call.getOperands().get(0);
  List<Expression> translatedOperands = new ArrayList<>();
  final ParameterExpression parameter =
      Expressions.parameter(Primitive.box(inputPhysType.getJavaRowType()),
          "_input");
  Expression wmColExpr =
      inputPhysType.fieldReference(parameter,
          ((RexInputRef) descriptor.getOperands().get(0)).getIndex(),
          outputPhysType.getJavaFieldType(
              inputPhysType.getRowType().getFieldCount()));
  translatedOperands.add(wmColExpr);
  translatedOperands.add(intervalExpression);

  return Expressions.call(BuiltInMethod.TUMBLING.method, inputEnumerable,
      EnumUtils.tumblingWindowSelector(inputPhysType, outputPhysType,
          translatedOperands.get(0), translatedOperands.get(1)));
}
 
Example #6
Source File: RexImpTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Expression unboxExpression(final Expression argValue) {
  Primitive fromBox = Primitive.ofBox(argValue.getType());
  if (fromBox == null || fromBox == Primitive.VOID) {
    return argValue;
  }
  // Optimization: for "long x";
  // "Long.valueOf(x)" generates "x"
  if (argValue instanceof MethodCallExpression) {
    MethodCallExpression mce = (MethodCallExpression) argValue;
    if (mce.method.getName().equals("valueOf") && mce.expressions.size() == 1) {
      Expression originArg = mce.expressions.get(0);
      if (Primitive.of(originArg.type) == fromBox) {
        return originArg;
      }
    }
  }
  return NullAs.NOT_POSSIBLE.handle(argValue);
}
 
Example #7
Source File: ElasticsearchEnumerators.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static Object convert(Object o, Class clazz) {
  if (o == null) {
    return null;
  }
  Primitive primitive = Primitive.of(clazz);
  if (primitive != null) {
    clazz = primitive.boxClass;
  } else {
    primitive = Primitive.ofBox(clazz);
  }
  if (clazz.isInstance(o)) {
    return o;
  }
  if (o instanceof Date && primitive != null) {
    o = ((Date) o).getTime() / DateTimeUtils.MILLIS_PER_DAY;
  }
  if (o instanceof Number && primitive != null) {
    return primitive.number((Number) o);
  }
  return o;
}
 
Example #8
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 #9
Source File: JavaTypeFactoryImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Creates a synthetic Java class whose fields have the same names and
 * relational types. */
private Type createSyntheticType(RelRecordType type) {
  final String name =
      "Record" + type.getFieldCount() + "_" + syntheticTypes.size();
  final SyntheticRecordType syntheticType =
      new SyntheticRecordType(type, name);
  for (final RelDataTypeField recordField : type.getFieldList()) {
    final Type javaClass = getJavaClass(recordField.getType());
    syntheticType.fields.add(
        new RecordFieldImpl(
            syntheticType,
            recordField.getName(),
            javaClass,
            recordField.getType().isNullable()
                && !Primitive.is(javaClass),
            Modifier.PUBLIC));
  }
  return register(syntheticType);
}
 
Example #10
Source File: PrimitiveTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Test for {@link Primitive#sortArray(Object)}. */
@Test void testArraySort() {
  char[] chars = {'m', 'o', 'n', 'o', 'l', 'a', 'k', 'e'};
  Primitive.CHAR.sortArray(chars);
  assertEquals("[a, e, k, l, m, n, o, o]",
      Primitive.CHAR.arrayToString(chars));

  // mixed true and false
  boolean[] booleans0 = {true, false, true, true, false};
  Primitive.BOOLEAN.sortArray(booleans0);
  assertEquals("[false, false, true, true, true]",
      Primitive.BOOLEAN.arrayToString(booleans0));

  // all false
  boolean[] booleans1 = {false, false, false, false, false};
  Primitive.BOOLEAN.sortArray(booleans1);
  assertEquals("[false, false, false, false, false]",
      Primitive.BOOLEAN.arrayToString(booleans1));

  // all true
  boolean[] booleans2 = {true, true, true, true, true};
  Primitive.BOOLEAN.sortArray(booleans2);
  assertEquals("[true, true, true, true, true]",
      Primitive.BOOLEAN.arrayToString(booleans2));

  // empty
  boolean[] booleans3 = {};
  Primitive.BOOLEAN.sortArray(booleans3);
  assertEquals("[]", Primitive.BOOLEAN.arrayToString(booleans3));

  // ranges specified
  boolean[] booleans4 = {true, true, false, false, true, false, false};
  Primitive.BOOLEAN.sortArray(booleans4, 1, 6);
  assertEquals("[true, false, false, false, true, true, false]",
      Primitive.BOOLEAN.arrayToString(booleans4));
}
 
Example #11
Source File: ColumnLoader.java    From calcite with Apache License 2.0 5 votes vote down vote up
ArrayTable.Representation chooseRep(int ordinal) {
  Primitive primitive = Primitive.of(clazz);
  Primitive boxPrimitive = Primitive.ofBox(clazz);
  Primitive p = primitive != null ? primitive : boxPrimitive;
  if (!containsNull && p != null) {
    switch (p) {
    case FLOAT:
    case DOUBLE:
      return new ArrayTable.PrimitiveArray(ordinal, p, p);
    case OTHER:
    case VOID:
      throw new AssertionError("wtf?!");
    }
    if (canBeLong(min) && canBeLong(max)) {
      return chooseFixedRep(
          ordinal, p, toLong(min), toLong(max));
    }
  }

  // We don't want to use a dictionary if:
  // (a) there are so many values that an object pointer (with one
  //     indirection) has about as many bits as a code (with two
  //     indirections); or
  // (b) if there are very few copies of each value.
  // The condition kind of captures this, but needs to be tuned.
  final int codeCount = map.size() + (containsNull ? 1 : 0);
  final int codeBitCount = log2(nextPowerOf2(codeCount));
  if (codeBitCount < 10 && values.size() > 2000) {
    final ArrayTable.Representation representation =
        chooseFixedRep(-1, Primitive.INT, 0, codeCount - 1);
    return new ArrayTable.ObjectDictionary(ordinal, representation);
  }
  return new ArrayTable.ObjectArray(ordinal);
}
 
Example #12
Source File: ArrayTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
BitSlicedPrimitiveArray(
    int ordinal, int bitCount, Primitive primitive, boolean signed) {
  assert bitCount > 0;
  this.ordinal = ordinal;
  this.bitCount = bitCount;
  this.primitive = primitive;
  this.signed = signed;
}
 
Example #13
Source File: ReflectiveSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static Enumerable toEnumerable(final Object o) {
  if (o.getClass().isArray()) {
    if (o instanceof Object[]) {
      return Linq4j.asEnumerable((Object[]) o);
    } else {
      return Linq4j.asEnumerable(Primitive.asList(o));
    }
  }
  if (o instanceof Iterable) {
    return Linq4j.asEnumerable((Iterable) o);
  }
  throw new RuntimeException(
      "Cannot convert " + o.getClass() + " into a Enumerable");
}
 
Example #14
Source File: PrimitiveTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Test for {@link Primitive#permute(Object, int[])}. */
@Test void testPermute() {
  char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
  int[] sources = {1, 2, 3, 4, 5, 6, 0};
  final Object permute = Primitive.CHAR.permute(chars, sources);
  assertTrue(permute instanceof char[]);
  assertEquals("bcdefga", String.valueOf((char[]) permute));
}
 
Example #15
Source File: JaninoRelMetadataProvider.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns e.g. ", ignoreNulls". */
private static StringBuilder safeArgList(StringBuilder buff, Method method) {
  for (Ord<Class<?>> t : Ord.zip(method.getParameterTypes())) {
    if (Primitive.is(t.e) || RexNode.class.isAssignableFrom(t.e)) {
      buff.append(", a").append(t.i);
    } else {
      buff.append(", ") .append(NullSentinel.class.getName())
          .append(".mask(a").append(t.i).append(")");
    }
  }
  return buff;
}
 
Example #16
Source File: OLAPTableScan.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public RelWriter explainTerms(RelWriter pw) {

    return super.explainTerms(pw)
            .item("ctx", context == null ? "" : String.valueOf(context.id) + "@" + context.realization)
            .item("fields", Primitive.asList(fields));
}
 
Example #17
Source File: GeodeUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static Object convert(Object o, Class clazz) {
  if (o == null) {
    return null;
  }
  Primitive primitive = Primitive.of(clazz);
  if (primitive != null) {
    clazz = primitive.boxClass;
  } else {
    primitive = Primitive.ofBox(clazz);
  }
  if (clazz == null) {
    return o.toString();
  }
  if (Map.class.isAssignableFrom(clazz)
          && o instanceof PdxInstance) {
    // This is in case of nested Objects!
    return Util.toString(
            ((PdxInstance) o).getFieldNames(), "PDX[", ",", "]");
  }
  if (clazz.isInstance(o)) {
    return o;
  }
  if (o instanceof Date && primitive != null) {
    o = ((Date) o).getTime() / DateTimeUtils.MILLIS_PER_DAY;
  }
  if (o instanceof Number && primitive != null) {
    return primitive.number((Number) o);
  }
  return o;
}
 
Example #18
Source File: MycatReflectiveSchema.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private static Enumerable toEnumerable(final Object o) {
  if (o.getClass().isArray()) {
    if (o instanceof Object[]) {
      return Linq4j.asEnumerable((Object[]) o);
    } else {
      return Linq4j.asEnumerable(Primitive.asList(o));
    }
  }
  if (o instanceof Iterable) {
    return Linq4j.asEnumerable((Iterable) o);
  }
  throw new RuntimeException(
      "Cannot convert " + o.getClass() + " into a Enumerable");
}
 
Example #19
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 5 votes vote down vote up
Expression checkNull(Expression expr) {
  if (Primitive.flavor(expr.getType())
      == Primitive.Flavor.PRIMITIVE) {
    return RexImpTable.FALSE_EXPR;
  }
  return Expressions.equal(expr, RexImpTable.NULL_EXPR);
}
 
Example #20
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 5 votes vote down vote up
Expression checkNotNull(Expression expr) {
  if (Primitive.flavor(expr.getType())
      == Primitive.Flavor.PRIMITIVE) {
    return RexImpTable.TRUE_EXPR;
  }
  return Expressions.notEqual(expr, RexImpTable.NULL_EXPR);
}
 
Example #21
Source File: PhysTypeImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
public PhysType makeNullable(boolean nullable) {
  if (!nullable) {
    return this;
  }
  return new PhysTypeImpl(typeFactory,
      typeFactory.createTypeWithNullability(rowType, true),
      Primitive.box(javaRowClass), format);
}
 
Example #22
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
static Expression optimize2(Expression operand, Expression expression) {
  if (Primitive.is(operand.getType())) {
    // Primitive values cannot be null
    return optimize(expression);
  } else {
    return optimize(
        Expressions.condition(
            Expressions.equal(operand, NULL_EXPR),
            NULL_EXPR,
            expression));
  }
}
 
Example #23
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
static Expression getDefaultValue(Type type) {
  if (Primitive.is(type)) {
    Primitive p = Primitive.of(type);
    return Expressions.constant(p.defaultValue, type);
  }
  return Expressions.constant(null, type);
}
 
Example #24
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override protected void implementNotNullReset(AggContext info,
    AggResetContext reset) {
  Expression acc = reset.accumulator().get(0);
  Primitive p = Primitive.of(acc.getType());
  boolean isMin = MIN == info.aggregation();
  Object inf = p == null ? null : (isMin ? p.max : p.min);
  reset.currentBlock().add(
      Expressions.statement(
          Expressions.assign(acc,
              Expressions.constant(inf, acc.getType()))));
}
 
Example #25
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Expression maybeBox(Expression expression) {
  final Primitive primitive = Primitive.of(expression.getType());
  if (primitive != null) {
    expression = Expressions.box(expression, primitive);
  }
  return expression;
}
 
Example #26
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
private RelDataType nullifyType(JavaTypeFactory typeFactory,
    final RelDataType type, final boolean nullable) {
  if (type instanceof RelDataTypeFactoryImpl.JavaType) {
    final Primitive primitive = Primitive.ofBox(
        ((RelDataTypeFactoryImpl.JavaType) type).getJavaClass());
    if (primitive != null) {
      return typeFactory.createJavaType(primitive.primitiveClass);
    }
  }
  return typeFactory.createTypeWithNullability(type, nullable);
}
 
Example #27
Source File: EnumUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static Expression fromInternal(Expression operand,
    Type fromType, Type targetType) {
  if (operand == ConstantUntypedNull.INSTANCE) {
    return operand;
  }
  if (!(operand.getType() instanceof Class)) {
    return operand;
  }
  if (Types.isAssignableFrom(targetType, fromType)) {
    return operand;
  }
  if (targetType == java.sql.Date.class) {
    // E.g. from "int" or "Integer" to "java.sql.Date",
    // generate "SqlFunctions.internalToDate".
    if (isA(fromType, Primitive.INT)) {
      return Expressions.call(BuiltInMethod.INTERNAL_TO_DATE.method, operand);
    }
  } else if (targetType == java.sql.Time.class) {
    // E.g. from "int" or "Integer" to "java.sql.Time",
    // generate "SqlFunctions.internalToTime".
    if (isA(fromType, Primitive.INT)) {
      return Expressions.call(BuiltInMethod.INTERNAL_TO_TIME.method, operand);
    }
  } else if (targetType == java.sql.Timestamp.class) {
    // E.g. from "long" or "Long" to "java.sql.Timestamp",
    // generate "SqlFunctions.internalToTimestamp".
    if (isA(fromType, Primitive.LONG)) {
      return Expressions.call(BuiltInMethod.INTERNAL_TO_TIMESTAMP.method, operand);
    }
  }
  if (Primitive.is(operand.type)
      && Primitive.isBox(targetType)) {
    // E.g. operand is "int", target is "Long", generate "(long) operand".
    return Expressions.convert_(operand,
        Primitive.ofBox(targetType).primitiveClass);
  }
  return operand;
}
 
Example #28
Source File: ResultSetEnumerable.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static Function1<ResultSet, Function0<Object>>
    primitiveRowBuilderFactory(final Primitive[] primitives) {
  return resultSet -> {
    final ResultSetMetaData metaData;
    final int columnCount;
    try {
      metaData = resultSet.getMetaData();
      columnCount = metaData.getColumnCount();
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
    assert columnCount == primitives.length;
    if (columnCount == 1) {
      return () -> {
        try {
          return resultSet.getObject(1);
        } catch (SQLException e) {
          throw new RuntimeException(e);
        }
      };
    }
    //noinspection unchecked
    return (Function0) () -> {
      try {
        final List<Object> list = new ArrayList<>();
        for (int i = 0; i < columnCount; i++) {
          list.add(primitives[i].jdbcGet(resultSet, i + 1));
        }
        return list.toArray();
      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
    };
  };
}
 
Example #29
Source File: SqlFunctions.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Converts a JDBC array to a list. */
public static List arrayToList(final java.sql.Array a) {
  if (a == null) {
    return null;
  }
  try {
    return Primitive.asList(a.getArray());
  } catch (SQLException e) {
    throw Util.toUnchecked(e);
  }
}
 
Example #30
Source File: ReflectiveSchemaTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static boolean isNumeric(Class type) {
  switch (Primitive.flavor(type)) {
  case BOX:
    return Primitive.ofBox(type).isNumeric();
  case PRIMITIVE:
    return Primitive.of(type).isNumeric();
  default:
    return Number.class.isAssignableFrom(type); // e.g. BigDecimal
  }
}