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

The following examples show how to use org.apache.calcite.avatica.ColumnMetaData.ScalarType. 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: 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 #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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: QuicksqlServerMeta.java    From Quicksql with MIT License 6 votes vote down vote up
public QueryResult getSparkQueryResult(Entry<List<Attribute>, List<GenericRowWithSchema>> sparkData)
    throws Exception {
    if (sparkData == null) {
        return new QueryResult(new ArrayList<>(), new ArrayList<>());
    }
    if (CollectionUtils.isEmpty(sparkData.getKey())) {
        throw new SparkException("collect data error");
    }
    List<Attribute> attributes = sparkData.getKey();
    List<GenericRowWithSchema> value = sparkData.getValue();
    List<Object> data = new ArrayList<>();
    List<ColumnMetaData> meta = new ArrayList<>();
    value.stream().forEach(column -> {
        data.add(column.values());
    });
    for (int index = 0; index < sparkData.getKey().size(); index++) {
        Attribute attribute = sparkData.getKey().get(index);
        ScalarType columnType = getColumnType(attribute.dataType());
        meta.add(new ColumnMetaData(index, false, true, false, false,
            attribute.nullable() ? 1 : 0, true, -1, attribute.name(), attribute.name(), null, -1, -1, null, null,
            columnType, true, false, false, columnType.columnClassName()));
    }
    return new QueryResult(meta, data);
}
 
Example #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Test public void booleanArrays() throws Exception {
  final Random r = new Random();
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.BOOLEAN, "BOOLEAN", Rep.BOOLEAN);
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 5; i++) {
      List<Boolean> elements = new ArrayList<>();
      for (int j = 0; j < 5; j++) {
        switch (r.nextInt(3)) {
        case 0:
          elements.add(Boolean.FALSE);
          break;
        case 1:
          elements.add(Boolean.TRUE);
          break;
        case 2:
          elements.add(null);
          break;
        default:
          fail();
        }
      }
      arrays.add(createArray("BOOLEAN", component, elements));
    }
    // Verify we can read and write the data
    writeAndReadArrays(conn, "boolean_arrays", "BOOLEAN", component, arrays,
        PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #16
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Test public void simpleArrayTest() throws Exception {
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType varcharComponent = ColumnMetaData.scalar(Types.VARCHAR, "VARCHAR", Rep.STRING);
    List<Array> varcharArrays = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
      List<String> value = Collections.singletonList(Integer.toString(i));
      varcharArrays.add(createArray("VARCHAR", varcharComponent, value));
    }
    writeAndReadArrays(conn, "varchar_arrays", "VARCHAR(30)",
        varcharComponent, varcharArrays, PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #17
Source File: QuicksqlServerMeta.java    From Quicksql with MIT License 5 votes vote down vote up
private ScalarType getColumnType2(org.apache.flink.table.types.DataType dataType) {
    if (dataType != null && StringUtils.isNotBlank(dataType.toString())) {
        if (dataType.equals(DataTypes.StringType)) {
            return ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING);
        } else if (dataType.equals(DataTypes.BinaryType)) {
            return ColumnMetaData.scalar(Types.BINARY, "char", Rep.CHARACTER);
        } else if (dataType.equals(DataTypes.BooleanType)) {
            return ColumnMetaData.scalar(Types.BOOLEAN, "boolean", Rep.BOOLEAN);
        } else if (dataType.equals(DataTypes.DateType)) {
            return ColumnMetaData.scalar(Types.DATE, "date", Rep.JAVA_SQL_DATE);
        } else if (dataType.equals(DataTypes.TimestampType)) {
            return ColumnMetaData.scalar(Types.TIMESTAMP, "timestamp", Rep.JAVA_SQL_TIMESTAMP);
        } else if (dataType.equals(DataTypes.CalendarIntervalType)) {
            return ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING);
        } else if (dataType.equals(DataTypes.DoubleType)) {
            return ColumnMetaData.scalar(Types.DOUBLE, "double", Rep.DOUBLE);
        } else if (dataType.equals(DataTypes.FloatType)) {
            return ColumnMetaData.scalar(Types.FLOAT, "float", Rep.FLOAT);
        } else if (dataType.equals(DataTypes.ByteType)) {
            return ColumnMetaData.scalar(Types.TINYINT, "byte", Rep.BYTE);
        } else if (dataType.equals(DataTypes.IntegerType)) {
            return ColumnMetaData.scalar(Types.INTEGER, "integer", Rep.INTEGER);
        } else if (dataType.equals(DataTypes.LongType)) {
            return ColumnMetaData.scalar(Types.BIGINT, "long", Rep.LONG);
        } else if (dataType.equals(DataTypes.ShortType)) {
            return ColumnMetaData.scalar(Types.INTEGER, "integer", Rep.INTEGER);
        } else if (dataType.equals(DataTypes.NullType)) {
            return ColumnMetaData.scalar(Types.NULL, "null", Rep.OBJECT);
        }
    }
    return ColumnMetaData.scalar(Types.JAVA_OBJECT, "object", Rep.OBJECT);
}
 
