Java Code Examples for io.vertx.sqlclient.Tuple

The following examples show how to use io.vertx.sqlclient.Tuple. These examples are extracted from open source projects. 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
@Test
public void testCustomType(TestContext ctx) {
  Async async = ctx.async();
  String expected = "Anytown";
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn
      .query("SELECT (address).city FROM \"CustomDataType\"").execute(ctx.asyncAssertSuccess(result -> {
        ctx.assertEquals(2, result.size());
        Row row = result.iterator().next();
        ColumnChecker.checkColumn(0, "city")
          .returns(Tuple::getValue, Row::getValue, expected)
          .returns(Tuple::getString, Row::getString, expected)
          .forRow(row);
        async.complete();
      }));
  }));
}
 
Example 2
@Test
public void testBufferArray(TestContext ctx) {
  Random r = new Random();
  int len = 2048;
  byte[] bytes = new byte[len];
  r.nextBytes(bytes);
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("SELECT ARRAY[$1::BYTEA] \"Bytea\"",
      ctx.asyncAssertSuccess(p -> {
        p.query().execute(Tuple.of(Buffer.buffer(bytes)), ctx.asyncAssertSuccess(result -> {
          ColumnChecker.checkColumn(0, "Bytea")
            .returns(Tuple::getValue, Row::getValue, new Buffer[]{Buffer.buffer(bytes)})
            .returns(Tuple::getBufferArray, Row::getBufferArray, new Buffer[]{Buffer.buffer(bytes)})
            .forRow(result.iterator().next());
          async.complete();
        }));
      }));
  }));
}
 
Example 3
Source Project: vertx-sql-client   Source File: QueryExecutor.java    License: Apache License 2.0 6 votes vote down vote up
void executeExtendedQuery(CommandScheduler scheduler, String sql, boolean autoCommit, Tuple arguments, Promise<L> promise) {
  ContextInternal context = (ContextInternal) promise.future().context();
  Object payload;
  if (tracer != null) {
    payload = tracer.sendRequest(context, sql, arguments);
  } else {
    payload = null;
  }
  Object metric;
  if (metrics != null) {
    metric = metrics.requestBegin(sql, sql);
    metrics.requestEnd(metric);
  } else {
    metric = null;
  }
  QueryResultBuilder handler = this.createHandler(promise, payload, metric);
  ExtendedQueryCommand cmd = createExtendedQueryCommand(sql, autoCommit, arguments, handler);
  scheduler.schedule(cmd, handler);
}
 
Example 4
Source Project: vertx-sql-client   Source File: PgClientTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleQuery(TestContext ctx) {
  Async async = ctx.async();
  connector.accept(ctx.asyncAssertSuccess(conn -> {
    conn.query("SELECT id, message from FORTUNE LIMIT 1;SELECT message, id from FORTUNE LIMIT 1")
      .execute(ctx.asyncAssertSuccess(result1 -> {
      ctx.assertEquals(1, result1.size());
      ctx.assertEquals(Arrays.asList("id", "message"), result1.columnsNames());
      Tuple row1 = result1.iterator().next();
      ctx.assertTrue(row1.getValue(0) instanceof Integer);
      ctx.assertTrue(row1.getValue(1) instanceof String);
      RowSet<Row> result2 = result1.next();
      ctx.assertNotNull(result2);
      ctx.assertEquals(1, result2.size());
      ctx.assertEquals(Arrays.asList("message", "id"), result2.columnsNames());
      Tuple row2 = result2.iterator().next();
      ctx.assertTrue(row2.getValue(0) instanceof String);
      ctx.assertTrue(row2.getValue(1) instanceof Integer);
      ctx.assertNull(result2.next());
      async.complete();
    }));
  }));
}
 
Example 5
Source Project: vertx-auth   Source File: SqlUserUtilImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SqlUserUtil createHashedUser(String username, String hash, Handler<AsyncResult<Void>> resultHandler) {
  if (username == null || hash == null) {
    resultHandler.handle(Future.failedFuture("username or password hash are null"));
    return this;
  }

  client.preparedQuery(insertUser).execute(Tuple.of(username, hash), prepare -> {
    if (prepare.succeeded()) {
      resultHandler.handle(Future.succeededFuture());
    } else {
      resultHandler.handle(Future.failedFuture(prepare.cause()));
    }
  });
  return this;
}
 
