Search in sources :

Example 6 with SQLConnection

use of org.folio.rest.persist.SQLConnection in project mod-source-record-manager by folio-org.

the class SourceRecordStateDaoImpl method save.

@Override
public Future<String> save(SourceRecordState state, String tenantId) {
    state.withId(UUID.randomUUID().toString());
    PostgresClient client = pgClientFactory.createInstance(tenantId);
    return DbUtil.executeInTransaction(client, sqlConnection -> get(state.getSourceRecordId(), sqlConnection, tenantId).compose(sourceRecordStateOptional -> {
        if (sourceRecordStateOptional.isPresent()) {
            return update(state, sqlConnection, tenantId).map(state.getId());
        } else {
            return save(state, sqlConnection, tenantId);
        }
    }));
}
Also used : ValidationHelper(org.folio.rest.tools.utils.ValidationHelper) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) Promise(io.vertx.core.Promise) Criteria(org.folio.rest.persist.Criteria.Criteria) SQLConnection(org.folio.rest.persist.SQLConnection) Autowired(org.springframework.beans.factory.annotation.Autowired) UUID(java.util.UUID) Future(io.vertx.core.Future) PostgresClient(org.folio.rest.persist.PostgresClient) NotFoundException(javax.ws.rs.NotFoundException) DaoUtil.constructCriteria(org.folio.dataimport.util.DaoUtil.constructCriteria) PostgresClientFactory(org.folio.dao.util.PostgresClientFactory) Logger(org.apache.logging.log4j.Logger) Criterion(org.folio.rest.persist.Criteria.Criterion) Results(org.folio.rest.persist.interfaces.Results) Optional(java.util.Optional) AsyncResult(io.vertx.core.AsyncResult) Repository(org.springframework.stereotype.Repository) LogManager(org.apache.logging.log4j.LogManager) DbUtil(org.folio.dao.util.DbUtil) SourceRecordState(org.folio.rest.jaxrs.model.SourceRecordState) PostgresClient(org.folio.rest.persist.PostgresClient)

Example 7 with SQLConnection

use of org.folio.rest.persist.SQLConnection in project mod-inventory-storage by folio-org.

the class ItemService method updateEffectiveCallNumbersAndLocation.

