org.apache.calcite.avatica.ColumnMetaData.Rep Java Examples

The following examples show how to use org.apache.calcite.avatica.ColumnMetaData.Rep. 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: TypedValue.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
Common.TypedValue serializeArray(List<Object> list, Common.TypedValue.Builder builder,
    Common.Rep protoArrayComponentRep) {
  for (Object element : list) {
    if (element instanceof List) {
      // We have a list of lists: recursively build up the protobuf
      @SuppressWarnings("unchecked")
      List<Object> subList = (List<Object>) element;
      Common.TypedValue.Builder subListBuilder = Common.TypedValue.newBuilder();
      // This is "technically" an array, but we just persist the underlying component type
      subListBuilder.setType(protoArrayComponentRep);
      Common.TypedValue protoSubList = serializeArray(subList, subListBuilder,
          protoArrayComponentRep);
      builder.addArrayValue(protoSubList);
    } else {
      // We have a list of "scalars", just serialize the value
      Common.TypedValue.Builder elementBuilder = Common.TypedValue.newBuilder();
      if (null == element) {
        writeToProtoWithType(elementBuilder, null, Common.Rep.NULL);
      } else {
        writeToProtoWithType(elementBuilder, element, protoArrayComponentRep);
      }
      builder.addArrayValue(elementBuilder.build());
    }
  }
  return builder.build();
}
 
Example #2
Source File: KylinClient.java    From kylin with Apache License 2.0 6 votes vote down vote up
private List<ColumnMetaData> convertColumnMeta(SQLResponseStub queryResp) {
    List<ColumnMetaData> metas = new ArrayList<ColumnMetaData>();
    for (int i = 0; i < queryResp.getColumnMetas().size(); i++) {
        SQLResponseStub.ColumnMetaStub scm = queryResp.getColumnMetas().get(i);
        Class columnClass = convertType(scm.getColumnType());
        ScalarType type = ColumnMetaData.scalar(scm.getColumnType(), scm.getColumnTypeName(), Rep.of(columnClass));

        ColumnMetaData meta = new ColumnMetaData(i, scm.isAutoIncrement(), scm.isCaseSensitive(),
                scm.isSearchable(), scm.isCurrency(), scm.getIsNullable(), scm.isSigned(), scm.getDisplaySize(),
                scm.getLabel(), scm.getName(), scm.getSchemaName(), scm.getPrecision(), scm.getScale(),
                scm.getTableName(), scm.getSchemaName(), type, scm.isReadOnly(), scm.isWritable(), scm.isWritable(),
                columnClass.getCanonicalName());

        metas.add(meta);
    }

    return metas;
}
 
Example #3
Source File: KylinClient.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private List<ColumnMetaData> convertColumnMeta(SQLResponseStub queryResp) {
    List<ColumnMetaData> metas = new ArrayList<ColumnMetaData>();
    for (int i = 0; i < queryResp.getColumnMetas().size(); i++) {
        SQLResponseStub.ColumnMetaStub scm = queryResp.getColumnMetas().get(i);
        Class columnClass = convertType(scm.getColumnType());
        ScalarType type = ColumnMetaData.scalar(scm.getColumnType(), scm.getColumnTypeName(), Rep.of(columnClass));

        ColumnMetaData meta = new ColumnMetaData(i, scm.isAutoIncrement(), scm.isCaseSensitive(),
                scm.isSearchable(), scm.isCurrency(), scm.getIsNullable(), scm.isSigned(), scm.getDisplaySize(),
                scm.getLabel(), scm.getName(), scm.getSchemaName(), scm.getPrecision(), scm.getScale(),
                scm.getTableName(), scm.getSchemaName(), type, scm.isReadOnly(), scm.isWritable(), scm.isWritable(),
                columnClass.getCanonicalName());

        metas.add(meta);
    }

    return metas;
}
 
Example #4
Source File: DummyClient.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public QueryResult executeQuery(String sql, List<Object> paramValues, Map<String, String> queryToggles) throws IOException {
    List<Object> data = new ArrayList<Object>();

    ZoneId utc = ZoneId.of("UTC");
    LocalDate localDate = Date.valueOf("2019-04-27").toLocalDate();
    LocalDateTime localDateTime = Timestamp.valueOf("2019-04-27 17:30:03").toLocalDateTime();
    Date date = new Date(localDate.atStartOfDay(utc).toInstant().toEpochMilli());
    Timestamp timestamp = new Timestamp(localDateTime.atZone(utc).toInstant().toEpochMilli());

    Object[] row = new Object[] { "foo", "bar", "tool", date, timestamp };
    data.add(row);

    List<ColumnMetaData> meta = new ArrayList<ColumnMetaData>();
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true));
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true));
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true));
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.DATE, "date", Rep.JAVA_SQL_DATE), true));
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.TIMESTAMP, "timestamp", Rep.JAVA_SQL_TIMESTAMP),
            true));

    return new QueryResult(meta, data);
}
 
