GroupDocumentSource.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. "use strict";
  2. var DocumentSource = require("./DocumentSource"),
  3. Accumulators = require("../accumulators/"),
  4. Document = require("../Document"),
  5. Expression = require("../expressions/Expression"),
  6. ConstantExpression = require("../expressions/ConstantExpression"),
  7. FieldPathExpression = require("../expressions/FieldPathExpression");
  8. var GroupDocumentSource = module.exports = (function(){
  9. // CONSTRUCTOR
  10. /**
  11. * A class for grouping documents together
  12. *
  13. * @class GroupDocumentSource
  14. * @namespace munge.pipeline.documentsource
  15. * @module munge
  16. * @constructor
  17. * @param {ExpressionContext}
  18. **/
  19. var klass = module.exports = GroupDocumentSource = function GroupDocumentSource(){
  20. this.populated = false;
  21. this.idExpression = null;
  22. this.groups = {}; // GroupsType Value -> Accumulators[]
  23. this.groupsKeys = []; // This is to faciliate easier look up of groups
  24. this.fieldNames = [];
  25. this.accumulatorFactories = [];
  26. this.expressions = [];
  27. this.currentDocument = null;
  28. this.currentGroupsKeysIndex = 0;
  29. }, base = DocumentSource, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  30. klass.GroupOps = {
  31. "$addToSet": Accumulators.AddToSet,
  32. "$avg": Accumulators.Avg,
  33. "$first": Accumulators.First,
  34. "$last": Accumulators.Last,
  35. "$max": Accumulators.MinMax.createMax,
  36. "$min": Accumulators.MinMax.createMin,
  37. "$push": Accumulators.Push,
  38. "$sum": Accumulators.Sum
  39. };
  40. klass.createFromJson = function createFromJson(groupObj) {
  41. if(!(groupObj instanceof Object && groupObj.constructor.name === "Object"))
  42. throw new Error("a group's fields must be specified in an object");
  43. var idSet = false,
  44. group = new GroupDocumentSource();
  45. for(var groupFieldName in groupObj){
  46. if(groupObj.hasOwnProperty(groupFieldName)){
  47. var groupField = groupObj[groupFieldName];
  48. if(groupFieldName === "_id"){
  49. if(idSet) {
  50. throw new Error("15948 a group's _id may only be specified once");
  51. }
  52. if(groupField instanceof Object && groupField.constructor.name === "Object"){
  53. var objCtx = new Expression.ObjectCtx({isDocumentOk:true});
  54. group.idExpression = Expression.parseObject(groupField, objCtx);
  55. idSet = true;
  56. }else if( typeof groupField === "string"){
  57. if(groupField[0] !== "$") {
  58. group.idExpression = new ConstantExpression(groupField);
  59. }
  60. else {
  61. var pathString = Expression.removeFieldPrefix(groupField);
  62. group.idExpression = new FieldPathExpression(pathString);
  63. }
  64. idSet = true;
  65. }else{
  66. //! @todo: _getTypeStr() breaks when trying to group on _id:null.
  67. var typeStr = group._getTypeStr(groupField);
  68. switch(typeStr){
  69. case "number":
  70. case "string":
  71. case "boolean":
  72. case "Object":
  73. case "Array":
  74. group.idExpression = new ConstantExpression(groupField);
  75. idSet = true;
  76. break;
  77. default:
  78. throw new Error("a group's _id may not include fields of type " + typeStr + "");
  79. }
  80. }
  81. }else{
  82. if(groupFieldName.indexOf(".") !== -1)
  83. throw new Error("16414 the group aggregate field name '" + groupFieldName + "' cannot contain '.'");
  84. if(groupFieldName[0] === "$")
  85. throw new Error("15950 the group aggregate field name '" + groupFieldName + "' cannot be an operator name");
  86. if(group._getTypeStr(groupFieldName) === "Object")
  87. throw new Error("15951 the group aggregate field '" + groupFieldName + "' must be defined as an expression inside an object");
  88. var subFieldCount = 0;
  89. for(var subFieldName in groupField){
  90. if(groupField.hasOwnProperty(subFieldName)){
  91. var subField = groupField[subFieldName],
  92. op = klass.GroupOps[subFieldName];
  93. if(!op)
  94. throw new Error("15952 unknown group operator '" + subFieldName + "'");
  95. var groupExpression,
  96. subFieldTypeStr = group._getTypeStr(subField);
  97. if(subFieldTypeStr === "Object"){
  98. var subFieldObjCtx = new Expression.ObjectCtx({isDocumentOk:true});
  99. groupExpression = Expression.parseObject(subField, subFieldObjCtx);
  100. }else if(subFieldTypeStr === "Array"){
  101. throw new Error("15953 aggregating group operators are unary (" + subFieldName + ")");
  102. }else{
  103. groupExpression = Expression.parseOperand(subField);
  104. }
  105. group.addAccumulator(groupFieldName,op, groupExpression);
  106. ++subFieldCount;
  107. }
  108. }
  109. if(subFieldCount != 1)
  110. throw new Error("15954 the computed aggregate '" + groupFieldName + "' must specify exactly one operator");
  111. }
  112. }
  113. }
  114. if(!idSet) {
  115. throw new Error("15955 a group specification must include an _id");
  116. }
  117. return group;
  118. };
  119. proto._getTypeStr = function _getTypeStr(obj){
  120. var typeofStr=typeof obj,
  121. typeStr=(typeofStr == "object" ? obj.constructor.name : typeofStr);
  122. return typeStr;
  123. };
  124. klass.groupName = "$group";
  125. proto.getSourceName = function getSourceName(){
  126. return klass.groupName;
  127. };
  128. proto.advance = function advance(){
  129. base.prototype.advance.call(this); // Check for interupts ????
  130. if(!this.populated)
  131. this.populate();
  132. //verify(this.currentGroupsKeysIndex < this.groupsKeys.length);
  133. ++this.currentGroupsKeysIndex;
  134. if(this.currentGroupsKeysIndex === this.groupsKeys.length){
  135. this.currentDocument = null;
  136. return false;
  137. }
  138. this.currentDocument = this.makeDocument(this.currentGroupsKeysIndex);
  139. return true;
  140. };
  141. proto.eof = function eof(){
  142. if(!this.populated)
  143. this.populate();
  144. return this.currentGroupsKeysIndex === this.groupsKeys.length;
  145. };
  146. proto.getCurrent = function getCurrent(){
  147. if(!this.populated)
  148. this.populate();
  149. return this.currentDocument;
  150. };
  151. proto.getDependencies = function getDependencies(deps) {
  152. var self = this;
  153. // add _id
  154. this.idExpression.addDependencies(deps);
  155. // add the rest
  156. this.fieldNames.forEach(function(field, i) {
  157. self.expressions[i].addDependencies(deps);
  158. });
  159. return DocumentSource.GetDepsReturn.EXHAUSTIVE;
  160. };
  161. proto.addAccumulator = function addAccumulator(fieldName, accumulatorFactory, expression){
  162. this.fieldNames.push(fieldName);
  163. this.accumulatorFactories.push(accumulatorFactory);
  164. this.expressions.push(expression);
  165. };
  166. proto.populate = function populate(){
  167. for(var hasNext = !this.pSource.eof(); hasNext; hasNext = this.pSource.advance()){
  168. var group,
  169. currentDocument = this.pSource.getCurrent(),
  170. _id = this.idExpression.evaluate(currentDocument);
  171. if(undefined === _id) {
  172. _id = null;
  173. }
  174. var idHash = JSON.stringify(_id); //! @todo USE A REAL HASH. I didn't have time to take collision into account.
  175. if(idHash in this.groups){
  176. group = this.groups[idHash];
  177. }else{
  178. this.groups[idHash] = group = [];
  179. this.groupsKeys[this.currentGroupsKeysIndex] = idHash;
  180. ++this.currentGroupsKeysIndex;
  181. for(var ai =0; ai < this.accumulatorFactories.length; ++ai){
  182. var accumulator = new this.accumulatorFactories[ai]();
  183. accumulator.addOperand(this.expressions[ai]);
  184. group.push(accumulator);
  185. }
  186. }
  187. // tickle all the accumulators for the group we found
  188. for(var gi=0; gi < group.length; ++gi)
  189. group[gi].evaluate(currentDocument);
  190. }
  191. this.currentGroupsKeysIndex = 0; // Start the group
  192. if(this.groupsKeys.length > 0)
  193. this.currentDocument = this.makeDocument(this.currentGroupsKeysIndex);
  194. this.populated = true;
  195. };
  196. proto.makeDocument = function makeDocument(groupKeyIndex){
  197. var groupKey = this.groupsKeys[groupKeyIndex],
  198. group = this.groups[groupKey],
  199. doc = {};
  200. doc[Document.ID_PROPERTY_NAME] = JSON.parse(groupKey);
  201. for(var i = 0; i < this.fieldNames.length; ++i){
  202. var fieldName = this.fieldNames[i],
  203. item = group[i];
  204. if((item !== "null") && (typeof item !== "undefined")){
  205. doc[fieldName] = item.getValue();
  206. }
  207. }
  208. return doc;
  209. };
  210. /**
  211. * Reset the document source so that it is ready for a new stream of data.
  212. * Note that this is a deviation from the mongo implementation.
  213. *
  214. * @method reset
  215. **/
  216. proto.reset = function reset(){
  217. this.populated = false;
  218. this.groups = [];
  219. this.groupsKeys = [];
  220. this.currentDocument = null;
  221. this.currentGroupsKeysIndex = 0;
  222. };
  223. return klass;
  224. })();