Search in sources :

Example 6 with SqlConnection

use of io.vertx.sqlclient.SqlConnection 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)

Example 7 with SqlConnection

use of io.vertx.sqlclient.SqlConnection in project vertx-examples by vert-x3.

the class SqlClientExample method start.

@Override
public void start() throws Exception {
    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.query("select * from test").execute(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();
                });
            });
        });
    });
}
Also used : PgConnectOptions(io.vertx.pgclient.PgConnectOptions) PoolOptions(io.vertx.sqlclient.PoolOptions) PgPool(io.vertx.pgclient.PgPool) Pool(io.vertx.sqlclient.Pool) SqlConnection(io.vertx.sqlclient.SqlConnection) Row(io.vertx.sqlclient.Row)

Example 8 with SqlConnection

use of io.vertx.sqlclient.SqlConnection in project raml-module-builder by folio-org.

the class PostgresClientIT method deleteByCqlWrapperThatThrowsException.

@Test
public void deleteByCqlWrapperThatThrowsException(TestContext context) {
    CQLWrapper cqlWrapper = new CQLWrapper() {

        @Override
        public String getWhereClause() {
            throw new RuntimeException("ping pong");
        }
    };
    createFoo(context).getSQLConnection(asyncAssertTx(context, sqlConnection -> {
        postgresClient.delete(sqlConnection, FOO, cqlWrapper, context.asyncAssertFailure(fail -> {
            context.assertTrue(fail.getMessage().contains("ping pong"));
        }));
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) TestContext(io.vertx.ext.unit.TestContext) RowStream(io.vertx.sqlclient.RowStream) Arrays(java.util.Arrays) PgNotification(io.vertx.pgclient.PgNotification) TransactionRollbackException(io.vertx.sqlclient.TransactionRollbackException) VertxUtils(org.folio.rest.tools.utils.VertxUtils) Tuple(io.vertx.sqlclient.Tuple) UpdateSection(org.folio.rest.persist.Criteria.UpdateSection) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) RowIterator(io.vertx.sqlclient.RowIterator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SqlResult(io.vertx.sqlclient.SqlResult) After(org.junit.After) JsonObject(io.vertx.core.json.JsonObject) Offset(org.folio.rest.persist.Criteria.Offset) Collector(java.util.stream.Collector) Transaction(io.vertx.sqlclient.Transaction) AfterClass(org.junit.AfterClass) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) RowImpl(io.vertx.pgclient.impl.RowImpl) Set(java.util.Set) UUID(java.util.UUID) FieldException(org.folio.cql2pgjson.exception.FieldException) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) IOUtils(org.apache.commons.io.IOUtils) CQL2PgJSON(org.folio.cql2pgjson.CQL2PgJSON) Base64(java.util.Base64) List(java.util.List) Stream(java.util.stream.Stream) Criterion(org.folio.rest.persist.Criteria.Criterion) Results(org.folio.rest.persist.interfaces.Results) Facet(org.folio.rest.jaxrs.model.Facet) RowDesc(io.vertx.sqlclient.impl.RowDesc) Async(io.vertx.ext.unit.Async) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) BeforeClass(org.junit.BeforeClass) FacetField(org.folio.rest.persist.facets.FacetField) PostgresTesterContainer(org.folio.postgres.testing.PostgresTesterContainer) Criteria(org.folio.rest.persist.Criteria.Criteria) CoreMatchers.not(org.hamcrest.CoreMatchers.not) RunWith(org.junit.runner.RunWith) Timeout(io.vertx.ext.unit.junit.Timeout) ResultInfo(org.folio.rest.jaxrs.model.ResultInfo) Function(java.util.function.Function) TotaledResults(org.folio.rest.persist.PostgresClient.TotaledResults) ArrayList(java.util.ArrayList) PreparedStatement(io.vertx.sqlclient.PreparedStatement) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) Poline(org.folio.rest.persist.helpers.Poline) PrepareOptions(io.vertx.sqlclient.PrepareOptions) SqlConnection(io.vertx.sqlclient.SqlConnection) Limit(org.folio.rest.persist.Criteria.Limit) QueryHelper(org.folio.rest.persist.PostgresClient.QueryHelper) RowSet(io.vertx.sqlclient.RowSet) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) AsyncResult(io.vertx.core.AsyncResult) LinkedList(java.util.LinkedList) DatabaseMetadata(io.vertx.sqlclient.spi.DatabaseMetadata) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) Before(org.junit.Before) Files(java.nio.file.Files) Query(io.vertx.sqlclient.Query) 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) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) PreparedQuery(io.vertx.sqlclient.PreparedQuery) JsonArray(io.vertx.core.json.JsonArray) PgConnection(io.vertx.pgclient.PgConnection) Rule(org.junit.Rule) Paths(java.nio.file.Paths) Row(io.vertx.sqlclient.Row) LocalRowSet(org.folio.rest.persist.helpers.LocalRowSet) Handler(io.vertx.core.Handler) SimplePojo(org.folio.rest.persist.helpers.SimplePojo) Collections(java.util.Collections) InputStream(java.io.InputStream) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) Test(org.junit.Test)