Example #5
Source File: TypedValueTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void testArrays() {
  List<Object> serialObj = Arrays.<Object>asList(1, 2, 3, 4);
  ArrayImpl.Factory factory = new ArrayFactoryImpl(Unsafe.localCalendar().getTimeZone());
  ScalarType scalarType = ColumnMetaData.scalar(Types.INTEGER, "INTEGER", Rep.INTEGER);
  Array a1 = factory.createArray(scalarType, serialObj);
  TypedValue tv1 = TypedValue.ofJdbc(Rep.ARRAY, a1, Unsafe.localCalendar());
  Object jdbcObj = tv1.toJdbc(Unsafe.localCalendar());
  assertTrue("The JDBC object is an " + jdbcObj.getClass(), jdbcObj instanceof Array);
  Object localObj = tv1.toLocal();
  assertTrue("The local object is an " + localObj.getClass(), localObj instanceof List);
  Common.TypedValue protoTv1 = tv1.toProto();
  assertEquals(serialObj.size(), protoTv1.getArrayValueCount());
  TypedValue tv1Copy = TypedValue.fromProto(protoTv1);
  Object jdbcObjCopy = tv1Copy.toJdbc(Unsafe.localCalendar());
  assertTrue("The JDBC object is an " + jdbcObjCopy.getClass(), jdbcObjCopy instanceof Array);
  Object localObjCopy = tv1Copy.toLocal();
  assertTrue("The local object is an " + localObjCopy.getClass(), localObjCopy instanceof List);
}
 
Example #6
Source File: TypedValueTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void testLegacyBase64StringEncodingForBytes() {
  // CALCITE-1103 CALCITE-1209 We observed that binary data was being
  // serialized as base-64 encoded strings instead of the native binary
  // data type in protobufs. We need to still handle older clients sending
  // data in this form.
  final byte[] bytes = "asdf".getBytes(UTF_8);
  final String base64Str = Base64.encodeBytes(bytes);
  Common.TypedValue.Builder builder = Common.TypedValue.newBuilder();
  builder.setStringValue(base64Str);
  builder.setType(Common.Rep.BYTE_STRING);
  Common.TypedValue protoTv = builder.build();

  TypedValue tv = TypedValue.fromProto(protoTv);
  assertEquals(Rep.BYTE_STRING, tv.type);
  assertEquals(base64Str, tv.value);
}
 
Example #7
Source File: TypedValueTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void testProtobufBytesNotSentAsBase64() {
  final byte[] bytes = "asdf".getBytes(UTF_8);
  final byte[] b64Bytes = Base64.encodeBytes(bytes).getBytes(UTF_8);
  TypedValue tv = TypedValue.ofLocal(Rep.BYTE_STRING, new ByteString(bytes));
  // JSON encodes it as base64
  assertEquals(new String(b64Bytes, UTF_8), tv.value);

  // Get the protobuf variant
  Common.TypedValue protoTv = tv.toProto();
  Common.Rep protoRep = protoTv.getType();
  assertEquals(Common.Rep.BYTE_STRING, protoRep);

  // The pb variant should have the native bytes of the original value
  com.google.protobuf.ByteString protoByteString = protoTv.getBytesValue();
  assertNotNull(protoByteString);
  assertArrayEquals(bytes, protoByteString.toByteArray());

  // We should have the b64 string as a backwards compatibility feature
  assertEquals(new String(b64Bytes, UTF_8),
      protoTv.getStringValue());
}
 
