Search in sources :

Example 11 with PgConnection

use of io.vertx.pgclient.PgConnection in project raml-module-builder by folio-org.

the class PostgresClientTest method testProcessQuery.

@Test
public void testProcessQuery() {
    PostgresClient testClient = PostgresClient.testClient();
    List<FacetField> facets = new ArrayList<FacetField>() {

        {
            add(new FacetField("jsonb->>'biz'"));
        }
    };
    QueryHelper queryHelper = new QueryHelper("test_jsonb_pojo");
    queryHelper.selectQuery = "SELECT id, foo, bar FROM test_jsonb_pojo LIMIT 30 OFFSET 1";
    int total = 30;
    PgConnection connection = new FakeSqlConnection(Future.succeededFuture(getMockTestJsonbPojoResultSet(total)), true);
    testClient.processQuery(connection, queryHelper, total, "get", totaledResults -> testClient.processResults(totaledResults.set, totaledResults.estimatedTotal, DEFAULT_OFFSET, DEFAULT_LIMIT, TestJsonbPojo.class), reply -> {
        List<TestJsonbPojo> results = reply.result().getResults();
        assertTestJsonbPojoResults(results, total);
    });
}
Also used : QueryHelper(org.folio.rest.persist.PostgresClient.QueryHelper) ArrayList(java.util.ArrayList) PgConnection(io.vertx.pgclient.PgConnection) FacetField(org.folio.rest.persist.facets.FacetField) AESTest(org.folio.rest.security.AESTest) Test(org.junit.Test)

Example 12 with PgConnection

use of io.vertx.pgclient.PgConnection in project raml-module-builder by folio-org.

the class PostgresClientTest method testProcessQueryException.

@Test
public void testProcessQueryException() {
    PostgresClient testClient = PostgresClient.testClient();
    QueryHelper queryHelper = new QueryHelper("test_jsonb_pojo");
    queryHelper.selectQuery = "SELECT foo";
    PgConnection connection = null;
    testClient.processQuery(connection, queryHelper, 30, "get", totaledResults -> testClient.processResults(totaledResults.set, totaledResults.estimatedTotal, DEFAULT_OFFSET, DEFAULT_LIMIT, TestJsonbPojo.class), reply -> {
        assertThat(reply.failed(), is(true));
        assertThat(reply.cause() instanceof NullPointerException, is(true));
    });
}
Also used : QueryHelper(org.folio.rest.persist.PostgresClient.QueryHelper) PgConnection(io.vertx.pgclient.PgConnection) AESTest(org.folio.rest.security.AESTest) Test(org.junit.Test)

Example 13 with PgConnection

use of io.vertx.pgclient.PgConnection in project raml-module-builder by folio-org.

the class PostgresClientTest method testProcessQueryFails.

@Test
public void testProcessQueryFails() {
    PostgresClient testClient = PostgresClient.testClient();
    QueryHelper queryHelper = new QueryHelper("test_jsonb_pojo");
    queryHelper.selectQuery = "SELECT foo";
    PgConnection connection = new FakeSqlConnection(Future.failedFuture("Bad query"), false);
    testClient.processQuery(connection, queryHelper, 30, "get", totaledResults -> testClient.processResults(totaledResults.set, totaledResults.estimatedTotal, DEFAULT_OFFSET, DEFAULT_LIMIT, TestJsonbPojo.class), reply -> {
        assertThat(reply.failed(), is(true));
        assertThat(reply.cause().getMessage(), is("Bad query"));
    });
}
Also used : QueryHelper(org.folio.rest.persist.PostgresClient.QueryHelper) PgConnection(io.vertx.pgclient.PgConnection) AESTest(org.folio.rest.security.AESTest) Test(org.junit.Test)

Example 14 with PgConnection

use of io.vertx.pgclient.PgConnection in project raml-module-builder by folio-org.

the class PostgresClient method getSQLConnection.

/**
 * Don't forget to close the connection!
 *
 * <p>Use closeAndHandleResult as replyHandler, for example:
 *
 * <pre>getSQLConnection(timeout, conn -> execute(conn, sql, params, closeAndHandleResult(conn, replyHandler)))</pre>
 *
 * <p>Or avoid this method and use the preferred {@link #withConn(int, Function)}.
 *
 * @see #withConn(Function)
 * @see #withConnection(Function)
 * @see #withTrans(Function)
 * @see #withTransaction(Function)
 */
