Java Code Examples for io.vertx.ext.sql.ResultSet

The following examples show how to use io.vertx.ext.sql.ResultSet. 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
Source Project: prebid-server-java   Source File: BasicJdbcClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> Future<T> executeQuery(String query, List<Object> params, Function<ResultSet, T> mapper,
                                  Timeout timeout) {
    final long remainingTimeout = timeout.remaining();
    if (remainingTimeout <= 0) {
        return Future.failedFuture(timeoutException());
    }
    final long startTime = clock.millis();
    final Promise<ResultSet> queryResultPromise = Promise.promise();

    // timeout implementation is inspired by this answer:
    // https://groups.google.com/d/msg/vertx/eSf3AQagGGU/K7pztnjLc_EJ
    final long timerId = vertx.setTimer(remainingTimeout, id -> timedOutResult(queryResultPromise, startTime));

    final Promise<SQLConnection> connectionPromise = Promise.promise();
    jdbcClient.getConnection(connectionPromise);
    connectionPromise.future()
            .recover(BasicJdbcClient::logConnectionError)
            .compose(connection -> makeQuery(connection, query, params))
            .setHandler(result -> handleResult(result, queryResultPromise, timerId, startTime));

    return queryResultPromise.future().map(mapper);
}
 
Example 2
public static StoredResponseDataResult map(ResultSet resultSet, Set<String> responseIds) {
    final Map<String, String> storedIdToResponse = new HashMap<>(responseIds.size());
    final List<String> errors = new ArrayList<>();

    if (resultSet == null || CollectionUtils.isEmpty(resultSet.getResults())) {
        handleEmptyResultError(responseIds, errors);
    } else {
        try {
            for (JsonArray result : resultSet.getResults()) {
                storedIdToResponse.put(result.getString(0), result.getString(1));
            }
        } catch (IndexOutOfBoundsException e) {
            errors.add("Result set column number is less than expected");
            return StoredResponseDataResult.of(Collections.emptyMap(), errors);
        }
        errors.addAll(responseIds.stream().filter(id -> !storedIdToResponse.containsKey(id))
                .map(id -> String.format("No stored response found for id: %s", id))
                .collect(Collectors.toList()));
    }

    return StoredResponseDataResult.of(storedIdToResponse, errors);
}
 
Example 3
Source Project: prebid-server-java   Source File: BasicJdbcClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void executeQueryShouldReturnFailedFutureIfConnectionAcquisitionFails() {
    // given
    given(vertx.setTimer(anyLong(), any())).willReturn(123L);

    givenGetConnectionReturning(Future.failedFuture(new RuntimeException("Failed to acquire connection")));

    // when
    final Future<ResultSet> future = jdbcClient.executeQuery("query", emptyList(), identity(), timeout);

    // then
    verify(vertx).cancelTimer(eq(123L));

    assertThat(future.failed()).isTrue();
    assertThat(future.cause()).isInstanceOf(RuntimeException.class).hasMessage("Failed to acquire connection");
}
 
Example 4
Source Project: prebid-server-java   Source File: BasicJdbcClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void executeQueryShouldReturnFailedFutureIfQueryFails() {
    // given
    given(vertx.setTimer(anyLong(), any())).willReturn(123L);

    final SQLConnection connection = mock(SQLConnection.class);
    givenGetConnectionReturning(Future.succeededFuture(connection));

    givenQueryReturning(connection, Future.failedFuture(new RuntimeException("Failed to execute query")));

    // when
    final Future<ResultSet> future = jdbcClient.executeQuery("query", emptyList(), identity(), timeout);

    // then
    verify(vertx).cancelTimer(eq(123L));

    assertThat(future.failed()).isTrue();
    assertThat(future.cause()).isInstanceOf(RuntimeException.class).hasMessage("Failed to execute query");
}
 
Example 5
Source Project: prebid-server-java   Source File: BasicJdbcClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void executeQueryShouldReturnSucceededFutureWithMappedQueryResult() {
    // given
    given(vertx.setTimer(anyLong(), any())).willReturn(123L);

    final SQLConnection connection = mock(SQLConnection.class);
    givenGetConnectionReturning(Future.succeededFuture(connection));

    givenQueryReturning(connection, Future.succeededFuture(
            new ResultSet().setResults(singletonList(new JsonArray().add("value")))));

    // when
    final Future<String> future = jdbcClient.executeQuery("query", emptyList(),
            resultSet -> resultSet.getResults().get(0).getString(0), timeout);

    // then
    verify(vertx).cancelTimer(eq(123L));

    assertThat(future.succeeded()).isTrue();
    assertThat(future.result()).isEqualTo("value");
}
 
