Java Code Examples for org.apache.calcite.avatica.ColumnMetaData#scalar()

The following examples show how to use org.apache.calcite.avatica.ColumnMetaData#scalar() . 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 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 2
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 3
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 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: 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 10
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 11
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 12
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 13
Source File: DremioColumnMetaDataList.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Gets AvaticaType carrying both JDBC {@code java.sql.Type.*} type code
 * and SQL type name for given RPC-level type (from batch schema).
 */
private static AvaticaType getAvaticaType( MajorType rpcDateType ) {
  final String sqlTypeName = Types.getSqlTypeName( rpcDateType );
  final int jdbcTypeId = Types.getJdbcTypeCode( sqlTypeName );
  return ColumnMetaData.scalar( jdbcTypeId, sqlTypeName,
      Rep.BOOLEAN /* dummy value, unused */ );
}
 
Example 14
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 15
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 16
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 17
Source File: QuicksqlServerResultSet.java    From Quicksql with MIT License 4 votes vote down vote up
/** Creates a frame containing a given number or unlimited number of rows
 * from a result set. */
static Meta.Frame frame(StatementInfo info, ResultSet resultSet, long offset,
    int fetchMaxRowCount, Calendar calendar, Optional<Signature> sig) throws SQLException {
  final ResultSetMetaData metaData = resultSet.getMetaData();
  final int columnCount = metaData.getColumnCount();
  final int[] types = new int[columnCount];
  Set<Integer> arrayOffsets = new HashSet<>();
  for (int i = 0; i < types.length; i++) {
    types[i] = metaData.getColumnType(i + 1);
    if (Types.ARRAY == types[i]) {
      arrayOffsets.add(i);
    }
  }
  final List<Object> rows = new ArrayList<>();
  // Meta prepare/prepareAndExecute 0 return 0 row and done
  boolean done = fetchMaxRowCount == 0;
  for (int i = 0; fetchMaxRowCount < 0 || i < fetchMaxRowCount; i++) {
    final boolean hasRow;
    if (null != info) {
      hasRow = info.next();
    } else {
      hasRow = resultSet.next();
    }
    if (!hasRow) {
      done = true;
      resultSet.close();
      break;
    }
    Object[] columns = new Object[columnCount];
    for (int j = 0; j < columnCount; j++) {
      columns[j] = getValue(resultSet, types[j], j, calendar);
      if (arrayOffsets.contains(j)) {
        // If we have an Array type, our Signature is lacking precision. We can't extract the
        // component type of an Array from metadata, we have to update it as we're serializing
        // the ResultSet.
        final Array array = resultSet.getArray(j + 1);
        // Only attempt to determine the component type for the array when non-null
        if (null != array && sig.isPresent()) {
          ColumnMetaData columnMetaData = sig.get().columns.get(j);
          ArrayType arrayType = (ArrayType) columnMetaData.type;
          SqlType componentSqlType = SqlType.valueOf(array.getBaseType());

          // Avatica Server will always return non-primitives to ensure nullable is guaranteed.
          ColumnMetaData.Rep rep = ColumnMetaData.Rep.serialRepOf(componentSqlType);
          AvaticaType componentType = ColumnMetaData.scalar(array.getBaseType(),
              array.getBaseTypeName(), rep);
          // Update the ArrayType from the Signature
          arrayType.updateComponentType(componentType);

          // We only need to update the array's type once.
          arrayOffsets.remove(j);
        }
      }
    }
    rows.add(columns);
  }
  // final List<Object> rows = new ArrayList<>();
  // rows.addAll(signature.columns);
  return new Meta.Frame(offset, done, rows);
}
 
Example 18
Source File: DremioColumnMetaDataList.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Gets AvaticaType carrying both JDBC {@code java.sql.Type.*} type code
 * and SQL type name for given SQL type name.
 */
private static AvaticaType getAvaticaType(String sqlTypeName) {
  final int jdbcTypeId = Types.getJdbcTypeCode(sqlTypeName);
  return ColumnMetaData.scalar( jdbcTypeId, sqlTypeName,
      Rep.BOOLEAN /* dummy value, unused */ );
}
 
Example 19
Source File: JdbcResultSet.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
/** Creates a frame containing a given number or unlimited number of rows
 * from a result set. */
static Meta.Frame frame(StatementInfo info, ResultSet resultSet, long offset,
    int fetchMaxRowCount, Calendar calendar, Optional<Meta.Signature> sig) throws SQLException {
  final ResultSetMetaData metaData = resultSet.getMetaData();
  final int columnCount = metaData.getColumnCount();
  final int[] types = new int[columnCount];
  Set<Integer> arrayOffsets = new HashSet<>();
  for (int i = 0; i < types.length; i++) {
    types[i] = metaData.getColumnType(i + 1);
    if (Types.ARRAY == types[i]) {
      arrayOffsets.add(i);
    }
  }
  final List<Object> rows = new ArrayList<>();
  // Meta prepare/prepareAndExecute 0 return 0 row and done
  boolean done = fetchMaxRowCount == 0;
  for (int i = 0; fetchMaxRowCount < 0 || i < fetchMaxRowCount; i++) {
    final boolean hasRow;
    if (null != info) {
      hasRow = info.next();
    } else {
      hasRow = resultSet.next();
    }
    if (!hasRow) {
      done = true;
      resultSet.close();
      break;
    }
    Object[] columns = new Object[columnCount];
    for (int j = 0; j < columnCount; j++) {
      columns[j] = getValue(resultSet, types[j], j, calendar);
      if (arrayOffsets.contains(j)) {
        // If we have an Array type, our Signature is lacking precision. We can't extract the
        // component type of an Array from metadata, we have to update it as we're serializing
        // the ResultSet.
        final Array array = resultSet.getArray(j + 1);
        // Only attempt to determine the component type for the array when non-null
        if (null != array && sig.isPresent()) {
          ColumnMetaData columnMetaData = sig.get().columns.get(j);
          ArrayType arrayType = (ArrayType) columnMetaData.type;
          SqlType componentSqlType = SqlType.valueOf(array.getBaseType());

          // Avatica Server will always return non-primitives to ensure nullable is guaranteed.
          ColumnMetaData.Rep rep = ColumnMetaData.Rep.serialRepOf(componentSqlType);
          AvaticaType componentType = ColumnMetaData.scalar(array.getBaseType(),
              array.getBaseTypeName(), rep);
          // Update the ArrayType from the Signature
          arrayType.updateComponentType(componentType);

          // We only need to update the array's type once.
          arrayOffsets.remove(j);
        }
      }
    }
    rows.add(columns);
  }
  return new Meta.Frame(offset, done, rows);
}
 
Example 20
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());
  }
}