private Future<RowSet<Row>> updateEffectiveCallNumbersAndLocation(AsyncResult<SQLConnection> connectionResult, Collection<Item> items, HoldingsRecord holdingsRecord) {
    final Promise<RowSet<Row>> allItemsUpdated = promise();
    final var batchFactories = items.stream().map(item -> effectiveValuesService.populateEffectiveValues(item, holdingsRecord)).map(this::updateSingleItemBatchFactory).collect(toList());
    final SQLConnection connection = connectionResult.result();
    Future<RowSet<Row>> lastUpdate = succeededFuture();
    for (var factory : batchFactories) {
        lastUpdate = lastUpdate.compose(prev -> factory.apply(connection));
    }
    lastUpdate.onComplete(allItemsUpdated);
    return allItemsUpdated.future();
}
Also used : ITEM_TABLE(org.folio.rest.impl.ItemStorageAPI.ITEM_TABLE) DeleteItemStorageItemsByItemIdResponse(org.folio.rest.jaxrs.resource.ItemStorage.DeleteItemStorageItemsByItemIdResponse) Promise.promise(io.vertx.core.Promise.promise) MAX_ENTITIES(org.folio.rest.impl.StorageHelper.MAX_ENTITIES) Date(java.util.Date) Context(io.vertx.core.Context) Tuple(io.vertx.sqlclient.Tuple) PgUtil.postgresClient(org.folio.rest.persist.PgUtil.postgresClient) CollectionUtil.deepCopy(org.folio.rest.support.CollectionUtil.deepCopy) Matcher(java.util.regex.Matcher) BatchOperationContextFactory.buildBatchOperationContext(org.folio.services.batch.BatchOperationContextFactory.buildBatchOperationContext) Map(java.util.Map) PgExceptionUtil(org.folio.rest.persist.PgExceptionUtil) JsonObject(io.vertx.core.json.JsonObject) HOLDINGS_RECORD_TABLE(org.folio.rest.impl.HoldingsStorageAPI.HOLDINGS_RECORD_TABLE) Collection(java.util.Collection) Future(io.vertx.core.Future) PostgresClient(org.folio.rest.persist.PostgresClient) PostItemStorageItemsResponse(org.folio.rest.jaxrs.resource.ItemStorage.PostItemStorageItemsResponse) PostItemStorageBatchSynchronousResponse(org.folio.rest.jaxrs.resource.ItemStorageBatchSynchronous.PostItemStorageBatchSynchronousResponse) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Response(javax.ws.rs.core.Response) BadRequestException(org.folio.rest.exceptions.BadRequestException) LogManager.getLogger(org.apache.logging.log4j.LogManager.getLogger) Pattern(java.util.regex.Pattern) PostgresClientFuturized(org.folio.rest.persist.PostgresClientFuturized) Future.succeededFuture(io.vertx.core.Future.succeededFuture) Item(org.folio.rest.jaxrs.model.Item) PgUtil.postSync(org.folio.rest.persist.PgUtil.postSync) ItemDomainEventPublisher(org.folio.services.domainevent.ItemDomainEventPublisher) CommonValidators(org.folio.validator.CommonValidators) ObjectMapperTool.readValue(org.folio.dbschema.ObjectMapperTool.readValue) Function(java.util.function.Function) HridValidators.refuseWhenHridChanged(org.folio.validator.HridValidators.refuseWhenHridChanged) HoldingsRecord(org.folio.rest.jaxrs.model.HoldingsRecord) RowSet(io.vertx.sqlclient.RowSet) AsyncResult(io.vertx.core.AsyncResult) ItemRepository(org.folio.persist.ItemRepository) Promise(io.vertx.core.Promise) PgUtil.deleteById(org.folio.rest.persist.PgUtil.deleteById) SQLConnection(org.folio.rest.persist.SQLConnection) PutItemStorageItemsByItemIdResponse(org.folio.rest.jaxrs.resource.ItemStorage.PutItemStorageItemsByItemIdResponse) HridManager(org.folio.rest.support.HridManager) ResponseException(org.folio.rest.tools.client.exceptions.ResponseException) ItemEffectiveValuesService(org.folio.services.ItemEffectiveValuesService) Collectors.toList(java.util.stream.Collectors.toList) PgUtil.post(org.folio.rest.persist.PgUtil.post) Row(io.vertx.sqlclient.Row) PostgresClient.pojo2JsonObject(org.folio.rest.persist.PostgresClient.pojo2JsonObject) SQLConnection(org.folio.rest.persist.SQLConnection) RowSet(io.vertx.sqlclient.RowSet)

Example 8 with SQLConnection

use of org.folio.rest.persist.SQLConnection in project mod-source-record-manager by folio-org.

the class JobExecutionProgressDaoImpl method updateByJobExecutionId.

@Override
public Future<JobExecutionProgress> updateByJobExecutionId(String jobExecutionId, UnaryOperator<JobExecutionProgress> progressMutator, String tenantId) {
    String rollbackMessage = String.format(ROLLBACK_MESSAGE, jobExecutionId);
    Promise<JobExecutionProgress> promise = Promise.promise();
    Promise<SQLConnection> tx = Promise.promise();
    PostgresClient pgClient = pgClientFactory.createInstance(tenantId);
    getSelectResult(tx, pgClient, jobExecutionId, tenantId).map(progressResults -> {
        Optional<JobExecutionProgress> optionalJobExecutionProgress = mapResultSetToOptionalJobExecutionProgress(progressResults);
        if (optionalJobExecutionProgress.isEmpty()) {
            throw new NotFoundException(rollbackMessage);
        }
        return progressMutator.apply(optionalJobExecutionProgress.get());
    }).compose(mutatedProgress -> updateProgressByJobExecutionId(tx.future(), mutatedProgress, tenantId)).onComplete(updateAr -> {
        if (updateAr.succeeded()) {
            pgClient.endTx(tx.future(), endTx -> promise.complete(updateAr.result()));
        } else {
            LOGGER.error(rollbackMessage, updateAr.cause());
            pgClient.rollbackTx(tx.future(), r -> promise.fail(updateAr.cause()));
        }
    });
    return promise.future();
}
Also used : ValidationHelper(org.folio.rest.tools.utils.ValidationHelper) Promise(io.vertx.core.Promise) PostgresClient.convertToPsqlStandard(org.folio.rest.persist.PostgresClient.convertToPsqlStandard) SQLConnection(org.folio.rest.persist.SQLConnection) Autowired(org.springframework.beans.factory.annotation.Autowired) UnaryOperator(java.util.function.UnaryOperator) Future(io.vertx.core.Future) NotFoundException(javax.ws.rs.NotFoundException) PostgresClient(org.folio.rest.persist.PostgresClient) Tuple(io.vertx.sqlclient.Tuple) PostgresClientFactory(org.folio.dao.util.PostgresClientFactory) RowIterator(io.vertx.sqlclient.RowIterator) Logger(org.apache.logging.log4j.Logger) JobExecutionProgress(org.folio.rest.jaxrs.model.JobExecutionProgress) Row(io.vertx.sqlclient.Row) Optional(java.util.Optional) RowSet(io.vertx.sqlclient.RowSet) AsyncResult(io.vertx.core.AsyncResult) Repository(org.springframework.stereotype.Repository) LogManager(org.apache.logging.log4j.LogManager) JobExecutionProgress(org.folio.rest.jaxrs.model.JobExecutionProgress) SQLConnection(org.folio.rest.persist.SQLConnection) NotFoundException(javax.ws.rs.NotFoundException) PostgresClient(org.folio.rest.persist.PostgresClient)

