Search in sources :

Example 1 with WriteRequest

use of com.mongodb.internal.bulk.WriteRequest 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);
        }
    });
}
Also used : LoopState(com.mongodb.internal.async.function.LoopState) AsyncCallbackRunnable(com.mongodb.internal.async.function.AsyncCallbackRunnable) LoopState(com.mongodb.internal.async.function.LoopState) WriteRequest(com.mongodb.internal.bulk.WriteRequest) CommandOperationHelper.addRetryableWriteErrorLabel(com.mongodb.internal.operation.CommandOperationHelper.addRetryableWriteErrorLabel) MongoBulkWriteException(com.mongodb.MongoBulkWriteException) MongoWriteConcernWithResponseException(com.mongodb.internal.connection.MongoWriteConcernWithResponseException) ProtocolHelper(com.mongodb.internal.connection.ProtocolHelper) ConnectionDescription(com.mongodb.connection.ConnectionDescription) BsonArray(org.bson.BsonArray) OperationHelper.validateWriteRequests(com.mongodb.internal.operation.OperationHelper.validateWriteRequests) OperationHelper.withSourceAndConnection(com.mongodb.internal.operation.OperationHelper.withSourceAndConnection) MongoException(com.mongodb.MongoException) AsyncCallbackSupplier(com.mongodb.internal.async.function.AsyncCallbackSupplier) Set(java.util.Set) Collectors(java.util.stream.Collectors) AsyncCallbackRunnable(com.mongodb.internal.async.function.AsyncCallbackRunnable) ServerVersionHelper.serverIsAtLeastVersionThreeDotSix(com.mongodb.internal.operation.ServerVersionHelper.serverIsAtLeastVersionThreeDotSix) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) REPLACE(com.mongodb.internal.bulk.WriteRequest.Type.REPLACE) RetryState(com.mongodb.internal.async.function.RetryState) List(java.util.List) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) Optional(java.util.Optional) RetryingSyncSupplier(com.mongodb.internal.async.function.RetryingSyncSupplier) InsertRequest(com.mongodb.internal.bulk.InsertRequest) RetryingAsyncCallbackSupplier(com.mongodb.internal.async.function.RetryingAsyncCallbackSupplier) CommandOperationHelper.logRetryExecute(com.mongodb.internal.operation.CommandOperationHelper.logRetryExecute) CommandOperationHelper.exceptionTransformingCallback(com.mongodb.internal.operation.CommandOperationHelper.exceptionTransformingCallback) ErrorHandlingResultCallback.errorHandlingCallback(com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback) BsonString(org.bson.BsonString) Supplier(java.util.function.Supplier) BsonDocument(org.bson.BsonDocument) LOGGER(com.mongodb.internal.operation.OperationHelper.LOGGER) Connection(com.mongodb.internal.connection.Connection) NoOpFieldNameValidator(com.mongodb.internal.validator.NoOpFieldNameValidator) WriteBinding(com.mongodb.internal.binding.WriteBinding) Assertions(com.mongodb.assertions.Assertions) WriteConcernResult(com.mongodb.WriteConcernResult) AsyncCallbackLoop(com.mongodb.internal.async.function.AsyncCallbackLoop) AsyncWriteBinding(com.mongodb.internal.binding.AsyncWriteBinding) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest) SessionContext(com.mongodb.internal.session.SessionContext) FieldNameValidator(org.bson.FieldNameValidator) OperationHelper.validateWriteRequestsAndCompleteIfInvalid(com.mongodb.internal.operation.OperationHelper.validateWriteRequestsAndCompleteIfInvalid) INSERT(com.mongodb.internal.bulk.WriteRequest.Type.INSERT) MongoNamespace(com.mongodb.MongoNamespace) UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) OperationHelper.isRetryableWrite(com.mongodb.internal.operation.OperationHelper.isRetryableWrite) CommandOperationHelper.transformWriteException(com.mongodb.internal.operation.CommandOperationHelper.transformWriteException) Assertions.isTrueArgument(com.mongodb.assertions.Assertions.isTrueArgument) Assertions.assertTrue(com.mongodb.assertions.Assertions.assertTrue) OperationHelper.withAsyncSourceAndConnection(com.mongodb.internal.operation.OperationHelper.withAsyncSourceAndConnection) BulkWriteResult(com.mongodb.bulk.BulkWriteResult) Nullable(com.mongodb.lang.Nullable) WriteConcern(com.mongodb.WriteConcern) UPDATE(com.mongodb.internal.bulk.WriteRequest.Type.UPDATE) AsyncConnection(com.mongodb.internal.connection.AsyncConnection) AttachmentKeys(com.mongodb.internal.operation.retry.AttachmentKeys) WriteConcernResult(com.mongodb.WriteConcernResult) UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) WriteRequest(com.mongodb.internal.bulk.WriteRequest) AsyncCallbackLoop(com.mongodb.internal.async.function.AsyncCallbackLoop) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest)

