Example #1
0
        public void FromCore_should_convert_from_core_exception_with_a_write_concern_error_when_original_models_exists()
        {
            var exception = new MongoBulkWriteOperationException(
                _connectionId,
                result: new BulkWriteOperationResult.Acknowledged(
                    requestCount: 1,
                    matchedCount: 1,
                    deletedCount: 0,
                    insertedCount: 0,
                    modifiedCount: 0,
                    processedRequests: new[] { new InsertRequest(new BsonDocument("b", 1)) { CorrelationId = 1 } },
                    upserts: new List<BulkWriteOperationUpsert>()),
                writeErrors: new[] { new BulkWriteOperationError(10, 1, "blah", new BsonDocument("a", 1)) },
                writeConcernError: new BulkWriteConcernError(11, "funny", new BsonDocument("c", 1)),
                unprocessedRequests: new[] { new InsertRequest(new BsonDocument("a", 1)) { CorrelationId = 0 } });

            var models = new [] 
            {
                new InsertOneModel<BsonDocument>(new BsonDocument("a", 1)),
                new InsertOneModel<BsonDocument>(new BsonDocument("b", 1))
            }; 
            var mapped = MongoBulkWriteException<BsonDocument>.FromCore(exception, models);

            mapped.Result.ProcessedRequests.Count.Should().Be(1);
            mapped.Result.ProcessedRequests[0].Should().BeSameAs(models[1]);
            mapped.WriteConcernError.Should().NotBeNull();
            mapped.WriteErrors.Count.Should().Be(1);
            mapped.WriteErrors[0].Should().NotBeNull();
            mapped.UnprocessedRequests.Count.Should().Be(1);
            mapped.UnprocessedRequests[0].Should().BeSameAs(models[0]);
        }
        private BulkWriteBatchResult ExecuteBatch(IChannelHandle channel, ICoreSessionHandle session, Run run, bool isLast, CancellationToken cancellationToken)
        {
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                switch (run.RequestType)
                {
                case WriteRequestType.Delete:
                    result = ExecuteDeletes(channel, session, run.Requests.Cast <DeleteRequest>(), isLast, cancellationToken);
                    break;

                case WriteRequestType.Insert:
                    result = ExecuteInserts(channel, session, run.Requests.Cast <InsertRequest>(), isLast, cancellationToken);
                    break;

                case WriteRequestType.Update:
                    result = ExecuteUpdates(channel, session, run.Requests.Cast <UpdateRequest>(), isLast, cancellationToken);
                    break;

                default:
                    throw new MongoInternalException("Unrecognized RequestType.");
                }
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(BulkWriteBatchResult.Create(result, exception, run.IndexMap));
        }
        public void constructor_should_initialize_subject()
        {
            var subject = new MongoBulkWriteOperationException(_connectionId, _result, _writeErrors, _writeConcernError, _unprocessedRequests);

            subject.ConnectionId.Should().BeSameAs(_connectionId);
            subject.Result.Should().BeSameAs(_result);
            subject.UnprocessedRequests.Should().BeSameAs(_unprocessedRequests);
            subject.WriteConcernError.Should().BeSameAs(_writeConcernError);
            subject.WriteErrors.Should().BeSameAs(_writeErrors);
        }
        public void constructor_should_initialize_subject()
        {
            var subject = new MongoBulkWriteOperationException(_connectionId, _result, _writeErrors, _writeConcernError, _unprocessedRequests);

            subject.ConnectionId.Should().BeSameAs(_connectionId);
            subject.Result.Should().BeSameAs(_result);
            subject.UnprocessedRequests.Should().BeSameAs(_unprocessedRequests);
            subject.WriteConcernError.Should().BeSameAs(_writeConcernError);
            subject.WriteErrors.Should().BeSameAs(_writeErrors);
        }
        // methods
        public async Task <WriteConcernResult> ExecuteAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, "channel");

            var requests = _documentSource.GetRemainingItems().Select(d =>
            {
                if (d == null)
                {
                    throw new ArgumentException("Batch contains one or more null documents.");
                }

                return(new InsertRequest(new BsonDocumentWrapper(d, _serializer)));
            });
            var operation = new BulkInsertOperation(_collectionNamespace, requests, _messageEncoderSettings)
            {
                IsOrdered      = !_continueOnError,
                MaxBatchCount  = _maxBatchCount,
                MaxBatchLength = _maxMessageSize,
                // ReaderSettings = ?
                WriteConcern = _writeConcern,
                // WriteSettings = ?
            };

            BulkWriteOperationResult         bulkWriteResult;
            MongoBulkWriteOperationException bulkWriteException = null;

            try
            {
                bulkWriteResult = await operation.ExecuteAsync(channel, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                bulkWriteResult    = ex.Result;
                bulkWriteException = ex;
            }

            var converter = new BulkWriteOperationResultConverter();

            if (bulkWriteException != null)
            {
                throw converter.ToWriteConcernException(channel.ConnectionDescription.ConnectionId, bulkWriteException);
            }
            else
            {
                if (_writeConcern.IsAcknowledged)
                {
                    return(converter.ToWriteConcernResult(bulkWriteResult));
                }
                else
                {
                    return(null);
                }
            }
        }
