org.apache.calcite.avatica.remote.TypedValue Java Examples

The following examples show how to use org.apache.calcite.avatica.remote.TypedValue. 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: CalciteMetaImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public ExecuteResult execute(StatementHandle h,
    List<TypedValue> parameterValues, int maxRowsInFirstFrame)
    throws NoSuchStatementException {
  final CalciteConnectionImpl calciteConnection = getConnection();
  CalciteServerStatement stmt = calciteConnection.server.getStatement(h);
  final Signature signature = stmt.getSignature();

  MetaResultSet metaResultSet;
  if (signature.statementType.canUpdate()) {
    final Iterable<Object> iterable =
        _createIterable(h, signature, parameterValues, null);
    final Iterator<Object> iterator = iterable.iterator();
    stmt.setResultSet(iterator);
    metaResultSet = MetaResultSet.count(h.connectionId, h.id,
        ((Number) iterator.next()).intValue());
  } else {
    // Don't populate the first frame.
    // It's not worth saving a round-trip, since we're local.
    final Meta.Frame frame =
        new Meta.Frame(0, false, Collections.emptyList());
    metaResultSet =
        MetaResultSet.create(h.connectionId, h.id, false, signature, frame);
  }

  return new ExecuteResult(ImmutableList.of(metaResultSet));
}
 
Example #2
Source File: QuicksqlServerMeta.java    From Quicksql with MIT License 6 votes vote down vote up
@Override
public ExecuteBatchResult executeBatchProtobuf(StatementHandle h,
    List<Requests.UpdateBatch> updateBatches) throws NoSuchStatementException {
    try {
        final StatementInfo info = statementCache.getIfPresent(h.id);
        if (null == info) {
            throw new NoSuchStatementException(h);
        }

        final PreparedStatement preparedStmt = (PreparedStatement) info.statement;
        for (Requests.UpdateBatch update : updateBatches) {
            int i = 1;
            for (Common.TypedValue value : update.getParameterValuesList()) {
                // Use the value and then increment
                preparedStmt.setObject(i++, TypedValue.protoToJdbc(value, calendar));
            }
            preparedStmt.addBatch();
        }
        return new ExecuteBatchResult(AvaticaUtils.executeLargeBatch(preparedStmt));
    } catch (SQLException e) {
        throw propagate(e);
    }
}
 
Example #3
Source File: Meta.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the value for a ColumnValue using the separated array and scalar attributes.
 *
 * @param column The protobuf ColumnValue object
 * @return The parse value for this column
 */
static Object parseColumn(Common.ColumnValue column) {
  // Verify that we have one or the other (scalar or array)
  validateColumnValue(column);

  if (!column.hasField(SCALAR_VALUE_DESCRIPTOR)) {
    // The column in this row is an Array (has multiple values)
    List<Object> array = new ArrayList<>(column.getArrayValueCount());
    for (Common.TypedValue arrayValue : column.getArrayValueList()) {
      // Duplicative because of the ColumnValue/TypedValue difference.
      if (Common.Rep.ARRAY == arrayValue.getType()) {
        // Each element in this Array is an Array.
        array.add(parseArray(arrayValue));
      } else {
        // The array element is a scalar.
        array.add(deserializeScalarValue(arrayValue));
      }
    }
    return array;
  } else {
    // Scalar
    return deserializeScalarValue(column.getScalarValue());
  }
}
 
Example #4
Source File: CalciteMetaImpl.java    From Quicksql with MIT License 6 votes vote down vote up
@Override public ExecuteResult execute(StatementHandle h,
    List<TypedValue> parameterValues, int maxRowsInFirstFrame)
    throws NoSuchStatementException {
  final CalciteConnectionImpl calciteConnection = getConnection();
  CalciteServerStatement stmt = calciteConnection.server.getStatement(h);
  final Signature signature = stmt.getSignature();

  MetaResultSet metaResultSet;
  if (signature.statementType.canUpdate()) {
    final Iterable<Object> iterable =
        _createIterable(h, signature, parameterValues, null);
    final Iterator<Object> iterator = iterable.iterator();
    stmt.setResultSet(iterator);
    metaResultSet = MetaResultSet.count(h.connectionId, h.id,
        ((Number) iterator.next()).intValue());
  } else {
    // Don't populate the first frame.
    // It's not worth saving a round-trip, since we're local.
    final Meta.Frame frame =
        new Meta.Frame(0, false, Collections.emptyList());
    metaResultSet =
        MetaResultSet.create(h.connectionId, h.id, false, signature, frame);
  }

  return new ExecuteResult(ImmutableList.of(metaResultSet));
}
 
