3 var Insert = require('./commands').Insert
4 , Update = require('./commands').Update
5 , Remove = require('./commands').Remove
6 , copy = require('../connection/utils').copy
7 , retrieveBSON = require('../connection/utils').retrieveBSON
8 , KillCursor = require('../connection/commands').KillCursor
9 , GetMore = require('../connection/commands').GetMore
10 , Query = require('../connection/commands').Query
11 , f = require('util').format
12 , CommandResult = require('../connection/command_result')
13 , MongoError = require('../error')
14 , getReadPreference = require('./shared').getReadPreference;
16 var BSON = retrieveBSON(),
19 // Write concern fields
20 var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync'];
22 var WireProtocol = function() {}
25 // Needs to support legacy mass insert as well as ordered/unordered legacy
28 WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) {
29 options = options || {};
30 // Default is ordered execution
31 var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
32 ops = Array.isArray(ops) ? ops :[ops];
34 // If we have more than a 1000 ops fails
35 if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000"));
38 var writeConcern = options.writeConcern || {w:1};
41 if(!ordered || writeConcern.w == 0) {
42 return executeUnordered('insert', Insert, ismaster, ns, bson, pool, ops, options, callback);
45 return executeOrdered('insert', Insert, ismaster, ns, bson, pool, ops, options, callback);
48 WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) {
49 options = options || {};
50 // Default is ordered execution
51 var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
52 ops = Array.isArray(ops) ? ops :[ops];
55 var writeConcern = options.writeConcern || {w:1};
58 if(!ordered || writeConcern.w == 0) {
59 return executeUnordered('update', Update, ismaster, ns, bson, pool, ops, options, callback);
62 return executeOrdered('update', Update, ismaster, ns, bson, pool, ops, options, callback);
65 WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) {
66 options = options || {};
67 // Default is ordered execution
68 var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
69 ops = Array.isArray(ops) ? ops :[ops];
72 var writeConcern = options.writeConcern || {w:1};
75 if(!ordered || writeConcern.w == 0) {
76 return executeUnordered('remove', Remove, ismaster, ns, bson, pool, ops, options, callback);
79 return executeOrdered('remove', Remove, ismaster, ns, bson, pool, ops, options, callback);
82 WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callback) {
83 // Create a kill cursor command
84 var killCursor = new KillCursor(bson, [cursorId]);
85 // Execute the kill cursor command
86 if(pool && pool.isConnected()) {
87 pool.write(killCursor, {
88 immediateRelease:true, noResponse: true
93 if(typeof callback == 'function') callback(null, null);
96 WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, options, callback) {
97 // Create getMore command
98 var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize});
101 var queryCallback = function(err, result) {
102 if(err) return callback(err);
103 // Get the raw message
104 var r = result.message;
106 // If we have a timed out query or a cursor that was killed
107 if((r.responseFlags & (1 << 0)) != 0) {
108 return callback(new MongoError("cursor does not exist, was killed or timed out"), null);
111 // Ensure we have a Long valie cursor id
112 var cursorId = typeof r.cursorId == 'number'
113 ? Long.fromNumber(r.cursorId)
116 // Set all the values
117 cursorState.documents = r.documents;
118 cursorState.cursorId = cursorId;
121 callback(null, null, r.connection);
124 // If we have a raw query decorate the function
126 queryCallback.raw = raw;
129 // Check if we need to promote longs
130 if(typeof cursorState.promoteLongs == 'boolean') {
131 queryCallback.promoteLongs = cursorState.promoteLongs;
134 if(typeof cursorState.promoteValues == 'boolean') {
135 queryCallback.promoteValues = cursorState.promoteValues;
138 if(typeof cursorState.promoteBuffers == 'boolean') {
139 queryCallback.promoteBuffers = cursorState.promoteBuffers;
142 // Write out the getMore command
143 connection.write(getMore, queryCallback);
146 WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) {
147 // Establish type of command
149 return setupClassicFind(bson, ns, cmd, cursorState, topology, options)
150 } else if(cursorState.cursorId != null) {
153 return setupCommand(bson, ns, cmd, cursorState, topology, options);
155 throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd)));
160 // Execute a find command
161 var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) {
162 // Ensure we have at least some options
163 options = options || {};
164 // Get the readPreference
165 var readPreference = getReadPreference(cmd, options);
166 // Set the optional batchSize
167 cursorState.batchSize = cmd.batchSize || cursorState.batchSize;
168 var numberToReturn = 0;
170 // Unpack the limit and batchSize values
171 if(cursorState.limit == 0) {
172 numberToReturn = cursorState.batchSize;
173 } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) {
174 numberToReturn = cursorState.limit;
176 numberToReturn = cursorState.batchSize;
179 var numberToSkip = cursorState.skip || 0;
180 // Build actual find command
182 // Using special modifier
183 var usesSpecialModifier = false;
185 // We have a Mongos topology, check if we need to add a readPreference
186 if(topology.type == 'mongos' && readPreference) {
187 findCmd['$readPreference'] = readPreference.toJSON();
188 usesSpecialModifier = true;
191 // Add special modifiers to the query
192 if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true;
193 if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true;
194 if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true;
195 if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true;
196 if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true;
197 if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true;
198 if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true;
199 if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true;
200 if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true;
201 if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true;
204 // nToReturn must be 0 (match all) or negative (match N and close cursor)
205 // nToReturn > 0 will give explain results equivalent to limit(0)
206 numberToReturn = -Math.abs(cmd.limit || 0);
207 usesSpecialModifier = true;
208 findCmd['$explain'] = true;
211 // If we have a special modifier
212 if(usesSpecialModifier) {
213 findCmd['$query'] = cmd.query;
218 // Throw on majority readConcern passed in
219 if(cmd.readConcern && cmd.readConcern.level != 'local') {
220 throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level));
223 // Remove readConcern, ensure no failing commands
224 if(cmd.readConcern) {
226 delete cmd['readConcern'];
229 // Set up the serialize and ignoreUndefined fields
230 var serializeFunctions = typeof options.serializeFunctions == 'boolean'
231 ? options.serializeFunctions : false;
232 var ignoreUndefined = typeof options.ignoreUndefined == 'boolean'
233 ? options.ignoreUndefined : false;
235 // Build Query object
236 var query = new Query(bson, ns, findCmd, {
237 numberToSkip: numberToSkip, numberToReturn: numberToReturn
238 , checkKeys: false, returnFieldSelector: cmd.fields
239 , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined
243 query.slaveOk = readPreference.slaveOk();
245 // Set up the option bits for wire protocol
246 if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable;
247 if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay;
248 if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout;
249 if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData;
250 if(typeof cmd.partial == 'boolean') query.partial = cmd.partial;
256 // Set up a command cursor
257 var setupCommand = function(bson, ns, cmd, cursorState, topology, options) {
258 // Set empty options object
259 options = options || {}
260 // Get the readPreference
261 var readPreference = getReadPreference(cmd, options);
264 for(var name in cmd) {
265 finalCmd[name] = cmd[name];
268 // Build command namespace
269 var parts = ns.split(/\./);
271 // Throw on majority readConcern passed in
272 if(cmd.readConcern && cmd.readConcern.level != 'local') {
273 throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level));
276 // Remove readConcern, ensure no failing commands
277 if(cmd.readConcern) delete cmd['readConcern'];
279 // Serialize functions
280 var serializeFunctions = typeof options.serializeFunctions == 'boolean'
281 ? options.serializeFunctions : false;
283 // Set up the serialize and ignoreUndefined fields
284 var ignoreUndefined = typeof options.ignoreUndefined == 'boolean'
285 ? options.ignoreUndefined : false;
287 // We have a Mongos topology, check if we need to add a readPreference
288 if(topology.type == 'mongos'
290 && readPreference.preference != 'primary') {
293 '$readPreference': readPreference.toJSON()
297 // Build Query object
298 var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, {
299 numberToSkip: 0, numberToReturn: -1
300 , checkKeys: false, serializeFunctions: serializeFunctions
301 , ignoreUndefined: ignoreUndefined
305 query.slaveOk = readPreference.slaveOk();
311 var hasWriteConcern = function(writeConcern) {
313 || writeConcern.wtimeout
314 || writeConcern.j == true
315 || writeConcern.fsync == true
316 || Object.keys(writeConcern).length == 0) {
322 var cloneWriteConcern = function(writeConcern) {
324 if(writeConcern.w != null) wc.w = writeConcern.w;
325 if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout;
326 if(writeConcern.j != null) wc.j = writeConcern.j;
327 if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync;
332 // Aggregate up all the results
334 var aggregateWriteOperationResults = function(opType, ops, results, connection) {
335 var finalResult = { ok: 1, n: 0 }
336 if(opType == 'update') {
337 finalResult.nModified = 0;
340 // Map all the results coming back
341 for(var i = 0; i < results.length; i++) {
342 var result = results[i];
345 if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) {
346 finalResult.upserted = [];
349 // Push the upserted document to the list of upserted values
350 if(result.upserted) {
351 finalResult.upserted.push({index: i, _id: result.upserted});
354 // We have an upsert where we passed in a _id
355 if(result.updatedExisting == false && result.n == 1 && result.upserted == null) {
356 finalResult.upserted.push({index: i, _id: op.q._id});
357 } else if(result.updatedExisting == true) {
358 finalResult.nModified += result.n;
361 // We have an insert command
362 if(result.ok == 1 && opType == 'insert' && result.err == null) {
363 finalResult.n = finalResult.n + 1;
366 // We have a command error
367 if(result != null && result.ok == 0 || result.err || result.errmsg) {
368 if(result.ok == 0) finalResult.ok = 0;
369 finalResult.code = result.code;
370 finalResult.errmsg = result.errmsg || result.err || result.errMsg;
372 // Check if we have a write error
373 if(result.code == 11000
374 || result.code == 11001
375 || result.code == 12582
376 || result.code == 16544
377 || result.code == 16538
378 || result.code == 16542
380 || result.code == 13511) {
381 if(finalResult.writeErrors == null) finalResult.writeErrors = [];
382 finalResult.writeErrors.push({
385 , errmsg: result.errmsg || result.err || result.errMsg
388 finalResult.writeConcernError = {
390 , errmsg: result.errmsg || result.err || result.errMsg
393 } else if(typeof result.n == 'number') {
394 finalResult.n += result.n;
399 // Result as expected
400 if(result != null && result.lastOp) finalResult.lastOp = result.lastOp;
403 // Return finalResult aggregated results
404 return new CommandResult(finalResult, connection);
408 // Execute all inserts in an ordered manner
410 var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, ops, options, callback) {
411 var _ops = ops.slice(0);
412 // Collect all the getLastErrors
413 var getLastErrors = [];
414 // Execute an operation
415 var executeOp = function(list, _callback) {
416 // No more items in the list
417 if(list.length == 0) {
418 return process.nextTick(function() {
419 _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null));
423 // Get the first operation
424 var doc = list.shift();
425 // Create an insert command
426 var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options);
428 var optionWriteConcern = options.writeConcern || {w:1};
429 // Final write concern
430 var writeConcern = cloneWriteConcern(optionWriteConcern);
433 var db = ns.split('.').shift();
436 // Add binary message to list of commands to execute
439 // Add getLastOrdered
440 var getLastErrorCmd = {getlasterror: 1};
441 // Merge all the fields
442 for(var i = 0; i < writeConcernFields.length; i++) {
443 if(writeConcern[writeConcernFields[i]] != null) {
444 getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]];
448 // Create a getLastError command
449 var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1});
450 // Add getLastError command to list of ops to execute
451 commands.push(getLastErrorOp);
453 // getLastError callback
454 var getLastErrorCallback = function(err, result) {
455 if(err) return callback(err);
457 var doc = result.result;
458 // Save the getLastError document
459 getLastErrors.push(doc);
461 // If we have an error terminate
462 if(doc.ok == 0 || doc.err || doc.errmsg) {
463 return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection));
466 // Execute the next op in the list
467 executeOp(list, callback);
470 // Write both commands out at the same time
471 pool.write(commands, getLastErrorCallback);
473 // We have a serialization error, rewrite as a write error to have same behavior as modern
475 getLastErrors.push({ ok: 1, errmsg: typeof err == 'string' ? err : err.message, code: 14 });
476 // Return due to an error
477 process.nextTick(function() {
478 _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null));
483 // Execute the operations
484 executeOp(_ops, callback);
487 var executeUnordered = function(opType, command, ismaster, ns, bson, pool, ops, options, callback) {
488 // Total operations to write
489 var totalOps = ops.length;
490 // Collect all the getLastErrors
491 var getLastErrors = [];
493 var optionWriteConcern = options.writeConcern || {w:1};
494 // Final write concern
495 var writeConcern = cloneWriteConcern(optionWriteConcern);
496 // Driver level error
499 // Execute all the operations
500 for(var i = 0; i < ops.length; i++) {
501 // Create an insert command
502 var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options);
504 var db = ns.split('.').shift();
507 // Add binary message to list of commands to execute
510 // If write concern 0 don't fire getLastError
511 if(hasWriteConcern(writeConcern)) {
512 var getLastErrorCmd = {getlasterror: 1};
513 // Merge all the fields
514 for(var j = 0; j < writeConcernFields.length; j++) {
515 if(writeConcern[writeConcernFields[j]] != null)
516 getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]];
519 // Create a getLastError command
520 var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1});
521 // Add getLastError command to list of ops to execute
522 commands.push(getLastErrorOp);
524 // Give the result from getLastError the right index
525 var callbackOp = function(_index) {
526 return function(err, result) {
528 // Update the number of operations executed
529 totalOps = totalOps - 1;
530 // Save the getLastError document
531 if(!err) getLastErrors[_index] = result.result;
532 // Check if we are done
534 process.nextTick(function() {
535 if(error) return callback(error);
536 callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection));
542 // Write both commands out at the same time
543 pool.write(commands, callbackOp(i));
545 pool.write(commands, {immediateRelease:true, noResponse:true});
548 // Update the number of operations executed
549 totalOps = totalOps - 1;
550 // We have a serialization error, rewrite as a write error to have same behavior as modern
552 getLastErrors[i] = { ok: 1, errmsg: typeof err == 'string' ? err : err.message, code: 14 };
553 // Check if we are done
555 callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null));
562 && writeConcern.w == 0 && callback) {
563 callback(null, new CommandResult({ok:1}, null));
567 module.exports = WireProtocol;