Example #6
0
        private async Task <BulkWriteBatchResult> ExecuteBatchAsync(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken)
        {
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                var operation = CreateUnmixedBatchOperation(batch);
                result = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(BulkWriteBatchResult.Create(result, exception, batch.IndexMap));
        }
Example #7
0
        private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken)
        {
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                var operation = CreateUnmixedBatchOperation(batch);
                result = operation.Execute(context, cancellationToken);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(BulkWriteBatchResult.Create(result, exception, batch.IndexMap));
        }
        public static BulkWriteBatchResult Create(
            BulkWriteOperationResult result,
            MongoBulkWriteOperationException exception,
            IndexMap indexMap)
        {
            var  matchedCount  = 0L;
            var  deletedCount  = 0L;
            var  insertedCount = 0L;
            long?modifiedCount = null;
            var  upserts       = __noUpserts;

            if (result.IsAcknowledged)
            {
                matchedCount  = result.MatchedCount;
                deletedCount  = result.DeletedCount;
                insertedCount = result.InsertedCount;
                modifiedCount = result.IsModifiedCountAvailable ? (long?)result.ModifiedCount : null;
                upserts       = result.Upserts;
            }

            var unprocessedRequests = __noWriteRequests;
            var writeErrors         = __noWriteErrors;
            BulkWriteConcernError writeConcernError = null;

            if (exception != null)
            {
                unprocessedRequests = exception.UnprocessedRequests;
                writeErrors         = exception.WriteErrors;
                writeConcernError   = exception.WriteConcernError;
            }

            return(new BulkWriteBatchResult(
                       result.RequestCount,
                       result.ProcessedRequests,
                       unprocessedRequests,
                       matchedCount,
                       deletedCount,
                       insertedCount,
                       modifiedCount,
                       upserts,
                       writeErrors,
                       writeConcernError,
                       indexMap));
        }
Example #9
0
        public void Serialization_should_work()
        {
            var subject = new MongoBulkWriteOperationException(_connectionId, _result, _writeErrors, _writeConcernError, _unprocessedRequests);

            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, subject);
                stream.Position = 0;
                var rehydrated = (MongoBulkWriteOperationException)formatter.Deserialize(stream);

                rehydrated.ConnectionId.Should().Be(subject.ConnectionId);
                rehydrated.Message.Should().Be(subject.Message);
                rehydrated.Result.Should().BeUsing(subject.Result, EqualityComparerRegistry.Default);
                rehydrated.UnprocessedRequests.Should().EqualUsing(subject.UnprocessedRequests, EqualityComparerRegistry.Default);
                rehydrated.WriteConcernError.Should().BeUsing(subject.WriteConcernError, EqualityComparerRegistry.Default);
                rehydrated.WriteErrors.Should().EqualUsing(subject.WriteErrors, EqualityComparerRegistry.Default);
            }
        }
