Search in sources :

Example 16 with CQL2PgJSON

use of org.folio.cql2pgjson.CQL2PgJSON in project raml-module-builder by folio-org.

the class PostgresClientTransactionsIT method updateTransaction.

private void updateTransaction(TestContext context) {
    PostgresClient c1 = PostgresClient.getInstance(vertx, tenant);
    Async async = context.async();
    // create connection
    c1.startTx(handler -> {
        if (handler.succeeded()) {
            SimplePojo z = new SimplePojo();
            z.setId("1");
            z.setName("me");
            // update record
            CQL2PgJSON cql2pgJson = null;
            try {
                cql2pgJson = new CQL2PgJSON(table + ".jsonb");
            } catch (FieldException e1) {
                e1.printStackTrace();
                context.fail(e1);
            }
            CQLWrapper cql = new CQLWrapper(cql2pgJson, "name==d");
            c1.update(handler, "z", z, cql, true, reply -> {
                if (reply.succeeded()) {
                    // make sure record is not updated since not committed yet
                    c1.select("SELECT jsonb->>'name' FROM " + fullTable, reply2 -> {
                        if (!reply2.succeeded()) {
                            context.fail(reply2.cause());
                        }
                        try {
                            String name = reply2.result().iterator().next().getString(0);
                            context.assertEquals("d", name, "Name property should not have been changed");
                        } catch (Exception e) {
                            e.printStackTrace();
                            context.fail(e.getMessage());
                        }
                        // end transaction / commit
                        c1.endTx(handler, done -> {
                            if (done.succeeded()) {
                                // record should have been updated
                                c1.select("SELECT jsonb->>'name' FROM " + fullTable, selectReply -> {
                                    if (!selectReply.succeeded()) {
                                        context.fail(selectReply.cause());
                                    } else {
                                        try {
                                            String name = selectReply.result().iterator().next().getString(0);
                                            context.assertEquals("me", name, "Name property should have been changed");
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            context.fail(e.getMessage());
                                        }
                                        async.complete();
                                    }
                                });
                            } else {
                                context.fail(done.cause());
                            }
                        });
                    });
                } else {
                    context.fail(reply.cause());
                }
            });
        } else {
            context.fail(handler.cause());
        }
    });
    async.await(5000);
    c1.closeClient(context.asyncAssertSuccess());
}
Also used : CQL2PgJSON(org.folio.cql2pgjson.CQL2PgJSON) FieldException(org.folio.cql2pgjson.exception.FieldException) Async(io.vertx.ext.unit.Async) SimplePojo(org.folio.rest.persist.helpers.SimplePojo) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) FieldException(org.folio.cql2pgjson.exception.FieldException)

Example 17 with CQL2PgJSON

use of org.folio.cql2pgjson.CQL2PgJSON in project raml-module-builder by folio-org.

the class CQL2PGCLIMain method handleOptions.

static String handleOptions(String[] args) throws FieldException, IOException, QueryValidationException, ParseException {
    Options options = new Options();
    Option database = Option.builder("t").hasArg().required(true).desc("Postgres table name").build();
    Option field = Option.builder("f").hasArg().required(false).desc("Postgres field name").build();
    Option dbschema = Option.builder("b").hasArg().required(false).desc("Path to RMB-style schema.json to describe database").build();
    options.addOption(database);
    options.addOption(field);
    options.addOption(dbschema);
    CommandLineParser parser = new DefaultParser();
    CommandLine line = parser.parse(options, args);
    CQL2PgJSON cql2pgJson = null;
    String fullFieldName = line.getOptionValue("t") + "." + line.getOptionValue("f", "jsonb");
    cql2pgJson = new CQL2PgJSON(fullFieldName);
    if (line.hasOption("b")) {
        cql2pgJson.setDbSchemaPath(line.getOptionValue("b"));
    }
    List<String> cliArgs = line.getArgList();
    String cql = cliArgs.get(0);
    return parseCQL(cql2pgJson, line.getOptionValue("t"), cql);
}
Also used : Options(org.apache.commons.cli.Options) CQL2PgJSON(org.folio.cql2pgjson.CQL2PgJSON) CommandLine(org.apache.commons.cli.CommandLine) Option(org.apache.commons.cli.Option) CommandLineParser(org.apache.commons.cli.CommandLineParser) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 18 with CQL2PgJSON

use of org.folio.cql2pgjson.CQL2PgJSON in project raml-module-builder by folio-org.

the class TestCLI method testCLIWithDBSchema.

@Test
public void testCLIWithDBSchema() throws FieldException, IOException, ParseException, QueryValidationException {
    String cql = "hrid=\"fcd64ce1-6995-48f0-840e-89ffa2\"";
    String[] args = new String[] { "-t", "instance", "-f", "jsonb", "-b", dbSchemaPath, cql };
    String fullFieldName = "instance.jsonb";
    CQL2PgJSON cql2pgjson = new CQL2PgJSON(fullFieldName);
    cql2pgjson.setDbSchemaPath(dbSchemaPath);
    String output = CQL2PGCLIMain.parseCQL(cql2pgjson, "instance", cql);
    String cli_output = CQL2PGCLIMain.handleOptions(args);
    assertNotNull(output);
    logger.info(output);
    logger.info(cli_output);
    assertEquals(output, cli_output);
}
Also used : CQL2PgJSON(org.folio.cql2pgjson.CQL2PgJSON) Test(org.junit.Test)