Example 6
Source Project: redpipe   Source File: WikiResource.java    License: Apache License 2.0 6 votes vote down vote up
@GET
public Single<Template> index(){
	return fiber((con) -> {
		ResultSet res = await(con.rxQuery(SQL.SQL_ALL_PAGES));
		List<String> pages = res.getResults()
				.stream()
				.map(json -> json.getString(0))
				.sorted()
				.collect(Collectors.toList());
		boolean canCreatePage = await(user.rxIsAuthorised("create"));
		return new Template("templates/index.ftl")
				.set("title", "Wiki home")
				.set("pages", pages)
				.set("canCreatePage", canCreatePage)
				.set("username", getUserName())
				.set("backup_gist_url", flash.get("backup_gist_url"));
	});
}
 
Example 7
Source Project: microtrader   Source File: AuditVerticleTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testStockTradesPersisted(TestContext context) throws ClassNotFoundException {
    Async async = context.async();
    JsonObject jdbcConfig = new JsonObject(config.getObject("jdbc").render(ConfigRenderOptions.concise()));
    JDBCClient jdbc = JDBCClient.createNonShared(vertx, jdbcConfig);
    Class.forName(jdbcConfig.getString("driverclass"));

    jdbc.getConnection(ar -> {
        SQLConnection connection = ar.result();
        if (ar.failed()) {
            context.fail(ar.cause());
        } else {
            connection.query(SELECT_STATEMENT, result -> {
                ResultSet set = result.result();
                List<JsonObject> operations = set.getRows().stream()
                        .map(json -> new JsonObject(json.getString("OPERATION")))
                        .collect(Collectors.toList());
                context.assertTrue(operations.size() >= 3);
                connection.close();
                async.complete();
            });
        }
    });
}
 
Example 8
@Override
public Single<Optional<CartEvent>> retrieveOne(Long id) {
  return client.rxGetConnection()
    .flatMap(conn ->
      conn.rxQueryWithParams(RETRIEVE_STATEMENT, new JsonArray().add(id))
        .map(ResultSet::getRows)
        .map(list -> {
          if (list.isEmpty()) {
            return Optional.<CartEvent>empty();
          } else {
            return Optional.of(list.get(0))
              .map(this::wrapCartEvent);
          }
        })
        .doAfterTerminate(conn::close)
    );
}
 
Example 9
@Override
public <Q extends Record> CompletableFuture<List<JsonObject>> findManyJson(Function<DSLContext, ? extends ResultQuery<Q>> queryFunction) {
    return getConnection().thenCompose(safeExecute(sqlConnection -> {
        Query query = createQuery(queryFunction);
        log(query);
        CompletableFuture<List<JsonObject>> cf = new VertxCompletableFuture<>(vertx);
        sqlConnection.queryWithParams(
                query.getSQL(),
                getBindValues(query),
                executeAndClose(ResultSet::getRows,
                        sqlConnection,
                        cf)
        );
        return cf;
    }));
}
 
Example 10
Source Project: vertx-jooq   Source File: AsyncClassicGenericQueryExecutor.java    License: MIT License 6 votes vote down vote up
@Override
public <Q extends Record> Future<JsonObject> findOneJson(Function<DSLContext, ? extends ResultQuery<Q>> queryFunction) {
    return getConnection().compose(safeExecute(sqlConnection -> {
        Query query = createQuery(queryFunction);
        log(query);
        Promise<JsonObject> promise = Promise.<JsonObject>promise();
        sqlConnection.queryWithParams(
                query.getSQL(),
                getBindValues(query),
                this.<ResultSet,JsonObject>executeAndClose(rs -> {
                            List<JsonObject> rows = rs.getRows();
                            switch (rows.size()) {
                                case 0: return null;
                                case 1: return rows.get(0);
                                default: throw new TooManyRowsException(String.format("Found more than one row: %d", rows.size()));
                            }
                        },
                        sqlConnection,
                        promise)
        );
        return promise.future();
    }));
}
 
