Java Code Examples for io.vertx.sqlclient.Tuple#size()

The following examples show how to use io.vertx.sqlclient.Tuple#size() . 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: ExtendedQueryCommandBaseCodec.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
void encodePreparedQuery(DRDAQueryRequest queryRequest, QueryInstance queryInstance, Tuple params) {
  int requiredParams = statement.paramDesc.paramDefinitions().columns_;
  if (params.size() != requiredParams) {
    completionHandler.handle(CommandResponse.failure("Only " + params.size()
        + " prepared statement parameters were provided " + "but " + requiredParams + " parameters are required."));
    return;
  }

  Object[] inputs = sanitize(params);
  if (queryInstance.cursor == null) {
    queryRequest.writeOpenQuery(statement.section, encoder.socketConnection.connMetadata.databaseName, cmd.fetch(),
        ResultSet.TYPE_FORWARD_ONLY, statement.paramDesc.paramDefinitions(), inputs);
  } else {
    queryRequest.writeFetch(statement.section, encoder.socketConnection.connMetadata.databaseName, cmd.fetch(),
        queryInstance.queryInstanceId);
  }
}
 
Example 2
Source File: PostgresClient.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
/**
   * Run a parameterized/prepared select query and return the first record, or null if there is no result.
   *
   * <p>This never closes the connection conn.
   *
   * <p>To update see {@link #execute(AsyncResult, String, Handler)}.
   *
   * @param conn  The connection on which to execute the query on.
   * @param sql  The sql query to run.
   * @param params  The parameters for the placeholders in sql.
   * @param replyHandler  The query result or the failure.
   */
public void selectSingle(AsyncResult<SQLConnection> conn, String sql, Tuple params,
                         Handler<AsyncResult<Row>> replyHandler) {
  try {
    if (conn.failed()) {
      replyHandler.handle(Future.failedFuture(conn.cause()));
      return;
    }
    if (params.size() == 0) {
      conn.result().conn.query(sql).execute(res -> selectReturn(res, replyHandler));
    } else {
      conn.result().conn.preparedQuery(sql).execute(params, res -> selectReturn(res, replyHandler));
    }
  } catch (Exception e) {
    log.error(e.getMessage(), e);
    replyHandler.handle(Future.failedFuture(e));
  }
}
 
Example 3
Source File: ExtendedQueryCommandBaseCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private static Object[] sanitize(Tuple params) {
  Object[] inputs = new Object[params.size()];
  for (int i = 0; i < params.size(); i++) {
    Object val = params.getValue(i);
    if (val instanceof Numeric)
      val = ((Numeric) val).bigDecimalValue();
    if (val instanceof Buffer)
      val = ((Buffer) val).getByteBuf();
    inputs[i] = val;
  }
  return inputs;
}
 
Example 4
Source File: ExtendedQueryCommandCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private String parseParamDefinitions(Tuple params) {
  StringBuilder stringBuilder = new StringBuilder();
  for (int i = 0; i < params.size(); i++) {
    Object param = params.getValue(i);
    stringBuilder.append("@P").append(i + 1).append(" ");
    stringBuilder.append(inferenceParamDefinitionByValueType(param));
    if (i != params.size() - 1) {
      stringBuilder.append(",");
    }
  }
  return stringBuilder.toString();
}
 
Example 5
Source File: ArrayTuple.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public ArrayTuple(Tuple tuple) {
  values = new Object[tuple.size()];
  size = values.length;
  for (int idx = 0;idx < size;idx++) {
    values[idx] = tuple.getValue(idx);
  }
}
 