Example 2 with WriteRequest

use of com.mongodb.internal.bulk.WriteRequest in project mongo-java-driver by mongodb.

the class OperationHelper method validateWriteRequestCollations.

static void validateWriteRequestCollations(final ConnectionDescription connectionDescription, final List<? extends WriteRequest> requests, final WriteConcern writeConcern) {
    Collation collation = null;
    for (WriteRequest request : requests) {
        if (request instanceof UpdateRequest) {
            collation = ((UpdateRequest) request).getCollation();
        } else if (request instanceof DeleteRequest) {
            collation = ((DeleteRequest) request).getCollation();
        }
        if (collation != null) {
            break;
        }
    }
    validateCollationAndWriteConcern(connectionDescription, collation, writeConcern);
}
Also used : UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) WriteRequest(com.mongodb.internal.bulk.WriteRequest) Collation(com.mongodb.client.model.Collation) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest)

Example 3 with WriteRequest

use of com.mongodb.internal.bulk.WriteRequest in project mongo-java-driver by mongodb.

the class BulkWriteBatch method createBulkWriteBatch.

static BulkWriteBatch createBulkWriteBatch(final MongoNamespace namespace, final ServerDescription serverDescription, final ConnectionDescription connectionDescription, final boolean ordered, final WriteConcern writeConcern, final Boolean bypassDocumentValidation, final boolean retryWrites, final List<? extends WriteRequest> writeRequests, final SessionContext sessionContext) {
    if (sessionContext.hasSession() && !sessionContext.isImplicitSession() && !sessionContext.hasActiveTransaction() && !writeConcern.isAcknowledged()) {
        throw new MongoClientException("Unacknowledged writes are not supported when using an explicit session");
    }
    boolean canRetryWrites = isRetryableWrite(retryWrites, writeConcern, serverDescription, connectionDescription, sessionContext);
    List<WriteRequestWithIndex> writeRequestsWithIndex = new ArrayList<WriteRequestWithIndex>();
    boolean writeRequestsAreRetryable = true;
    for (int i = 0; i < writeRequests.size(); i++) {
        WriteRequest writeRequest = writeRequests.get(i);
        writeRequestsAreRetryable = writeRequestsAreRetryable && isRetryable(writeRequest);
        writeRequestsWithIndex.add(new WriteRequestWithIndex(writeRequest, i));
    }
    if (canRetryWrites && !writeRequestsAreRetryable) {
        canRetryWrites = false;
        LOGGER.debug("retryWrites set but one or more writeRequests do not support retryable writes");
    }
    return new BulkWriteBatch(namespace, connectionDescription, ordered, writeConcern, bypassDocumentValidation, canRetryWrites, new BulkWriteBatchCombiner(connectionDescription.getServerAddress(), ordered, writeConcern), writeRequestsWithIndex, sessionContext);
}
Also used : MongoClientException(com.mongodb.MongoClientException) WriteRequestWithIndex(com.mongodb.internal.bulk.WriteRequestWithIndex) WriteRequest(com.mongodb.internal.bulk.WriteRequest) ArrayList(java.util.ArrayList) BulkWriteBatchCombiner(com.mongodb.internal.connection.BulkWriteBatchCombiner)

