Search in sources :

Example 1 with Tuple

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

the class PostgresClientIT method executeList.

@Test
public void executeList(TestContext context) {
    Async async = context.async();
    JsonArray ids = new JsonArray().add(randomUuid()).add(randomUuid());
    List<Tuple> list = new ArrayList<>(2);
    list.add(Tuple.of(UUID.fromString(ids.getString(0))));
    list.add(Tuple.of(UUID.fromString(ids.getString(1))));
    insertXAndSingleQuotePojo(context, ids).execute("DELETE FROM tenant_raml_module_builder.foo WHERE id=$1", list, res -> {
        assertSuccess(context, res);
        List<RowSet<Row>> result = res.result();
        context.assertEquals(2, result.size());
        context.assertEquals(1, result.get(0).rowCount());
        context.assertEquals(1, result.get(1).rowCount());
        async.complete();
    });
}
Also used : JsonArray(io.vertx.core.json.JsonArray) Async(io.vertx.ext.unit.Async) ArrayList(java.util.ArrayList) RowSet(io.vertx.sqlclient.RowSet) LocalRowSet(org.folio.rest.persist.helpers.LocalRowSet) Tuple(io.vertx.sqlclient.Tuple) Test(org.junit.Test)

Example 2 with Tuple

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

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

the class Conn method saveBatch.

/**
 * Insert or upsert the entities into table.
 *
 * <p>A transaction must be open on this {@link #Conn} so that SELECT ... FOR UPDATE works.
 *
 * @param upsert  true for upsert, false for insert with fail on duplicate id
 * @param table  destination table to insert into
 * @param entities  each array element is a String with the content for the JSONB field of table; if id is missing a random id is generated
 * @return one result row per inserted row, containing the id field
 */
Future<RowSet<Row>> saveBatch(boolean upsert, String table, JsonArray entities) {
    try {
        List<Tuple> list = new ArrayList<>();
        if (entities != null) {
            for (int i = 0; i < entities.size(); i++) {
                String json = entities.getString(i);
                JsonObject jsonObject = new JsonObject(json);
                String id = jsonObject.getString("id");
                list.add(Tuple.of(id == null ? UUID.randomUUID() : UUID.fromString(id), jsonObject));
            }
        }
        return saveBatchInternal(upsert, table, list);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Future.failedFuture(e);
    }
}
Also used : ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Tuple(io.vertx.sqlclient.Tuple) FunctionWithException(org.folio.rest.persist.PostgresClient.FunctionWithException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) UncheckedIOException(java.io.UncheckedIOException)

Example 4 with Tuple

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

the class Conn method updateBatch.

/**
 * Update the entities in the table , match using the id property.
 *
 * <p>A transaction must be open on this {@link #Conn} so that SELECT ... FOR UPDATE works.
 *
 * @param entities  each array element is a String with the content for the JSONB field of table
 * @return one {@link RowSet} per array element with {@link RowSet#rowCount()} information
 */
public Future<RowSet<Row>> updateBatch(String table, JsonArray entities) {
    try {
        if (entities == null || entities.size() == 0) {
            return Future.succeededFuture();
        }
        List<Tuple> list = new ArrayList<>(entities.size());
        for (int i = 0; i < entities.size(); i++) {
            Object o = entities.getValue(i);
            list.add(Tuple.of(o instanceof JsonObject ? o : new JsonObject(o.toString())));
        }
        return updateBatchInternal(table, list);
    } catch (Throwable t) {
        log.error("updateBatch error " + t.getMessage(), t);
        return Future.failedFuture(t);
    }
}
Also used : ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject) Tuple(io.vertx.sqlclient.Tuple)

Example 5 with Tuple

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

the class Conn method saveBatch.

/**
 * A transaction must be open on this {@link #Conn} so that SELECT ... FOR UPDATE works.
 */
<T> Future<RowSet<Row>> saveBatch(boolean upsert, String table, List<T> entities) {
    try {
        if (entities == null || entities.isEmpty()) {
            return Future.succeededFuture(emptyRowSetOfId());
        }
        List<Tuple> batch = new ArrayList<>(entities.size());
        // We must use reflection, the POJOs don't have an interface/superclass in common.
        Method getIdMethod = entities.get(0).getClass().getDeclaredMethod("getId");
        for (Object entity : entities) {
            Object obj = getIdMethod.invoke(entity);
            UUID id = obj == null ? UUID.randomUUID() : UUID.fromString((String) obj);
            batch.add(Tuple.of(id, PostgresClient.pojo2JsonObject(entity)));
        }
        return saveBatchInternal(upsert, table, batch);
    } catch (Exception e) {
        log.error("saveBatch error " + e.getMessage(), e);
        return Future.failedFuture(e);
    }
}
Also used : ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Method(java.lang.reflect.Method) UUID(java.util.UUID) Tuple(io.vertx.sqlclient.Tuple) FunctionWithException(org.folio.rest.persist.PostgresClient.FunctionWithException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) UncheckedIOException(java.io.UncheckedIOException)

Aggregations

Tuple (io.vertx.sqlclient.Tuple)5 ArrayList (java.util.ArrayList)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 JsonObject (io.vertx.core.json.JsonObject)3 UncheckedIOException (java.io.UncheckedIOException)2 FunctionWithException (org.folio.rest.persist.PostgresClient.FunctionWithException)2 TemplateException (freemarker.template.TemplateException)1 JsonArray (io.vertx.core.json.JsonArray)1 Async (io.vertx.ext.unit.Async)1 PgConnection (io.vertx.pgclient.PgConnection)1 Row (io.vertx.sqlclient.Row)1 RowSet (io.vertx.sqlclient.RowSet)1 IOException (java.io.IOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 HashMap (java.util.HashMap)1 UUID (java.util.UUID)1 LocalRowSet (org.folio.rest.persist.helpers.LocalRowSet)1 Test (org.junit.Test)1