ordered.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. "use strict";
  2. var common = require('./common')
  3. , utils = require('../utils')
  4. , toError = require('../utils').toError
  5. , f = require('util').format
  6. , handleCallback = require('../utils').handleCallback
  7. , shallowClone = utils.shallowClone
  8. , WriteError = common.WriteError
  9. , BulkWriteResult = common.BulkWriteResult
  10. , LegacyOp = common.LegacyOp
  11. , ObjectID = require('mongodb-core').BSON.ObjectID
  12. , Define = require('../metadata')
  13. , Batch = common.Batch
  14. , mergeBatchResults = common.mergeBatchResults;
  15. /**
  16. * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly)
  17. * @class
  18. * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance.
  19. */
  20. var FindOperatorsOrdered = function(self) {
  21. this.s = self.s;
  22. }
  23. /**
  24. * Add a single update document to the bulk operation
  25. *
  26. * @method
  27. * @param {object} doc update operations
  28. * @throws {MongoError}
  29. * @return {OrderedBulkOperation}
  30. */
  31. FindOperatorsOrdered.prototype.update = function(updateDocument) {
  32. // Perform upsert
  33. var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false;
  34. // Establish the update command
  35. var document = {
  36. q: this.s.currentOp.selector
  37. , u: updateDocument
  38. , multi: true
  39. , upsert: upsert
  40. }
  41. // Clear out current Op
  42. this.s.currentOp = null;
  43. // Add the update document to the list
  44. return addToOperationsList(this, common.UPDATE, document);
  45. }
  46. /**
  47. * Add a single update one document to the bulk operation
  48. *
  49. * @method
  50. * @param {object} doc update operations
  51. * @throws {MongoError}
  52. * @return {OrderedBulkOperation}
  53. */
  54. FindOperatorsOrdered.prototype.updateOne = function(updateDocument) {
  55. // Perform upsert
  56. var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false;
  57. // Establish the update command
  58. var document = {
  59. q: this.s.currentOp.selector
  60. , u: updateDocument
  61. , multi: false
  62. , upsert: upsert
  63. }
  64. // Clear out current Op
  65. this.s.currentOp = null;
  66. // Add the update document to the list
  67. return addToOperationsList(this, common.UPDATE, document);
  68. }
  69. /**
  70. * Add a replace one operation to the bulk operation
  71. *
  72. * @method
  73. * @param {object} doc the new document to replace the existing one with
  74. * @throws {MongoError}
  75. * @return {OrderedBulkOperation}
  76. */
  77. FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) {
  78. this.updateOne(updateDocument);
  79. }
  80. /**
  81. * Upsert modifier for update bulk operation
  82. *
  83. * @method
  84. * @throws {MongoError}
  85. * @return {FindOperatorsOrdered}
  86. */
  87. FindOperatorsOrdered.prototype.upsert = function() {
  88. this.s.currentOp.upsert = true;
  89. return this;
  90. }
  91. /**
  92. * Add a remove one operation to the bulk operation
  93. *
  94. * @method
  95. * @throws {MongoError}
  96. * @return {OrderedBulkOperation}
  97. */
  98. FindOperatorsOrdered.prototype.deleteOne = function() {
  99. // Establish the update command
  100. var document = {
  101. q: this.s.currentOp.selector
  102. , limit: 1
  103. }
  104. // Clear out current Op
  105. this.s.currentOp = null;
  106. // Add the remove document to the list
  107. return addToOperationsList(this, common.REMOVE, document);
  108. }
  109. // Backward compatibility
  110. FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne;
  111. /**
  112. * Add a remove operation to the bulk operation
  113. *
  114. * @method
  115. * @throws {MongoError}
  116. * @return {OrderedBulkOperation}
  117. */
  118. FindOperatorsOrdered.prototype.delete = function() {
  119. // Establish the update command
  120. var document = {
  121. q: this.s.currentOp.selector
  122. , limit: 0
  123. }
  124. // Clear out current Op
  125. this.s.currentOp = null;
  126. // Add the remove document to the list
  127. return addToOperationsList(this, common.REMOVE, document);
  128. }
  129. // Backward compatibility
  130. FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete;
  131. // Add to internal list of documents
  132. var addToOperationsList = function(_self, docType, document) {
  133. // Get the bsonSize
  134. var bsonSize = _self.s.bson.calculateObjectSize(document, false);
  135. // Throw error if the doc is bigger than the max BSON size
  136. if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes);
  137. // Create a new batch object if we don't have a current one
  138. if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex);
  139. // Check if we need to create a new batch
  140. if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize)
  141. || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes)
  142. || (_self.s.currentBatch.batchType != docType)) {
  143. // Save the batch to the execution stack
  144. _self.s.batches.push(_self.s.currentBatch);
  145. // Create a new batch
  146. _self.s.currentBatch = new Batch(docType, _self.s.currentIndex);
  147. // Reset the current size trackers
  148. _self.s.currentBatchSize = 0;
  149. _self.s.currentBatchSizeBytes = 0;
  150. } else {
  151. // Update current batch size
  152. _self.s.currentBatchSize = _self.s.currentBatchSize + 1;
  153. _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize;
  154. }
  155. if(docType == common.INSERT) {
  156. _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id});
  157. }
  158. // We have an array of documents
  159. if(Array.isArray(document)) {
  160. throw toError("operation passed in cannot be an Array");
  161. } else {
  162. _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex);
  163. _self.s.currentBatch.operations.push(document)
  164. _self.s.currentIndex = _self.s.currentIndex + 1;
  165. }
  166. // Return self
  167. return _self;
  168. }
  169. /**
  170. * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
  171. * @class
  172. * @property {number} length Get the number of operations in the bulk.
  173. * @return {OrderedBulkOperation} a OrderedBulkOperation instance.
  174. */
  175. function OrderedBulkOperation(topology, collection, options) {
  176. options = options == null ? {} : options;
  177. // TODO Bring from driver information in isMaster
  178. var self = this;
  179. var executed = false;
  180. // Current item
  181. var currentOp = null;
  182. // Handle to the bson serializer, used to calculate running sizes
  183. var bson = topology.bson;
  184. // Namespace for the operation
  185. var namespace = collection.collectionName;
  186. // Set max byte size
  187. var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize
  188. ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16);
  189. var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize
  190. ? topology.isMasterDoc.maxWriteBatchSize : 1000;
  191. // Get the write concern
  192. var writeConcern = common.writeConcern(shallowClone(options), collection, options);
  193. // Get the promiseLibrary
  194. var promiseLibrary = options.promiseLibrary;
  195. // No promise library selected fall back
  196. if(!promiseLibrary) {
  197. promiseLibrary = typeof global.Promise == 'function' ?
  198. global.Promise : require('es6-promise').Promise;
  199. }
  200. // Current batch
  201. var currentBatch = null;
  202. var currentIndex = 0;
  203. var currentBatchSize = 0;
  204. var currentBatchSizeBytes = 0;
  205. var batches = [];
  206. // Final results
  207. var bulkResult = {
  208. ok: 1
  209. , writeErrors: []
  210. , writeConcernErrors: []
  211. , insertedIds: []
  212. , nInserted: 0
  213. , nUpserted: 0
  214. , nMatched: 0
  215. , nModified: 0
  216. , nRemoved: 0
  217. , upserted: []
  218. };
  219. // Internal state
  220. this.s = {
  221. // Final result
  222. bulkResult: bulkResult
  223. // Current batch state
  224. , currentBatch: null
  225. , currentIndex: 0
  226. , currentBatchSize: 0
  227. , currentBatchSizeBytes: 0
  228. , batches: []
  229. // Write concern
  230. , writeConcern: writeConcern
  231. // Max batch size options
  232. , maxBatchSizeBytes: maxBatchSizeBytes
  233. , maxWriteBatchSize: maxWriteBatchSize
  234. // Namespace
  235. , namespace: namespace
  236. // BSON
  237. , bson: bson
  238. // Topology
  239. , topology: topology
  240. // Options
  241. , options: options
  242. // Current operation
  243. , currentOp: currentOp
  244. // Executed
  245. , executed: executed
  246. // Collection
  247. , collection: collection
  248. // Promise Library
  249. , promiseLibrary: promiseLibrary
  250. // Fundamental error
  251. , err: null
  252. // Bypass validation
  253. , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false
  254. }
  255. }
  256. var define = OrderedBulkOperation.define = new Define('OrderedBulkOperation', OrderedBulkOperation, false);
  257. OrderedBulkOperation.prototype.raw = function(op) {
  258. var key = Object.keys(op)[0];
  259. // Set up the force server object id
  260. var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean'
  261. ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId;
  262. // Update operations
  263. if((op.updateOne && op.updateOne.q)
  264. || (op.updateMany && op.updateMany.q)
  265. || (op.replaceOne && op.replaceOne.q)) {
  266. op[key].multi = op.updateOne || op.replaceOne ? false : true;
  267. return addToOperationsList(this, common.UPDATE, op[key]);
  268. }
  269. // Crud spec update format
  270. if(op.updateOne || op.updateMany || op.replaceOne) {
  271. var multi = op.updateOne || op.replaceOne ? false : true;
  272. var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi}
  273. operation.upsert = op[key].upsert ? true: false;
  274. return addToOperationsList(this, common.UPDATE, operation);
  275. }
  276. // Remove operations
  277. if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) {
  278. op[key].limit = op.removeOne ? 1 : 0;
  279. return addToOperationsList(this, common.REMOVE, op[key]);
  280. }
  281. // Crud spec delete operations, less efficient
  282. if(op.deleteOne || op.deleteMany) {
  283. var limit = op.deleteOne ? 1 : 0;
  284. var operation = {q: op[key].filter, limit: limit}
  285. return addToOperationsList(this, common.REMOVE, operation);
  286. }
  287. // Insert operations
  288. if(op.insertOne && op.insertOne.document == null) {
  289. if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID();
  290. return addToOperationsList(this, common.INSERT, op.insertOne);
  291. } else if(op.insertOne && op.insertOne.document) {
  292. if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID();
  293. return addToOperationsList(this, common.INSERT, op.insertOne.document);
  294. }
  295. if(op.insertMany) {
  296. for(var i = 0; i < op.insertMany.length; i++) {
  297. if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID();
  298. addToOperationsList(this, common.INSERT, op.insertMany[i]);
  299. }
  300. return;
  301. }
  302. // No valid type of operation
  303. throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany");
  304. }
  305. /**
  306. * Add a single insert document to the bulk operation
  307. *
  308. * @param {object} doc the document to insert
  309. * @throws {MongoError}
  310. * @return {OrderedBulkOperation}
  311. */
  312. OrderedBulkOperation.prototype.insert = function(document) {
  313. if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID();
  314. return addToOperationsList(this, common.INSERT, document);
  315. }
  316. /**
  317. * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne
  318. *
  319. * @method
  320. * @param {object} selector The selector for the bulk operation.
  321. * @throws {MongoError}
  322. * @return {FindOperatorsOrdered}
  323. */
  324. OrderedBulkOperation.prototype.find = function(selector) {
  325. if (!selector) {
  326. throw toError("Bulk find operation must specify a selector");
  327. }
  328. // Save a current selector
  329. this.s.currentOp = {
  330. selector: selector
  331. }
  332. return new FindOperatorsOrdered(this);
  333. }
  334. Object.defineProperty(OrderedBulkOperation.prototype, 'length', {
  335. enumerable: true,
  336. get: function() {
  337. return this.s.currentIndex;
  338. }
  339. });
  340. //
  341. // Execute next write command in a chain
  342. var executeCommands = function(self, callback) {
  343. if(self.s.batches.length == 0) {
  344. return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult));
  345. }
  346. // Ordered execution of the command
  347. var batch = self.s.batches.shift();
  348. var resultHandler = function(err, result) {
  349. // Error is a driver related error not a bulk op error, terminate
  350. if(err && err.driver || err && err.message) {
  351. return handleCallback(callback, err);
  352. }
  353. // If we have and error
  354. if(err) err.ok = 0;
  355. // Merge the results together
  356. var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result);
  357. if(mergeResult != null) {
  358. return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult));
  359. }
  360. // If we are ordered and have errors and they are
  361. // not all replication errors terminate the operation
  362. if(self.s.bulkResult.writeErrors.length > 0) {
  363. return handleCallback(callback, toError(self.s.bulkResult.writeErrors[0]), new BulkWriteResult(self.s.bulkResult));
  364. }
  365. // Execute the next command in line
  366. executeCommands(self, callback);
  367. }
  368. var finalOptions = {ordered: true}
  369. if(self.s.writeConcern != null) {
  370. finalOptions.writeConcern = self.s.writeConcern;
  371. }
  372. // Set an operationIf if provided
  373. if(self.operationId) {
  374. resultHandler.operationId = self.operationId;
  375. }
  376. // Serialize functions
  377. if(self.s.options.serializeFunctions) {
  378. finalOptions.serializeFunctions = true
  379. }
  380. // Serialize functions
  381. if(self.s.options.ignoreUndefined) {
  382. finalOptions.ignoreUndefined = true
  383. }
  384. // Is the bypassDocumentValidation options specific
  385. if(self.s.bypassDocumentValidation == true) {
  386. finalOptions.bypassDocumentValidation = true;
  387. }
  388. try {
  389. if(batch.batchType == common.INSERT) {
  390. self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler);
  391. } else if(batch.batchType == common.UPDATE) {
  392. self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler);
  393. } else if(batch.batchType == common.REMOVE) {
  394. self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler);
  395. }
  396. } catch(err) {
  397. // Force top level error
  398. err.ok = 0;
  399. // Merge top level error and return
  400. handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null));
  401. }
  402. }
  403. /**
  404. * The callback format for results
  405. * @callback OrderedBulkOperation~resultCallback
  406. * @param {MongoError} error An error instance representing the error during the execution.
  407. * @param {BulkWriteResult} result The bulk write result.
  408. */
  409. /**
  410. * Execute the ordered bulk operation
  411. *
  412. * @method
  413. * @param {object} [options=null] Optional settings.
  414. * @param {(number|string)} [options.w=null] The write concern.
  415. * @param {number} [options.wtimeout=null] The write concern timeout.
  416. * @param {boolean} [options.j=false] Specify a journal write concern.
  417. * @param {boolean} [options.fsync=false] Specify a file sync write concern.
  418. * @param {OrderedBulkOperation~resultCallback} [callback] The result callback
  419. * @throws {MongoError}
  420. * @return {Promise} returns Promise if no callback passed
  421. */
  422. OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) {
  423. var self = this;
  424. if(this.s.executed) throw new toError("batch cannot be re-executed");
  425. if(typeof _writeConcern == 'function') {
  426. callback = _writeConcern;
  427. } else {
  428. this.s.writeConcern = _writeConcern;
  429. }
  430. // If we have current batch
  431. if(this.s.currentBatch) this.s.batches.push(this.s.currentBatch);
  432. // If we have no operations in the bulk raise an error
  433. if(this.s.batches.length == 0) {
  434. throw toError("Invalid Operation, No operations in bulk");
  435. }
  436. // Execute using callback
  437. if(typeof callback == 'function') {
  438. return executeCommands(this, callback);
  439. }
  440. // Return a Promise
  441. return new this.s.promiseLibrary(function(resolve, reject) {
  442. executeCommands(self, function(err, r) {
  443. if(err) return reject(err);
  444. resolve(r);
  445. });
  446. });
  447. }
  448. define.classMethod('execute', {callback: true, promise:false});
  449. /**
  450. * Returns an unordered batch object
  451. * @ignore
  452. */
  453. var initializeOrderedBulkOp = function(topology, collection, options) {
  454. return new OrderedBulkOperation(topology, collection, options);
  455. }
  456. initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation;
  457. module.exports = initializeOrderedBulkOp;
  458. module.exports.Bulk = OrderedBulkOperation;