Example 4 with WriteRequest

use of com.mongodb.internal.bulk.WriteRequest in project mongo-java-driver by mongodb.

the class OperationHelper method validateWriteRequestHints.

static void validateWriteRequestHints(final ConnectionDescription connectionDescription, final List<? extends WriteRequest> requests, final WriteConcern writeConcern) {
    for (WriteRequest request : requests) {
        Bson hint = null;
        String hintString = null;
        if (request instanceof UpdateRequest) {
            hint = ((UpdateRequest) request).getHint();
            hintString = ((UpdateRequest) request).getHintString();
        } else if (request instanceof DeleteRequest) {
            hint = ((DeleteRequest) request).getHint();
            hintString = ((DeleteRequest) request).getHintString();
        }
        if (hint != null || hintString != null) {
            validateWriteRequestHint(connectionDescription, writeConcern, request);
            break;
        }
    }
}
Also used : UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) WriteRequest(com.mongodb.internal.bulk.WriteRequest) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest) Bson(org.bson.conversions.Bson)

Example 5 with WriteRequest

use of com.mongodb.internal.bulk.WriteRequest in project mongo-java-driver by mongodb.

the class Operations method bulkWrite.

@SuppressWarnings("unchecked")
public MixedBulkWriteOperation bulkWrite(final List<? extends WriteModel<? extends TDocument>> requests, final BulkWriteOptions options) {
    notNull("requests", requests);
    List<WriteRequest> writeRequests = new ArrayList<>(requests.size());
    for (WriteModel<? extends TDocument> writeModel : requests) {
        WriteRequest writeRequest;
        if (writeModel == null) {
            throw new IllegalArgumentException("requests can not contain a null value");
        } else if (writeModel instanceof InsertOneModel) {
            TDocument document = ((InsertOneModel<TDocument>) writeModel).getDocument();
            if (getCodec() instanceof CollectibleCodec) {
                document = ((CollectibleCodec<TDocument>) getCodec()).generateIdIfAbsentFromDocument(document);
            }
            writeRequest = new InsertRequest(documentToBsonDocument(document));
        } else if (writeModel instanceof ReplaceOneModel) {
            ReplaceOneModel<TDocument> replaceOneModel = (ReplaceOneModel<TDocument>) writeModel;
            writeRequest = new UpdateRequest(toBsonDocument(replaceOneModel.getFilter()), documentToBsonDocument(replaceOneModel.getReplacement()), WriteRequest.Type.REPLACE).upsert(replaceOneModel.getReplaceOptions().isUpsert()).collation(replaceOneModel.getReplaceOptions().getCollation()).hint(replaceOneModel.getReplaceOptions().getHint()).hintString(replaceOneModel.getReplaceOptions().getHintString());
        } else if (writeModel instanceof UpdateOneModel) {
            UpdateOneModel<TDocument> updateOneModel = (UpdateOneModel<TDocument>) writeModel;
            BsonValue update = updateOneModel.getUpdate() != null ? toBsonDocument(updateOneModel.getUpdate()) : new BsonArray(toBsonDocumentList(updateOneModel.getUpdatePipeline()));
            writeRequest = new UpdateRequest(toBsonDocument(updateOneModel.getFilter()), update, WriteRequest.Type.UPDATE).multi(false).upsert(updateOneModel.getOptions().isUpsert()).collation(updateOneModel.getOptions().getCollation()).arrayFilters(toBsonDocumentList(updateOneModel.getOptions().getArrayFilters())).hint(updateOneModel.getOptions().getHint()).hintString(updateOneModel.getOptions().getHintString());
        } else if (writeModel instanceof UpdateManyModel) {
            UpdateManyModel<TDocument> updateManyModel = (UpdateManyModel<TDocument>) writeModel;
            BsonValue update = updateManyModel.getUpdate() != null ? toBsonDocument(updateManyModel.getUpdate()) : new BsonArray(toBsonDocumentList(updateManyModel.getUpdatePipeline()));
            writeRequest = new UpdateRequest(toBsonDocument(updateManyModel.getFilter()), update, WriteRequest.Type.UPDATE).multi(true).upsert(updateManyModel.getOptions().isUpsert()).collation(updateManyModel.getOptions().getCollation()).arrayFilters(toBsonDocumentList(updateManyModel.getOptions().getArrayFilters())).hint(updateManyModel.getOptions().getHint()).hintString(updateManyModel.getOptions().getHintString());
        } else if (writeModel instanceof DeleteOneModel) {
            DeleteOneModel<TDocument> deleteOneModel = (DeleteOneModel<TDocument>) writeModel;
            writeRequest = new DeleteRequest(toBsonDocument(deleteOneModel.getFilter())).multi(false).collation(deleteOneModel.getOptions().getCollation()).hint(deleteOneModel.getOptions().getHint()).hintString(deleteOneModel.getOptions().getHintString());
        } else if (writeModel instanceof DeleteManyModel) {
            DeleteManyModel<TDocument> deleteManyModel = (DeleteManyModel<TDocument>) writeModel;
            writeRequest = new DeleteRequest(toBsonDocument(deleteManyModel.getFilter())).multi(true).collation(deleteManyModel.getOptions().getCollation()).hint(deleteManyModel.getOptions().getHint()).hintString(deleteManyModel.getOptions().getHintString());
        } else {
            throw new UnsupportedOperationException(format("WriteModel of type %s is not supported", writeModel.getClass()));
        }
        writeRequests.add(writeRequest);
    }
    return new MixedBulkWriteOperation(namespace, writeRequests, options.isOrdered(), writeConcern, retryWrites).bypassDocumentValidation(options.getBypassDocumentValidation());
}
Also used : InsertOneModel(com.mongodb.client.model.InsertOneModel) CollectibleCodec(org.bson.codecs.CollectibleCodec) UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) WriteRequest(com.mongodb.internal.bulk.WriteRequest) InsertRequest(com.mongodb.internal.bulk.InsertRequest) ReplaceOneModel(com.mongodb.client.model.ReplaceOneModel) ArrayList(java.util.ArrayList) DeleteOneModel(com.mongodb.client.model.DeleteOneModel) UpdateOneModel(com.mongodb.client.model.UpdateOneModel) BsonArray(org.bson.BsonArray) UpdateManyModel(com.mongodb.client.model.UpdateManyModel) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest) BsonValue(org.bson.BsonValue) DeleteManyModel(com.mongodb.client.model.DeleteManyModel)