Example 9 with SQLConnection

use of org.folio.rest.persist.SQLConnection in project mod-source-record-manager by folio-org.

the class JobExecutionProgressDaoImpl method getSelectResult.

private Future<RowSet<Row>> getSelectResult(Promise<SQLConnection> tx, PostgresClient pgClient, String jobExecutionId, String tenantId) {
    Tuple queryParams = Tuple.of(jobExecutionId);
    return Future.succeededFuture().compose(v -> {
        pgClient.startTx(tx);
        return tx.future();
    }).compose(sqlConnection -> {
        String selectProgressQuery = buildSelectProgressQuery(tenantId);
        Promise<RowSet<Row>> selectResult = Promise.promise();
        pgClient.execute(tx.future(), selectProgressQuery, queryParams, selectResult);
        return selectResult.future();
    }).compose(selectResult -> {
        Promise<RowSet<Row>> getProgressPromise = Promise.promise();
        String query = buildSelectByJobExecutionIdQuery(tenantId);
        pgClient.execute(tx.future(), query, queryParams, getProgressPromise);
        return getProgressPromise.future();
    });
}
Also used : ValidationHelper(org.folio.rest.tools.utils.ValidationHelper) Promise(io.vertx.core.Promise) PostgresClient.convertToPsqlStandard(org.folio.rest.persist.PostgresClient.convertToPsqlStandard) SQLConnection(org.folio.rest.persist.SQLConnection) Autowired(org.springframework.beans.factory.annotation.Autowired) UnaryOperator(java.util.function.UnaryOperator) Future(io.vertx.core.Future) NotFoundException(javax.ws.rs.NotFoundException) PostgresClient(org.folio.rest.persist.PostgresClient) Tuple(io.vertx.sqlclient.Tuple) PostgresClientFactory(org.folio.dao.util.PostgresClientFactory) RowIterator(io.vertx.sqlclient.RowIterator) Logger(org.apache.logging.log4j.Logger) JobExecutionProgress(org.folio.rest.jaxrs.model.JobExecutionProgress) Row(io.vertx.sqlclient.Row) Optional(java.util.Optional) RowSet(io.vertx.sqlclient.RowSet) AsyncResult(io.vertx.core.AsyncResult) Repository(org.springframework.stereotype.Repository) LogManager(org.apache.logging.log4j.LogManager) Promise(io.vertx.core.Promise) RowSet(io.vertx.sqlclient.RowSet) Row(io.vertx.sqlclient.Row) Tuple(io.vertx.sqlclient.Tuple)

Example 10 with SQLConnection

use of org.folio.rest.persist.SQLConnection in project mod-circulation-storage by folio-org.

the class ExpirationTool method getExpiredRequests.

