use of org.folio.dao.util.RecordDaoUtil in project mod-source-record-storage by folio-org.
the class RecordServiceTest method getMarcSourceRecordsByListOfIdsThatAreDeleted.
private void getMarcSourceRecordsByListOfIdsThatAreDeleted(TestContext context, Record.RecordType recordType, RecordType parsedRecordType) {
Async async = context.async();
List<Record> records = TestMocks.getRecords().stream().map(record -> {
Record deletedRecord = new Record().withId(record.getId()).withSnapshotId(record.getSnapshotId()).withMatchedId(record.getMatchedId()).withRecordType(record.getRecordType()).withState(State.DELETED).withGeneration(record.getGeneration()).withOrder(record.getOrder()).withLeaderRecordStatus(record.getLeaderRecordStatus()).withRawRecord(record.getRawRecord()).withParsedRecord(record.getParsedRecord()).withAdditionalInfo(record.getAdditionalInfo()).withExternalIdsHolder(record.getExternalIdsHolder());
if (Objects.nonNull(record.getMetadata())) {
deletedRecord.withMetadata(record.getMetadata());
}
if (Objects.nonNull(record.getErrorRecord())) {
deletedRecord.withErrorRecord(record.getErrorRecord());
}
return deletedRecord;
}).collect(Collectors.toList());
RecordCollection recordCollection = new RecordCollection().withRecords(records).withTotalRecords(records.size());
saveRecords(recordCollection.getRecords()).onComplete(batch -> {
if (batch.failed()) {
context.fail(batch.cause());
}
List<String> ids = records.stream().filter(r -> r.getRecordType().equals(recordType)).map(Record::getMatchedId).collect(Collectors.toList());
recordService.getSourceRecords(ids, IdType.RECORD, parsedRecordType, true, TENANT_ID).onComplete(get -> {
if (get.failed()) {
context.fail(get.cause());
}
List<SourceRecord> expected = records.stream().filter(r -> r.getRecordType().equals(recordType)).map(RecordDaoUtil::toSourceRecord).sorted(comparing(SourceRecord::getRecordId)).collect(Collectors.toList());
get.result().getSourceRecords().sort(comparing(SourceRecord::getRecordId));
context.assertEquals(expected.size(), get.result().getTotalRecords());
compareSourceRecords(context, expected, get.result().getSourceRecords());
async.complete();
});
});
}
use of org.folio.dao.util.RecordDaoUtil in project mod-source-record-storage by folio-org.
the class RecordServiceTest method getMarcSourceRecords.
private void getMarcSourceRecords(TestContext context, RecordType parsedRecordType, Record.RecordType recordType) {
Async async = context.async();
List<Record> records = TestMocks.getRecords();
RecordCollection recordCollection = new RecordCollection().withRecords(records).withTotalRecords(records.size());
saveRecords(recordCollection.getRecords()).onComplete(batch -> {
if (batch.failed()) {
context.fail(batch.cause());
}
Condition condition = DSL.trueCondition();
List<OrderField<?>> orderFields = new ArrayList<>();
recordService.getSourceRecords(condition, parsedRecordType, orderFields, 0, 10, TENANT_ID).onComplete(get -> {
if (get.failed()) {
context.fail(get.cause());
}
List<SourceRecord> expected = records.stream().filter(r -> r.getRecordType().equals(recordType)).map(RecordDaoUtil::toSourceRecord).sorted(comparing(SourceRecord::getRecordId)).collect(Collectors.toList());
get.result().getSourceRecords().sort(comparing(SourceRecord::getRecordId));
context.assertEquals(expected.size(), get.result().getTotalRecords());
compareSourceRecords(context, expected, get.result().getSourceRecords());
async.complete();
});
});
}
use of org.folio.dao.util.RecordDaoUtil in project mod-source-record-storage by folio-org.
the class RecordServiceTest method getMarcSourceRecordsBetweenDates.
private void getMarcSourceRecordsBetweenDates(TestContext context, Record.RecordType recordType, RecordType parsedRecordType, OffsetDateTime earliestDate, OffsetDateTime latestDate) {
Async async = context.async();
List<Record> records = TestMocks.getRecords();
RecordCollection recordCollection = new RecordCollection().withRecords(records).withTotalRecords(records.size());
saveRecords(recordCollection.getRecords()).onComplete(batch -> {
if (batch.failed()) {
context.fail(batch.cause());
}
Condition condition = RECORDS_LB.CREATED_DATE.between(earliestDate, latestDate);
List<OrderField<?>> orderFields = new ArrayList<>();
recordService.getSourceRecords(condition, parsedRecordType, orderFields, 0, 10, TENANT_ID).onComplete(get -> {
if (get.failed()) {
context.fail(get.cause());
}
List<SourceRecord> expected = records.stream().filter(r -> r.getRecordType().equals(recordType)).map(RecordDaoUtil::toSourceRecord).sorted(comparing(SourceRecord::getRecordId)).collect(Collectors.toList());
get.result().getSourceRecords().sort(comparing(SourceRecord::getRecordId));
context.assertEquals(expected.size(), get.result().getTotalRecords());
compareSourceRecords(context, expected, get.result().getSourceRecords());
async.complete();
});
});
}
use of org.folio.dao.util.RecordDaoUtil in project mod-source-record-storage by folio-org.
the class RecordServiceTest method getMarcSourceRecordsByListOfIds.
private void getMarcSourceRecordsByListOfIds(TestContext context, Record.RecordType recordType, RecordType parsedRecordType) {
Async async = context.async();
List<Record> records = TestMocks.getRecords();
RecordCollection recordCollection = new RecordCollection().withRecords(records).withTotalRecords(records.size());
saveRecords(recordCollection.getRecords()).onComplete(batch -> {
if (batch.failed()) {
context.fail(batch.cause());
}
List<String> ids = records.stream().filter(r -> r.getRecordType().equals(recordType)).map(Record::getMatchedId).collect(Collectors.toList());
recordService.getSourceRecords(ids, IdType.RECORD, parsedRecordType, false, TENANT_ID).onComplete(get -> {
if (get.failed()) {
context.fail(get.cause());
}
List<SourceRecord> expected = records.stream().filter(r -> r.getRecordType().equals(recordType)).map(RecordDaoUtil::toSourceRecord).sorted(comparing(SourceRecord::getRecordId)).collect(Collectors.toList());
sortByRecordId(get);
context.assertEquals(expected.size(), get.result().getTotalRecords());
compareSourceRecords(context, expected, get.result().getSourceRecords());
async.complete();
});
});
}
use of org.folio.dao.util.RecordDaoUtil in project mod-source-record-storage by folio-org.
the class RecordDaoImpl method saveRecords.
@Override
public Future<RecordsBatchResponse> saveRecords(RecordCollection recordCollection, String tenantId) {
Promise<RecordsBatchResponse> promise = Promise.promise();
Set<UUID> matchedIds = new HashSet<>();
Set<String> snapshotIds = new HashSet<>();
Set<String> recordTypes = new HashSet<>();
List<RecordsLbRecord> dbRecords = new ArrayList<>();
List<RawRecordsLbRecord> dbRawRecords = new ArrayList<>();
List<Record2<UUID, JSONB>> dbParsedRecords = new ArrayList<>();
List<ErrorRecordsLbRecord> dbErrorRecords = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
recordCollection.getRecords().stream().map(RecordDaoUtil::ensureRecordHasId).map(RecordDaoUtil::ensureRecordHasSuppressDiscovery).map(RecordDaoUtil::ensureRecordForeignKeys).forEach(record -> {
// collect unique matched ids to query to determine generation
matchedIds.add(UUID.fromString(record.getMatchedId()));
// make sure only one snapshot id
snapshotIds.add(record.getSnapshotId());
if (snapshotIds.size() > 1) {
throw new BadRequestException("Batch record collection only supports single snapshot");
}
if (Objects.nonNull(record.getRecordType())) {
recordTypes.add(record.getRecordType().name());
} else {
throw new BadRequestException(StringUtils.defaultIfEmpty(record.getErrorRecord().getDescription(), String.format("Record with id %s has not record type", record.getId())));
}
// make sure only one record type
if (recordTypes.size() > 1) {
throw new BadRequestException("Batch record collection only supports single record type");
}
// if record has parsed record, validate by attempting format
if (Objects.nonNull(record.getParsedRecord())) {
try {
RecordType recordType = toRecordType(record.getRecordType().name());
recordType.formatRecord(record);
Record2<UUID, JSONB> dbParsedRecord = recordType.toDatabaseRecord2(record.getParsedRecord());
dbParsedRecords.add(dbParsedRecord);
} catch (Exception e) {
// create error record and remove from record
Object content = Objects.nonNull(record.getParsedRecord()) ? record.getParsedRecord().getContent() : null;
ErrorRecord errorRecord = new ErrorRecord().withId(record.getId()).withDescription(e.getMessage()).withContent(content);
errorMessages.add(format(INVALID_PARSED_RECORD_MESSAGE_TEMPLATE, record.getId(), e.getMessage()));
record.withErrorRecord(errorRecord).withParsedRecord(null).withLeaderRecordStatus(null);
}
}
if (Objects.nonNull(record.getRawRecord())) {
dbRawRecords.add(RawRecordDaoUtil.toDatabaseRawRecord(record.getRawRecord()));
}
if (Objects.nonNull(record.getErrorRecord())) {
dbErrorRecords.add(ErrorRecordDaoUtil.toDatabaseErrorRecord(record.getErrorRecord()));
}
dbRecords.add(RecordDaoUtil.toDatabaseRecord(record));
});
UUID snapshotId = UUID.fromString(snapshotIds.stream().findFirst().orElseThrow());
RecordType recordType = toRecordType(recordTypes.stream().findFirst().orElseThrow());
try (Connection connection = getConnection(tenantId)) {
DSL.using(connection).transaction(ctx -> {
DSLContext dsl = DSL.using(ctx);
// validate snapshot
Optional<SnapshotsLbRecord> snapshot = DSL.using(ctx).selectFrom(SNAPSHOTS_LB).where(SNAPSHOTS_LB.ID.eq(snapshotId)).fetchOptional();
if (snapshot.isPresent()) {
if (Objects.isNull(snapshot.get().getProcessingStartedDate())) {
throw new BadRequestException(format(SNAPSHOT_NOT_STARTED_MESSAGE_TEMPLATE, snapshot.get().getStatus()));
}
} else {
throw new NotFoundException(format(SNAPSHOT_NOT_FOUND_TEMPLATE, snapshotId));
}
List<UUID> ids = new ArrayList<>();
Map<UUID, Integer> matchedGenerations = new HashMap<>();
// lookup latest generation by matched id and committed snapshot updated before current snapshot
dsl.select(RECORDS_LB.MATCHED_ID, RECORDS_LB.ID, RECORDS_LB.GENERATION).distinctOn(RECORDS_LB.MATCHED_ID).from(RECORDS_LB).innerJoin(SNAPSHOTS_LB).on(RECORDS_LB.SNAPSHOT_ID.eq(SNAPSHOTS_LB.ID)).where(RECORDS_LB.MATCHED_ID.in(matchedIds).and(SNAPSHOTS_LB.STATUS.in(JobExecutionStatus.COMMITTED, JobExecutionStatus.ERROR)).and(SNAPSHOTS_LB.UPDATED_DATE.lessThan(dsl.select(SNAPSHOTS_LB.PROCESSING_STARTED_DATE).from(SNAPSHOTS_LB).where(SNAPSHOTS_LB.ID.eq(snapshotId))))).orderBy(RECORDS_LB.MATCHED_ID.asc(), RECORDS_LB.GENERATION.desc()).fetchStream().forEach(r -> {
UUID id = r.get(RECORDS_LB.ID);
UUID matchedId = r.get(RECORDS_LB.MATCHED_ID);
int generation = r.get(RECORDS_LB.GENERATION);
ids.add(id);
matchedGenerations.put(matchedId, generation);
});
// update matching records state
dsl.update(RECORDS_LB).set(RECORDS_LB.STATE, RecordState.OLD).where(RECORDS_LB.ID.in(ids)).execute();
// batch insert records updating generation if required
List<LoaderError> recordsLoadingErrors = dsl.loadInto(RECORDS_LB).batchAfter(1000).bulkAfter(500).commitAfter(1000).onErrorAbort().loadRecords(dbRecords.stream().map(record -> {
Integer generation = matchedGenerations.get(record.getMatchedId());
if (Objects.nonNull(generation)) {
record.setGeneration(generation + 1);
} else if (Objects.isNull(record.getGeneration())) {
record.setGeneration(0);
}
return record;
}).collect(Collectors.toList())).fieldsFromSource().execute().errors();
recordsLoadingErrors.forEach(error -> {
if (error.exception().sqlState().equals(UNIQUE_VIOLATION_SQL_STATE)) {
throw new DuplicateEventException("SQL Unique constraint violation prevented repeatedly saving the record");
}
LOG.warn("Error occurred on batch execution: {}", error.exception().getCause().getMessage());
LOG.debug("Failed to execute statement from batch: {}", error.query());
});
// batch insert raw records
dsl.loadInto(RAW_RECORDS_LB).batchAfter(250).commitAfter(1000).onDuplicateKeyUpdate().onErrorAbort().loadRecords(dbRawRecords).fieldsFromSource().execute();
// batch insert parsed records
recordType.toLoaderOptionsStep(dsl).batchAfter(250).commitAfter(1000).onDuplicateKeyUpdate().onErrorAbort().loadRecords(dbParsedRecords).fieldsFromSource().execute();
if (!dbErrorRecords.isEmpty()) {
// batch insert error records
dsl.loadInto(ERROR_RECORDS_LB).batchAfter(250).commitAfter(1000).onDuplicateKeyUpdate().onErrorAbort().loadRecords(dbErrorRecords).fieldsFromSource().execute();
}
promise.complete(new RecordsBatchResponse().withRecords(recordCollection.getRecords()).withTotalRecords(recordCollection.getRecords().size()).withErrorMessages(errorMessages));
});
} catch (DuplicateEventException e) {
LOG.info("Skipped saving records due to duplicate event: {}", e.getMessage());
promise.fail(e);
} catch (SQLException | DataAccessException e) {
LOG.error("Failed to save records", e);
promise.fail(e);
}
return promise.future();
}
Aggregations