Aggregations

WriteRequest (com.mongodb.internal.bulk.WriteRequest)5 DeleteRequest (com.mongodb.internal.bulk.DeleteRequest)4 UpdateRequest (com.mongodb.internal.bulk.UpdateRequest)4 InsertRequest (com.mongodb.internal.bulk.InsertRequest)2 ArrayList (java.util.ArrayList)2 MongoBulkWriteException (com.mongodb.MongoBulkWriteException)1 MongoClientException (com.mongodb.MongoClientException)1 MongoException (com.mongodb.MongoException)1 MongoNamespace (com.mongodb.MongoNamespace)1 WriteConcern (com.mongodb.WriteConcern)1 WriteConcernResult (com.mongodb.WriteConcernResult)1 Assertions (com.mongodb.assertions.Assertions)1 Assertions.assertTrue (com.mongodb.assertions.Assertions.assertTrue)1 Assertions.isTrueArgument (com.mongodb.assertions.Assertions.isTrueArgument)1 Assertions.notNull (com.mongodb.assertions.Assertions.notNull)1 BulkWriteResult (com.mongodb.bulk.BulkWriteResult)1 Collation (com.mongodb.client.model.Collation)1 DeleteManyModel (com.mongodb.client.model.DeleteManyModel)1 DeleteOneModel (com.mongodb.client.model.DeleteOneModel)1 InsertOneModel (com.mongodb.client.model.InsertOneModel)1