Example #18
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 #19
Source File: QuicksqlServerMeta.java    From Quicksql with MIT License 5 votes vote down vote up
private ScalarType getColumnType(DataType dataType) {
    if (dataType != null && StringUtils.isNotBlank(dataType.typeName())) {
        if (dataType.equals(DataTypes.StringType)) {
            return ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING);
        } else if (dataType.equals(DataTypes.BinaryType)) {
            return ColumnMetaData.scalar(Types.BINARY, "char", Rep.CHARACTER);
        } else if (dataType.equals(DataTypes.BooleanType)) {
            return ColumnMetaData.scalar(Types.BOOLEAN, "boolean", Rep.BOOLEAN);
        } else if (dataType.equals(DataTypes.DateType)) {
            return ColumnMetaData.scalar(Types.DATE, "date", Rep.JAVA_SQL_DATE);
        } else if (dataType.equals(DataTypes.TimestampType)) {
            return ColumnMetaData.scalar(Types.TIMESTAMP, "timestamp", Rep.JAVA_SQL_TIMESTAMP);
        } else if (dataType.equals(DataTypes.CalendarIntervalType)) {
            return ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING);
        } else if (dataType.equals(DataTypes.DoubleType)) {
            return ColumnMetaData.scalar(Types.DOUBLE, "double", Rep.DOUBLE);
        } else if (dataType.equals(DataTypes.FloatType)) {
            return ColumnMetaData.scalar(Types.FLOAT, "float", Rep.FLOAT);
        } else if (dataType.equals(DataTypes.ByteType)) {
            return ColumnMetaData.scalar(Types.TINYINT, "byte", Rep.BYTE);
        } else if (dataType.equals(DataTypes.IntegerType)) {
            return ColumnMetaData.scalar(Types.INTEGER, "integer", Rep.INTEGER);
        } else if (dataType.equals(DataTypes.LongType)) {
            return ColumnMetaData.scalar(Types.BIGINT, "long", Rep.LONG);
        } else if (dataType.equals(DataTypes.ShortType)) {
            return ColumnMetaData.scalar(Types.INTEGER, "integer", Rep.INTEGER);
        } else if (dataType.equals(DataTypes.NullType)) {
            return ColumnMetaData.scalar(Types.NULL, "null", Rep.OBJECT);
        }
    }
    return ColumnMetaData.scalar(Types.JAVA_OBJECT, "object", Rep.OBJECT);
}
 
Example #20
Source File: QuicksqlServerMeta.java    From Quicksql with MIT License 5 votes vote down vote up
public QueryResult getFlinkQueryResult(Entry<TableSchema, List<Row>> sparkData) throws Exception {
    if (sparkData == null) {
        return new QueryResult(new ArrayList<>(), new ArrayList<>());
    }
    TableSchema tableSchema = sparkData.getKey();
    if (tableSchema == null || tableSchema.getFieldDataTypes().length != tableSchema.getFieldNames().length) {
        throw new SparkException("collect data error");
    }
    org.apache.flink.table.types.DataType[] fieldDataTypes = tableSchema.getFieldDataTypes();
    String[] fieldNames = tableSchema.getFieldNames();
    List<Row> value = sparkData.getValue();
    List<Object> data = new ArrayList<>();
    List<ColumnMetaData> meta = new ArrayList<>();
    value.stream().forEach(column -> {
        Object[] objects = new Object[column.getArity()];
        for (int i = 0; i < column.getArity(); i++) {
            objects[i] = column.getField(i);
        }
        data.add(Arrays.asList(objects));
    });
    for (int index = 0; index < fieldNames.length; index++) {
        ScalarType columnType = getColumnType2(fieldDataTypes[index]);
        meta.add(new ColumnMetaData(index, false, true, false, false,
            1, true, -1, fieldNames[index], fieldNames[index], null, -1, -1, null, null,
            columnType, true, false, false, columnType.columnClassName()));
    }
    return new QueryResult(meta, data);
}
 