Example #5
Source File: Meta.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
static void parseColumn(Common.Row.Builder rowBuilder, Object column) {
  final Common.ColumnValue.Builder columnBuilder = Common.ColumnValue.newBuilder();

  if (column instanceof List) {
    columnBuilder.setHasArrayValue(true);
    List<?> list = (List<?>) column;
    // Add each element in the list/array to the column's value
    for (Object listItem : list) {
      final Common.TypedValue scalarListItem = serializeScalar(listItem);
      columnBuilder.addArrayValue(scalarListItem);
      // Add the deprecated 'value' repeated attribute for backwards compat
      columnBuilder.addValue(scalarListItem);
    }
  } else {
    // The default value, but still explicit.
    columnBuilder.setHasArrayValue(false);
    // Only one value for this column, a scalar.
    final Common.TypedValue scalarVal = serializeScalar(column);
    columnBuilder.setScalarValue(scalarVal);
    // Add the deprecated 'value' repeated attribute for backwards compat
    columnBuilder.addValue(scalarVal);
  }

  // Add value to row
  rowBuilder.addValue(columnBuilder.build());
}
 
Example #6
Source File: JdbcMeta.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Override public ExecuteBatchResult executeBatchProtobuf(StatementHandle h,
    List<Requests.UpdateBatch> updateBatches) throws NoSuchStatementException {
  try {
    final StatementInfo info = statementCache.getIfPresent(h.id);
    if (null == info) {
      throw new NoSuchStatementException(h);
    }

    final PreparedStatement preparedStmt = (PreparedStatement) info.statement;
    for (Requests.UpdateBatch update : updateBatches) {
      int i = 1;
      for (Common.TypedValue value : update.getParameterValuesList()) {
        // Use the value and then increment
        preparedStmt.setObject(i++, TypedValue.protoToJdbc(value, calendar));
      }
      preparedStmt.addBatch();
    }
    return new ExecuteBatchResult(AvaticaUtils.executeLargeBatch(preparedStmt));
  } catch (SQLException e) {
    throw propagate(e);
  }
}
 
Example #7
Source File: JsonHandlerTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void testExecuteRequestWithNumberParameter() {
  final List<TypedValue> expectedParameterValues = new ArrayList<>();
  final Service service = new ParameterValuesCheckingService(expectedParameterValues);
  final JsonService jsonService = new LocalJsonService(service);
  final JsonHandler jsonHandler = new JsonHandler(jsonService, NoopMetricsSystem.getInstance());

  final List<TypedValue> parameterValues = Arrays.asList(
      TypedValue.create("NUMBER", new BigDecimal("123")),
      TypedValue.create("STRING", "calcite"));

  jsonHandler.apply(
      "{'request':'execute',"
      + "'parameterValues':[{'type':'NUMBER','value':123},"
      + "{'type':'STRING','value':'calcite'}]}");
  assertThat(expectedParameterValues.size(), is(2));
  assertThat(expectedParameterValues.get(0), is(parameterValues.get(0)));
  assertThat(expectedParameterValues.get(1), is(parameterValues.get(1)));
}
 
Example #8
Source File: Meta.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
static Common.TypedValue serializeScalar(Object element) {
  final Common.TypedValue.Builder valueBuilder = Common.TypedValue.newBuilder();

  // Let TypedValue handle the serialization for us.
  TypedValue.toProto(valueBuilder, element);

  return valueBuilder.build();
}
 
Example #9
Source File: MetaImpl.java    From kareldb with Apache License 2.0 5 votes vote down vote up
@Override
public ExecuteBatchResult executeBatch(StatementHandle h,
                                       List<List<TypedValue>> parameterValueLists) throws NoSuchStatementException {
    begin();
    try {
        return super.executeBatch(h, parameterValueLists);
    } finally {
        if (isAutoCommit()) {
            commit(connection.handle);
        }
    }
}
 
Example #10
Source File: AvaticaResultSet.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/**
 * Executes this result set. (Not a JDBC method.)
 *
 * <p>Note that execute cannot occur in the constructor, because the
 * constructor occurs while the statement is locked, to make sure that
 * execute/cancel don't happen at the same time.</p>
 *
 * @see org.apache.calcite.avatica.AvaticaConnection.Trojan#execute(AvaticaResultSet)
 *
 * @throws SQLException if execute fails for some reason.
 */
