Search in sources :

Example 1 with Schema

use of org.folio.dbschema.Schema in project raml-module-builder by folio-org.

the class TenantAPIIT method previousSchemaSqlExistsTrue2.

@Test
public void previousSchemaSqlExistsTrue2(TestContext context) {
    TenantAPI tenantAPI = new TenantAPI();
    String tenantId = TenantTool.tenantId(okapiHeaders);
    Async async = context.async();
    // only run create.ftl .. This makes previousSchema to find nothing on 2nd invocation
    tenantAPI.sqlFile(vertx.getOrCreateContext(), tenantId, null, false).compose(files -> tenantAPI.postgresClient(vertx.getOrCreateContext()).runSQLFile(files[0], true)).compose(x -> tenantAPI.previousSchema(vertx.getOrCreateContext(), tenantId, true).onComplete(context.asyncAssertSuccess(schema -> {
        context.assertNull(schema);
        async.complete();
    })));
    async.await();
}
Also used : TestContext(io.vertx.ext.unit.TestContext) CoreMatchers(org.hamcrest.CoreMatchers) Async(io.vertx.ext.unit.Async) Date(java.util.Date) PostgresTesterContainer(org.folio.postgres.testing.PostgresTesterContainer) TemplateException(freemarker.template.TemplateException) RunWith(org.junit.runner.RunWith) SimpleDateFormat(java.text.SimpleDateFormat) HashMap(java.util.HashMap) VertxUtils(org.folio.rest.tools.utils.VertxUtils) Context(io.vertx.core.Context) Map(java.util.Map) Timeout(org.junit.rules.Timeout) Schema(org.folio.dbschema.Schema) JsonObject(io.vertx.core.json.JsonObject) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) AsyncResult(io.vertx.core.AsyncResult) TenantJob(org.folio.rest.jaxrs.model.TenantJob) TimeZone(java.util.TimeZone) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) UUID(java.util.UUID) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) TenantTool(org.folio.rest.tools.utils.TenantTool) Future(io.vertx.core.Future) PostgresClient(org.folio.rest.persist.PostgresClient) Book(org.folio.rest.jaxrs.model.Book) Mockito(org.mockito.Mockito) List(java.util.List) PgUtil(org.folio.rest.persist.PgUtil) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) TenantAttributes(org.folio.rest.jaxrs.model.TenantAttributes) org.junit(org.junit) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Async(io.vertx.ext.unit.Async)

Example 2 with Schema

use of org.folio.dbschema.Schema in project raml-module-builder by folio-org.

the class DbSchemaUtilsTest method setupSchema.

@Before
public void setupSchema() {
    Schema schema = new Schema();
    table = new Table();
    table.setTableName("users");
    table.setFullTextIndex(Arrays.asList(newIndex("name")));
    table.setGinIndex(Arrays.asList(newIndex("name")));
    table.setIndex(Arrays.asList(newIndex("name")));
    table.setUniqueIndex(Arrays.asList(newIndex("email")));
    table.setLikeIndex(Arrays.asList(newIndex("address")));
    schema.setTables(Arrays.asList(table));
}
Also used : Table(org.folio.dbschema.Table) Schema(org.folio.dbschema.Schema) Before(org.junit.Before)

Example 3 with Schema

use of org.folio.dbschema.Schema in project raml-module-builder by folio-org.

the class AdminAPI method putAdminPostgresCreateIndexes.

@Validate
@Override
public void putAdminPostgresCreateIndexes(Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
    try {
        String tenantId = TenantTool.tenantId(okapiHeaders);
        SchemaMaker sMaker = new SchemaMaker(tenantId, PostgresClient.getModuleName(), TenantOperation.CREATE, null, null);
        InputStream tableInput = AdminAPI.class.getClassLoader().getResourceAsStream(TenantAPI.TABLE_JSON);
        String tableInputStr = null;
        if (tableInput != null) {
            tableInputStr = IOUtils.toString(tableInput, "UTF8");
            Schema schema = ObjectMapperTool.getMapper().readValue(tableInputStr, Schema.class);
            sMaker.setSchema(schema);
        }
        String sqlFile = sMaker.generateIndexesOnly();
        PostgresClient.getInstance(vertxContext.owner()).runSQLFile(sqlFile, true, reply -> {
            try {
                StringBuilder res = new StringBuilder();
                if (reply.succeeded()) {
                    boolean failuresExist = false;
                    if (reply.result().size() > 0) {
                        failuresExist = true;
                    }
                    res.append(new JsonArray(reply.result()).encodePrettily());
                    if (failuresExist) {
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutAdminPostgresCreateIndexesResponse.respond400WithTextPlain(res.toString())));
                    } else {
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutAdminPostgresCreateIndexesResponse.respond204()));
                    }
                } else {
                    log.error(reply.cause().getMessage(), reply.cause());
                    asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutAdminPostgresCreateIndexesResponse.respond500WithTextPlain(reply.cause().getMessage())));
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutAdminPostgresCreateIndexesResponse.respond500WithTextPlain(e.getMessage())));
            }
        });
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutAdminPostgresCreateIndexesResponse.respond500WithTextPlain(e.getMessage())));
    }
}
Also used : JsonArray(io.vertx.core.json.JsonArray) InputStream(java.io.InputStream) Schema(org.folio.dbschema.Schema) SchemaMaker(org.folio.rest.persist.ddlgen.SchemaMaker) Validate(org.folio.rest.annotations.Validate)