void getSQLConnection(int queryTimeout, Handler<AsyncResult<SQLConnection>> handler) {
    getConnection(res -> {
        if (res.failed()) {
            handler.handle(Future.failedFuture(res.cause()));
            return;
        }
        PgConnection pgConnection = res.result();
        if (queryTimeout == 0) {
            handler.handle(Future.succeededFuture(new SQLConnection(pgConnection, null, null)));
            return;
        }
        long timerId = vertx.setTimer(queryTimeout, id -> pgConnection.cancelRequest(ar -> {
            if (ar.succeeded()) {
                log.warn(String.format("Cancelling request due to timeout after : %d ms", queryTimeout));
            } else {
                log.warn("Failed to send cancelling request", ar.cause());
            }
        }));
        SQLConnection sqlConnection = new SQLConnection(pgConnection, null, timerId);
        handler.handle(Future.succeededFuture(sqlConnection));
    });
}
Also used : RowStream(io.vertx.sqlclient.RowStream) Arrays(java.util.Arrays) AES(org.folio.rest.security.AES) Tuple(io.vertx.sqlclient.Tuple) UpdateSection(org.folio.rest.persist.Criteria.UpdateSection) MetadataUtil(org.folio.rest.tools.utils.MetadataUtil) OpenSSLEngineOptions(io.vertx.core.net.OpenSSLEngineOptions) RowIterator(io.vertx.sqlclient.RowIterator) Matcher(java.util.regex.Matcher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ObjectMapperTool(org.folio.dbschema.ObjectMapperTool) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) Transaction(io.vertx.sqlclient.Transaction) Method(java.lang.reflect.Method) JdkSSLEngineOptions(io.vertx.core.net.JdkSSLEngineOptions) FacetManager(org.folio.rest.persist.facets.FacetManager) UUID(java.util.UUID) Future(io.vertx.core.Future) PoolOptions(io.vertx.sqlclient.PoolOptions) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Criterion(org.folio.rest.persist.Criteria.Criterion) Results(org.folio.rest.persist.interfaces.Results) Buffer(io.vertx.core.buffer.Buffer) Pattern(java.util.regex.Pattern) SecretKey(javax.crypto.SecretKey) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) FacetField(org.folio.rest.persist.facets.FacetField) TemplateException(freemarker.template.TemplateException) HashMap(java.util.HashMap) ResultInfo(org.folio.rest.jaxrs.model.ResultInfo) Function(java.util.function.Function) PreparedStatement(io.vertx.sqlclient.PreparedStatement) ArrayList(java.util.ArrayList) SqlConnection(io.vertx.sqlclient.SqlConnection) RowSet(io.vertx.sqlclient.RowSet) AsyncResult(io.vertx.core.AsyncResult) PemTrustOptions(io.vertx.core.net.PemTrustOptions) LinkedList(java.util.LinkedList) PostgresTester(org.folio.util.PostgresTester) OpenSsl(io.netty.handler.ssl.OpenSsl) Iterator(java.util.Iterator) Envs(org.folio.rest.tools.utils.Envs) Promise(io.vertx.core.Promise) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) PgPool(io.vertx.pgclient.PgPool) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) HashedMap(org.apache.commons.collections4.map.HashedMap) MultiKeyMap(org.apache.commons.collections4.map.MultiKeyMap) TimeUnit(java.util.concurrent.TimeUnit) JsonArray(io.vertx.core.json.JsonArray) PgConnection(io.vertx.pgclient.PgConnection) Row(io.vertx.sqlclient.Row) PgConnectOptions(io.vertx.pgclient.PgConnectOptions) Option(java.lang.StackWalker.Option) Handler(io.vertx.core.Handler) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) SslMode(io.vertx.pgclient.SslMode) PgConnection(io.vertx.pgclient.PgConnection)

Example 15 with PgConnection

use of io.vertx.pgclient.PgConnection in project raml-module-builder by folio-org.

the class PostgresClient method doStreamGetCount.

/**
 * private for now, might be public later (and renamed)
 * @param <T>
 * @param connection
 * @param table
 * @param clazz
 * @param fieldName
 * @param wrapper
 * @param returnIdField
 * @param distinctOn
 * @param facets
 * @param replyHandler
 */
