Java Code Examples for org.apache.calcite.avatica.ColumnMetaData#Rep

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: SqlTests.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static ColumnMetaData.Rep rep(int columnType) {
  switch (columnType) {
  case Types.BOOLEAN:
    return ColumnMetaData.Rep.BOOLEAN;
  case Types.TINYINT:
    return ColumnMetaData.Rep.BYTE;
  case Types.SMALLINT:
    return ColumnMetaData.Rep.SHORT;
  case Types.INTEGER:
    return ColumnMetaData.Rep.INTEGER;
  case Types.BIGINT:
    return ColumnMetaData.Rep.LONG;
  case Types.REAL:
    return ColumnMetaData.Rep.FLOAT;
  case Types.DOUBLE:
    return ColumnMetaData.Rep.DOUBLE;
  case Types.TIME:
    return ColumnMetaData.Rep.JAVA_SQL_TIME;
  case Types.TIMESTAMP:
    return ColumnMetaData.Rep.JAVA_SQL_TIMESTAMP;
  case Types.DATE:
    return ColumnMetaData.Rep.JAVA_SQL_DATE;
  default:
    return ColumnMetaData.Rep.OBJECT;
  }
}
 
Example 2
Source File: DruidQuery.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void run() throws InterruptedException {
  final List<ColumnMetaData.Rep> fieldTypes = new ArrayList<>();
  for (RelDataTypeField field : query.getRowType().getFieldList()) {
    fieldTypes.add(getPrimitive(field));
  }
  final DruidConnectionImpl connection =
      new DruidConnectionImpl(query.druidTable.schema.url,
          query.druidTable.schema.coordinatorUrl);
  final boolean limitQuery = containsLimit(querySpec);
  final DruidConnectionImpl.Page page = new DruidConnectionImpl.Page();
  do {
    final String queryString =
        querySpec.getQueryString(page.pagingIdentifier, page.offset);
    connection.request(querySpec.queryType, queryString, sink,
        querySpec.fieldNames, fieldTypes, page);
  } while (!limitQuery
      && page.pagingIdentifier != null
      && page.totalRowCount > 0);
}
 
Example 3
Source File: DruidQuery.java    From Quicksql with MIT License 6 votes vote down vote up
public void run() throws InterruptedException {
    final List<ColumnMetaData.Rep> fieldTypes = new ArrayList<>();
    for (RelDataTypeField field : query.getRowType().getFieldList()) {
        fieldTypes.add(getPrimitive(field));
    }
    final DruidConnectionImpl connection =
        new DruidConnectionImpl(query.druidTable.schema.url,
            query.druidTable.schema.coordinatorUrl);
    final boolean limitQuery = containsLimit(querySpec);
    final DruidConnectionImpl.Page page = new DruidConnectionImpl.Page();
    do {
        final String queryString =
            querySpec.getQueryString(page.pagingIdentifier, page.offset);
        connection.request(querySpec.queryType, queryString, sink,
            querySpec.fieldNames, fieldTypes, page);
    } while (!limitQuery
        && page.pagingIdentifier != null
        && page.totalRowCount > 0);
}
 
