Search in sources :

Example 1 with Row

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();
                });
            });
        });
    });
}
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 2 with Row

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))));
}
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) RowImpl(io.vertx.pgclient.impl.RowImpl) LocalRowSet(org.folio.rest.persist.helpers.LocalRowSet) RowSet(io.vertx.sqlclient.RowSet) LocalRowSet(org.folio.rest.persist.helpers.LocalRowSet) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Row(io.vertx.sqlclient.Row) RowDesc(io.vertx.sqlclient.impl.RowDesc) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 3 with Row

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());
}
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) QueryHelper(org.folio.rest.persist.PostgresClient.QueryHelper) Transaction(io.vertx.sqlclient.Transaction) Async(io.vertx.ext.unit.Async) JsonObject(io.vertx.core.json.JsonObject) Row(io.vertx.sqlclient.Row) ResultInfo(org.folio.rest.jaxrs.model.ResultInfo) Test(org.junit.Test)

Example 4 with Row

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));
            }
        });
    });
}
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 5 with Row

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());
}
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)

Aggregations

Row (io.vertx.sqlclient.Row)22 PgPool (io.vertx.pgclient.PgPool)12 ArrayList (java.util.ArrayList)11 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)10 IOException (java.io.IOException)10 PgConnection (io.vertx.pgclient.PgConnection)9 RowSet (io.vertx.sqlclient.RowSet)9 SqlConnection (io.vertx.sqlclient.SqlConnection)9 Transaction (io.vertx.sqlclient.Transaction)9 LinkedList (java.util.LinkedList)9 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)9 Handler (io.vertx.core.Handler)8 RowImpl (io.vertx.pgclient.impl.RowImpl)8 PreparedStatement (io.vertx.sqlclient.PreparedStatement)8 Tuple (io.vertx.sqlclient.Tuple)8 RowDesc (io.vertx.sqlclient.impl.RowDesc)8 LocalRowSet (org.folio.rest.persist.helpers.LocalRowSet)8 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)7 AsyncResult (io.vertx.core.AsyncResult)7 Future (io.vertx.core.Future)7