Example #8
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void longArrays() throws Exception {
  final Random r = new Random();
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.BIGINT, "BIGINT", Rep.LONG);
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 5; i++) {
      List<Long> elements = new ArrayList<>();
      for (int j = 0; j < 5; j++) {
        elements.add(r.nextLong());
      }
      arrays.add(createArray("BIGINT", component, elements));
    }
    // Verify read/write
    writeAndReadArrays(conn, "long_arrays", "BIGINT", component, arrays,
        PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #9
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void shortArrays() throws Exception {
  final Random r = new Random();
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.SMALLINT, "SMALLINT", Rep.SHORT);
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 5; i++) {
      List<Short> elements = new ArrayList<>();
      for (int j = 0; j < 5; j++) {
        short value = (short) r.nextInt(Short.MAX_VALUE);
        // 50% of the time, negate the value
        if (0 == r.nextInt(2)) {
          value *= -1;
        }
        elements.add(Short.valueOf(value));
      }
      arrays.add(createArray("SMALLINT", component, elements));
    }
    // Verify read/write
    writeAndReadArrays(conn, "short_arrays", "SMALLINT", component, arrays,
        PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #10
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void shortArraysWithNull() throws Exception {
  final Random r = new Random();
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.SMALLINT, "SMALLINT", Rep.SHORT);
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 5; i++) {
      List<Short> elements = new ArrayList<>();
      for (int j = 0; j < 4; j++) {
        short value = (short) r.nextInt(Short.MAX_VALUE);
        // 50% of the time, negate the value
        if (0 == r.nextInt(2)) {
          value *= -1;
        }
        elements.add(Short.valueOf(value));
      }
      elements.add(null);
      arrays.add(createArray("SMALLINT", component, elements));
    }
    // Verify read/write
    writeAndReadArrays(conn, "short_arrays", "SMALLINT", component, arrays,
        PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #11
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void stringArrays() throws Exception {
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.VARCHAR, "VARCHAR", Rep.STRING);
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 5; i++) {
      List<String> elements = new ArrayList<>();
      for (int j = 0; j < 5; j++) {
        elements.add(i + "_" + j);
      }
      arrays.add(createArray("VARCHAR", component, elements));
    }
    // Verify read/write
    writeAndReadArrays(conn, "string_arrays", "VARCHAR", component, arrays,
        PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #12
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void doubleArrays() throws Exception {
  final Random r = new Random();
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.DOUBLE, "DOUBLE", Rep.DOUBLE);
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 3; i++) {
      List<Double> elements = new ArrayList<>();
      for (int j = 0; j < 7; j++) {
        double element = r.nextDouble();
        if (r.nextBoolean()) {
          element *= -1;
        }
        elements.add(element);
      }
      arrays.add(createArray("DOUBLE", component, elements));
    }
    writeAndReadArrays(conn, "float_arrays", "DOUBLE", component, arrays,
        PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #13
Source File: DummyClient.java    From kylin with Apache License 2.0 6 votes vote down vote up
@Override
public QueryResult executeQuery(String sql, List<Object> paramValues, Map<String, String> queryToggles) throws IOException {
    List<Object> data = new ArrayList<Object>();

    ZoneId utc = ZoneId.of("UTC");
    LocalDate localDate = Date.valueOf("2019-04-27").toLocalDate();
    LocalDateTime localDateTime = Timestamp.valueOf("2019-04-27 17:30:03").toLocalDateTime();
    Date date = new Date(localDate.atStartOfDay(utc).toInstant().toEpochMilli());
    Timestamp timestamp = new Timestamp(localDateTime.atZone(utc).toInstant().toEpochMilli());

    Object[] row = new Object[] { "foo", "bar", "tool", date, timestamp };
    data.add(row);

    List<ColumnMetaData> meta = new ArrayList<ColumnMetaData>();
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true));
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true));
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true));
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.DATE, "date", Rep.JAVA_SQL_DATE), true));
    meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.TIMESTAMP, "timestamp", Rep.JAVA_SQL_TIMESTAMP),
            true));

    return new QueryResult(meta, data);
}
 
Example #14
Source File: ArrayImplTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void testArrayWithOffsets() throws Exception {
  // Define the struct type we're creating
  ScalarType intType = ColumnMetaData.scalar(Types.INTEGER, "INTEGER", Rep.INTEGER);
  ArrayImpl.Factory factory = new ArrayFactoryImpl(Unsafe.localCalendar().getTimeZone());
  // Create some arrays from the structs
  Array array1 = factory.createArray(intType, Arrays.<Object>asList(1, 2));
  Array array3 = factory.createArray(intType, Arrays.<Object>asList(4, 5, 6));

  Object[] data = (Object[]) array1.getArray(2, 1);
  assertEquals(1, data.length);
  assertEquals(2, data[0]);
  data = (Object[]) array3.getArray(1, 1);
  assertEquals(1, data.length);
  assertEquals(4, data[0]);
  data = (Object[]) array3.getArray(2, 2);
  assertEquals(2, data.length);
  assertEquals(5, data[0]);
  assertEquals(6, data[1]);
  data = (Object[]) array3.getArray(1, 3);
  assertEquals(3, data.length);
  assertEquals(4, data[0]);
  assertEquals(5, data[1]);
  assertEquals(6, data[2]);
}
 