Example 11
Source Project: Lealone-Plugins   Source File: VertxJdbcClientTest.java    License: Apache License 2.0 6 votes vote down vote up
static void query(String sql, Handler<ResultSet> resultHandler) {
    log.info(sql);
    getConnection(connection -> {
        connection.query(sql, res -> {
            try {
                if (res.succeeded()) {
                    ResultSet rs = res.result();
                    resultHandler.handle(rs);
                } else {
                    fail(res.cause());
                }
            } finally {
                connection.close();
            }
        });
    });
}
 
Example 12
Source Project: Lealone-Plugins   Source File: VertxJdbcClientTest.java    License: Apache License 2.0 6 votes vote down vote up
static void query(String sql, JsonArray params, Handler<ResultSet> resultHandler) {
    log.info(sql);
    getConnection(connection -> {
        connection.queryWithParams(sql, params, res -> {
            try {
                if (res.succeeded()) {
                    ResultSet rs = res.result();
                    resultHandler.handle(rs);
                } else {
                    fail(res.cause());
                }
            } finally {
                connection.close();
            }
        });
    });
}
 
Example 13
Source Project: vertx-jdbc-client   Source File: SQLExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example3_1(SQLConnection connection) {

    String query = "SELECT ID, FNAME, LNAME, SHOE_SIZE from PEOPLE WHERE LNAME=? AND SHOE_SIZE > ?";
    JsonArray params = new JsonArray().add("Fox").add(9);

    connection.queryWithParams(query, params, res -> {

      if (res.succeeded()) {
        // Get the result set
        ResultSet resultSet = res.result();
      } else {
        // Failed!
      }
    });

  }
 
Example 14
Source Project: vertx-jdbc-client   Source File: SQLExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example8(SQLConnection connection) {
  // Assume that there is a SQL function like this:
  //
  // create function one_hour_ago() returns timestamp
  //    return now() - 1 hour;

  // note that you do not need to declare the output for functions
  String func = "{ call one_hour_ago() }";

  connection.call(func, res -> {

    if (res.succeeded()) {
      ResultSet result = res.result();
    } else {
      // Failed!
    }
  });
}
 
Example 15
Source Project: vertx-jdbc-client   Source File: SQLExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example10(SQLConnection connection) {
  // Assume that there is a SQL procedure like this:
  //
  // create procedure customer_lastname(IN firstname varchar(50), OUT lastname varchar(50))
  //   modifies sql data
  //   select lastname into lastname from customers where firstname = firstname;

  String func = "{ call customer_lastname(?, ?) }";

  connection.callWithParams(func, new JsonArray().add("John"), new JsonArray().addNull().add("VARCHAR"), res -> {

    if (res.succeeded()) {
      ResultSet result = res.result();
    } else {
      // Failed!
    }
  });
}
 
Example 16
Source Project: vertx-jdbc-client   Source File: JDBCExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example4(JDBCClient client) {

    // Now do stuff with it:

    client.getConnection(res -> {
      if (res.succeeded()) {

        SQLConnection connection = res.result();

        connection.query("SELECT * FROM some_table", res2 -> {
          if (res2.succeeded()) {

            ResultSet rs = res2.result();
            // Do something with results
          }
        });
      } else {
        // Failed to get connection - deal with it
      }
    });

  }
 
Example 17
Source Project: vertx-jdbc-client   Source File: ResultSetTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void before() {

  columnNames = Arrays.asList("foo", "bar", "wibble");
  results = new ArrayList<>();
  int numRows = 10;
  for (int i = 0; i < numRows; i++) {
    JsonArray result = new JsonArray();
    for (int j = 0; j < columnNames.size(); j++) {
      result.add("res" + j);
    }
    results.add(result);
  }

  rs = new ResultSet(columnNames, results, null);
}
 
Example 18
Source Project: prebid-server-java   Source File: BasicJdbcClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Fails result {@link Promise} with timeout exception.
 */
private void timedOutResult(Promise<ResultSet> queryResultPromise, long startTime) {
    // no need for synchronization since timer is fired on the same event loop thread
    if (!queryResultPromise.future().isComplete()) {
        metrics.updateDatabaseQueryTimeMetric(clock.millis() - startTime);
        queryResultPromise.fail(timeoutException());
    }
}
 
Example 19
Source Project: prebid-server-java   Source File: BasicJdbcClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Performs query to DB.
 */
private static Future<ResultSet> makeQuery(SQLConnection connection, String query, List<Object> params) {
    final Promise<ResultSet> resultSetPromise = Promise.promise();
    connection.queryWithParams(query, new JsonArray(params),
            ar -> {
                connection.close();
                resultSetPromise.handle(ar);
            });
    return resultSetPromise.future();
}
 