Example 6
Source Project: vertx-sql-client   Source File: PgPoolTestBase.java    License: Apache License 2.0 6 votes vote down vote up
private void testQueryWithParams(TestContext ctx, PgConnectOptions options) {
  int num = 2;
  Async async = ctx.async(num);
  PgPool pool = createPool(options, 1);
  for (int i = 0;i < num;i++) {
    pool.preparedQuery("SELECT id, randomnumber from WORLD where id=$1").execute(Tuple.of(i + 1), ar -> {
      if (ar.succeeded()) {
        SqlResult result = ar.result();
        ctx.assertEquals(1, result.size());
      } else {
        ar.cause().printStackTrace();
        ctx.assertEquals("closed", ar.cause().getMessage());
      }
      async.countDown();
    });
  }
}
 
Example 7
Source Project: vertx-sql-client   Source File: PgPoolTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateWithParams(TestContext ctx) {
  int num = 1000;
  Async async = ctx.async(num);
  PgPool pool = createPool(options, 4);
  for (int i = 0;i < num;i++) {
    pool.preparedQuery("UPDATE Fortune SET message = 'Whatever' WHERE id = $1").execute(Tuple.of(9), ar -> {
      if (ar.succeeded()) {
        SqlResult result = ar.result();
        ctx.assertEquals(1, result.rowCount());
      } else {
        ctx.assertEquals("closed", ar.cause().getMessage());
      }
      async.countDown();
    });
  }
}
 