Example 6
Source File: PostgresClient.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * Send an INSERT, UPDATE or DELETE parameterized/prepared statement within a transaction.
 *
 * <p>Example:
 * <pre>
 *  postgresClient.startTx(beginTx -> {
 *        try {
 *          postgresClient.execute(beginTx, sql, params, reply -> {...
 * </pre>
 * @param conn - connection - see {@link #startTx(Handler)}
 * @param sql - the sql to run
 * @param replyHandler - reply handler with UpdateResult
 */
public void execute(AsyncResult<SQLConnection> conn, String sql, Tuple params,
                    Handler<AsyncResult<RowSet<Row>>> replyHandler) {
  try {
    if (conn.failed()) {
      replyHandler.handle(Future.failedFuture(conn.cause()));
      return;
    }
    PgConnection connection = conn.result().conn;
    long start = System.nanoTime();
    // more than optimization.. preparedQuery does not work for multiple SQL statements
    if (params.size() == 0) {
      connection.query(sql).execute(query -> {
        statsTracker(EXECUTE_STAT_METHOD, sql, start);
        replyHandler.handle(query);
      });
    } else {
      connection.preparedQuery(sql).execute(params, query -> {
        statsTracker(EXECUTE_STAT_METHOD, sql, start);
        replyHandler.handle(query);
      });
    }
  } catch (Exception e) {
    log.error(e.getMessage(), e);
    replyHandler.handle(Future.failedFuture(e));
  }
}
 
Example 7
Source File: PgEncoder.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * The message gives the name of the prepared statement, the name of portal,
 * and the values to use for any parameter values present in the prepared statement.
 * The supplied parameter set must match those needed by the prepared statement.
 * <p>
 * The response is either {@link BindComplete} or {@link ErrorResponse}.
 */
void writeBind(Bind bind, String portal, Tuple paramValues) {
  ensureBuffer();
  int pos = out.writerIndex();
  out.writeByte(BIND);
  out.writeInt(0);
  if (portal != null) {
    out.writeCharSequence(portal, UTF_8);
  }
  out.writeByte(0);
  if (bind.statement == 0) {
    out.writeByte(0);
  } else {
    out.writeLong(bind.statement);
  }
  int paramLen = paramValues.size();
  out.writeShort(paramLen);
  // Parameter formats
  for (int c = 0;c < paramLen;c++) {
    // for now each format is Binary
    out.writeShort(bind.paramTypes[c].supportsBinary ? 1 : 0);
  }
  out.writeShort(paramLen);
  for (int c = 0;c < paramLen;c++) {
    Object param = paramValues.getValue(c);
    if (param == null) {
      // NULL value
      out.writeInt(-1);
    } else {
      DataType dataType = bind.paramTypes[c];
      if (dataType.supportsBinary) {
        int idx = out.writerIndex();
        out.writeInt(0);
        DataTypeCodec.encodeBinary(dataType, param, out);
        out.setInt(idx, out.writerIndex() - idx - 4);
      } else {
        DataTypeCodec.encodeText(dataType, param, out);
      }
    }
  }

  // MAKE resultColumsn non null to avoid null check

  // Result columns are all in Binary format
  if (bind.resultColumns.length > 0) {
    out.writeShort(bind.resultColumns.length);
    for (PgColumnDesc resultColumn : bind.resultColumns) {
      out.writeShort(resultColumn.dataType.supportsBinary ? 1 : 0);
    }
  } else {
    out.writeShort(1);
    out.writeShort(1);
  }
  out.setInt(pos + 1, out.writerIndex() - pos - 1);
}
 
Example 8
Source File: TemplateBuilderTest.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private static void assertTupleEquals(Tuple actual, Tuple expected) {
  assertEquals(actual.size(), expected.size());
  for (int idx = 0;idx < actual.size();idx++) {
    assertEquals(actual.getValue(idx), expected.getValue(idx));
  }
}
 
Example 9
Source File: ExtendedQueryCommandCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private void sendPrepexecRequest() {
  ChannelHandlerContext chctx = encoder.chctx;

  ByteBuf packet = chctx.alloc().ioBuffer();

  // packet header
  packet.writeByte(MessageType.RPC.value());
  packet.writeByte(MessageStatus.NORMAL.value() | MessageStatus.END_OF_MESSAGE.value());
  int packetLenIdx = packet.writerIndex();
  packet.writeShort(0); // set length later
  packet.writeShort(0x00);
  packet.writeByte(0x00); // FIXME packet ID
  packet.writeByte(0x00);

  int start = packet.writerIndex();
  packet.writeIntLE(0x00); // TotalLength for ALL_HEADERS
  encodeTransactionDescriptor(packet, 0, 1);
  // set TotalLength for ALL_HEADERS
  packet.setIntLE(start, packet.writerIndex() - start);

  /*
    RPCReqBatch
   */
  packet.writeShortLE(0xFFFF);
  packet.writeShortLE(ProcId.Sp_PrepExec);

  // Option flags
  packet.writeShortLE(0x0000);

  // Parameter

  // OUT Parameter
  packet.writeByte(0x00);
  packet.writeByte(0x01); // By reference
  packet.writeByte(MSSQLDataTypeId.INTNTYPE_ID);
  packet.writeByte(0x04);
  packet.writeByte(0x04);
  packet.writeIntLE(0x00);

  Tuple params = cmd.params();

  // Param definitions
  String paramDefinitions = parseParamDefinitions(params);
  encodeNVarcharParameter(packet, paramDefinitions);

  // SQL text
  encodeNVarcharParameter(packet, cmd.sql());

  // Param values
  for (int i = 0; i < params.size(); i++) {
    encodeParamValue(packet, params.getValue(i));
  }

  int packetLen = packet.writerIndex() - packetLenIdx + 2;
  packet.setShort(packetLenIdx, packetLen);

  chctx.writeAndFlush(packet);
}
 
Example 10
Source File: ExtendedBatchQueryCommandCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private void sendBatchStatementExecuteCommand(MySQLPreparedStatement statement, Tuple params) {
  ByteBuf packet = allocateBuffer();
  // encode packet header
  int packetStartIdx = packet.writerIndex();
  packet.writeMediumLE(0); // will set payload length later by calculation
  packet.writeByte(sequenceId);

  // encode packet payload
  packet.writeByte(CommandType.COM_STMT_EXECUTE);
  packet.writeIntLE((int) statement.statementId);
  packet.writeByte(CURSOR_TYPE_NO_CURSOR);
  // iteration count, always 1
  packet.writeIntLE(1);

  /*
   * Null-bit map and type should always be reconstructed for every batch of parameters here
   */
  int numOfParams = statement.bindingTypes().length;
  int bitmapLength = (numOfParams + 7) / 8;
  byte[] nullBitmap = new byte[bitmapLength];

  int pos = packet.writerIndex();

  if (numOfParams > 0) {
    // write a dummy bitmap first
    packet.writeBytes(nullBitmap);
    packet.writeByte(1);
    for (int i = 0; i < params.size(); i++) {
      Object param = params.getValue(i);
      DataType dataType = DataTypeCodec.inferDataTypeByEncodingValue(param);
      packet.writeByte(dataType.id);
      packet.writeByte(0); // parameter flag: signed
    }

    for (int i = 0; i < numOfParams; i++) {
      Object value = params.getValue(i);
      if (value != null) {
        DataTypeCodec.encodeBinary(DataTypeCodec.inferDataTypeByEncodingValue(value), value, encoder.encodingCharset, packet);
      } else {
        nullBitmap[i / 8] |= (1 << (i & 7));
      }
    }

    // padding null-bitmap content
    packet.setBytes(pos, nullBitmap);
  }

  // set payload length
  int payloadLength = packet.writerIndex() - packetStartIdx - 4;
  packet.setMediumLE(packetStartIdx, payloadLength);

  sendPacket(packet, payloadLength);
}