Example 4
Source File: JdbcUtils.java    From Quicksql with MIT License 5 votes vote down vote up
public static Function1<ResultSet, Function0<Object[]>> factory(
    final List<Pair<ColumnMetaData.Rep, Integer>> list) {
  return resultSet -> {
    try {
      return new ObjectArrayRowBuilder(
          resultSet,
          Pair.left(list).toArray(new ColumnMetaData.Rep[list.size()]),
          Ints.toArray(Pair.right(list)));
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  };
}
 
Example 5
Source File: CloneSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static <T> Table createCloneTable(final JavaTypeFactory typeFactory,
    final RelProtoDataType protoRowType,
    final List<ColumnMetaData.Rep> repList,
    final Enumerable<T> source) {
  return createCloneTable(typeFactory, protoRowType, ImmutableList.of(),
      repList, source);
}
 
Example 6
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/** Converts a value to the exact type required for the given
 * representation. */
private static Object serialToLocal(ColumnMetaData.Rep rep, Object value) {
  assert value != null;
  if (value.getClass() == rep.clazz) {
    return value;
  }
  switch (rep) {
  case BYTE:
    return ((Number) value).byteValue();
  case SHORT:
    return ((Number) value).shortValue();
  case INTEGER:
  case JAVA_SQL_DATE:
  case JAVA_SQL_TIME:
    return ((Number) value).intValue();
  case LONG:
  case JAVA_UTIL_DATE:
  case JAVA_SQL_TIMESTAMP:
    return ((Number) value).longValue();
  case FLOAT:
    return ((Number) value).floatValue();
  case DOUBLE:
    return ((Number) value).doubleValue();
  case NUMBER:
    return value instanceof BigDecimal ? value
        : value instanceof BigInteger ? new BigDecimal((BigInteger) value)
        : value instanceof Double ? new BigDecimal((Double) value)
        : value instanceof Float ? new BigDecimal((Float) value)
        : new BigDecimal(((Number) value).longValue());
  case BYTE_STRING:
    return ByteString.ofBase64((String) value);
  case ARRAY:
    //List<Object>
    return value;
  default:
    throw new IllegalArgumentException("cannot convert " + value + " ("
        + value.getClass() + ") to " + rep);
  }
}
 
Example 7
Source File: CloneSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static <T> Table createCloneTable(final JavaTypeFactory typeFactory,
    final RelProtoDataType protoRowType, final List<RelCollation> collations,
    final List<ColumnMetaData.Rep> repList, final Enumerable<T> source) {
  final Type elementType;
  if (source instanceof QueryableTable) {
    elementType = ((QueryableTable) source).getElementType();
  } else if (protoRowType.apply(typeFactory).getFieldCount() == 1) {
    if (repList != null) {
      elementType = repList.get(0).clazz;
    } else {
      elementType = Object.class;
    }
  } else {
    elementType = Object[].class;
  }
  return new ArrayTable(
      elementType,
      protoRowType,
      Suppliers.memoize(() -> {
        final ColumnLoader loader =
            new ColumnLoader<>(typeFactory, source, protoRowType,
                repList);
        final List<RelCollation> collation2 =
            collations.isEmpty()
                && loader.sortField >= 0
                ? RelCollations.createSingleton(loader.sortField)
                : collations;
        return new ArrayTable.Content(loader.representationValues,
            loader.size(), collation2);
      }));
}
 
Example 8
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 9
Source File: JdbcUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static Function1<ResultSet, Function0<Object[]>> factory(
    final List<Pair<ColumnMetaData.Rep, Integer>> list) {
  return resultSet -> {
    try {
      return new ObjectArrayRowBuilder(
          resultSet,
          Pair.left(list).toArray(new ColumnMetaData.Rep[list.size()]),
          Ints.toArray(Pair.right(list)));
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  };
}
 
Example 10
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/** Creates a TypedValue from a value in JDBC representation,
 * deducing its type. */
public static TypedValue ofJdbc(Object value, Calendar calendar) {
  if (value == null) {
    return EXPLICIT_NULL;
  }
  final ColumnMetaData.Rep rep = ColumnMetaData.Rep.of(value.getClass());
  return new TypedValue(rep, jdbcToSerial(rep, value, calendar));
}
 
Example 11
Source File: CloneSchema.java    From Quicksql with MIT License 5 votes vote down vote up
public static <T> Table createCloneTable(final JavaTypeFactory typeFactory,
    final RelProtoDataType protoRowType, final List<RelCollation> collations,
    final List<ColumnMetaData.Rep> repList, final Enumerable<T> source) {
  final Type elementType;
  if (source instanceof QueryableTable) {
    elementType = ((QueryableTable) source).getElementType();
  } else if (protoRowType.apply(typeFactory).getFieldCount() == 1) {
    if (repList != null) {
      elementType = repList.get(0).clazz;
    } else {
      elementType = Object.class;
    }
  } else {
    elementType = Object[].class;
  }
  return new ArrayTable(
      elementType,
      protoRowType,
      Suppliers.memoize(() -> {
        final ColumnLoader loader =
            new ColumnLoader<>(typeFactory, source, protoRowType,
                repList);
        final List<RelCollation> collation2 =
            collations.isEmpty()
                && loader.sortField >= 0
                ? RelCollations.createSingleton(loader.sortField)
                : collations;
        return new ArrayTable.Content(loader.representationValues,
            loader.size(), collation2);
      }));
}
 
Example 12
Source File: CloneSchema.java    From Quicksql with MIT License 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static <T> Table createCloneTable(final JavaTypeFactory typeFactory,
    final RelProtoDataType protoRowType,
    final List<ColumnMetaData.Rep> repList,
    final Enumerable<T> source) {
  return createCloneTable(typeFactory, protoRowType, ImmutableList.of(),
      repList, source);
}
 
Example 13
Source File: JdbcUtils.java    From Quicksql with MIT License 5 votes vote down vote up
ObjectArrayRowBuilder(ResultSet resultSet, ColumnMetaData.Rep[] reps,
    int[] types)
    throws SQLException {
  this.resultSet = resultSet;
  this.reps = reps;
  this.types = types;
  this.columnCount = resultSet.getMetaData().getColumnCount();
}
 
Example 14
Source File: DruidConnectionImpl.java    From Quicksql with MIT License 4 votes vote down vote up
private void parseFields(List<String> fieldNames, List<ColumnMetaData.Rep> fieldTypes,
    int posTimestampField, Row.RowBuilder rowBuilder, JsonParser parser) throws IOException {
    while (parser.nextToken() == JsonToken.FIELD_NAME) {
        parseField(fieldNames, fieldTypes, posTimestampField, rowBuilder, parser);
    }
}
 
Example 15
Source File: DruidConnectionImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
private void parseFields(List<String> fieldNames, List<ColumnMetaData.Rep> fieldTypes,
    int posTimestampField, Row.RowBuilder rowBuilder, JsonParser parser) throws IOException {
  while (parser.nextToken() == JsonToken.FIELD_NAME) {
    parseField(fieldNames, fieldTypes, posTimestampField, rowBuilder, parser);
  }
}
 
Example 16
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
/**
 * Converts the given value from serial form to JDBC form.
 *
 * @param type The type of the value
 * @param value The value
 * @param calendar A calendar instance
 * @return The JDBC representation of the value.
 */
private static Object serialToJdbc(ColumnMetaData.Rep type, ColumnMetaData.Rep componentRep,
    Object value, Calendar calendar) {
  switch (type) {
  case BYTE_STRING:
    return ByteString.ofBase64((String) value).getBytes();
  case JAVA_UTIL_DATE:
    return new java.util.Date(adjust((Number) value, calendar));
  case JAVA_SQL_DATE:
    return new java.sql.Date(
        adjust(((Number) value).longValue() * DateTimeUtils.MILLIS_PER_DAY,
            calendar));
  case JAVA_SQL_TIME:
    return new java.sql.Time(adjust((Number) value, calendar));
  case JAVA_SQL_TIMESTAMP:
    return new java.sql.Timestamp(adjust((Number) value, calendar));
  case ARRAY:
    if (null == value) {
      return null;
    }
    final List<?> list = (List<?>) value;
    final List<Object> copy = new ArrayList<>(list.size());
    // Copy the list from the serial representation to a JDBC representation
    for (Object o : list) {
      if (null == o) {
        copy.add(null);
      } else if (o instanceof TypedValue) {
        // Protobuf can maintain the TypedValue hierarchy to simplify things
        copy.add(((TypedValue) o).toJdbc(calendar));
      } else {
        // We can't get the above recursion with the JSON serialization
        copy.add(serialToJdbc(componentRep, null, o, calendar));
      }
    }
    if (componentRep == null && list.size() > 0) {
      componentRep = ((TypedValue) list.get(0)).type;
      if (componentRep == null) {
        throw new RuntimeException("ComponentRep of element must not be null for ARRAYs");
      }
    }
    AvaticaType elementType = new AvaticaType(componentRep.typeId, componentRep.name(),
        componentRep);
    return new ArrayFactoryImpl(calendar.getTimeZone()).createArray(elementType, copy);
  default:
    return serialToLocal(type, value);
  }
}
 
Example 17
Source File: SqlTests.java    From Quicksql with MIT License 4 votes vote down vote up
/**
 * Compares the first column of a result set against a String-valued
 * reference set, disregarding order entirely.
 *
 * @param resultSet Result set
 * @param refSet    Expected results
 * @throws Exception .
 */
public static void compareResultSet(
    ResultSet resultSet,
    Set<String> refSet) throws Exception {
  Set<String> actualSet = new HashSet<>();
  final int columnType = resultSet.getMetaData().getColumnType(1);
  final ColumnMetaData.Rep rep = rep(columnType);
  while (resultSet.next()) {
    final String s = resultSet.getString(1);
    final String s0 = s == null ? "0" : s;
    final boolean wasNull0 = resultSet.wasNull();
    actualSet.add(s);
    switch (rep) {
    case BOOLEAN:
      assertThat(resultSet.getBoolean(1), equalTo(Boolean.valueOf(s)));
      break;
    case BYTE:
    case SHORT:
    case INTEGER:
    case LONG:
      long l;
      try {
        l = Long.parseLong(s0);
      } catch (NumberFormatException e) {
        // Large integers come out in scientific format, say "5E+06"
        l = (long) Double.parseDouble(s0);
      }
      assertThat(resultSet.getByte(1), equalTo((byte) l));
      assertThat(resultSet.getShort(1), equalTo((short) l));
      assertThat(resultSet.getInt(1), equalTo((int) l));
      assertThat(resultSet.getLong(1), equalTo(l));
      break;
    case FLOAT:
    case DOUBLE:
      final double d = Double.parseDouble(s0);
      assertThat(resultSet.getFloat(1), equalTo((float) d));
      assertThat(resultSet.getDouble(1), equalTo(d));
      break;
    }
    final boolean wasNull1 = resultSet.wasNull();
    final Object object = resultSet.getObject(1);
    final boolean wasNull2 = resultSet.wasNull();
    assertThat(object == null, equalTo(wasNull0));
    assertThat(wasNull1, equalTo(wasNull0));
    assertThat(wasNull2, equalTo(wasNull0));
  }
  resultSet.close();
  assertEquals(refSet, actualSet);
}
 
Example 18
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 19
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
private TypedValue(ColumnMetaData.Rep rep, Object value) {
  this(rep, null, value);
}
 
Example 20
Source File: DruidConnectionImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
private void parseField(List<String> fieldNames, List<ColumnMetaData.Rep> fieldTypes,
    int posTimestampField, Row.RowBuilder rowBuilder, JsonParser parser) throws IOException {
  final String fieldName = parser.getCurrentName();
  parseFieldForName(fieldNames, fieldTypes, posTimestampField, rowBuilder, parser, fieldName);
}