Example 8
@Test
public void testEncodeUUID(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"CharacterDataType\" SET \"uuid\" = $1 WHERE \"id\" = $2 RETURNING \"uuid\"",
      ctx.asyncAssertSuccess(p -> {
        UUID uuid = UUID.fromString("92b53cf1-2ad0-49f9-be9d-ca48966e43ee");
        p.query().execute(Tuple.tuple()
          .addUUID(uuid)
          .addInteger(2), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          ctx.assertEquals(1, result.rowCount());
          Row row = result.iterator().next();
          ColumnChecker.checkColumn(0, "uuid")
            .returns(Tuple::getValue, Row::getValue, uuid)
            .returns(Tuple::getUUID, Row::getUUID, uuid)
            .forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example 9
@Test
public void testEncodeTimeTz(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"TemporalDataType\" SET \"TimeTz\" = $1 WHERE \"id\" = $2 RETURNING \"TimeTz\"",
      ctx.asyncAssertSuccess(p -> {
        OffsetTime ot = OffsetTime.parse("20:55:04.905120+03:07");
        p.query().execute(Tuple.tuple()
          .addOffsetTime(ot)
          .addInteger(2), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          ctx.assertEquals(1, result.rowCount());
          Row row = result.iterator().next();
          ColumnChecker.checkColumn(0, "TimeTz")
            .returns(Tuple::getValue, Row::getValue, ot)
            .returns(Tuple::getOffsetTime, Row::getOffsetTime, ot)
            .returns(Tuple::getTemporal, Row::getTemporal, ot)
            .forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example 10
@Test
public void testDecodeInt4(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("SELECT $1 :: INT4 \"Integer\"",
      ctx.asyncAssertSuccess(p -> {
        p.query().execute(Tuple.tuple().addInteger(Integer.MAX_VALUE), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          ctx.assertEquals(1, result.rowCount());
          Row row = result.iterator().next();
          ColumnChecker.checkColumn(0, "Integer")
            .returns(Tuple::getValue, Row::getValue, Integer.MAX_VALUE)
            .returns(Tuple::getShort, Row::getShort, (short) -1)
            .returns(Tuple::getInteger, Row::getInteger, Integer.MAX_VALUE)
            .returns(Tuple::getLong, Row::getLong, 2147483647L)
            .returns(Tuple::getFloat, Row::getFloat, 2147483647f)
            .returns(Tuple::getDouble, Row::getDouble, 2147483647d)
            .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(2147483647))
            .returns(Numeric.class, Numeric.create(2147483647))
            .forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example 11
Source Project: vertx-sql-client   Source File: DB2DataTypeTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * DB2 has no BYTE or BOOLEAN column type, and instead maps it to a
 * 2-byte SMALLINT column type. This means Java byte types must be
 * converted into SMALLINT formats
 */
@Test
public void testByteIntoSmallIntColumn(TestContext ctx) {
    connect(ctx.asyncAssertSuccess(conn -> {
        conn.preparedQuery("INSERT INTO db2_types (id,test_byte) VALUES (?, ?)")
          .execute(Tuple.of(2, (byte) 0xCA), ctx.asyncAssertSuccess(insertResult -> {
             conn.preparedQuery("SELECT id,test_byte FROM db2_types WHERE id = 2")
               .execute(ctx.asyncAssertSuccess(rows -> {
                 ctx.assertEquals(1, rows.size());
                 Row row = rows.iterator().next();
                 ctx.assertEquals(2, row.getInteger(0));
                 ctx.assertEquals((byte) 0xCA, row.get(Byte.class, 1));
               }));
          }));
      }));
}
 
Example 12
@Test
public void testEncodeTime(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE  \"TemporalDataType\" SET \"Time\" = $1 WHERE \"id\" = $2 RETURNING \"Time\"",
      ctx.asyncAssertSuccess(p -> {
        LocalTime lt = LocalTime.parse("22:55:04.905120");
        p.query().execute(Tuple.tuple()
            .addLocalTime(lt)
            .addInteger(2)
          , ctx.asyncAssertSuccess(result -> {
            ctx.assertEquals(1, result.size());
            ctx.assertEquals(1, result.rowCount());
            Row row = result.iterator().next();
            ColumnChecker.checkColumn(0, "Time")
              .returns(Tuple::getValue, Row::getValue, lt)
              .returns(Tuple::getLocalTime, Row::getLocalTime, lt)
              .returns(Tuple::getTemporal, Row::getTemporal, lt)
              .forRow(row);
            async.complete();
          }));
      }));
  }));
}
 
Example 13
Source Project: vertx-sql-client   Source File: SqlClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void usingConnections03(SqlConnection connection) {
  connection.prepare("INSERT INTO USERS (id, name) VALUES ($1, $2)", ar1 -> {
    if (ar1.succeeded()) {
      PreparedStatement prepared = ar1.result();

      // Create a query : bind parameters
      List<Tuple> batch = new ArrayList();

      // Add commands to the createBatch
      batch.add(Tuple.of("julien", "Julien Viet"));
      batch.add(Tuple.of("emad", "Emad Alblueshi"));
      batch.add(Tuple.of("andy", "Andy Guibert"));

      prepared.query().executeBatch(batch, res -> {
        if (res.succeeded()) {

          // Process rows
          RowSet<Row> rows = res.result();
        } else {
          System.out.println("Batch failed " + res.cause());
        }
      });
    }
  });
}
 
Example 14
Source Project: raml-module-builder   Source File: PostgresClient.java    License: Apache License 2.0 6 votes vote down vote up
<T> void doStreamGetQuery(SQLConnection connection, QueryHelper queryHelper,
                          ResultInfo resultInfo, Class<T> clazz,
                          Handler<AsyncResult<PostgresClientStreamResult<T>>> replyHandler) {
  // decide if we need to close transaction+connection ourselves
  final PgConnection closeConnection = connection.tx == null ? connection.conn : null;
  if (closeConnection != null) {
    closeConnection.begin();
  }
  connection.conn.prepare(queryHelper.selectQuery, prepareRes -> {
    if (prepareRes.failed()) {
      connection.conn.close();
      log.error(prepareRes.cause().getMessage(), prepareRes.cause());
      replyHandler.handle(Future.failedFuture(prepareRes.cause()));
      return;
    }
    PreparedStatement pq = prepareRes.result();
    RowStream<Row> stream = pq.createStream(STREAM_GET_DEFAULT_CHUNK_SIZE, Tuple.tuple());
    PostgresClientStreamResult<T> streamResult = new PostgresClientStreamResult(resultInfo);
    doStreamRowResults(stream, clazz, closeConnection, queryHelper,
        streamResult, replyHandler);
  });
}
 
Example 15
@Test
public void testDecodeSerial8(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("SELECT \"BigSerial\" FROM \"NumericDataType\" WHERE \"id\" = $1",
      ctx.asyncAssertSuccess(p -> {
        p.query().execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          ctx.assertEquals(1, result.rowCount());
          Row row = result.iterator().next();
          ColumnChecker.checkColumn(0, "BigSerial")
            .returns(Tuple::getValue, Row::getValue, 1L)
            .returns(Tuple::getShort, Row::getShort, (short) 1)
            .returns(Tuple::getInteger, Row::getInteger, 1)
            .returns(Tuple::getLong, Row::getLong, 1L)
            .returns(Tuple::getFloat, Row::getFloat, 1f)
            .returns(Tuple::getDouble, Row::getDouble, 1d)
            .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(1))
            .returns(Numeric.class, Numeric.create(1))
            .forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example 16
@Test
public void testEncodeEnumArrayEmptyValues(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"ArrayDataType\" SET \"Enum\" = $1 WHERE \"id\" = $2 RETURNING \"Enum\", \"Boolean\"",
      ctx.asyncAssertSuccess(p -> {
        p.query().execute(Tuple.tuple()
            .addStringArray(new String[]{})
            .addInteger(2)
          , ctx.asyncAssertSuccess(result -> {
            ColumnChecker.checkColumn(0, "Enum")
              .returns(Tuple::getValue, Row::getValue, new String[]{})
              .returns(Tuple::getStringArray, Row::getStringArray, new String[]{})
              .forRow(result.iterator().next());
            ColumnChecker.checkColumn(1, "Boolean")
              .returns(Tuple::getValue, Row::getValue, new Boolean[]{true})
              .returns(Tuple::getBooleanArray, Row::getBooleanArray, new Boolean[]{true})
              .forRow(result.iterator().next());
            async.complete();
          }));
      }));
  }));
}
 
Example 17
Source Project: vertx-sql-client   Source File: MySQLQueryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCachePreparedStatementBatchWithSameSql(TestContext ctx) {
  MySQLConnection.connect(vertx, options.setCachePreparedStatements(true), ctx.asyncAssertSuccess(conn -> {
    conn.query("SHOW VARIABLES LIKE 'max_prepared_stmt_count'").execute(ctx.asyncAssertSuccess(res1 -> {
      Row row = res1.iterator().next();
      int maxPreparedStatementCount = Integer.parseInt(row.getString(1));
      ctx.assertEquals("max_prepared_stmt_count", row.getString(0));
      ctx.assertEquals(16382, maxPreparedStatementCount);

      for (int i = 0; i < 20000; i++) {
        int val = i * 1000;
        List<Tuple> tuples = new ArrayList<>();
        tuples.add(Tuple.of(val));
        tuples.add(Tuple.of(val + 1));
        conn.preparedQuery("Select cast(? AS CHAR)").executeBatch(tuples, ctx.asyncAssertSuccess(res2 -> {
          String v1 = res2.iterator().next().getString(0);
          String v2 = res2.next().iterator().next().getString(0);
          ctx.assertEquals("" + val, v1);
          ctx.assertEquals("" + (val + 1), v2);
        }));
      }
    }));
  }));
}
 
Example 18
@Test
public void testEncodeLocalTimeArray(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"ArrayDataType\" SET \"LocalTime\" = $1  WHERE \"id\" = $2 RETURNING \"LocalTime\"",
      ctx.asyncAssertSuccess(p -> {
        final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss.SSSSS");
        final LocalTime dt = LocalTime.parse("17:55:04.90512", dtf);
        p.query().execute(Tuple.tuple()
            .addLocalTimeArray(new LocalTime[]{dt})
            .addInteger(2)
          , ctx.asyncAssertSuccess(result -> {
            ColumnChecker.checkColumn(0, "LocalTime")
              .returns(Tuple::getValue, Row::getValue, new LocalTime[]{dt})
              .returns(Tuple::getLocalTimeArray, Row::getLocalTimeArray, new LocalTime[]{dt})
              .forRow(result.iterator().next());
            async.complete();
          }));
      }));
  }));
}
 
Example 19
@Test
public void testEncodeIntervalArray(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"ArrayDataType\" SET \"Interval\" = $1  WHERE \"id\" = $2 RETURNING \"Interval\"",
      ctx.asyncAssertSuccess(p -> {
        Interval[] intervals = new Interval[]{
          Interval.of().years(10).months(3).days(332).hours(20).minutes(20).seconds(20).microseconds(999991),
          Interval.of().minutes(20).seconds(20).microseconds(123456),
          Interval.of().years(-2).months(-6),
          Interval.of()
        };
        p.query().execute(Tuple.tuple()
            .addValue(intervals)
            .addInteger(2)
          , ctx.asyncAssertSuccess(result -> {
            ColumnChecker.checkColumn(0, "Interval")
              .returns(Tuple::getValue, Row::getValue, intervals)
              .returns(Interval.class, intervals)
              .forRow(result.iterator().next());
            async.complete();
          }));
      }));
  }));
}
 