Example #15
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
private boolean isSerial(ColumnMetaData.Rep rep, Object value) {
  if (value == null) {
    return true;
  }
  switch (rep) {
  case BYTE_STRING:
    return value instanceof String;
  case JAVA_SQL_DATE:
  case JAVA_SQL_TIME:
    return value instanceof Integer;
  case JAVA_SQL_TIMESTAMP:
  case JAVA_UTIL_DATE:
    return value instanceof Long;
  default:
    return true;
  }
}
 
Example #16
Source File: ArrayFactoryImpl.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Override public ResultSet create(AvaticaType elementType, Iterable<Object> elements)
    throws SQLException {
  // The ColumnMetaData for offset "1" in the ResultSet for an Array.
  ScalarType arrayOffsetType = ColumnMetaData.scalar(Types.INTEGER, "INTEGER", Rep.PRIMITIVE_INT);
  // Two columns (types) in the ResultSet we will create
  List<ColumnMetaData> types = Arrays.asList(ColumnMetaData.dummy(arrayOffsetType, false),
      ColumnMetaData.dummy(elementType, true));
  List<List<Object>> rows = createResultSetRowsForArrayData(elements);
  // `(List<Object>) rows` is a compile error.
  @SuppressWarnings({ "unchecked", "rawtypes" })
  List<Object> untypedRows = (List<Object>) ((List) rows);
  try (ListIteratorCursor cursor = new ListIteratorCursor(rows.iterator())) {
    final String sql = "MOCKED";
    QueryState state = new QueryState(sql);
    Meta.Signature signature = new Meta.Signature(types, sql,
        Collections.<AvaticaParameter>emptyList(), Collections.<String, Object>emptyMap(),
        Meta.CursorFactory.LIST, Meta.StatementType.SELECT);
    AvaticaResultSetMetaData resultSetMetaData = new AvaticaResultSetMetaData(null, sql,
        signature);
    Meta.Frame frame = new Meta.Frame(0, true, untypedRows);
    AvaticaResultSet resultSet = new AvaticaResultSet(null, state, signature, resultSetMetaData,
        timeZone, frame);
    resultSet.execute2(cursor, types);
    return resultSet;
  }
}
 
Example #17
Source File: AvaticaConnection.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
  checkOpen();
  @SuppressWarnings("unchecked")
  List<Object> elementList = (List<Object>) AvaticaUtils.primitiveList(elements);
  SqlType type;
  try {
    type = SqlType.valueOf(typeName);
  } catch (IllegalArgumentException e) {
    throw new SQLException("Could not find JDBC type for '" + typeName + "'");
  }
  AvaticaType avaticaType = null;
  switch (type) {
  case ARRAY:
    // TODO: Nested ARRAYs
    throw HELPER.createException("Cannot create an ARRAY of ARRAY's");
  case STRUCT:
    // TODO: ARRAYs of STRUCTs
    throw HELPER.createException("Cannot create an ARRAY of STRUCT's");
  default:
    // This is an ARRAY, we need to use Objects, not primitives (nullable).
    avaticaType = ColumnMetaData.scalar(type.id, typeName, Rep.nonPrimitiveRepOf(type));
  }
  ArrayFactoryImpl arrayFactory = new ArrayFactoryImpl(getTimeZone());
  return arrayFactory.createArray(avaticaType, elementList);
}
 
Example #18
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a JDBC {@link Array} from a list of values.
 *
 * @param typeName the SQL type name of the elements in the array
 * @param componentType The Avatica type for the array elements
 * @param arrayValues The array elements
 * @return An Array instance for the given component and values
 */
@SuppressWarnings("unchecked")
private <T> Array createArray(String typeName, AvaticaType componentType, List<T> arrayValues) {
  // Make a "row" with one "column" (which is really a list)
  final List<Object> oneRow = Collections.singletonList((Object) arrayValues);
  // Make an iterator over this one "row"
  final Iterator<List<Object>> rowIterator = Collections.singletonList(oneRow).iterator();

  ArrayType array = ColumnMetaData.array(componentType, typeName, Rep.ARRAY);
  try (ListIteratorCursor cursor = new ListIteratorCursor(rowIterator)) {
    List<ColumnMetaData> types = Collections.singletonList(ColumnMetaData.dummy(array, true));
    Calendar calendar = Unsafe.localCalendar();
    List<Accessor> accessors = cursor.createAccessors(types, calendar, null);
    assertTrue("Expected at least one accessor, found " + accessors.size(),
        !accessors.isEmpty());
    ArrayAccessor arrayAccessor = (ArrayAccessor) accessors.get(0);

    return new ArrayImpl((List<Object>) arrayValues, arrayAccessor);
  }
}
 