Example #10
0
        // methods
        public async Task <WriteConcernResult> ExecuteAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, "channel");

            var requests = new[] { _request };

            var operation = new BulkUpdateOperation(_collectionNamespace, requests, _messageEncoderSettings)
            {
                IsOrdered    = true,
                WriteConcern = _writeConcern
            };

            BulkWriteOperationResult         bulkWriteResult;
            MongoBulkWriteOperationException bulkWriteException = null;

            try
            {
                bulkWriteResult = await operation.ExecuteAsync(channel, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                bulkWriteResult    = ex.Result;
                bulkWriteException = ex;
            }

            var converter = new BulkWriteOperationResultConverter();

            if (bulkWriteException != null)
            {
                throw converter.ToWriteConcernException(channel.ConnectionDescription.ConnectionId, bulkWriteException);
            }
            else
            {
                if (_writeConcern.IsAcknowledged)
                {
                    return(converter.ToWriteConcernResult(bulkWriteResult));
                }
                else
                {
                    return(null);
                }
            }
        }
        public async Task <WriteConcernResult> ExecuteAsync(IChannelHandle channel, ICoreSessionHandle session, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, nameof(channel));

            var operation = CreateOperation();
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                result = await operation.ExecuteAsync(channel, session, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(CreateResultOrThrow(channel, result, exception));
        }
        // public methods
        public WriteConcernResult Execute(RetryableWriteContext context, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(context, nameof(context));

            var operation = CreateOperation();
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                result = operation.Execute(context, cancellationToken);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(CreateResultOrThrow(context.Channel, result, exception));
        }
        public async Task <WriteConcernResult> ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(context, nameof(context));

            var operation = CreateOperation();
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                result = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(CreateResultOrThrow(context.Channel, result, exception));
        }
        public void Serialization_should_work()
        {
            var subject = new MongoBulkWriteOperationException(_connectionId, _result, _writeErrors, _writeConcernError, _unprocessedRequests);

            var formatter = new BinaryFormatter();

            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, subject);
                stream.Position = 0;
                var rehydrated = (MongoBulkWriteOperationException)formatter.Deserialize(stream);

                rehydrated.ConnectionId.Should().Be(subject.ConnectionId);
                rehydrated.Message.Should().Be(subject.Message);
                rehydrated.Result.Should().BeUsing(subject.Result, EqualityComparerRegistry.Default);
                rehydrated.UnprocessedRequests.Should().EqualUsing(subject.UnprocessedRequests, EqualityComparerRegistry.Default);
                rehydrated.WriteConcernError.Should().BeUsing(subject.WriteConcernError, EqualityComparerRegistry.Default);
                rehydrated.WriteErrors.Should().EqualUsing(subject.WriteErrors, EqualityComparerRegistry.Default);
            }
        }
        // public methods
        public WriteConcernResult Execute(IChannelHandle channel, ICoreSessionHandle session, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, nameof(channel));

            var operation = CreateOperation();
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                result = operation.Execute(channel, session, cancellationToken);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(CreateResultOrThrow(channel, result, exception));
        }
        // public methods
        public Exception ToWriteConcernException(ConnectionId connectionId, MongoBulkWriteOperationException bulkWriteException)
        {
            var writeConcernResult = ToWriteConcernResult(bulkWriteException.Result, bulkWriteException);

            var exception = ExceptionMapper.Map(connectionId, writeConcernResult.Response);
            if (exception == null)
            {
                exception = ExceptionMapper.Map(connectionId, writeConcernResult);
            }
            if (exception == null)
            {
                exception = new MongoWriteConcernException(connectionId, bulkWriteException.Message, writeConcernResult);
            }

            var writeConcernException = exception as MongoWriteConcernException;
            if (writeConcernException != null)
            { 
                writeConcernException.Data["results"] = new List<WriteConcernResult>(new[] { writeConcernResult });
            }

            return exception; // usually a WriteConcernException unless ExceptionMapper chose a different type
        }
        private async Task <BulkWriteBatchResult> ExecuteBatchAsync(IChannelHandle channel, Run run, CancellationToken cancellationToken)
        {
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                switch (run.RequestType)
                {
                case WriteRequestType.Delete:
                    result = await ExecuteDeletesAsync(channel, run.Requests.Cast <DeleteRequest>(), cancellationToken).ConfigureAwait(false);

                    break;

                case WriteRequestType.Insert:
                    result = await ExecuteInsertsAsync(channel, run.Requests.Cast <InsertRequest>(), cancellationToken).ConfigureAwait(false);

                    break;

                case WriteRequestType.Update:
                    result = await ExecuteUpdatesAsync(channel, run.Requests.Cast <UpdateRequest>(), cancellationToken).ConfigureAwait(false);

                    break;

                default:
                    throw new MongoInternalException("Unrecognized RequestType.");
                }
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(BulkWriteBatchResult.Create(result, exception, run.IndexMap));
        }