Example 20
@Test
public void testEncodeLargeVarchar(TestContext ctx) {
  int len = 2048;
  StringBuilder builder = new StringBuilder();
  for (int i = 0; i < len; i++) {
    builder.append((char) ('A' + (i % 26)));
  }
  String value = builder.toString();
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("SELECT $1::VARCHAR(" + len + ")",
      ctx.asyncAssertSuccess(p -> {
        p.query().execute(Tuple.of(value), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(value, result.iterator().next().getString(0));
          async.complete();
        }));
      }));
  }));
}
 
Example 21
Source Project: raml-module-builder   Source File: PostgresClient.java    License: 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 22
Source Project: vertx-sql-client   Source File: JsonBinaryCodecTest.java    License: Apache License 2.0 6 votes vote down vote up
private void testEncodeJson(TestContext ctx, Tuple params, Object expected, Consumer<Row> checker, String insertScript) {
  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.preparedQuery(CREATE_TABLE).execute(ctx.asyncAssertSuccess(createTable -> {
      conn.preparedQuery(insertScript).execute(params, ctx.asyncAssertSuccess(insert -> {
        conn.preparedQuery(QUERY_JSON).execute(ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          Row row = result.iterator().next();
          ctx.assertEquals(expected, row.getValue(0));
          ctx.assertEquals(expected, row.getValue("json"));
          if (checker != null) {
            checker.accept(row);
          }
          conn.close();
        }));
      }));
    }));
  }));
}
 