private static Future<List<Request>> getExpiredRequests(AsyncResult<SQLConnection> conn, Vertx vertx, String tenant) {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    df.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
    PostgresClient pgClient = PostgresClient.getInstance(vertx, tenant);
    Promise<RowSet<Row>> promise = Promise.promise();
    String where = format("WHERE " + "(jsonb->>'status' = '%1$s' AND jsonb->>'requestExpirationDate' < '%5$s') OR " + "(jsonb->>'status' = '%2$s' AND jsonb->>'requestExpirationDate' < '%5$s') OR " + "(jsonb->>'status' = '%3$s' AND jsonb->>'requestExpirationDate' < '%5$s') OR " + "(jsonb->>'status' = '%4$s' AND jsonb->>'holdShelfExpirationDate' < '%5$s') " + "LIMIT 150", OPEN_NOT_YET_FILLED.value(), OPEN_AWAITING_DELIVERY.value(), OPEN_IN_TRANSIT.value(), OPEN_AWAITING_PICKUP.value(), df.format(new Date()));
    String fullTableName = format("%s.%s", PostgresClient.convertToPsqlStandard(tenant), REQUEST_TABLE);
    String query = format("SELECT jsonb FROM %s %s", fullTableName, where);
    pgClient.select(conn, query, promise);
    return promise.future().map(rs -> rowSetToStream(rs).map(row -> row.get(JsonObject.class, row.getColumnIndex(JSONB_COLUMN))).map(json -> json.mapTo(Request.class)).collect(toList()));
}
Also used : Future.succeededFuture(io.vertx.core.Future.succeededFuture) OPEN_AWAITING_DELIVERY(org.folio.rest.jaxrs.model.Request.Status.OPEN_AWAITING_DELIVERY) REQUEST_EXPIRED(org.folio.support.exception.LogEventType.REQUEST_EXPIRED) Date(java.util.Date) SimpleDateFormat(java.text.SimpleDateFormat) REQUESTS(org.folio.support.LogEventPayloadField.REQUESTS) ArrayList(java.util.ArrayList) OPEN_NOT_YET_FILLED(org.folio.rest.jaxrs.model.Request.Status.OPEN_NOT_YET_FILLED) HashSet(java.util.HashSet) OPEN_AWAITING_PICKUP(org.folio.rest.jaxrs.model.Request.Status.OPEN_AWAITING_PICKUP) DbUtil.rowSetToStream(org.folio.support.DbUtil.rowSetToStream) REQUEST_TABLE(org.folio.support.ModuleConstants.REQUEST_TABLE) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Request(org.folio.rest.jaxrs.model.Request) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) RowSet(io.vertx.sqlclient.RowSet) ZoneOffset(java.time.ZoneOffset) AsyncResult(io.vertx.core.AsyncResult) CLOSED_UNFILLED(org.folio.rest.jaxrs.model.Request.Status.CLOSED_UNFILLED) Collectors.toSet(java.util.stream.Collectors.toSet) OPEN_IN_TRANSIT(org.folio.rest.jaxrs.model.Request.Status.OPEN_IN_TRANSIT) GenericCompositeFuture(org.folio.okapi.common.GenericCompositeFuture) ORIGINAL(org.folio.support.LogEventPayloadField.ORIGINAL) Collections.emptyList(java.util.Collections.emptyList) TimeZone(java.util.TimeZone) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Set(java.util.Set) SQLConnection(org.folio.rest.persist.SQLConnection) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) String.format(java.lang.String.format) PostgresClient(org.folio.rest.persist.PostgresClient) CLOSED_PICKUP_EXPIRED(org.folio.rest.jaxrs.model.Request.Status.CLOSED_PICKUP_EXPIRED) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Row(io.vertx.sqlclient.Row) UPDATED(org.folio.support.LogEventPayloadField.UPDATED) EventPublisherService(org.folio.service.EventPublisherService) Comparator(java.util.Comparator) LogManager(org.apache.logging.log4j.LogManager) RowSet(io.vertx.sqlclient.RowSet) Request(org.folio.rest.jaxrs.model.Request) PostgresClient(org.folio.rest.persist.PostgresClient) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Aggregations

AsyncResult (io.vertx.core.AsyncResult)12 Future (io.vertx.core.Future)12 Promise (io.vertx.core.Promise)12 PostgresClient (org.folio.rest.persist.PostgresClient)12 SQLConnection (org.folio.rest.persist.SQLConnection)12 Row (io.vertx.sqlclient.Row)11 RowSet (io.vertx.sqlclient.RowSet)11 Logger (org.apache.logging.log4j.Logger)11 LogManager (org.apache.logging.log4j.LogManager)10 List (java.util.List)8 Future.succeededFuture (io.vertx.core.Future.succeededFuture)7 JsonObject (io.vertx.core.json.JsonObject)7 ArrayList (java.util.ArrayList)7 Date (java.util.Date)7 Map (java.util.Map)7 String.format (java.lang.String.format)6 ZoneOffset (java.time.ZoneOffset)6 Collectors (java.util.stream.Collectors)6 Collectors.toList (java.util.stream.Collectors.toList)6 Vertx (io.vertx.core.Vertx)5