use of io.vertx.sqlclient.Row in project vertx-examples by vert-x3.
the class SqlClientExample method start.
@Override
public void start() {
Pool pool = PgPool.pool(vertx, new PgConnectOptions().setPort(5432).setHost("the-host").setDatabase("the-db").setUser("user").setPassword("secret"), new PoolOptions().setMaxSize(4));
// Uncomment for MySQL
// Pool pool = MySQLPool.pool(vertx, new MySQLConnectOptions()
// .setPort(5432)
// .setHost("the-host")
// .setDatabase("the-db")
// .setUser("user")
// .setPassword("secret"), new PoolOptions().setMaxSize(4));
pool.getConnection(res1 -> {
if (res1.failed()) {
System.err.println(res1.cause().getMessage());
return;
}
SqlConnection connection = res1.result();
// create a test table
connection.query("create table test(id int primary key, name varchar(255))").execute(res2 -> {
if (res2.failed()) {
connection.close();
System.err.println("Cannot create the table");
res2.cause().printStackTrace();
return;
}
// insert some test data
connection.query("insert into test values (1, 'Hello'), (2, 'World')").execute(res3 -> {
// query some data with arguments
connection.preparedQuery("select * from test where id = ?").execute(Tuple.of(2), rs -> {
if (rs.failed()) {
System.err.println("Cannot retrieve the data from the database");
rs.cause().printStackTrace();
return;
}
for (Row line : rs.result()) {
System.out.println("" + line);
}
// and close the connection
connection.close();
});
});
});
});
}
use of io.vertx.sqlclient.Row in project raml-module-builder by folio-org.
the class PostgresClientIT method selectReturnOneRow.
@Test
public void selectReturnOneRow(TestContext context) {
List<String> columns = new LinkedList<>();
columns.add("field");
RowDesc rowDesc = new RowDesc(columns);
List<Row> rows = new LinkedList<>();
Row row = new RowImpl(rowDesc);
row.addString("value");
rows.add(row);
RowSet rowSet = new LocalRowSet(1).withColumns(columns).withRows(rows);
Promise<RowSet<Row>> promise = Promise.promise();
promise.complete(rowSet);
PostgresClient.selectReturn(promise.future(), context.asyncAssertSuccess(res -> context.assertEquals("value", res.getString(0))));
}
use of io.vertx.sqlclient.Row in project raml-module-builder by folio-org.
the class PostgresClientIT method streamGetResultException.
@Test
public void streamGetResultException(TestContext context) {
createTableWithPoLines(context);
ResultInfo resultInfo = new ResultInfo();
context.assertNotNull(vertx);
RowStream<Row> sqlRowStream = new MySQLRowStream();
StringBuilder events = new StringBuilder();
Async async = context.async();
PostgresClientStreamResult<Object> streamResult = new PostgresClientStreamResult(resultInfo);
Transaction transaction = null;
postgresClient.doStreamRowResults(sqlRowStream, Object.class, transaction, new QueryHelper("table_name"), streamResult, context.asyncAssertSuccess(sr -> {
sr.handler(streamHandler -> {
events.append("[handler]");
});
sr.endHandler(x -> {
events.append("[endHandler]");
throw new NullPointerException("null");
});
sr.exceptionHandler(x -> {
events.append("[exception]");
context.assertEquals("SQLRowStream exception", x.getMessage());
async.complete();
});
}));
async.await(1000);
context.assertEquals("[exception]", events.toString());
}
use of io.vertx.sqlclient.Row in project raml-module-builder by folio-org.
the class PostgresClient method getById.
/**
* Get jsonb by id for a list of ids.
* <p>
* The result is a map of all found records where the key is the id
* and the value is the jsonb.
*
* @param table the table to search in
* @param ids the values of the id field
* @param function how to convert the (String encoded) JSON
* @param replyHandler the result after applying function
*/
private <R> void getById(String table, JsonArray ids, FunctionWithException<String, R, Exception> function, Handler<AsyncResult<Map<String, R>>> replyHandler) {
if (ids == null || ids.isEmpty()) {
replyHandler.handle(Future.succeededFuture(Collections.emptyMap()));
return;
}
getConnection(res -> {
if (res.failed()) {
replyHandler.handle(Future.failedFuture(res.cause()));
return;
}
Tuple list = Tuple.tuple();
for (int i = 0; i < ids.size(); i++) {
list.addUUID(UUID.fromString(ids.getString(i)));
}
PgConnection connection = res.result();
StringBuilder sql = new StringBuilder().append(SELECT).append(ID_FIELD).append(", ").append(DEFAULT_JSONB_FIELD_NAME).append(FROM).append(schemaName).append(DOT).append(table).append(WHERE).append(ID_FIELD).append(" IN ($1");
for (int i = 2; i <= ids.size(); i++) {
sql.append(", $" + i);
}
sql.append(")");
connection.preparedQuery(sql.toString()).execute(list, query -> {
connection.close();
if (query.failed()) {
replyHandler.handle(Future.failedFuture(query.cause()));
return;
}
try {
Map<String, R> result = new HashMap<>();
Iterator<Row> iterator = query.result().iterator();
while (iterator.hasNext()) {
Row row = iterator.next();
result.put(row.getValue(0).toString(), function.apply(row.getValue(1).toString()));
}
replyHandler.handle(Future.succeededFuture(result));
} catch (Exception e) {
replyHandler.handle(Future.failedFuture(e));
}
});
});
}
use of io.vertx.sqlclient.Row in project raml-module-builder by folio-org.
the class PostgresClientMockTest method testGetById.
@Test
public void testGetById(TestContext context) {
String table = "a";
String id = UUID.randomUUID().toString();
PostgresClient pc = spy(PostgresClient.testClient());
// mock empty query result
@SuppressWarnings("unchecked") RowSet<Row> mockRowSet = mock(RowSet.class);
when(mockRowSet.size()).thenReturn(0);
@SuppressWarnings("unchecked") PreparedQuery<RowSet<Row>> mockPreparedQuery = mock(PreparedQuery.class);
when(mockPreparedQuery.execute(any(Tuple.class))).thenReturn(Future.succeededFuture(mockRowSet));
PgConnection mockPgConnection = mock(PgConnection.class);
when(mockPgConnection.preparedQuery(anyString())).thenReturn(mockPreparedQuery);
PgPool mockPgPool = mock(PgPool.class);
when(mockPgPool.getConnection()).thenReturn(Future.succeededFuture(mockPgConnection));
when(pc.getClient()).thenReturn(mockPgPool);
SQLConnection mockSQLConnection = new SQLConnection(mockPgConnection, null, null);
AsyncResult<SQLConnection> mockConn = Future.succeededFuture(mockSQLConnection);
// tests
pc.getByIdAsString(table, id, context.asyncAssertSuccess());
pc.getByIdAsString(mockConn, table, id, context.asyncAssertSuccess());
pc.getByIdAsStringForUpdate(mockConn, table, id, context.asyncAssertSuccess());
pc.getById(table, id, context.asyncAssertSuccess());
pc.getById(mockConn, table, id, context.asyncAssertSuccess());
pc.getByIdForUpdate(mockConn, table, id, context.asyncAssertSuccess());
pc.getById(table, id, Map.class, context.asyncAssertSuccess());
pc.getById(mockConn, table, id, Map.class, context.asyncAssertSuccess());
pc.getByIdForUpdate(mockConn, table, id, Map.class, context.asyncAssertSuccess());
// mock query result
String jsonString = "{\"id\": \"abc\"}";
when(mockRowSet.size()).thenReturn(1);
@SuppressWarnings("unchecked") RowIterator<Row> mockRowIterator = mock(RowIterator.class);
Row mockRow = mock(Row.class);
when(mockRowSet.iterator()).thenReturn(mockRowIterator);
when(mockRowIterator.next()).thenReturn(mockRow);
when(mockRow.getValue(anyInt())).thenReturn(jsonString);
// tests
pc.getByIdAsString(table, id, assertGetByIdAsString(context));
pc.getByIdAsString(mockConn, table, id, assertGetByIdAsString(context));
pc.getByIdAsStringForUpdate(mockConn, table, id, assertGetByIdAsString(context));
pc.getById(table, id, assertGetByIdAsJson(context));
pc.getById(mockConn, table, id, assertGetByIdAsJson(context));
pc.getByIdForUpdate(mockConn, table, id, assertGetByIdAsJson(context));
pc.getById(table, id, Map.class, assertGetByIdAsObject(context));
pc.getById(mockConn, table, id, Map.class, assertGetByIdAsObject(context));
pc.getByIdForUpdate(mockConn, table, id, Map.class, assertGetByIdAsObject(context));
// test exceptions
pc.getByIdAsString(Future.failedFuture("fail"), table, id, context.asyncAssertFailure());
when(mockPgPool.getConnection()).thenReturn(Future.failedFuture("fail"));
pc.getByIdAsString(table, id, context.asyncAssertFailure());
when(mockPreparedQuery.execute(any(Tuple.class))).thenReturn(Future.failedFuture("fail"));
pc.getByIdAsString(mockConn, table, id, context.asyncAssertFailure());
when(mockPreparedQuery.execute(any(Tuple.class))).thenReturn(Future.succeededFuture(mockRowSet));
when(mockRow.getValue(anyInt())).thenThrow(new RuntimeException("fail"));
pc.getByIdAsString(mockConn, table, id, context.asyncAssertFailure());
pc.getByIdAsString(mockConn, table, "1", context.asyncAssertFailure());
}
Aggregations