Example 23
Source Project: vertx-sql-client   Source File: DB2DataTypeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUUID(TestContext ctx) {
  UUID uuid = UUID.randomUUID();
  connect(ctx.asyncAssertSuccess(conn -> {
    conn.preparedQuery("INSERT INTO db2_types (id,test_vchar) VALUES (?,?)").execute(Tuple.of(6, uuid),
        ctx.asyncAssertSuccess(insertResult -> {
          conn.preparedQuery("SELECT id,test_vchar FROM db2_types WHERE id = ?").execute(Tuple.of(6),
              ctx.asyncAssertSuccess(rows -> {
                ctx.assertEquals(1, rows.size());
                Row row = rows.iterator().next();
                ctx.assertEquals(6, row.getInteger(0));
                ctx.assertEquals(uuid, row.getUUID(1));
                ctx.assertEquals(uuid, row.getUUID("test_vchar"));
                ctx.assertEquals(uuid, row.get(UUID.class, 1));
              }));
        }));
  }));
}
 
Example 24
@Test
public void testEncodeDateBeforePgEpoch(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"TemporalDataType\" SET \"Date\" = $1 WHERE \"id\" = $2 RETURNING \"Date\"",
      ctx.asyncAssertSuccess(p -> {
        LocalDate ld = LocalDate.parse("1981-06-30");
        p.query().execute(Tuple.tuple()
          .addLocalDate(ld)
          .addInteger(1), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          ctx.assertEquals(1, result.rowCount());
          Row row = result.iterator().next();
          ColumnChecker.checkColumn(0, "Date")
            .returns(Tuple::getValue, Row::getValue, ld)
            .returns(Tuple::getLocalDate, Row::getLocalDate, ld)
            .returns(Tuple::getTemporal, Row::getTemporal, ld)
            .forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example 25
Source Project: vertx-sql-client   Source File: PgConnectionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchUpdate(TestContext ctx) {
  Async async = ctx.async();
  connector.accept(ctx.asyncAssertSuccess(conn -> {
    deleteFromTestTable(ctx, conn, () -> {
      insertIntoTestTable(ctx, conn, 10, () -> {
        conn.prepare("UPDATE Test SET val=$1 WHERE id=$2", ctx.asyncAssertSuccess(ps -> {
          List<Tuple> batch = new ArrayList<>();
          batch.add(Tuple.of("val0", 0));
          batch.add(Tuple.of("val1", 1));
          ps.query().executeBatch(batch, ctx.asyncAssertSuccess(result -> {
            for (int i = 0;i < 2;i++) {
              ctx.assertEquals(1, result.rowCount());
              result = result.next();
            }
            ctx.assertNull(result);
            ps.close(ctx.asyncAssertSuccess(v -> {
              async.complete();
            }));
          }));
        }));
      });
    });
  }));
}
 
Example 26
@Test
public void testDecodeBooleanArray(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("SELECT \"Boolean\" FROM \"ArrayDataType\" WHERE \"id\" = $1",
      ctx.asyncAssertSuccess(p -> {
        p.query().execute(Tuple.tuple()
          .addInteger(1), ctx.asyncAssertSuccess(result -> {
          ColumnChecker.checkColumn(0, "Boolean")
            .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new boolean[]{Boolean.TRUE}))
            .returns(Tuple::getBooleanArray, Row::getBooleanArray, ColumnChecker.toObjectArray(new boolean[]{Boolean.TRUE}))
            .forRow(result.iterator().next());
          async.complete();
        }));
      }));
  }));
}
 