Example 4 with Schema

use of org.folio.dbschema.Schema in project raml-module-builder by folio-org.

the class TenantAPI method sqlFile.

/**
 * @param tenantExists false for initial installation, true for upgrading
 * @param tenantAttributes parameters like module version that may influence generated SQL
 * @param previousSchema schema to upgrade from, may be null if unknown and on initial install
 * @return the SQL commands . 0 is immediate script (create, disable), 1 (optional) is update schema script.
 * @throws NoSchemaJsonException when templates/db_scripts/schema.json doesn't exist
 * @throws TemplateException when processing templates/db_scripts/schema.json fails
 */
public String[] sqlFile(String tenantId, boolean tenantExists, TenantAttributes tenantAttributes, Schema previousSchema) throws IOException, TemplateException {
    InputStream tableInput = TenantAPI.class.getClassLoader().getResourceAsStream(getTablePath());
    if (tableInput == null) {
        log.info("Could not find templates/db_scripts/schema.json , " + " RMB will not run any scripts for " + tenantId);
        throw new NoSchemaJsonException();
    }
    TenantOperation op = TenantOperation.CREATE;
    String previousVersion = null;
    String newVersion = tenantAttributes == null ? null : tenantAttributes.getModuleTo();
    if (tenantExists) {
        op = TenantOperation.UPDATE;
        if (tenantAttributes != null) {
            previousVersion = tenantAttributes.getModuleFrom();
        }
    }
    SchemaMaker sMaker = new SchemaMaker(tenantId, PostgresClient.getModuleName(), op, previousVersion, newVersion);
    String tableInputStr = IOUtils.toString(tableInput, StandardCharsets.UTF_8);
    sMaker.setSchemaJson(tableInputStr);
    Schema schema = ObjectMapperTool.readValue(tableInputStr, Schema.class);
    sMaker.setSchema(schema);
    sMaker.setPreviousSchema(previousSchema);
    if (tenantAttributes != null && Boolean.TRUE.equals(tenantAttributes.getPurge())) {
        return new String[] { sMaker.generatePurge() };
    }
    if (tenantAttributes != null && tenantAttributes.getModuleFrom() != null && tenantAttributes.getModuleTo() == null) {
        return new String[] { "" };
    }
    String[] scripts = new String[] { sMaker.generateCreate(), sMaker.generateSchemas() };
    log.debug("GENERATED CREATE {}", scripts[0]);
    log.debug("GENERATED SCHEMAS {}", scripts[1]);
    return scripts;
}
Also used : InputStream(java.io.InputStream) Schema(org.folio.dbschema.Schema) TenantOperation(org.folio.dbschema.TenantOperation) SchemaMaker(org.folio.rest.persist.ddlgen.SchemaMaker)

Example 5 with Schema

use of org.folio.dbschema.Schema in project raml-module-builder by folio-org.

the class SchemaMakerIT method triggerExists.

private boolean triggerExists(TestContext context, String name) {
    AtomicBoolean exists = new AtomicBoolean();
    Async async = context.async();
    PostgresClient postgresClient = PostgresClient.getInstance(vertx, tenant);
    postgresClient.selectSingle("SELECT count(*) FROM pg_trigger " + "WHERE tgrelid = '" + schema + ".test_tenantapi'::regclass AND tgname='" + name + "'", context.asyncAssertSuccess(count -> {
        exists.set(count.getInteger(0) == 1);
        async.complete();
    }));
    async.await(5000);
    return exists.get();
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) Arrays(java.util.Arrays) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) PostgresClientITBase(org.folio.rest.persist.PostgresClientITBase) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Timeout(io.vertx.ext.unit.junit.Timeout) Test(org.junit.Test) UUID(java.util.UUID) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) PostgresClient(org.folio.rest.persist.PostgresClient) TenantOperation(org.folio.dbschema.TenantOperation) List(java.util.List) Rule(org.junit.Rule) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ObjectMapperTool(org.folio.dbschema.ObjectMapperTool) ResourceUtil(org.folio.util.ResourceUtil) Schema(org.folio.dbschema.Schema) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Before(org.junit.Before) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Async(io.vertx.ext.unit.Async) PostgresClient(org.folio.rest.persist.PostgresClient)

Aggregations

Schema (org.folio.dbschema.Schema)10 Test (org.junit.Test)5 Async (io.vertx.ext.unit.Async)4 TestContext (io.vertx.ext.unit.TestContext)4 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)4 List (java.util.List)4 UUID (java.util.UUID)4 TenantOperation (org.folio.dbschema.TenantOperation)4 PostgresClient (org.folio.rest.persist.PostgresClient)4 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)4 Before (org.junit.Before)4 RunWith (org.junit.runner.RunWith)4 Timeout (io.vertx.ext.unit.junit.Timeout)3 Arrays (java.util.Arrays)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 ObjectMapperTool (org.folio.dbschema.ObjectMapperTool)3 InputStream (java.io.InputStream)2 PostgresClientITBase (org.folio.rest.persist.PostgresClientITBase)2 SchemaMaker (org.folio.rest.persist.ddlgen.SchemaMaker)2