// Method has >7 parameters
@SuppressWarnings({ "squid:S00107" })
<T> void doStreamGetCount(PgConnection connection, boolean startTransaction, String table, Class<T> clazz, String fieldName, CQLWrapper wrapper, boolean returnIdField, String distinctOn, List<FacetField> facets, Handler<AsyncResult<PostgresClientStreamResult<T>>> replyHandler) {
    try {
        QueryHelper queryHelper = buildQueryHelper(table, fieldName, wrapper, returnIdField, facets, distinctOn);
        Future<Integer> countQuery;
        if (wrapper == null || wrapper.hasReturnCount()) {
            countQuery = connection.query(queryHelper.countQuery).execute().map(result -> result.iterator().next().getInteger(0));
        } else {
            countQuery = Future.succeededFuture(null);
        }
        countQuery.onSuccess(count -> {
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.setTotalRecords(count);
            doStreamGetQuery(connection, startTransaction, queryHelper, resultInfo, clazz, replyHandler);
        }).onFailure(e -> {
            log.error(e.getMessage(), e);
            replyHandler.handle(Future.failedFuture(e));
        });
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        replyHandler.handle(Future.failedFuture(e));
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RowStream(io.vertx.sqlclient.RowStream) Arrays(java.util.Arrays) AES(org.folio.rest.security.AES) Tuple(io.vertx.sqlclient.Tuple) UpdateSection(org.folio.rest.persist.Criteria.UpdateSection) MetadataUtil(org.folio.rest.tools.utils.MetadataUtil) OpenSSLEngineOptions(io.vertx.core.net.OpenSSLEngineOptions) RowIterator(io.vertx.sqlclient.RowIterator) Matcher(java.util.regex.Matcher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ObjectMapperTool(org.folio.dbschema.ObjectMapperTool) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) Transaction(io.vertx.sqlclient.Transaction) Method(java.lang.reflect.Method) JdkSSLEngineOptions(io.vertx.core.net.JdkSSLEngineOptions) FacetManager(org.folio.rest.persist.facets.FacetManager) UUID(java.util.UUID) Future(io.vertx.core.Future) PoolOptions(io.vertx.sqlclient.PoolOptions) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Criterion(org.folio.rest.persist.Criteria.Criterion) Results(org.folio.rest.persist.interfaces.Results) Buffer(io.vertx.core.buffer.Buffer) Pattern(java.util.regex.Pattern) SecretKey(javax.crypto.SecretKey) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) FacetField(org.folio.rest.persist.facets.FacetField) TemplateException(freemarker.template.TemplateException) HashMap(java.util.HashMap) ResultInfo(org.folio.rest.jaxrs.model.ResultInfo) Function(java.util.function.Function) PreparedStatement(io.vertx.sqlclient.PreparedStatement) ArrayList(java.util.ArrayList) SqlConnection(io.vertx.sqlclient.SqlConnection) RowSet(io.vertx.sqlclient.RowSet) AsyncResult(io.vertx.core.AsyncResult) PemTrustOptions(io.vertx.core.net.PemTrustOptions) LinkedList(java.util.LinkedList) PostgresTester(org.folio.util.PostgresTester) OpenSsl(io.netty.handler.ssl.OpenSsl) Iterator(java.util.Iterator) Envs(org.folio.rest.tools.utils.Envs) Promise(io.vertx.core.Promise) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) PgPool(io.vertx.pgclient.PgPool) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) HashedMap(org.apache.commons.collections4.map.HashedMap) MultiKeyMap(org.apache.commons.collections4.map.MultiKeyMap) TimeUnit(java.util.concurrent.TimeUnit) JsonArray(io.vertx.core.json.JsonArray) PgConnection(io.vertx.pgclient.PgConnection) Row(io.vertx.sqlclient.Row) PgConnectOptions(io.vertx.pgclient.PgConnectOptions) Option(java.lang.StackWalker.Option) Handler(io.vertx.core.Handler) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) SslMode(io.vertx.pgclient.SslMode) ResultInfo(org.folio.rest.jaxrs.model.ResultInfo) InvocationTargetException(java.lang.reflect.InvocationTargetException) TemplateException(freemarker.template.TemplateException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Aggregations

PgConnection (io.vertx.pgclient.PgConnection)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)9 RowSet (io.vertx.sqlclient.RowSet)9 IOException (java.io.IOException)8 Handler (io.vertx.core.Handler)7 PgPool (io.vertx.pgclient.PgPool)7 Row (io.vertx.sqlclient.Row)7 SqlConnection (io.vertx.sqlclient.SqlConnection)7 PreparedStatement (io.vertx.sqlclient.PreparedStatement)6 Transaction (io.vertx.sqlclient.Transaction)6 TemplateException (freemarker.template.TemplateException)5 Tuple (io.vertx.sqlclient.Tuple)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)5 ArrayList (java.util.ArrayList)5 Function (java.util.function.Function)5 QueryHelper (org.folio.rest.persist.PostgresClient.QueryHelper)5 FacetField (org.folio.rest.persist.facets.FacetField)5 Test (org.junit.Test)5 AsyncResult (io.vertx.core.AsyncResult)4 Future (io.vertx.core.Future)4