Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

command_cursor.js 9.4KB

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