Example 20
Source Project: prebid-server-java   Source File: BasicJdbcClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Propagates responded {@link ResultSet} (or failure) to result {@link Promise}.
 */
private void handleResult(
        AsyncResult<ResultSet> result, Promise<ResultSet> queryResultPromise, long timerId, long startTime) {

    vertx.cancelTimer(timerId);

    // check is to avoid harmless exception if timeout exceeds before successful result becomes ready
    if (!queryResultPromise.future().isComplete()) {
        metrics.updateDatabaseQueryTimeMetric(clock.millis() - startTime);
        queryResultPromise.handle(result);
    }
}
 
Example 21
Source Project: prebid-server-java   Source File: BasicJdbcClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void executeQueryShouldReturnFailedFutureIfGlobalTimeoutAlreadyExpired() {
    // when
    final Future<ResultSet> future = jdbcClient.executeQuery("query", emptyList(), identity(), expiredTimeout());

    // then
    assertThat(future.failed()).isTrue();
    assertThat(future.cause()).isInstanceOf(TimeoutException.class)
            .hasMessage("Timed out while executing SQL query");
    verifyNoMoreInteractions(vertx, vertxJdbcClient);
}
 
Example 22
Source Project: prebid-server-java   Source File: BasicJdbcClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void executeQueryShouldReturnFailedFutureIfItTakesLongerThanRemainingTimeout() {
    // given
    given(vertx.setTimer(anyLong(), any())).willAnswer(invocation -> {
        ((Handler<Long>) invocation.getArgument(1)).handle(123L);
        return 123L;
    });

    final SQLConnection connection = mock(SQLConnection.class);
    givenGetConnectionReturning(Future.succeededFuture(connection));

    givenQueryReturning(connection, Future.succeededFuture(new ResultSet()));

    // when
    final Future<ResultSet> future = jdbcClient.executeQuery("query", emptyList(), identity(), timeout);

    // then
    final ArgumentCaptor<Long> timeoutCaptor = ArgumentCaptor.forClass(Long.class);
    verify(vertx).setTimer(timeoutCaptor.capture(), any());
    assertThat(timeoutCaptor.getValue()).isEqualTo(500L);

    verify(vertx).cancelTimer(eq(123L));

    assertThat(future.failed()).isTrue();
    assertThat(future.cause()).isInstanceOf(TimeoutException.class)
            .hasMessage("Timed out while executing SQL query");
}
 
Example 23
Source Project: prebid-server-java   Source File: BasicJdbcClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void executeQueryShouldReportMetricsIfQueryFails() {
    // given
    final SQLConnection connection = mock(SQLConnection.class);
    givenGetConnectionReturning(Future.succeededFuture(connection));

    givenQueryReturning(connection, Future.failedFuture(new RuntimeException("Failed to execute query")));

    // when
    final Future<ResultSet> future = jdbcClient.executeQuery("query", emptyList(), identity(), timeout);

    // then
    assertThat(future.failed()).isTrue();
    verify(metrics).updateDatabaseQueryTimeMetric(anyLong());
}
 
Example 24
Source Project: prebid-server-java   Source File: BasicJdbcClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void executeQueryShouldReportMetricsIfQuerySucceeds() {
    // given
    final SQLConnection connection = mock(SQLConnection.class);
    givenGetConnectionReturning(Future.succeededFuture(connection));

    givenQueryReturning(connection, Future.succeededFuture(new ResultSet().setResults(emptyList())));

    // when
    final Future<String> future = jdbcClient.executeQuery("query", emptyList(), Object::toString, timeout);

    // then
    assertThat(future.succeeded()).isTrue();
    verify(metrics).updateDatabaseQueryTimeMetric(anyLong());
}
 
Example 25
Source Project: prebid-server-java   Source File: BasicJdbcClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void givenQueryReturning(SQLConnection connection, AsyncResult<ResultSet> result) {
    given(connection.queryWithParams(anyString(), any(), any())).willAnswer(invocation -> {
        ((Handler<AsyncResult<ResultSet>>) invocation.getArgument(2)).handle(result);
        return null;
    });
}
 