protected AvaticaResultSet execute() throws SQLException {
  final Iterable<Object> iterable1 =
      statement.connection.meta.createIterable(statement.handle, state, signature,
          Collections.<TypedValue>emptyList(), firstFrame);
  this.cursor = MetaImpl.createCursor(signature.cursorFactory, iterable1);
  this.accessorList =
      cursor.createAccessors(columnMetaDataList, localCalendar, this);
  this.row = 0;
  this.beforeFirst = true;
  this.afterLast = false;
  return this;
}
 
Example #11
Source File: MetaImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/** Returns whether a list of parameter values has any null elements. */
public static boolean checkParameterValueHasNull(List<TypedValue> parameterValues) {
  for (TypedValue x : parameterValues) {
    if (x == null) {
      return true;
    }
  }
  return false;
}
 
Example #12
Source File: MetaImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Override public Iterable<Object> createIterable(StatementHandle handle, QueryState state,
    Signature signature, List<TypedValue> parameterValues, Frame firstFrame) {
  // `parameterValues` is intentionally unusued (in method signature for historic reasons)
  // Left to preserve API compatibility with Calcite
  if (firstFrame != null && firstFrame.done) {
    return firstFrame.rows;
  }
  AvaticaStatement stmt;
  try {
    stmt = connection.lookupStatement(handle);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
  return new FetchIterable(stmt, state, firstFrame);
}
 
Example #13
Source File: AvaticaStatement.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/** Returns a list of bound parameter values.
 *
 * <p>If any of the parameters have not been bound, throws.
 * If parameters have been bound to null, the value in the list is null.
 */
protected List<TypedValue> getBoundParameterValues() throws SQLException {
  final List<TypedValue> parameterValues = getParameterValues();
  for (Object parameterValue : parameterValues) {
    if (parameterValue == null) {
      throw new SQLException("unbound parameter");
    }
  }
  return parameterValues;
}
 
Example #14
Source File: QuicksqlServerMeta.java    From Quicksql with MIT License 5 votes vote down vote up
@Override
public ExecuteResult execute(StatementHandle h,
    List<TypedValue> parameterValues, int maxRowsInFirstFrame) throws NoSuchStatementException {
    final StatementInfo statementInfo = statementCache.getIfPresent(h.id);
    if (null == statementInfo) {
        throw new NoSuchStatementException(h);
    }
    String sql = h.signature.sql;
    for (TypedValue value : parameterValues) {
        if (value.type == Rep.BYTE || value.type == Rep.SHORT || value.type == Rep.LONG || value.type == Rep.DOUBLE
            || value.type == Rep.INTEGER || value.type == Rep.FLOAT) {
            sql = sql.replaceFirst("\\?", value.value.toString());
        } else {
            sql = sql.replaceFirst("\\?", "'" + value.value.toString() + "'");
        }
    }
    ExecuteResult executeResult = null;
    try {
        QuicksqlConnectionImpl connection = (QuicksqlConnectionImpl) getConnection(h.connectionId);
        String jdbcUrl = connection.getInfoByName("jdbcUrl");
        if (StringUtils.isNotBlank(jdbcUrl)) {
            executeResult = jdbcExecute(h, jdbcUrl, connection.getInfoByName("user"), connection
                .getInfoByName("password"), sql);
        } else {
            executeResult = getExecuteResultSet(h, connection, sql);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    return executeResult;
}
 
Example #15
Source File: CalciteMetaImpl.java    From Quicksql with MIT License 5 votes vote down vote up
@Override public ExecuteBatchResult executeBatch(StatementHandle h,
    List<List<TypedValue>> parameterValueLists) throws NoSuchStatementException {
  final List<Long> updateCounts = new ArrayList<>();
  for (List<TypedValue> parameterValueList : parameterValueLists) {
    ExecuteResult executeResult = execute(h, parameterValueList, -1);
    final long updateCount =
        executeResult.resultSets.size() == 1
            ? executeResult.resultSets.get(0).updateCount
            : -1L;
    updateCounts.add(updateCount);
  }
  return new ExecuteBatchResult(Longs.toArray(updateCounts));
}
 
Example #16
Source File: KylinPreparedStatement.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
protected List<Object> getParameterJDBCValues() {
    List<TypedValue> typeValues = getParameterValues();
    List<Object> jdbcValues = new ArrayList<Object>(typeValues.size());
    for (TypedValue typeValue : typeValues) {
        jdbcValues.add(typeValue.toJdbc(getCalendar()));
    }
    return jdbcValues;
}
 
Example #17
Source File: TableEnv.java    From marble with Apache License 2.0 5 votes vote down vote up
public DataTable fromJdbcResultSet(
    ResultSet resultSet) {
  try {
    final RelDataTypeFactory.Builder builder = calciteCatalogReader
        .getTypeFactory()
        .builder();
    ResultSetMetaData metaData = resultSet.getMetaData();
    int columnCount = metaData.getColumnCount();
    for (int i = 1; i <= columnCount; i++) {
      String columnName = metaData.getColumnLabel(i);
      int jdbcType = metaData.getColumnType(i);
      builder.add(columnName.toUpperCase(),
          getSqlTypeNameForJdbcType(jdbcType)).nullable(true);
    }
    RelDataType rowType = builder.build();
    List<Object[]> convertRows = new ArrayList<>();
    Calendar calendar = Calendar
        .getInstance(tableConfig.getTimeZone(), Locale.ROOT);
    while (resultSet.next()) {
      Object[] row = new Object[columnCount];
      for (int i = 1; i <= columnCount; i++) {
        Object jdbcObject = resultSet.getObject(i);
        Object convertedCalciteObject = TypedValue.ofJdbc(jdbcObject,
            calendar).value;
        row[i - 1] = convertedCalciteObject;
      }
      convertRows.add(row);
    }
    return new DataTable(rowType, convertRows);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #18
Source File: CalciteMetaImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public ExecuteBatchResult executeBatch(StatementHandle h,
    List<List<TypedValue>> parameterValueLists) throws NoSuchStatementException {
  final List<Long> updateCounts = new ArrayList<>();
  for (List<TypedValue> parameterValueList : parameterValueLists) {
    ExecuteResult executeResult = execute(h, parameterValueList, -1);
    final long updateCount =
        executeResult.resultSets.size() == 1
            ? executeResult.resultSets.get(0).updateCount
            : -1L;
    updateCounts.add(updateCount);
  }
  return new ExecuteBatchResult(Longs.toArray(updateCounts));
}
 
Example #19
Source File: Meta.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/**
 * For Calcite 1.5, we made the mistake of using array length to determine when the value for a
 * column is a scalar or an array. This method performs the old parsing for backwards
 * compatibility.
 *
 * @param column The protobuf ColumnValue object
 * @return The parsed value for this column
 */
static Object parseOldStyleColumn(Common.ColumnValue column) {
  if (column.getValueCount() > 1) {
    List<Object> array = new ArrayList<>(column.getValueCount());
    for (Common.TypedValue columnValue : column.getValueList()) {
      array.add(deserializeScalarValue(columnValue));
    }
    return array;
  } else {
    return deserializeScalarValue(column.getValue(0));
  }
}
 
Example #20
Source File: Meta.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/**
 * Recursively parses a TypedValue while it is an array.
 */
static Object parseArray(Common.TypedValue array) {
  List<Object> convertedArray = new ArrayList<>(array.getArrayValueCount());
  for (Common.TypedValue arrayElement : array.getArrayValueList()) {
    if (Common.Rep.ARRAY == arrayElement.getType()) {
      // Recurse
      convertedArray.add(parseArray(arrayElement));
    } else {
      // The component type of this array is a scalar.
      convertedArray.add(deserializeScalarValue(arrayElement));
    }
  }
  return convertedArray;
}
 
Example #21
Source File: Meta.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
static Object deserializeScalarValue(Common.TypedValue protoElement) {
  // ByteString is a single case where TypedValue is representing the data differently
  // (in its "local" form) than Frame does. We need to unwrap the Base64 encoding.
  if (Common.Rep.BYTE_STRING == protoElement.getType()) {
    // Protobuf is sending native bytes (not b64) across the wire. B64 bytes is only for
    // TypedValue's benefit
    return protoElement.getBytesValue().toByteArray();
  }
  // Again, let TypedValue deserialize things for us.
  return TypedValue.fromProto(protoElement).value;
}
 
Example #22
Source File: AvaticaSite.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
public AvaticaSite(AvaticaParameter parameter, Calendar calendar, int index,
    TypedValue[] slots) {
  assert calendar != null;
  assert parameter != null;
  assert slots != null;
  this.parameter = parameter;
  this.calendar = calendar;
  this.index = index;
  this.slots = slots;
}
 
Example #23
Source File: AvaticaPreparedStatement.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an AvaticaPreparedStatement.
 *
 * @param connection Connection
 * @param h Statement handle
 * @param signature Result of preparing statement
 * @param resultSetType Result set type
 * @param resultSetConcurrency Result set concurrency
 * @param resultSetHoldability Result set holdability
 * @throws SQLException If fails due to underlying implementation reasons.
 */
protected AvaticaPreparedStatement(AvaticaConnection connection,
    Meta.StatementHandle h,
    Meta.Signature signature,
    int resultSetType,
    int resultSetConcurrency,
    int resultSetHoldability) throws SQLException {
  super(connection, h, resultSetType, resultSetConcurrency,
      resultSetHoldability, signature);
  this.slots = new TypedValue[signature.parameters.size()];
  this.resultSetMetaData =
      connection.factory.newResultSetMetaData(this, signature);
  this.parameterValueBatch = new ArrayList<>();
}
 
Example #24
Source File: AvaticaPreparedStatement.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/** Returns a copy of the current parameter values.
 * @return A copied list of the parameter values
 */
protected List<TypedValue> copyParameterValues() {
  // For implementing batch update, we need to make a copy of slots, not just a thin reference
  // to it as as list. Otherwise, subsequent setFoo(..) calls will alter the underlying array
  // and modify our cached TypedValue list.
  List<TypedValue> copy = new ArrayList<>(slots.length);
  for (TypedValue value : slots) {
    copy.add(value);
  }
  return copy;
}
 
Example #25
Source File: DremioMetaImpl.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public ExecuteResult execute(StatementHandle h, List<TypedValue> parameterValues, int maxRowsInFirstFrame)
    throws NoSuchStatementException {
  // Signature might have been zeroed by AvaticaConnection#executeQueryInternal()
  // Get it from the original handle
  final AvaticaStatement stmt;
  try {
     stmt = connection.lookupStatement(h);
  } catch(SQLException e) {
    throw new NoSuchStatementException(h);
  }
    MetaResultSet metaResultSet =
        MetaResultSet.create(h.connectionId, h.id, false, stmt.handle.signature, null);
  return new ExecuteResult(ImmutableList.of(metaResultSet));
}
 
Example #26
Source File: DremioMetaImpl.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public ExecuteBatchResult executeBatch(StatementHandle h, List<List<TypedValue>> parameterValueLists)
    throws NoSuchStatementException {
  final List<Long> updateCounts = new ArrayList<>();
  for (List<TypedValue> parameterValueList : parameterValueLists) {
    ExecuteResult executeResult = execute(h, parameterValueList, -1);
    final long updateCount =
        executeResult.resultSets.size() == 1
            ? executeResult.resultSets.get(0).updateCount
            : -1L;
    updateCounts.add(updateCount);
  }
  return new ExecuteBatchResult(Longs.toArray(updateCounts));
}
 
Example #27
Source File: QuarkMetaImpl.java    From quark with Apache License 2.0 5 votes vote down vote up
@Override
public ExecuteResult execute(StatementHandle statementHandle,
                             List<TypedValue> list,
                             int i)
        throws NoSuchStatementException {
  return null;
}
 
Example #28
Source File: KylinPreparedStatement.java    From kylin with Apache License 2.0 5 votes vote down vote up
protected List<Object> getParameterJDBCValues() {
    List<TypedValue> typeValues = getParameterValues();
    List<Object> jdbcValues = new ArrayList<Object>(typeValues.size());
    for (TypedValue typeValue : typeValues) {
        jdbcValues.add(typeValue.toJdbc(getCalendar()));
    }
    return jdbcValues;
}
 
Example #29
Source File: CalciteMetaImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
Iterable<Object> _createIterable(StatementHandle handle,
    Signature signature, List<TypedValue> parameterValues, Frame firstFrame) {
  try {
    //noinspection unchecked
    final CalcitePrepare.CalciteSignature<Object> calciteSignature =
        (CalcitePrepare.CalciteSignature<Object>) signature;
    return getConnection().enumerable(handle, calciteSignature);
  } catch (SQLException e) {
    throw new RuntimeException(e.getMessage());
  }
}
 
Example #30
Source File: MetaImpl.java    From kareldb with Apache License 2.0 5 votes vote down vote up
@Override
public ExecuteResult execute(StatementHandle h,
                             List<TypedValue> parameterValues, int maxRowsInFirstFrame)
    throws NoSuchStatementException {
    begin();
    try {
        return super.execute(h, parameterValues, maxRowsInFirstFrame);
    } finally {
        if (isAutoCommit()) {
            commit(connection.handle);
        }
    }
}