Search in sources :

Example 1 with PgConnection

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

the class PostgresClientIT method postgresClientConnectionThrowsException.

/**
 * @return a PostgresClient where invoking SQLConnection::update(...) or SQLConnection::updateWithParams
 * throws an RuntimeException.
 */
private PostgresClient postgresClientConnectionThrowsException() {
    PgConnection pgConnection = new PgConnection() {

        @Override
        public PgConnection notificationHandler(Handler<PgNotification> handler) {
            throw new RuntimeException();
        }

        @Override
        public PgConnection cancelRequest(Handler<AsyncResult<Void>> handler) {
            throw new RuntimeException();
        }

        @Override
        public int processId() {
            throw new RuntimeException();
        }

        @Override
        public int secretKey() {
            throw new RuntimeException();
        }

        @Override
        public PgConnection prepare(String s, Handler<AsyncResult<PreparedStatement>> handler) {
            throw new RuntimeException();
        }

        @Override
        public Future<PreparedStatement> prepare(String s) {
            return null;
        }

        @Override
        public SqlConnection prepare(String sql, PrepareOptions options, Handler<AsyncResult<PreparedStatement>> handler) {
            return null;
        }

        @Override
        public Future<PreparedStatement> prepare(String s, PrepareOptions prepareOptions) {
            return null;
        }

        @Override
        public PgConnection exceptionHandler(Handler<Throwable> handler) {
            return null;
        }

        @Override
        public PgConnection closeHandler(Handler<Void> handler) {
            return null;
        }

        @Override
        public void begin(Handler<AsyncResult<Transaction>> handler) {
        }

        @Override
        public Future<Transaction> begin() {
            return null;
        }

        @Override
        public boolean isSSL() {
            return false;
        }

        @Override
        public void close(Handler<AsyncResult<Void>> handler) {
            close().onComplete(handler);
        }

        @Override
        public Future<Void> close() {
            return Future.succeededFuture();
        }

        @Override
        public Query<RowSet<Row>> query(String s) {
            throw new RuntimeException();
        }

        @Override
        public PreparedQuery<RowSet<Row>> preparedQuery(String s, PrepareOptions options) {
            throw new RuntimeException();
        }

        @Override
        public PreparedQuery<RowSet<Row>> preparedQuery(String s) {
            throw new RuntimeException();
        }

        @Override
        public DatabaseMetadata databaseMetadata() {
            throw new RuntimeException();
        }
    };
    PgPool client = new PgPoolBase() {

        @Override
        public Future<SqlConnection> getConnection() {
            return Future.succeededFuture(pgConnection);
        }
    };
    try {
        PostgresClient postgresClient = new PostgresClient(vertx, TENANT);
        postgresClient.setClient(client);
        return postgresClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : PgPool(io.vertx.pgclient.PgPool) PgConnection(io.vertx.pgclient.PgConnection) RowSet(io.vertx.sqlclient.RowSet) LocalRowSet(org.folio.rest.persist.helpers.LocalRowSet) Handler(io.vertx.core.Handler) PreparedStatement(io.vertx.sqlclient.PreparedStatement) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) TransactionRollbackException(io.vertx.sqlclient.TransactionRollbackException) FieldException(org.folio.cql2pgjson.exception.FieldException) UncheckedIOException(java.io.UncheckedIOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Transaction(io.vertx.sqlclient.Transaction) PrepareOptions(io.vertx.sqlclient.PrepareOptions) SqlConnection(io.vertx.sqlclient.SqlConnection)

Example 2 with PgConnection

use of io.vertx.pgclient.PgConnection 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));
            }
        });
    });
}
Also used : HashMap(java.util.HashMap) PgConnection(io.vertx.pgclient.PgConnection) Row(io.vertx.sqlclient.Row) Tuple(io.vertx.sqlclient.Tuple) InvocationTargetException(java.lang.reflect.InvocationTargetException) TemplateException(freemarker.template.TemplateException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Example 3 with PgConnection

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

the class PostgresClientIT method postgresClientQueryReturnBadResults.

/**
 * @return a PostgresClient where invoking SQLConnection::queryWithParams will return null ResultSet
 */
private PostgresClient postgresClientQueryReturnBadResults() {
    PgConnection pgConnection = new PgConnection() {

        @Override
        public PgConnection notificationHandler(Handler<PgNotification> handler) {
            return null;
        }

        @Override
        public PgConnection cancelRequest(Handler<AsyncResult<Void>> handler) {
            return this;
        }

        @Override
        public int processId() {
            return 0;
        }

        @Override
        public int secretKey() {
            return 0;
        }

        @Override
        public PgConnection prepare(String s, Handler<AsyncResult<PreparedStatement>> handler) {
            return null;
        }

        @Override
        public Future<PreparedStatement> prepare(String s) {
            return null;
        }

        @Override
        public SqlConnection prepare(String sql, PrepareOptions options, Handler<AsyncResult<PreparedStatement>> handler) {
            return null;
        }

        @Override
        public Future<PreparedStatement> prepare(String sql, PrepareOptions options) {
            return null;
        }

        @Override
        public PgConnection exceptionHandler(Handler<Throwable> handler) {
            return null;
        }

        @Override
        public PgConnection closeHandler(Handler<Void> handler) {
            return null;
        }

        @Override
        public void begin(Handler<AsyncResult<Transaction>> handler) {
        }

        @Override
        public Future<Transaction> begin() {
            return null;
        }

        @Override
        public boolean isSSL() {
            return false;
        }

        @Override
        public void close(Handler<AsyncResult<Void>> handler) {
        }

        @Override
        public Query<RowSet<Row>> query(String s) {
            return null;
        }

        @Override
        public PreparedQuery<RowSet<Row>> preparedQuery(String s) {
            return null;
        }

        @Override
        public PreparedQuery<RowSet<Row>> preparedQuery(String sql, PrepareOptions options) {
            return preparedQuery(sql);
        }

        @Override
        public Future<Void> close() {
            return null;
        }

        @Override
        public DatabaseMetadata databaseMetadata() {
            return null;
        }
    };
    PgPool client = new PgPoolBase() {

        @Override
        public Future<SqlConnection> getConnection() {
            return Future.succeededFuture(pgConnection);
        }
    };
    try {
        PostgresClient postgresClient = new PostgresClient(vertx, TENANT);
        postgresClient.setClient(client);
        return postgresClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : PgPool(io.vertx.pgclient.PgPool) PgConnection(io.vertx.pgclient.PgConnection) RowSet(io.vertx.sqlclient.RowSet) LocalRowSet(org.folio.rest.persist.helpers.LocalRowSet) Handler(io.vertx.core.Handler) PreparedStatement(io.vertx.sqlclient.PreparedStatement) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) TransactionRollbackException(io.vertx.sqlclient.TransactionRollbackException) FieldException(org.folio.cql2pgjson.exception.FieldException) UncheckedIOException(java.io.UncheckedIOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Transaction(io.vertx.sqlclient.Transaction) PrepareOptions(io.vertx.sqlclient.PrepareOptions) SqlConnection(io.vertx.sqlclient.SqlConnection)

Example 4 with PgConnection

use of io.vertx.pgclient.PgConnection 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());
}
Also used : PgPool(io.vertx.pgclient.PgPool) RowSet(io.vertx.sqlclient.RowSet) PgConnection(io.vertx.pgclient.PgConnection) Row(io.vertx.sqlclient.Row) Tuple(io.vertx.sqlclient.Tuple) Test(org.junit.Test)

Example 5 with PgConnection

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

the class PostgresClientTransactionsIT method postgresClientMonitor.

private PostgresClient postgresClientMonitor(AtomicInteger open, AtomicInteger active) {
    try {
        PostgresClient postgresClient = new PostgresClient(vertx, tenant);
        PgPool ePool = postgresClient.getClient();
        PgPool client = new PgPoolBase() {

            @Override
            public Future<SqlConnection> getConnection() {
                return ePool.getConnection().map(conn -> new MonitorPgConnection((PgConnection) conn, open, active));
            }

            @Override
            public Query<RowSet<Row>> query(String s) {
                return ePool.query(s);
            }

            @Override
            public PreparedQuery<RowSet<Row>> preparedQuery(String s) {
                return ePool.preparedQuery(s);
            }

            @Override
            public Future<Void> close() {
                return ePool.close();
            }
        };
        postgresClient.setClient(client);
        return postgresClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : PgPool(io.vertx.pgclient.PgPool) PgConnection(io.vertx.pgclient.PgConnection) RowSet(io.vertx.sqlclient.RowSet) SqlConnection(io.vertx.sqlclient.SqlConnection) FieldException(org.folio.cql2pgjson.exception.FieldException)

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