c0d86ca77c90b5a2beb82de4a17a31062d444616
[aai/esr-gui.git] /
1 "use strict";
2
3 var inherits = require('util').inherits
4   , f = require('util').format
5   , toError = require('./utils').toError
6   , getSingleProperty = require('./utils').getSingleProperty
7   , formattedOrderClause = require('./utils').formattedOrderClause
8   , handleCallback = require('./utils').handleCallback
9   , Logger = require('mongodb-core').Logger
10   , EventEmitter = require('events').EventEmitter
11   , ReadPreference = require('./read_preference')
12   , MongoError = require('mongodb-core').MongoError
13   , Readable = require('stream').Readable || require('readable-stream').Readable
14   , Define = require('./metadata')
15   , CoreCursor = require('./cursor')
16   , Query = require('mongodb-core').Query
17   , CoreReadPreference = require('mongodb-core').ReadPreference;
18
19 /**
20  * @fileOverview The **CommandCursor** class is an internal class that embodies a
21  * generalized cursor based on a MongoDB command allowing for iteration over the
22  * results returned. It supports one by one document iteration, conversion to an
23  * array or can be iterated as a Node 0.10.X or higher stream
24  *
25  * **CommandCursor Cannot directly be instantiated**
26  * @example
27  * var MongoClient = require('mongodb').MongoClient,
28  *   test = require('assert');
29  * // Connection url
30  * var url = 'mongodb://localhost:27017/test';
31  * // Connect using MongoClient
32  * MongoClient.connect(url, function(err, db) {
33  *   // Create a collection we want to drop later
34  *   var col = db.collection('listCollectionsExample1');
35  *   // Insert a bunch of documents
36  *   col.insert([{a:1, b:1}
37  *     , {a:2, b:2}, {a:3, b:3}
38  *     , {a:4, b:4}], {w:1}, function(err, result) {
39  *     test.equal(null, err);
40  *
41  *     // List the database collections available
42  *     db.listCollections().toArray(function(err, items) {
43  *       test.equal(null, err);
44  *       db.close();
45  *     });
46  *   });
47  * });
48  */
49
50 /**
51  * Namespace provided by the browser.
52  * @external Readable
53  */
54
55 /**
56  * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly)
57  * @class CommandCursor
58  * @extends external:Readable
59  * @fires CommandCursor#data
60  * @fires CommandCursor#end
61  * @fires CommandCursor#close
62  * @fires CommandCursor#readable
63  * @return {CommandCursor} an CommandCursor instance.
64  */
65 var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) {
66   CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
67   var self = this;
68   var state = CommandCursor.INIT;
69   var streamOptions = {};
70
71   // MaxTimeMS
72   var maxTimeMS = null;
73
74   // Get the promiseLibrary
75   var promiseLibrary = options.promiseLibrary;
76
77   // No promise library selected fall back
78   if(!promiseLibrary) {
79     promiseLibrary = typeof global.Promise == 'function' ?
80       global.Promise : require('es6-promise').Promise;
81   }
82
83   // Set up
84   Readable.call(this, {objectMode: true});
85
86   // Internal state
87   this.s = {
88     // MaxTimeMS
89       maxTimeMS: maxTimeMS
90     // State
91     , state: state
92     // Stream options
93     , streamOptions: streamOptions
94     // BSON
95     , bson: bson
96     // Namespae
97     , ns: ns
98     // Command
99     , cmd: cmd
100     // Options
101     , options: options
102     // Topology
103     , topology: topology
104     // Topology Options
105     , topologyOptions: topologyOptions
106     // Promise library
107     , promiseLibrary: promiseLibrary
108   }
109 }
110
111 /**
112  * CommandCursor stream data event, fired for each document in the cursor.
113  *
114  * @event CommandCursor#data
115  * @type {object}
116  */
117
118 /**
119  * CommandCursor stream end event
120  *
121  * @event CommandCursor#end
122  * @type {null}
123  */
124
125 /**
126  * CommandCursor stream close event
127  *
128  * @event CommandCursor#close
129  * @type {null}
130  */
131
132 /**
133  * CommandCursor stream readable event
134  *
135  * @event CommandCursor#readable
136  * @type {null}
137  */
138
139 // Inherit from Readable
140 inherits(CommandCursor, Readable);
141
142 // Set the methods to inherit from prototype
143 var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray'
144   , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill'
145   , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled'];
146
147 // Only inherit the types we need
148 for(var i = 0; i < methodsToInherit.length; i++) {
149   CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]];
150 }
151
152 var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true);
153
154 /**
155  * Set the ReadPreference for the cursor.
156  * @method
157  * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
158  * @throws {MongoError}
159  * @return {Cursor}
160  */
161 CommandCursor.prototype.setReadPreference = function(r) {
162   if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
163   if(this.s.state != CommandCursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true});
164
165   if(r instanceof ReadPreference) {
166     this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessMS: r.maxStalenessMS});
167   } else if(typeof r == 'string') {
168     this.s.options.readPreference = new CoreReadPreference(r);
169   } else if(r instanceof CoreReadPreference) {
170     this.s.options.readPreference = r;
171   }
172
173   return this;
174 }
175
176 define.classMethod('setReadPreference', {callback: false, promise:false, returns: [CommandCursor]});
177
178 /**
179  * Set the batch size for the cursor.
180  * @method
181  * @param {number} value The batchSize for the cursor.
182  * @throws {MongoError}
183  * @return {CommandCursor}
184  */
185 CommandCursor.prototype.batchSize = function(value) {
186   if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
187   if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true});
188   if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value;
189   this.setCursorBatchSize(value);
190   return this;
191 }
192
193 define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]});
194
195 /**
196  * Add a maxTimeMS stage to the aggregation pipeline
197  * @method
198  * @param {number} value The state maxTimeMS value.
199  * @return {CommandCursor}
200  */
201 CommandCursor.prototype.maxTimeMS = function(value) {
202   if(this.s.topology.lastIsMaster().minWireVersion > 2) {
203     this.s.cmd.maxTimeMS = value;
204   }
205   return this;
206 }
207
208 define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]});
209
210 CommandCursor.prototype.get = CommandCursor.prototype.toArray;
211
212 define.classMethod('get', {callback: true, promise:false});
213
214 // Inherited methods
215 define.classMethod('toArray', {callback: true, promise:true});
216 define.classMethod('each', {callback: true, promise:false});
217 define.classMethod('forEach', {callback: true, promise:false});
218 define.classMethod('next', {callback: true, promise:true});
219 define.classMethod('close', {callback: true, promise:true});
220 define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]});
221 define.classMethod('rewind', {callback: false, promise:false});
222 define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]});
223 define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]});
224
225 /**
226  * Get the next available document from the cursor, returns null if no more documents are available.
227  * @function CommandCursor.prototype.next
228  * @param {CommandCursor~resultCallback} [callback] The result callback.
229  * @throws {MongoError}
230  * @return {Promise} returns Promise if no callback passed
231  */
232
233 /**
234  * The callback format for results
235  * @callback CommandCursor~toArrayResultCallback
236  * @param {MongoError} error An error instance representing the error during the execution.
237  * @param {object[]} documents All the documents the satisfy the cursor.
238  */
239
240 /**
241  * Returns an array of documents. The caller is responsible for making sure that there
242  * is enough memory to store the results. Note that the array only contain partial
243  * results when this cursor had been previouly accessed.
244  * @method CommandCursor.prototype.toArray
245  * @param {CommandCursor~toArrayResultCallback} [callback] The result callback.
246  * @throws {MongoError}
247  * @return {Promise} returns Promise if no callback passed
248  */
249
250 /**
251  * The callback format for results
252  * @callback CommandCursor~resultCallback
253  * @param {MongoError} error An error instance representing the error during the execution.
254  * @param {(object|null)} result The result object if the command was executed successfully.
255  */
256
257 /**
258  * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
259  * not all of the elements will be iterated if this cursor had been previouly accessed.
260  * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
261  * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
262  * at any given time if batch size is specified. Otherwise, the caller is responsible
263  * for making sure that the entire result can fit the memory.
264  * @method CommandCursor.prototype.each
265  * @param {CommandCursor~resultCallback} callback The result callback.
266  * @throws {MongoError}
267  * @return {null}
268  */
269
270 /**
271  * Close the cursor, sending a KillCursor command and emitting close.
272  * @method CommandCursor.prototype.close
273  * @param {CommandCursor~resultCallback} [callback] The result callback.
274  * @return {Promise} returns Promise if no callback passed
275  */
276
277 /**
278  * Is the cursor closed
279  * @method CommandCursor.prototype.isClosed
280  * @return {boolean}
281  */
282
283 /**
284  * Clone the cursor
285  * @function CommandCursor.prototype.clone
286  * @return {CommandCursor}
287  */
288
289 /**
290  * Resets the cursor
291  * @function CommandCursor.prototype.rewind
292  * @return {CommandCursor}
293  */
294
295 /**
296  * The callback format for the forEach iterator method
297  * @callback CommandCursor~iteratorCallback
298  * @param {Object} doc An emitted document for the iterator
299  */
300
301 /**
302  * The callback error format for the forEach iterator method
303  * @callback CommandCursor~endCallback
304  * @param {MongoError} error An error instance representing the error during the execution.
305  */
306
307 /*
308  * Iterates over all the documents for this cursor using the iterator, callback pattern.
309  * @method CommandCursor.prototype.forEach
310  * @param {CommandCursor~iteratorCallback} iterator The iteration callback.
311  * @param {CommandCursor~endCallback} callback The end callback.
312  * @throws {MongoError}
313  * @return {null}
314  */
315
316 CommandCursor.INIT = 0;
317 CommandCursor.OPEN = 1;
318 CommandCursor.CLOSED = 2;
319
320 module.exports = CommandCursor;