Example #19
Source File: TypedValueTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void testBase64() {
  byte[] bytes = "qwertyasdf".getBytes(UTF_8);
  // Plain bytes get put into protobuf for simplicitly
  Common.TypedValue proto = Common.TypedValue.newBuilder().setBytesValue(
      com.google.protobuf.ByteString.copyFrom(bytes))
      .setType(Common.Rep.BYTE_STRING).build();

  // But we should get back a b64-string to make sure TypedValue doesn't get confused.
  Object deserializedObj = TypedValue.getSerialFromProto(proto);
  assertThat(deserializedObj, is(instanceOf(String.class)));
  assertEquals(new ByteString(bytes).toBase64String(), (String) deserializedObj);

  // But we should get a non-b64 byte array as the JDBC representation
  deserializedObj =
      TypedValue.protoToJdbc(proto, DateTimeUtils.calendar());
  assertThat(deserializedObj, is(instanceOf(byte[].class)));
  assertArrayEquals(bytes, (byte[]) deserializedObj);
}
 
Example #20
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void varbinaryArrays() throws Exception {
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.VARBINARY, "VARBINARY", Rep.BYTE_STRING);
    // [ Array(binary, binary, binary), Array(binary, binary, binary), ...]
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 5; i++) {
      List<byte[]> elements = new ArrayList<>();
      for (int j = 0; j < 5; j++) {
        elements.add((i + "_" + j).getBytes(UTF_8));
      }
      arrays.add(createArray("VARBINARY", component, elements));
    }
    writeAndReadArrays(conn, "binary_arrays", "VARBINARY", component, arrays,
        BYTE_ARRAY_ARRAY_VALIDATOR);
  }
}
 
Example #21
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void arraysOfByteArrays() throws Exception {
  final Random r = new Random();
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.TINYINT, "TINYINT", Rep.BYTE);
    // [ Array([b, b, b]), Array([b, b, b]), ... ]
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 5; i++) {
      List<Byte> elements = new ArrayList<>();
      for (int j = 0; j < 5; j++) {
        byte value = (byte) r.nextInt(Byte.MAX_VALUE);
        // 50% of the time, negate the value
        if (0 == r.nextInt(2)) {
          value *= -1;
        }
        elements.add(Byte.valueOf(value));
      }
      arrays.add(createArray("TINYINT", component, elements));
    }
    // Verify read/write
    writeAndReadArrays(conn, "byte_arrays", "TINYINT", component, arrays, BYTE_ARRAY_VALIDATOR);
  }
}
 
Example #22
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void bigintArrays() throws Exception {
  final Random r = new Random();
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.BIGINT, "BIGINT", Rep.LONG);
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 3; i++) {
      List<Long> elements = new ArrayList<>();
      for (int j = 0; j < 7; j++) {
        long element = r.nextLong();
        if (r.nextBoolean()) {
          element *= -1;
        }
        elements.add(element);
      }
      arrays.add(createArray("BIGINT", component, elements));
    }
    writeAndReadArrays(conn, "long_arrays", "BIGINT", component, arrays,
        PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #23
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/** Converts a value from internal format to a type that can be serialized
 * as JSON. */
private static Object localToSerial(ColumnMetaData.Rep rep, Object value) {
  switch (rep) {
  case BYTE_STRING:
    return ((ByteString) value).toBase64String();
  default:
    return value;
  }
}
 
Example #24
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a protocol buffer equivalent object for <code>this</code>.
 * @return A protobuf TypedValue equivalent for <code>this</code>
 */
public Common.TypedValue toProto() {
  final Common.TypedValue.Builder builder = Common.TypedValue.newBuilder();
  // This isn't a static method, therefore we have a non-null TypedValue. Thus, this message
  // cannot be implicitly null
  builder.setImplicitlyNull(false);

  Common.Rep protoRep = type.toProto();
  // Protobuf has an explicit BIG_DECIMAL representation enum value.
  if (Common.Rep.NUMBER == protoRep && value instanceof BigDecimal) {
    protoRep = Common.Rep.BIG_DECIMAL;
  } else if (Common.Rep.ARRAY == protoRep) {
    // This column value is an Array (many TypedValue's)
    builder.setType(Common.Rep.ARRAY);
    // Get the array component's type
    Common.Rep protoComponentRep = componentType.toProto();
    // Set the array's component on the message
    builder.setComponentType(protoComponentRep);
    // Serialize that array into the builder
    @SuppressWarnings("unchecked")
    List<Object> list = (List<Object>) value;
    return serializeArray(list, builder, protoComponentRep);
  }

  // Serialize the type into the protobuf
  writeToProtoWithType(builder, value, protoRep);

  return builder.build();
}
 
Example #25
Source File: QuicksqlServerMeta.java    From Quicksql with MIT License 5 votes vote down vote up
public QueryResult getExplainResult(String explainResult) {
    if (StringUtils.isBlank(explainResult)) {
        throw new RuntimeException("explain result is empty");
    }
    List<Object> data = new ArrayList<>();
    Object[] objects = new Object[1];
    objects[0] = explainResult;
    data.add(Arrays.asList(objects));
    List<ColumnMetaData> meta = new ArrayList<>();
    meta.add(new ColumnMetaData(0, false, true, false, false,
        1, true, -1, "explain", "explain", null, -1, -1, null, null,
        ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true, false, false, ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING).columnClassName()));
    return new QueryResult(meta, data);
}
 