Example #18
0
        // public methods
        public Exception ToWriteConcernException(ConnectionId connectionId, MongoBulkWriteOperationException bulkWriteException)
        {
            var writeConcernResult = ToWriteConcernResult(bulkWriteException.Result, bulkWriteException);

            var exception = ExceptionMapper.Map(connectionId, writeConcernResult.Response);

            if (exception == null)
            {
                exception = ExceptionMapper.Map(connectionId, writeConcernResult);
            }
            if (exception == null)
            {
                exception = new MongoWriteConcernException(connectionId, bulkWriteException.Message, writeConcernResult);
            }

            var writeConcernException = exception as MongoWriteConcernException;

            if (writeConcernException != null)
            {
                writeConcernException.Data["results"] = new List <WriteConcernResult>(new[] { writeConcernResult });
            }

            return(exception); // usually a WriteConcernException unless ExceptionMapper chose a different type
        }
        private WriteConcernResult CreateResultOrThrow(IChannelHandle channel, BulkWriteOperationResult result, MongoBulkWriteOperationException exception)
        {
            var converter = new BulkWriteOperationResultConverter();

            if (exception != null)
            {
                throw converter.ToWriteConcernException(channel.ConnectionDescription.ConnectionId, exception);
            }
            else
            {
                if (_writeConcern.IsAcknowledged)
                {
                    return(converter.ToWriteConcernResult(result));
                }
                else
                {
                    return(null);
                }
            }
        }
        public static BulkWriteBatchResult Create(
           BulkWriteOperationResult result,
           MongoBulkWriteOperationException exception,
           IndexMap indexMap)
        {
            var matchedCount = 0L;
            var deletedCount = 0L;
            var insertedCount = 0L;
            long? modifiedCount = null;
            var upserts = __noUpserts;
            if (result.IsAcknowledged)
            {
                matchedCount = result.MatchedCount;
                deletedCount = result.DeletedCount;
                insertedCount = result.InsertedCount;
                modifiedCount = result.IsModifiedCountAvailable ? (long?)result.ModifiedCount : null;
                upserts = result.Upserts;
            }

            var unprocessedRequests = __noWriteRequests;
            var writeErrors = __noWriteErrors;
            BulkWriteConcernError writeConcernError = null;
            if (exception != null)
            {
                unprocessedRequests = exception.UnprocessedRequests;
                writeErrors = exception.WriteErrors;
                writeConcernError = exception.WriteConcernError;
            }

            return new BulkWriteBatchResult(
                result.RequestCount,
                result.ProcessedRequests,
                unprocessedRequests,
                matchedCount,
                deletedCount,
                insertedCount,
                modifiedCount,
                upserts,
                writeErrors,
                writeConcernError,
                indexMap);
        }
        // private methods
        private WriteConcernResult ToWriteConcernResult(BulkWriteOperationResult bulkWriteResult, MongoBulkWriteOperationException bulkWriteException)
        {
            if (!bulkWriteResult.IsAcknowledged)
            {
                return null;
            }

            // don't include InsertedCount in getLastErrorResponse
            var documentsAffectedCount =
                bulkWriteResult.DeletedCount +
                bulkWriteResult.MatchedCount +
                bulkWriteResult.Upserts.Count;

            var isUpdate = bulkWriteResult.ProcessedRequests.Any(r => r.RequestType == WriteRequestType.Update);

            var updatedExisting = false;
            BulkWriteOperationUpsert upsert = null;
            if (isUpdate)
            {
                upsert = bulkWriteResult.Upserts.LastOrDefault();
                updatedExisting = documentsAffectedCount > 0 && upsert == null;
            }

            var code = 0;
            string message = null;
            BsonDocument details = null;
            if (bulkWriteException != null)
            {
                var lastWriteError = bulkWriteException.WriteErrors.LastOrDefault();
                var writeConcernError = bulkWriteException.WriteConcernError;

                code = 8; // UnknownError
                if (lastWriteError != null)
                {
                    code = lastWriteError.Code;
                    message = lastWriteError.Message;
                    details = lastWriteError.Details;
                }
                else if (writeConcernError != null)
                {
                    code = writeConcernError.Code;
                    message = writeConcernError.Message;
                    details = writeConcernError.Details;
                }
            }

            var getLastErrorResponse = new BsonDocument
            {
                { "ok", 1 },
                { "code", code, code != 0 },
                { "err", message, message != null },
                { "n", documentsAffectedCount },
                { "updatedExisting", updatedExisting, isUpdate },
                { "upserted", () => upsert.Id, isUpdate && upsert != null },
            };
            if (details != null)
            {
                getLastErrorResponse.Merge(details, false); // don't overwrite existing elements
            }

            return new WriteConcernResult(getLastErrorResponse);
        }
 private WriteConcernResult CreateResultOrThrow(IChannelHandle channel, BulkWriteOperationResult result, MongoBulkWriteOperationException exception)
 {
     var converter = new BulkWriteOperationResultConverter();
     if (exception != null)
     {
         throw converter.ToWriteConcernException(channel.ConnectionDescription.ConnectionId, exception);
     }
     else
     {
         if (_writeConcern.IsAcknowledged)
         {
             return converter.ToWriteConcernResult(result);
         }
         else
         {
             return null;
         }
     }
 }