Example 19 with CQL2PgJSON

use of org.folio.cql2pgjson.CQL2PgJSON in project raml-module-builder by folio-org.

the class ConnIT method streamGet.

@ParameterizedTest
@CsvSource({ "key=*, 2", "key=b, 1", "key=x, 0" })
void streamGet(String cql, int total, VertxTestContext vtc) throws CQL2PgJSONException {
    AtomicInteger count = new AtomicInteger();
    AtomicBoolean end = new AtomicBoolean();
    CQLWrapper cqlWrapper = new CQLWrapper(new CQL2PgJSON("jsonb"), cql);
    with(randomUuid(), "a", randomUuid(), "b", trans -> {
        return trans.streamGet("t", Pojo.class, cqlWrapper, as -> {
            PostgresClientStreamResult<Pojo> r = as.result();
            assertThat(r.resultInfo().getTotalRecords()).isEqualTo(total);
            r.handler(x -> count.incrementAndGet());
            r.exceptionHandler(t -> vtc.failNow(t));
            r.endHandler(x -> end.set(true));
        });
    }).onComplete(succeedingThenComplete(vtc, x -> {
        assertThat(count.get()).isEqualTo(total);
        assertThat(end.get()).isTrue();
    }));
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) CsvSource(org.junit.jupiter.params.provider.CsvSource) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) BiFunction(java.util.function.BiFunction) PostgresTesterContainer(org.folio.postgres.testing.PostgresTesterContainer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WithAssertions(org.assertj.core.api.WithAssertions) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Timeout(io.vertx.junit5.Timeout) AfterAll(org.junit.jupiter.api.AfterAll) CQL2PgJSONException(org.folio.cql2pgjson.exception.CQL2PgJSONException) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BeforeAll(org.junit.jupiter.api.BeforeAll) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Vertx(io.vertx.core.Vertx) UUID(java.util.UUID) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Mockito(org.mockito.Mockito) JsonArray(io.vertx.core.json.JsonArray) CQL2PgJSON(org.folio.cql2pgjson.CQL2PgJSON) PgConnection(io.vertx.pgclient.PgConnection) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Handler(io.vertx.core.Handler) Collections(java.util.Collections) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CQL2PgJSON(org.folio.cql2pgjson.CQL2PgJSON) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) CsvSource(org.junit.jupiter.params.provider.CsvSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 20 with CQL2PgJSON

use of org.folio.cql2pgjson.CQL2PgJSON in project raml-module-builder by folio-org.

the class PostgresClientIT method getCQLWrapperFailure.

@Test
public void getCQLWrapperFailure(TestContext context) throws IOException, FieldException {
    final String tableDefiniton = "id UUID PRIMARY KEY , jsonb JSONB NOT NULL, distinct_test_field TEXT";
    createTableWithPoLines(context, MOCK_POLINES_TABLE, tableDefiniton);
    CQL2PgJSON cql2pgJson = new CQL2PgJSON("jsonb");
    {
        CQLWrapper cqlWrapper = new CQLWrapper(cql2pgJson, // syntax error
        "cql.allRecords=");
        Async async = context.async();
        postgresClient.get(MOCK_POLINES_TABLE, Object.class, "*", cqlWrapper, true, true, null, null, /*facets*/
        handler -> {
            context.assertTrue(handler.failed());
            async.complete();
        });
        async.awaitSuccess();
    }
}
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) CQL2PgJSON(org.folio.cql2pgjson.CQL2PgJSON) Async(io.vertx.ext.unit.Async) JsonObject(io.vertx.core.json.JsonObject) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) Test(org.junit.Test)

Aggregations

CQL2PgJSON (org.folio.cql2pgjson.CQL2PgJSON)25 CQLWrapper (org.folio.rest.persist.cql.CQLWrapper)22 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)16 Test (org.junit.Test)16 AsyncResult (io.vertx.core.AsyncResult)14 Future (io.vertx.core.Future)14 Handler (io.vertx.core.Handler)14 Vertx (io.vertx.core.Vertx)14 JsonArray (io.vertx.core.json.JsonArray)14 JsonObject (io.vertx.core.json.JsonObject)14 Async (io.vertx.ext.unit.Async)14 PgConnection (io.vertx.pgclient.PgConnection)14 Collections (java.util.Collections)14 UUID (java.util.UUID)14 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)14 Function (java.util.function.Function)14 PostgresTesterContainer (org.folio.postgres.testing.PostgresTesterContainer)14 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)12 CompositeFuture (io.vertx.core.CompositeFuture)12 Promise (io.vertx.core.Promise)12