use of com.mongodb.bulk.BulkWriteResult in project mongo-java-driver by mongodb.
the class JsonPoweredCrudTestHelper method getBulkWriteResult.
BsonDocument getBulkWriteResult(final BsonDocument collectionOptions, final BsonDocument arguments, @Nullable final ClientSession clientSession) {
List<WriteModel<BsonDocument>> writeModels = new ArrayList<WriteModel<BsonDocument>>();
for (BsonValue bsonValue : arguments.getArray("requests")) {
BsonDocument cur = bsonValue.asDocument();
String name = cur.getString("name").getValue();
BsonDocument requestArguments = cur.getDocument("arguments");
if (name.equals("insertOne")) {
writeModels.add(new InsertOneModel<BsonDocument>(requestArguments.getDocument("document")));
} else if (name.equals("updateOne")) {
if (requestArguments.isDocument("update")) {
writeModels.add(new UpdateOneModel<BsonDocument>(requestArguments.getDocument("filter"), requestArguments.getDocument("update"), getUpdateOptions(requestArguments)));
} else {
// update is a pipeline
writeModels.add(new UpdateOneModel<BsonDocument>(requestArguments.getDocument("filter"), getListOfDocuments(requestArguments.getArray("update")), getUpdateOptions(requestArguments)));
}
} else if (name.equals("updateMany")) {
if (requestArguments.isDocument("update")) {
writeModels.add(new UpdateManyModel<BsonDocument>(requestArguments.getDocument("filter"), requestArguments.getDocument("update"), getUpdateOptions(requestArguments)));
} else {
// update is a pipeline
writeModels.add(new UpdateManyModel<BsonDocument>(requestArguments.getDocument("filter"), getListOfDocuments(requestArguments.getArray("update")), getUpdateOptions(requestArguments)));
}
} else if (name.equals("deleteOne")) {
writeModels.add(new DeleteOneModel<BsonDocument>(requestArguments.getDocument("filter"), getDeleteOptions(requestArguments)));
} else if (name.equals("deleteMany")) {
writeModels.add(new DeleteManyModel<BsonDocument>(requestArguments.getDocument("filter"), getDeleteOptions(requestArguments)));
} else if (name.equals("replaceOne")) {
writeModels.add(new ReplaceOneModel<BsonDocument>(requestArguments.getDocument("filter"), requestArguments.getDocument("replacement"), getReplaceOptions(requestArguments)));
} else {
throw new UnsupportedOperationException(format("Unsupported write request type: %s", name));
}
}
try {
BulkWriteResult bulkWriteResult;
BsonDocument optionsDocument = arguments.getDocument("options", new BsonDocument());
BulkWriteOptions options = new BulkWriteOptions().ordered(optionsDocument.getBoolean("ordered", BsonBoolean.TRUE).getValue());
if (optionsDocument.containsKey("bypassDocumentValidation")) {
options.bypassDocumentValidation(optionsDocument.getBoolean("bypassDocumentValidation").getValue());
}
if (clientSession == null) {
bulkWriteResult = getCollection(collectionOptions).bulkWrite(writeModels, options);
} else {
bulkWriteResult = getCollection(collectionOptions).bulkWrite(clientSession, writeModels, options);
}
return toResult(bulkWriteResult, writeModels, Collections.<BulkWriteError>emptyList());
} catch (MongoBulkWriteException e) {
BsonDocument result = toResult(e.getWriteResult(), writeModels, e.getWriteErrors());
result.put("error", BsonBoolean.TRUE);
return result;
}
}
use of com.mongodb.bulk.BulkWriteResult in project mongo-java-driver by mongodb.
the class MixedBulkWriteOperation method executeAsync.
public void executeAsync(final AsyncWriteBinding binding, final SingleResultCallback<BulkWriteResult> callback) {
// see the comment in `execute(WriteBinding)` explaining the manual tracking of attempts
RetryState retryState = new RetryState();
BulkWriteTracker.attachNew(retryState, retryWrites);
binding.retain();
AsyncCallbackSupplier<BulkWriteResult> retryingBulkWrite = this.<BulkWriteResult>decorateWriteWithRetries(retryState, funcCallback -> {
logRetryExecute(retryState);
withAsyncSourceAndConnection(binding::getWriteConnectionSource, true, funcCallback, (source, connection, releasingCallback) -> {
ConnectionDescription connectionDescription = connection.getDescription();
int maxWireVersion = connectionDescription.getMaxWireVersion();
// attach `maxWireVersion` ASAP because it is used to check whether we can retry
retryState.attach(AttachmentKeys.maxWireVersion(), maxWireVersion, true);
BulkWriteTracker bulkWriteTracker = retryState.attachment(AttachmentKeys.bulkWriteTracker()).orElseThrow(Assertions::fail);
SessionContext sessionContext = binding.getSessionContext();
WriteConcern writeConcern = getAppliedWriteConcern(sessionContext);
if (!retryState.isFirstAttempt() && !isRetryableWrite(retryWrites, writeConcern, source.getServerDescription(), connectionDescription, sessionContext)) {
Throwable prospectiveFailedResult = retryState.exception().orElse(null);
if (retryState.breakAndCompleteIfRetryAnd(() -> !(prospectiveFailedResult instanceof MongoWriteConcernWithResponseException), releasingCallback)) {
return;
}
bulkWriteTracker.batch().ifPresent(bulkWriteBatch -> {
assertTrue(prospectiveFailedResult instanceof MongoWriteConcernWithResponseException);
bulkWriteBatch.addResult((BsonDocument) ((MongoWriteConcernWithResponseException) prospectiveFailedResult).getResponse());
BulkWriteTracker.attachNext(retryState, bulkWriteBatch);
});
}
if (validateWriteRequestsAndCompleteIfInvalid(connectionDescription, bypassDocumentValidation, writeRequests, writeConcern, releasingCallback)) {
return;
}
if (writeConcern.isAcknowledged() || serverIsAtLeastVersionThreeDotSix(connectionDescription)) {
try {
if (!bulkWriteTracker.batch().isPresent()) {
BulkWriteTracker.attachNew(retryState, BulkWriteBatch.createBulkWriteBatch(namespace, source.getServerDescription(), connectionDescription, ordered, writeConcern, bypassDocumentValidation, retryWrites, writeRequests, sessionContext));
}
} catch (Throwable t) {
releasingCallback.onResult(null, t);
return;
}
logRetryExecute(retryState);
executeBulkWriteBatchAsync(retryState, binding, connection, maxWireVersion, releasingCallback);
} else {
retryState.markAsLastAttempt();
executeLegacyBatchesAsync(binding, connection, releasingCallback);
}
});
}).whenComplete(binding::release);
retryingBulkWrite.get(exceptionTransformingCallback(errorHandlingCallback(callback, LOGGER)));
}
use of com.mongodb.bulk.BulkWriteResult in project mongo-java-driver by mongodb.
the class MixedBulkWriteOperation method executeLegacyBatchesAsync.
private void executeLegacyBatchesAsync(final AsyncWriteBinding binding, final AsyncConnection connection, final SingleResultCallback<BulkWriteResult> callback) {
List<? extends WriteRequest> writeRequests = getWriteRequests();
LoopState loopState = new LoopState();
AsyncCallbackRunnable loop = new AsyncCallbackLoop(loopState, iterationCallback -> {
int i = loopState.iteration();
if (loopState.breakAndCompleteIf(() -> i == writeRequests.size(), iterationCallback)) {
return;
}
WriteRequest writeRequest = writeRequests.get(i);
SingleResultCallback<WriteConcernResult> commandCallback = (ignored, t) -> iterationCallback.onResult(null, t);
if (writeRequest.getType() == INSERT) {
connection.insertAsync(getNamespace(), isOrdered(), (InsertRequest) writeRequest, binding.getRequestContext(), commandCallback);
} else if (writeRequest.getType() == UPDATE || writeRequest.getType() == REPLACE) {
connection.updateAsync(getNamespace(), isOrdered(), (UpdateRequest) writeRequest, binding.getRequestContext(), commandCallback);
} else {
connection.deleteAsync(getNamespace(), isOrdered(), (DeleteRequest) writeRequest, binding.getRequestContext(), commandCallback);
}
});
loop.run((voidResult, t) -> {
if (t != null) {
callback.onResult(null, t);
} else {
callback.onResult(BulkWriteResult.unacknowledged(), null);
}
});
}
use of com.mongodb.bulk.BulkWriteResult in project mongo-java-driver by mongodb.
the class MongoCollectionImplTest method testBulkWrite.
@Test
public void testBulkWrite() {
List<WriteModel<Document>> requests = singletonList(new InsertOneModel<>(new Document()));
BulkWriteOptions options = new BulkWriteOptions().ordered(false);
assertAll("bulkWrite", () -> assertAll("check validation", () -> assertThrows(IllegalArgumentException.class, () -> collection.bulkWrite(null)), () -> assertThrows(IllegalArgumentException.class, () -> collection.bulkWrite(requests, null)), () -> assertThrows(IllegalArgumentException.class, () -> collection.bulkWrite(clientSession, null)), () -> assertThrows(IllegalArgumentException.class, () -> collection.bulkWrite(clientSession, requests, null)), () -> assertThrows(IllegalArgumentException.class, () -> collection.bulkWrite(null, requests)), () -> assertThrows(IllegalArgumentException.class, () -> collection.bulkWrite(null, requests, options))), () -> {
Publisher<BulkWriteResult> expected = mongoOperationPublisher.bulkWrite(null, requests, new BulkWriteOptions());
assertPublisherIsTheSameAs(expected, collection.bulkWrite(requests), "Default");
}, () -> {
Publisher<BulkWriteResult> expected = mongoOperationPublisher.bulkWrite(null, requests, options);
assertPublisherIsTheSameAs(expected, collection.bulkWrite(requests, options), "With options");
}, () -> {
Publisher<BulkWriteResult> expected = mongoOperationPublisher.bulkWrite(clientSession, requests, new BulkWriteOptions());
assertPublisherIsTheSameAs(expected, collection.bulkWrite(clientSession, requests), "With client session");
}, () -> {
Publisher<BulkWriteResult> expected = mongoOperationPublisher.bulkWrite(clientSession, requests, options);
assertPublisherIsTheSameAs(expected, collection.bulkWrite(clientSession, requests, options), "With client session & options");
});
}
use of com.mongodb.bulk.BulkWriteResult in project immutables by immutables.
the class MongoSession method update.
/**
* Uses <a href="https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/">replaceOne</a> operation
* with <a href="https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/">bulkWrite</a>. Right now has to convert
* object to BsonDocument to extract {@code _id} attribute.
*/
private <T> Publisher<WriteResult> update(StandardOperations.Update operation) {
ReplaceOptions options = new ReplaceOptions();
if (operation.upsert()) {
options.upsert(operation.upsert());
}
List<ReplaceOneModel<Object>> docs = operation.values().stream().map(value -> new ReplaceOneModel<>(new BsonDocument(Mongos.ID_FIELD_NAME, toBsonValue(keyExtractor.extract(value))), value, options)).collect(Collectors.toList());
Publisher<BulkWriteResult> publisher = ((MongoCollection<Object>) collection).bulkWrite(docs);
return Flowable.fromPublisher(publisher).map(x -> WriteResult.unknown());
}
Aggregations