Example #21
Source File: ArrayImplTest.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
@Test public void resultSetFromArray() throws Exception {
  // Define the struct type we're creating
  ScalarType intType = ColumnMetaData.scalar(Types.INTEGER, "INTEGER", Rep.INTEGER);
  ArrayType arrayType = ColumnMetaData.array(intType, "INTEGER", Rep.INTEGER);
  ColumnMetaData arrayMetaData = MetaImpl.columnMetaData("MY_ARRAY", 1, arrayType, false);
  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 array2 = factory.createArray(intType, Arrays.<Object>asList(3));
  Array array3 = factory.createArray(intType, Arrays.<Object>asList(4, 5, 6));
  List<List<Object>> rows = Arrays.asList(Collections.<Object>singletonList(array1),
      Collections.<Object>singletonList(array2), Collections.<Object>singletonList(array3));
  // Create two rows, each with one (array) column
  try (Cursor cursor = new ListIteratorCursor(rows.iterator())) {
    List<Accessor> accessors = cursor.createAccessors(Collections.singletonList(arrayMetaData),
        Unsafe.localCalendar(), factory);
    assertEquals(1, accessors.size());
    Accessor accessor = accessors.get(0);

    assertTrue(cursor.next());
    Array actualArray = accessor.getArray();
    // An Array's result set has one row per array element.
    // Each row has two columns. Column 1 is the array offset (1-based), Column 2 is the value.
    ResultSet actualArrayResultSet = actualArray.getResultSet();
    assertEquals(2, actualArrayResultSet.getMetaData().getColumnCount());
    assertTrue(actualArrayResultSet.next());
    // Order is Avatica implementation specific
    assertEquals(1, actualArrayResultSet.getInt(1));
    assertEquals(1, actualArrayResultSet.getInt(2));
    assertTrue(actualArrayResultSet.next());
    assertEquals(2, actualArrayResultSet.getInt(1));
    assertEquals(2, actualArrayResultSet.getInt(2));
    assertFalse(actualArrayResultSet.next());

    assertTrue(cursor.next());
    actualArray = accessor.getArray();
    actualArrayResultSet = actualArray.getResultSet();
    assertEquals(2, actualArrayResultSet.getMetaData().getColumnCount());
    assertTrue(actualArrayResultSet.next());
    assertEquals(1, actualArrayResultSet.getInt(1));
    assertEquals(3, actualArrayResultSet.getInt(2));
    assertFalse(actualArrayResultSet.next());

    assertTrue(cursor.next());
    actualArray = accessor.getArray();
    actualArrayResultSet = actualArray.getResultSet();
    assertEquals(2, actualArrayResultSet.getMetaData().getColumnCount());
    assertTrue(actualArrayResultSet.next());
    assertEquals(1, actualArrayResultSet.getInt(1));
    assertEquals(4, actualArrayResultSet.getInt(2));
    assertTrue(actualArrayResultSet.next());
    assertEquals(2, actualArrayResultSet.getInt(1));
    assertEquals(5, actualArrayResultSet.getInt(2));
    assertTrue(actualArrayResultSet.next());
    assertEquals(3, actualArrayResultSet.getInt(1));
    assertEquals(6, actualArrayResultSet.getInt(2));
    assertFalse(actualArrayResultSet.next());

    assertFalse(cursor.next());
  }
}
 
Example #22
Source File: ProtobufTranslationImplTest.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a collection of Responses whose serialization will be tested.
 */