Example #26
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a {@link TypedValue} from the protocol buffer representation.
 *
 * @param proto The protobuf Typedvalue
 * @return A {@link TypedValue} instance
 */
public static TypedValue fromProto(Common.TypedValue proto) {
  ColumnMetaData.Rep rep = ColumnMetaData.Rep.fromProto(proto.getType());
  ColumnMetaData.Rep componentRep = ColumnMetaData.Rep.fromProto(proto.getComponentType());
  Object value = getSerialFromProto(proto);

  return new TypedValue(rep, componentRep, value);
}
 
Example #27
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the JDBC value from protobuf-TypedValue representation.
 *
 * @param protoValue Protobuf TypedValue
 * @param calendar Instance of a calendar
 * @return The JDBC representation of this TypedValue
 */
public static Object protoToJdbc(Common.TypedValue protoValue, Calendar calendar) {
  Object o = getSerialFromProto(Objects.requireNonNull(protoValue));
  // Shortcircuit the null
  if (null == o) {
    return o;
  }
  return serialToJdbc(Rep.fromProto(protoValue.getType()), null, o, calendar);
}
 
Example #28
Source File: ProtobufTranslationImplTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
private static ColumnMetaData getArrayColumnMetaData(ScalarType componentType, int index,
    String name) {
  ArrayType arrayType = ColumnMetaData.array(componentType, "Array", Rep.ARRAY);
  return new ColumnMetaData(
      index, false, true, false, false, DatabaseMetaData.columnNullable,
      true, -1, name, name, null,
      0, 0, null, null, arrayType, true, false, false,
      "ARRAY");
}
 
Example #29
Source File: TypedValueTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Test public void testLegacyDecimalParsing() {
  final BigDecimal decimal = new BigDecimal("123451234512345");
  final Calendar calendar = DateTimeUtils.calendar();

  // CALCITE-1103 Decimals were (incorrectly) getting serialized as normal "numbers" which
  // caused them to use the numberValue field. TypedValue should still be able to handle
  // values like this (but large values will be truncated and return bad values).
  Common.TypedValue oldProtoStyle = Common.TypedValue.newBuilder().setType(Common.Rep.NUMBER)
      .setNumberValue(decimal.longValue()).build();

  TypedValue fromProtoTv = TypedValue.fromProto(oldProtoStyle);
  Object o = fromProtoTv.toJdbc(calendar);
  assertEquals(decimal, o);
}
 
Example #30
Source File: TypedValueTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Test public void testDecimal() {
  final BigDecimal decimal = new BigDecimal("1.2345");
  final TypedValue decimalTypedValue = TypedValue.ofLocal(Rep.NUMBER, decimal);
  serializeAndEqualityCheck(decimalTypedValue);

  final Common.TypedValue protoTypedValue = decimalTypedValue.toProto();
  assertEquals(Common.Rep.BIG_DECIMAL, protoTypedValue.getType());
  final String strValue = protoTypedValue.getStringValue();
  assertNotNull(strValue);
  assertEquals(decimal.toPlainString(), strValue);
}