Example 27
Source Project: vertx-sql-client   Source File: TsTypesExtendedCodecTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_tsvector_array(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("SELECT c \"TsVector\" FROM ( VALUES ( ARRAY[to_tsvector ('english', $1 ), to_tsvector ('english', $2 )] )) as t (c) GROUP BY c",
      ctx.asyncAssertSuccess(p -> {
        p.query().execute(Tuple.tuple()
          .addString("postgraduate")
          .addString("a fat cat sat on a mat and ate a fat rat"), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          ctx.assertEquals(1, result.rowCount());
          Row row = result.iterator().next();
          String[] expected = new String[]{"'postgradu':1", "'ate':9 'cat':3 'fat':2,11 'mat':7 'rat':12 'sat':4"};
          ColumnChecker.checkColumn(0, "TsVector")
            .returns(Tuple::getStringArray, Row::getStringArray, expected)
            .returns(Tuple::getValue, Row::getValue, expected)
            .forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example 28
Source Project: vertx-sql-client   Source File: PgClientTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBatchSelect(TestContext ctx) {
  Async async = ctx.async();
  connector.accept(ctx.asyncAssertSuccess(conn -> {
    List<Tuple> batch = new ArrayList<>();
    batch.add(Tuple.tuple());
    batch.add(Tuple.tuple());
    conn
      .preparedQuery("SELECT count(id) FROM World")
      .executeBatch(batch, ctx.asyncAssertSuccess(result -> {
      ctx.assertEquals(result.size(), result.next().size());
      async.complete();
    }));
  }));
}
 
Example 29
@Override
public CompletionStage<Long> selectLong(String sql, Object[] paramValues) {
	return preparedQuery( sql, Tuple.wrap( paramValues ) )
			.thenApply( rowSet -> {
				for (Row row: rowSet) {
					return row.getLong(0);
				}
				return null;
			} );
}
 
Example 30
@Test
public void testDecodeNullBigInt(TestContext ctx) {
  testDecodeNullValue(ctx, "test_bigint", row -> {
    ColumnChecker.checkColumn(0, "test_bigint")
      .returns(Tuple::getValue, Row::getValue, LONG_NULL_VALUE)
      .returns(Tuple::getLong, Row::getLong, LONG_NULL_VALUE)
      .returns(Long.class, LONG_NULL_VALUE)
      .forRow(row);
  });
}