private static List<Response> getResponses() {
  final RpcMetadataResponse rpcMetadata = new RpcMetadataResponse("localhost:8765");
  LinkedList<Response> responses = new LinkedList<>();

  // Nested classes (Signature, ColumnMetaData, CursorFactory, etc) are implicitly getting tested)

  // Stub out the metadata for a row
  ScalarType arrayComponentType = ColumnMetaData.scalar(Types.INTEGER, "integer", Rep.INTEGER);
  ColumnMetaData arrayColumnMetaData = getArrayColumnMetaData(arrayComponentType, 2, "counts");
  List<ColumnMetaData> columns =
      Arrays.asList(MetaImpl.columnMetaData("str", 0, String.class, true),
          MetaImpl.columnMetaData("count", 1, Integer.class, true),
          arrayColumnMetaData);
  List<AvaticaParameter> params =
      Arrays.asList(
          new AvaticaParameter(false, 10, 0, Types.VARCHAR, "VARCHAR",
              String.class.getName(), "str"));
  Meta.CursorFactory cursorFactory = Meta.CursorFactory.create(Style.LIST, Object.class,
      Arrays.asList("str", "count", "counts"));
  // The row values
  List<Object> rows = new ArrayList<>();
  rows.add(new Object[] {"str_value1", 50, Arrays.asList(1, 2, 3)});
  rows.add(new Object[] {"str_value2", 100, Arrays.asList(1)});

  // Create the signature and frame using the metadata and values
  Signature signature = Signature.create(columns, "sql", params, cursorFactory,
      Meta.StatementType.SELECT);
  Frame frame = Frame.create(Integer.MAX_VALUE, true, rows);

  // And then create a ResultSetResponse
  ResultSetResponse results1 = new ResultSetResponse("connectionId", Integer.MAX_VALUE, true,
      signature, frame, Long.MAX_VALUE, rpcMetadata);
  responses.add(results1);

  responses.add(new CloseStatementResponse(rpcMetadata));

  ConnectionPropertiesImpl connProps = new ConnectionPropertiesImpl(false, true,
      Integer.MAX_VALUE, "catalog", "schema");
  responses.add(new ConnectionSyncResponse(connProps, rpcMetadata));

  responses.add(new OpenConnectionResponse(rpcMetadata));
  responses.add(new CloseConnectionResponse(rpcMetadata));

  responses.add(new CreateStatementResponse("connectionId", Integer.MAX_VALUE, rpcMetadata));

  Map<Meta.DatabaseProperty, Object> propertyMap = new HashMap<>();
  for (Meta.DatabaseProperty prop : Meta.DatabaseProperty.values()) {
    propertyMap.put(prop, prop.defaultValue);
  }
  responses.add(new DatabasePropertyResponse(propertyMap, rpcMetadata));

  responses.add(
      new ExecuteResponse(Arrays.asList(results1, results1, results1), false, rpcMetadata));
  responses.add(new FetchResponse(frame, false, false, rpcMetadata));
  responses.add(new FetchResponse(frame, true, true, rpcMetadata));
  responses.add(new FetchResponse(frame, false, true, rpcMetadata));
  responses.add(
      new PrepareResponse(
          new Meta.StatementHandle("connectionId", Integer.MAX_VALUE, signature),
          rpcMetadata));

  StringWriter sw = new StringWriter();
  new Exception().printStackTrace(new PrintWriter(sw));
  responses.add(
      new ErrorResponse(Collections.singletonList(sw.toString()), "Test Error Message",
          ErrorResponse.UNKNOWN_ERROR_CODE, ErrorResponse.UNKNOWN_SQL_STATE,
          AvaticaSeverity.WARNING, rpcMetadata));

  // No more results, statement not missing
  responses.add(new SyncResultsResponse(false, false, rpcMetadata));
  // Missing statement, no results
  responses.add(new SyncResultsResponse(false, true, rpcMetadata));
  // More results, no missing statement
  responses.add(new SyncResultsResponse(true, false, rpcMetadata));

  // Some tests to make sure ErrorResponse doesn't fail.
  responses.add(new ErrorResponse((List<String>) null, null, 0, null, null, null));
  responses.add(
      new ErrorResponse(Arrays.asList("stacktrace1", "stacktrace2"), null, 0, null, null, null));

  responses.add(new CommitResponse());
  responses.add(new RollbackResponse());

  long[] updateCounts = new long[]{1, 0, 1, 1};
  responses.add(
      new ExecuteBatchResponse("connectionId", 12345, updateCounts, false, rpcMetadata));

  return responses;
}