Example 26
Source Project: Summer   Source File: ResultSetMapper.java    License: MIT License 5 votes vote down vote up
public  <T> T mapper(ResultSet resultSet,Class<T> t){
    if (resultSet==null||resultSet.getResults()==null||
            resultSet.getResults().size()==0||resultSet.getColumnNames()==null
            ){
        return null;
    }
    return mapperOne(resultSet.getColumnNames(),resultSet.getResults().get(0),t);
}
 
Example 27
Source Project: Summer   Source File: ResultSetMapper.java    License: MIT License 5 votes vote down vote up
public  <T> List<T> mapperList(ResultSet resultSet,Class<T> t){
    if (resultSet==null||resultSet.getResults()==null||
            resultSet.getResults().size()==0||resultSet.getColumnNames()==null
            ){
        return null;
    }
    List<T> list = new ArrayList<>();
    for (JsonArray ja:resultSet.getResults()) {
        T mt = mapperOne(resultSet.getColumnNames(),ja,t);
        list.add(mt);
    }

    return list;

}
 
Example 28
Source Project: redpipe   Source File: WikiResource.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/wiki/{page}")
@GET
public Single<Template> renderPage(@PathParam("page") String page){
	return fiber((con) -> {
		ResultSet res = await(con.rxQueryWithParams(SQL.SQL_GET_PAGE, new JsonArray().add(page)));
		JsonArray row = res.getResults()
				.stream()
				.findFirst().orElse(null);
		Integer id; 
		String rawContent;
		boolean newPage = row == null;
		if(newPage){
			id = -1;
			rawContent = EMPTY_PAGE_MARKDOWN;
		}else{
			id = row.getInteger(0);
			rawContent = row.getString(1);
		}
		if(newPage && !await(user.rxIsAuthorised("create")))
			throw new AuthorizationException("Not authorized");
		boolean canUpdate = await(user.rxIsAuthorised("update"));
		boolean canDelete = await(user.rxIsAuthorised("delete"));
		return new Template("templates/page.ftl")
				.set("username", getUserName())
				.set("title", page)
				.set("id", id)
				.set("newPage", newPage ? "yes" : "no")
				.set("rawContent", rawContent)
				.set("canUpdatePage", canUpdate)
				.set("canDeletePage", canDelete)
				.set("content", Processor.process(rawContent))
				.set("timestamp", new Date().toString());
	});
}
 
Example 29
Source Project: vertx-kubernetes-workshop   Source File: AuditVerticle.java    License: Apache License 2.0 5 votes vote down vote up
private void retrieveOperations(RoutingContext context) {
    // We retrieve the operation using the following process:
    // 1. Get the connection
    // 2. When done, execute the query
    // 3. When done, iterate over the result to build a list taking the `operation` value of each json object
    // 5. write this list into the response
    // 4. close the connection

    //TODO
    // ----
    jdbc.getConnection(ar -> {
        SQLConnection connection = ar.result();
        if (ar.failed()) {
            context.fail(ar.cause());
        } else {
            connection.query(SELECT_STATEMENT, result -> {
                if (result.failed()) {
                    context.fail(result.cause());
                } else {
                    ResultSet set = result.result();
                    List<JsonObject> operations = set.getRows().stream()
                        .map(json -> new JsonObject(json.getString("operation")))
                        .collect(Collectors.toList());
                    // 5. write this list into the response
                    context.response().setStatusCode(200).end(Json.encodePrettily(operations));
                    // 6. close the connection
                    connection.close();
                }
            });
        }
    });
    // ----
}
 
Example 30
private void getRecommendationsFromDb(RoutingContext ctx) {
    jdbcClient.getConnection(res -> {
        if (res.succeeded()) {
            try (final SQLConnection connection = res.result()) {
                String sql = "SELECT * FROM recommendation;";
                connection.query(sql, rs -> {
                    final ResultSet resultSet = rs.result();

                    if (resultSet != null) {
                        count++;
                        final List<String> recommendations = findRecommendation(resultSet);
                        // final List<String> recommendations = findRecommendationNew(resultSet);
                        ctx.response().end(String.format(RESPONSE_RECOMMENDATION_STRING_FORMAT, String.join(",", recommendations), HOSTNAME, count));
                    } else {
                        ctx.response()
                            .setStatusCode(500)
                            .end(String.format("Connection to database couldn't be established: %s", res.cause()));
                    }
                });
            }
        } else {
            ctx.response()
                .setStatusCode(500)
                .end(String.format("Connection to database couldn't be established: %s", res.cause()));
        }
    });
}