Example #23
0
        // private methods
        private WriteConcernResult ToWriteConcernResult(BulkWriteOperationResult bulkWriteResult, MongoBulkWriteOperationException bulkWriteException)
        {
            if (!bulkWriteResult.IsAcknowledged)
            {
                return(null);
            }

            // don't include InsertedCount in getLastErrorResponse
            var documentsAffectedCount =
                bulkWriteResult.DeletedCount +
                bulkWriteResult.MatchedCount +
                bulkWriteResult.Upserts.Count;

            var isUpdate = bulkWriteResult.ProcessedRequests.Any(r => r.RequestType == WriteRequestType.Update);

            var updatedExisting             = false;
            BulkWriteOperationUpsert upsert = null;

            if (isUpdate)
            {
                upsert          = bulkWriteResult.Upserts.LastOrDefault();
                updatedExisting = documentsAffectedCount > 0 && upsert == null;
            }

            var          code    = 0;
            string       message = null;
            BsonDocument details = null;

            if (bulkWriteException != null)
            {
                var lastWriteError    = bulkWriteException.WriteErrors.LastOrDefault();
                var writeConcernError = bulkWriteException.WriteConcernError;

                code = 8; // UnknownError
                if (lastWriteError != null)
                {
                    code    = lastWriteError.Code;
                    message = lastWriteError.Message;
                    details = lastWriteError.Details;
                }
                else if (writeConcernError != null)
                {
                    code    = writeConcernError.Code;
                    message = writeConcernError.Message;
                    details = writeConcernError.Details;
                }
            }

            var getLastErrorResponse = new BsonDocument
            {
                { "ok", 1 },
                { "code", code, code != 0 },
                { "err", message, message != null },
                { "n", documentsAffectedCount },
                { "updatedExisting", updatedExisting, isUpdate },
                { "upserted", () => upsert.Id, isUpdate&& upsert != null },
            };

            if (details != null)
            {
                getLastErrorResponse.Merge(details, false); // don't overwrite existing elements
            }

            return(new WriteConcernResult(getLastErrorResponse));
        }