unordered.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. 'use strict';
  2. const common = require('./common');
  3. const BulkOperationBase = common.BulkOperationBase;
  4. const utils = require('../utils');
  5. const toError = utils.toError;
  6. const handleCallback = utils.handleCallback;
  7. const BulkWriteResult = common.BulkWriteResult;
  8. const Batch = common.Batch;
  9. const mergeBatchResults = common.mergeBatchResults;
  10. const executeOperation = utils.executeOperation;
  11. const MongoWriteConcernError = require('mongodb-core').MongoWriteConcernError;
  12. const handleMongoWriteConcernError = require('./common').handleMongoWriteConcernError;
  13. const bson = common.bson;
  14. const isPromiseLike = require('../utils').isPromiseLike;
  15. /**
  16. * Add to internal list of Operations
  17. *
  18. * @param {UnorderedBulkOperation} bulkOperation
  19. * @param {number} docType number indicating the document type
  20. * @param {object} document
  21. * @return {UnorderedBulkOperation}
  22. */
  23. function addToOperationsList(bulkOperation, docType, document) {
  24. // Get the bsonSize
  25. const bsonSize = bson.calculateObjectSize(document, {
  26. checkKeys: false,
  27. // Since we don't know what the user selected for BSON options here,
  28. // err on the safe side, and check the size with ignoreUndefined: false.
  29. ignoreUndefined: false
  30. });
  31. // Throw error if the doc is bigger than the max BSON size
  32. if (bsonSize >= bulkOperation.s.maxBatchSizeBytes)
  33. throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes);
  34. // Holds the current batch
  35. bulkOperation.s.currentBatch = null;
  36. // Get the right type of batch
  37. if (docType === common.INSERT) {
  38. bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch;
  39. } else if (docType === common.UPDATE) {
  40. bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch;
  41. } else if (docType === common.REMOVE) {
  42. bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch;
  43. }
  44. const maxKeySize = bulkOperation.s.maxKeySize;
  45. // Create a new batch object if we don't have a current one
  46. if (bulkOperation.s.currentBatch == null)
  47. bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
  48. // Check if we need to create a new batch
  49. if (
  50. bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize ||
  51. bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >=
  52. bulkOperation.s.maxBatchSizeBytes ||
  53. bulkOperation.s.currentBatch.batchType !== docType
  54. ) {
  55. // Save the batch to the execution stack
  56. bulkOperation.s.batches.push(bulkOperation.s.currentBatch);
  57. // Create a new batch
  58. bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
  59. }
  60. // We have an array of documents
  61. if (Array.isArray(document)) {
  62. throw toError('operation passed in cannot be an Array');
  63. }
  64. bulkOperation.s.currentBatch.operations.push(document);
  65. bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex);
  66. bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1;
  67. // Save back the current Batch to the right type
  68. if (docType === common.INSERT) {
  69. bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch;
  70. bulkOperation.s.bulkResult.insertedIds.push({
  71. index: bulkOperation.s.bulkResult.insertedIds.length,
  72. _id: document._id
  73. });
  74. } else if (docType === common.UPDATE) {
  75. bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch;
  76. } else if (docType === common.REMOVE) {
  77. bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch;
  78. }
  79. // Update current batch size
  80. bulkOperation.s.currentBatch.size += 1;
  81. bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize;
  82. // Return bulkOperation
  83. return bulkOperation;
  84. }
  85. /**
  86. * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
  87. * @class
  88. * @property {number} length Get the number of operations in the bulk.
  89. * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance.
  90. */
  91. class UnorderedBulkOperation extends BulkOperationBase {
  92. constructor(topology, collection, options) {
  93. options = options || {};
  94. options = Object.assign(options, { addToOperationsList });
  95. super(topology, collection, options, false);
  96. }
  97. /**
  98. * The callback format for results
  99. * @callback UnorderedBulkOperation~resultCallback
  100. * @param {MongoError} error An error instance representing the error during the execution.
  101. * @param {BulkWriteResult} result The bulk write result.
  102. */
  103. /**
  104. * Execute the ordered bulk operation
  105. *
  106. * @method
  107. * @param {object} [options] Optional settings.
  108. * @param {(number|string)} [options.w] The write concern.
  109. * @param {number} [options.wtimeout] The write concern timeout.
  110. * @param {boolean} [options.j=false] Specify a journal write concern.
  111. * @param {boolean} [options.fsync=false] Specify a file sync write concern.
  112. * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback
  113. * @throws {MongoError}
  114. * @return {Promise} returns Promise if no callback passed
  115. */
  116. execute(_writeConcern, options, callback) {
  117. const ret = this.bulkExecute(_writeConcern, options, callback);
  118. if (!ret || isPromiseLike(ret)) {
  119. return ret;
  120. }
  121. options = ret.options;
  122. callback = ret.callback;
  123. return executeOperation(this.s.topology, executeBatches, [this, options, callback]);
  124. }
  125. }
  126. /**
  127. * Execute the command
  128. *
  129. * @param {UnorderedBulkOperation} bulkOperation
  130. * @param {object} batch
  131. * @param {object} options
  132. * @param {function} callback
  133. */
  134. function executeBatch(bulkOperation, batch, options, callback) {
  135. function resultHandler(err, result) {
  136. // Error is a driver related error not a bulk op error, terminate
  137. if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
  138. return handleCallback(callback, err);
  139. }
  140. // If we have and error
  141. if (err) err.ok = 0;
  142. if (err instanceof MongoWriteConcernError) {
  143. return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, false, err, callback);
  144. }
  145. handleCallback(
  146. callback,
  147. null,
  148. mergeBatchResults(false, batch, bulkOperation.s.bulkResult, err, result)
  149. );
  150. }
  151. bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
  152. }
  153. /**
  154. * Execute all the commands
  155. *
  156. * @param {UnorderedBulkOperation} bulkOperation
  157. * @param {object} options
  158. * @param {function} callback
  159. */
  160. function executeBatches(bulkOperation, options, callback) {
  161. let numberOfCommandsToExecute = bulkOperation.s.batches.length;
  162. let hasErrored = false;
  163. // Execute over all the batches
  164. for (let i = 0; i < bulkOperation.s.batches.length; i++) {
  165. executeBatch(bulkOperation, bulkOperation.s.batches[i], options, function(err) {
  166. if (hasErrored) {
  167. return;
  168. }
  169. if (err) {
  170. hasErrored = true;
  171. return handleCallback(callback, err);
  172. }
  173. // Count down the number of commands left to execute
  174. numberOfCommandsToExecute = numberOfCommandsToExecute - 1;
  175. // Execute
  176. if (numberOfCommandsToExecute === 0) {
  177. // Driver level error
  178. if (err) return handleCallback(callback, err);
  179. const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
  180. if (bulkOperation.handleWriteError(callback, writeResult)) return;
  181. return handleCallback(callback, null, writeResult);
  182. }
  183. });
  184. }
  185. }
  186. /**
  187. * Returns an unordered batch object
  188. * @ignore
  189. */
  190. function initializeUnorderedBulkOp(topology, collection, options) {
  191. return new UnorderedBulkOperation(topology, collection, options);
  192. }
  193. initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation;
  194. module.exports = initializeUnorderedBulkOp;
  195. module.exports.Bulk = UnorderedBulkOperation;