SortDocumentSource.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. "use strict";
  2. /**
  3. * A document source sorter
  4. *
  5. * //NOTE: DEVIATION FROM THE MONGO: We don't have shards, this inherits from DocumentSource, instead of SplittableDocumentSource
  6. *
  7. * @class SortDocumentSource
  8. * @namespace mungedb-aggregate.pipeline.documentSources
  9. * @module mungedb-aggregate
  10. * @constructor
  11. * @param [ctx] {ExpressionContext}
  12. **/
  13. var SortDocumentSource = module.exports = function SortDocumentSource(ctx){
  14. if (arguments.length > 1) throw new Error("up to one arg expected");
  15. base.call(this, ctx);
  16. /*
  17. * Before returning anything, this source must fetch everything from
  18. * the underlying source and group it. populate() is used to do that
  19. * on the first call to any method on this source. The populated
  20. * boolean indicates that this has been done
  21. **/
  22. this.populated = false;
  23. this.current = null;
  24. this.docIterator = null; // a number tracking our position in the documents array
  25. this.documents = []; // an array of documents
  26. this.vSortKey = [];
  27. this.vAscending = [];
  28. }, klass = SortDocumentSource, base = require('./DocumentSource'), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  29. // DEPENDENCIES
  30. var FieldPathExpression = require("../expressions/FieldPathExpression"),
  31. Value = require("../Value");
  32. klass.sortName = "$sort";
  33. proto.getSourceName = function getSourceName(){
  34. return klass.sortName;
  35. };
  36. proto.getFactory = function getFactory(){
  37. return klass; // using the ctor rather than a separate .create() method
  38. };
  39. klass.GetDepsReturn = {
  40. SEE_NEXT: "SEE_NEXT" // Add the next Source's deps to the set
  41. };
  42. proto.getDependencies = function getDependencies(deps) {
  43. for(var i = 0; i < this.vSortKey.length; ++i) {
  44. this.vSortKey[i].addDependencies(deps);
  45. }
  46. return klass.GetDepsReturn.SEE_NEXT;
  47. };
  48. /**
  49. * Is the source at EOF?
  50. * @method eof
  51. * @return {bool} return if we have hit the end of input
  52. **/
  53. proto.eof = function eof() {
  54. if (!this.populated) this.populate();
  55. return (this.docIterator == this.documents.length);
  56. };
  57. /**
  58. * some implementations do the equivalent of verify(!eof()) so check eof() first
  59. * @method getCurrent
  60. * @returns {Document} the current Document without advancing
  61. **/
  62. proto.getCurrent = function getCurrent() {
  63. if (!this.populated) this.populate();
  64. return this.current;
  65. };
  66. /**
  67. * Advance the state of the DocumentSource so that it will return the next Document.
  68. * The default implementation returns false, after checking for interrupts.
  69. * Derived classes can call the default implementation in their own implementations in order to check for interrupts.
  70. *
  71. * @method advance
  72. * @returns {Boolean} whether there is another document to fetch, i.e., whether or not getCurrent() will succeed. This default implementation always returns false.
  73. **/
  74. proto.advance = function advance() {
  75. base.prototype.advance.call(this); // check for interrupts
  76. if (!this.populated) this.populate();
  77. if (this.docIterator == this.documents.length) throw new Error("This should never happen");
  78. ++this.docIterator;
  79. if (this.docIterator == this.documents.length) {
  80. this.current = null;
  81. return false;
  82. }
  83. this.current = this.documents[this.docIterator];
  84. return true;
  85. };
  86. /**
  87. * Create an object that represents the document source. The object
  88. * will have a single field whose name is the source's name. This
  89. * will be used by the default implementation of addToJsonArray()
  90. * to add this object to a pipeline being represented in JSON.
  91. *
  92. * @method sourceToJson
  93. * @param {Object} builder JSONObjBuilder: a blank object builder to write to
  94. * @param {Boolean} explain create explain output
  95. **/
  96. proto.sourceToJson = function sourceToJson(builder, explain) {
  97. var insides = {};
  98. this.sortKeyToJson(insides, false);
  99. builder[this.getSourceName()] = insides;
  100. };
  101. /**
  102. * Add sort key field.
  103. *
  104. * Adds a sort key field to the key being built up. A concatenated
  105. * key is built up by calling this repeatedly.
  106. *
  107. * @param {String} fieldPath the field path to the key component
  108. * @param {bool} ascending if true, use the key for an ascending sort, otherwise, use it for descending
  109. **/
  110. proto.addKey = function addKey(fieldPath, ascending) {
  111. var pathExpr = new FieldPathExpression(fieldPath);
  112. this.vSortKey.push(pathExpr);
  113. if (ascending === true || ascending === false) {
  114. this.vAscending.push(ascending);
  115. } else {
  116. throw new Error("ascending must be true or false");
  117. }
  118. };
  119. proto.populate = function populate() {
  120. /* make sure we've got a sort key */
  121. if (this.vSortKey.length === null) throw new Error("This should never happen");
  122. /* pull everything from the underlying source */
  123. for(var hasNext = !this.source.eof(); hasNext; hasNext = this.source.advance()) {
  124. var doc = this.source.getCurrent();
  125. this.documents.push(doc);
  126. }
  127. /* sort the list */
  128. this.documents.sort(SortDocumentSource.prototype.compare.bind(this));
  129. /* start the sort iterator */
  130. this.docIterator = 0;
  131. if (this.docIterator < this.documents.length) {
  132. this.current = this.documents[this.docIterator];
  133. }
  134. this.populated = true;
  135. };
  136. /**
  137. * Compare two documents according to the specified sort key.
  138. *
  139. * @param {Object} pL the left side doc
  140. * @param {Object} pR the right side doc
  141. * @returns {Number} a number less than, equal to, or greater than zero, indicating pL < pR, pL == pR, or pL > pR, respectively
  142. **/
  143. proto.compare = function compare(pL,pR) {
  144. /**
  145. * populate() already checked that there is a non-empty sort key,
  146. * so we shouldn't have to worry about that here.
  147. *
  148. * However, the tricky part is what to do is none of the sort keys are
  149. * present. In this case, consider the document less.
  150. **/
  151. var n = this.vSortKey.length;
  152. for(var i = 0; i < n; ++i) {
  153. /* evaluate the sort keys */
  154. var pathExpr = new FieldPathExpression(this.vSortKey[i].getFieldPath(false));
  155. var left = pathExpr.evaluate(pL), right = pathExpr.evaluate(pR);
  156. /*
  157. Compare the two values; if they differ, return. If they are
  158. the same, move on to the next key.
  159. */
  160. var cmp = Value.compare(left, right);
  161. if (cmp) {
  162. /* if necessary, adjust the return value by the key ordering */
  163. if (!this.vAscending[i])
  164. cmp = -cmp;
  165. return cmp;
  166. }
  167. }
  168. /**
  169. * If we got here, everything matched (or didn't exist), so we'll
  170. * consider the documents equal for purposes of this sort
  171. **/
  172. return 0;
  173. };
  174. /**
  175. * Write out an object whose contents are the sort key.
  176. *
  177. * @param {Object} builder initialized object builder.
  178. * @param {bool} fieldPrefix specify whether or not to include the field
  179. **/
  180. proto.sortKeyToJson = function sortKeyToJson(builder, usePrefix) {
  181. // add the key fields
  182. var n = this.vSortKey.length;
  183. for(var i = 0; i < n; ++i) {
  184. // create the "field name"
  185. var ss = this.vSortKey[i].getFieldPath(usePrefix); // renamed write to get
  186. // push a named integer based on the sort order
  187. builder[ss] = this.vAscending[i] > 0 ? 1 : -1;
  188. }
  189. };
  190. /**
  191. * Creates a new SortDocumentSource
  192. * @param {Object} jsonElement
  193. **/
  194. klass.createFromJson = function createFromJson(jsonElement, ctx) {
  195. if (typeof jsonElement !== "object") throw new Error("code 15973; the " + klass.sortName + " key specification must be an object");
  196. var Sort = proto.getFactory(),
  197. nextSort = new Sort(ctx);
  198. /* check for then iterate over the sort object */
  199. var sortKeys = 0;
  200. for(var key in jsonElement) {
  201. var sortOrder = 0;
  202. if (typeof jsonElement[key] !== "number") throw new Error("code 15974; " + klass.sortName + " key ordering must be specified using a number");
  203. sortOrder = jsonElement[key];
  204. if ((sortOrder != 1) && (sortOrder !== -1)) throw new Error("code 15975; " + klass.sortName + " key ordering must be 1 (for ascending) or 0 (for descending)");
  205. nextSort.addKey(key, (sortOrder > 0));
  206. ++sortKeys;
  207. }
  208. if (sortKeys <= 0) throw new Error("code 15976; " + klass.sortName + " must have at least one sort key");
  209. return nextSort;
  210. };