Example 9 with SqlConnection

use of io.vertx.sqlclient.SqlConnection in project raml-module-builder by folio-org.

the class PostgresClientIT method postgresClientQueryFails.

/**
 * @return a PostgresClient where invoking SQLConnection::update, SQLConnection::updateWithParams or
 * SQLConnection::queryWithParams will report a failure via the resultHandler.
 */
private PostgresClient postgresClientQueryFails() {
    PgConnection pgConnection = new PgConnection() {

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

        @Override
        public PgConnection cancelRequest(Handler<AsyncResult<Void>> handler) {
            handler.handle(Future.failedFuture("cancelRequestFails"));
            return this;
        }

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

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

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

        @Override
        public Future<PreparedStatement> prepare(String s) {
            return Future.failedFuture("preparedFails");
        }

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

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

        @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 new Query<RowSet<Row>>() {

                @Override
                public void execute(Handler<AsyncResult<RowSet<Row>>> handler) {
                    handler.handle(execute());
                }

                @Override
                public Future<RowSet<Row>> execute() {
                    return Future.failedFuture("queryFails");
                }

                @Override
                public <R> Query<SqlResult<R>> collecting(Collector<Row, ?, R> collector) {
                    return null;
                }

                @Override
                public <U> Query<RowSet<U>> mapping(Function<Row, U> function) {
                    return null;
                }
            };
        }

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

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

        @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 : SqlResult(io.vertx.sqlclient.SqlResult) Query(io.vertx.sqlclient.Query) PreparedQuery(io.vertx.sqlclient.PreparedQuery) 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) Function(java.util.function.Function) Transaction(io.vertx.sqlclient.Transaction) PrepareOptions(io.vertx.sqlclient.PrepareOptions) Collector(java.util.stream.Collector) SqlConnection(io.vertx.sqlclient.SqlConnection) Row(io.vertx.sqlclient.Row)

Example 10 with SqlConnection

use of io.vertx.sqlclient.SqlConnection 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)

Aggregations

PgPool (io.vertx.pgclient.PgPool)10 SqlConnection (io.vertx.sqlclient.SqlConnection)10 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 PgConnection (io.vertx.pgclient.PgConnection)7 RowSet (io.vertx.sqlclient.RowSet)7 IOException (java.io.IOException)7 FieldException (org.folio.cql2pgjson.exception.FieldException)7 Handler (io.vertx.core.Handler)6 PreparedStatement (io.vertx.sqlclient.PreparedStatement)6 Row (io.vertx.sqlclient.Row)6 Transaction (io.vertx.sqlclient.Transaction)6 TransactionRollbackException (io.vertx.sqlclient.TransactionRollbackException)6 UncheckedIOException (java.io.UncheckedIOException)6 PrepareOptions (io.vertx.sqlclient.PrepareOptions)5 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 AsyncResult (io.vertx.core.AsyncResult)3 Future (io.vertx.core.Future)3 Promise (io.vertx.core.Promise)3 Vertx (io.vertx.core.Vertx)3 JsonArray (io.vertx.core.json.JsonArray)3