ObjectExpression.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. var ObjectExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /**
  4. * Create an empty expression. Until fields are added, this will evaluate to an empty document (object).
  5. *
  6. * @class ObjectExpression
  7. * @namespace mungedb.aggregate.pipeline.expressions
  8. * @module mungedb-aggregate
  9. * @extends munge.pipeline.expressions.Expression
  10. * @constructor
  11. **/
  12. var klass = function ObjectExpression(){
  13. if(arguments.length !== 0) throw new Error("zero args expected");
  14. this.excludeId = false; /// <Boolean> for if _id is to be excluded
  15. this._expressions = {}; /// <Object<Expression>> mapping from fieldname to Expression to generate the value NULL expression means include from source document
  16. this._order = []; /// <Array<String>> this is used to maintain order for generated fields not in the source document
  17. }, Expression = require("./Expression"), base = Expression, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  18. // DEPENDENCIES
  19. var Document = require("../Document"),
  20. FieldPath = require("../FieldPath");
  21. // INSTANCE VARIABLES
  22. /**
  23. * <Boolean> for if _id is to be excluded
  24. * @property excludeId
  25. **/
  26. proto.excludeId = undefined;
  27. /**
  28. * <Object<Expression>> mapping from fieldname to Expression to generate the value NULL expression means include from source document
  29. **/
  30. proto._expressions = undefined;
  31. //TODO: might be able to completely ditch _order everywhere in here since `Object`s are mostly ordered anyhow but need to come back and revisit that later
  32. /**
  33. * <Array<String>> this is used to maintain order for generated fields not in the source document
  34. **/
  35. proto._order = [];
  36. // PROTOTYPE MEMBERS
  37. /**
  38. * evaluate(), but return a Document instead of a Value-wrapped Document.
  39. * @method evaluateDocument
  40. * @param pDocument the input Document
  41. * @returns the result document
  42. **/
  43. proto.evaluateDocument = function evaluateDocument(doc) {
  44. // create and populate the result
  45. var pResult = {};
  46. this.addToDocument(pResult, pResult, doc); // No inclusion field matching.
  47. return pResult;
  48. };
  49. proto.evaluate = function evaluate(doc) { //TODO: collapse with #evaluateDocument()?
  50. return this.evaluateDocument(doc);
  51. };
  52. proto.optimize = function optimize(){
  53. for (var key in this._expressions) {
  54. var expr = this._expressions[key];
  55. if (expr !== undefined && expr !== null) this._expressions[key] = expr.optimize();
  56. }
  57. return this;
  58. };
  59. proto.getIsSimple = function getIsSimple(){
  60. for (var key in this._expressions) {
  61. var expr = this._expressions[key];
  62. if (expr !== undefined && expr !== null && !expr.getIsSimple()) return false;
  63. }
  64. return true;
  65. };
  66. proto.addDependencies = function addDependencies(deps, path){
  67. var depsSet = {};
  68. var pathStr = "";
  69. if (path instanceof Array) {
  70. if (path.length === 0) {
  71. // we are in the top level of a projection so _id is implicit
  72. if (!this.excludeId) depsSet[Document.ID_PROPERTY_NAME] = 1;
  73. } else {
  74. pathStr = new FieldPath(path).getPath() + ".";
  75. }
  76. } else {
  77. if (this.excludeId) throw new Error("excludeId is true!");
  78. }
  79. for (var key in this._expressions) {
  80. var expr = this._expressions[key];
  81. if (expr !== undefined && expr !== null) {
  82. if (path instanceof Array) path.push(key);
  83. expr.addDependencies(deps, path);
  84. if (path instanceof Array) path.pop();
  85. } else { // inclusion
  86. if (path === undefined || path === null) throw new Error("inclusion not supported in objects nested in $expressions; uassert code 16407");
  87. depsSet[pathStr + key] = 1;
  88. }
  89. }
  90. //Array.prototype.push.apply(deps, Object.getOwnPropertyNames(depsSet));
  91. for(key in depsSet) {
  92. deps[key] = 1;
  93. }
  94. return deps; // NOTE: added to munge as a convenience
  95. };
  96. /**
  97. * evaluate(), but add the evaluated fields to a given document instead of creating a new one.
  98. * @method addToDocument
  99. * @param pResult the Document to add the evaluated expressions to
  100. * @param pDocument the input Document for this level
  101. * @param rootDoc the root of the whole input document
  102. **/
  103. proto.addToDocument = function addToDocument(pResult, pDocument, rootDoc){
  104. var atRoot = (pDocument === rootDoc);
  105. var doneFields = {}; // This is used to mark fields we've done so that we can add the ones we haven't
  106. for(var fieldName in pDocument){
  107. if (!pDocument.hasOwnProperty(fieldName)) continue;
  108. var fieldValue = pDocument[fieldName];
  109. // This field is not supposed to be in the output (unless it is _id)
  110. if (!this._expressions.hasOwnProperty(fieldName)) {
  111. if (!this.excludeId && atRoot && fieldName == Document.ID_PROPERTY_NAME) {
  112. // _id from the root doc is always included (until exclusion is supported)
  113. // not updating doneFields since "_id" isn't in _expressions
  114. pResult[fieldName] = fieldValue;
  115. }
  116. continue;
  117. }
  118. // make sure we don't add this field again
  119. doneFields[fieldName] = true;
  120. // This means pull the matching field from the input document
  121. var expr = this._expressions[fieldName];
  122. if (!(expr instanceof Expression)) {
  123. pResult[fieldName] = fieldValue;
  124. continue;
  125. }
  126. // Check if this expression replaces the whole field
  127. if ((fieldValue.constructor !== Object && fieldValue.constructor !== Array) || !(expr instanceof ObjectExpression)) {
  128. var pValue = expr.evaluate(rootDoc);
  129. // don't add field if nothing was found in the subobject
  130. if (expr instanceof ObjectExpression && pValue instanceof Object && Object.getOwnPropertyNames(pValue).length === 0) continue;
  131. // Don't add non-existent values (note: different from NULL); this is consistent with existing selection syntax which doesn't force the appearnance of non-existent fields.
  132. // TODO make missing distinct from Undefined
  133. if (pValue !== undefined) pResult[fieldName] = pValue;
  134. continue;
  135. }
  136. // Check on the type of the input value. If it's an object, just walk down into that recursively, and add it to the result.
  137. if (fieldValue.constructor === Object) {
  138. pResult[fieldName] = expr.addToDocument({}, fieldValue, rootDoc); //TODO: pretty sure this is broken;
  139. } else if (fieldValue.constructor == Array) {
  140. // If it's an array, we have to do the same thing, but to each array element. Then, add the array of results to the current document.
  141. var result = [];
  142. for(var fvi = 0, fvl = fieldValue.length; fvi < fvl; fvi++){
  143. var subValue = fieldValue[fvi];
  144. if (subValue.constructor !== Object) continue; // can't look for a subfield in a non-object value.
  145. result.push(expr.addToDocument({}, subValue, rootDoc));
  146. }
  147. pResult[fieldName] = result;
  148. } else {
  149. throw new Error("should never happen"); //verify( false );
  150. }
  151. }
  152. if (Object.getOwnPropertyNames(doneFields).length == Object.getOwnPropertyNames(this._expressions).length) return pResult; //NOTE: munge returns result as a convenience
  153. // add any remaining fields we haven't already taken care of
  154. for(var i = 0, l = this._order.length; i < l; i++){
  155. var fieldName2 = this._order[i];
  156. var expr2 = this._expressions[fieldName2];
  157. // if we've already dealt with this field, above, do nothing
  158. if (doneFields.hasOwnProperty(fieldName2)) continue;
  159. // this is a missing inclusion field
  160. if (!expr2) continue;
  161. var value = expr2.evaluate(rootDoc);
  162. // Don't add non-existent values (note: different from NULL); this is consistent with existing selection syntax which doesn't force the appearnance of non-existent fields.
  163. if (value === undefined) continue;
  164. // don't add field if nothing was found in the subobject
  165. if (expr2 instanceof ObjectExpression && value && value instanceof Object && Object.getOwnPropertyNames(value).length === 0) continue;
  166. pResult[fieldName2] = value;
  167. }
  168. return pResult; //NOTE: munge returns result as a convenience
  169. };
  170. /**
  171. * estimated number of fields that will be output
  172. * @method getSizeHint
  173. **/
  174. proto.getSizeHint = function getSizeHint(){
  175. // Note: this can overestimate, but that is better than underestimating
  176. return Object.getOwnPropertyNames(this._expressions).length + (this.excludeId ? 0 : 1);
  177. };
  178. /**
  179. * Add a field to the document expression.
  180. * @method addField
  181. * @param fieldPath the path the evaluated expression will have in the result Document
  182. * @param pExpression the expression to evaluate obtain this field's Value in the result Document
  183. **/
  184. proto.addField = function addField(fieldPath, pExpression){
  185. if(!(fieldPath instanceof FieldPath)) fieldPath = new FieldPath(fieldPath);
  186. var fieldPart = fieldPath.fields[0],
  187. haveExpr = this._expressions.hasOwnProperty(fieldPart),
  188. subObj = this._expressions[fieldPart]; // inserts if !haveExpr //NOTE: not in munge & JS it doesn't, handled manually below
  189. if (!haveExpr) {
  190. this._order.push(fieldPart);
  191. } else { // we already have an expression or inclusion for this field
  192. if (fieldPath.getPathLength() == 1) { // This expression is for right here
  193. if (!(subObj instanceof ObjectExpression && typeof pExpression == "object" && pExpression instanceof ObjectExpression)){
  194. throw new Error("can't add an expression for field `" + fieldPart + "` because there is already an expression for that field or one of its sub-fields; uassert code 16400"); // we can merge them
  195. }
  196. // Copy everything from the newSubObj to the existing subObj
  197. // This is for cases like { $project:{ 'b.c':1, b:{ a:1 } } }
  198. for (var key in pExpression._expressions) {
  199. if (pExpression._expressions.hasOwnProperty(key)) {
  200. subObj.addField(key, pExpression._expressions[key]); // asserts if any fields are dupes
  201. }
  202. }
  203. return;
  204. } else { // This expression is for a subfield
  205. if(!subObj) throw new Error("can't add an expression for a subfield of `" + fieldPart + "` because there is already an expression that applies to the whole field; uassert code 16401");
  206. }
  207. }
  208. if (fieldPath.getPathLength() == 1) {
  209. if(haveExpr) throw new Error("Internal error."); // haveExpr case handled above.
  210. this._expressions[fieldPart] = pExpression;
  211. return;
  212. }
  213. if (!haveExpr) subObj = this._expressions[fieldPart] = new ObjectExpression();
  214. subObj.addField(fieldPath.tail(), pExpression);
  215. };
  216. /**
  217. * Add a field path to the set of those to be included.
  218. *
  219. * Note that including a nested field implies including everything on the path leading down to it.
  220. *
  221. * @method includePath
  222. * @param fieldPath the name of the field to be included
  223. **/
  224. proto.includePath = function includePath(path){
  225. this.addField(path, undefined);
  226. };
  227. /**
  228. * Get a count of the added fields.
  229. * @method getFieldCount
  230. * @returns how many fields have been added
  231. **/
  232. proto.getFieldCount = function getFieldCount(){
  233. return Object.getOwnPropertyNames(this._expressions).length;
  234. };
  235. ///**
  236. //* Specialized BSON conversion that allows for writing out a $project specification.
  237. //* This creates a standalone object, which must be added to a containing object with a name
  238. //*
  239. //* @param pBuilder where to write the object to
  240. //* @param requireExpression see Expression::addToBsonObj
  241. //**/
  242. //TODO: proto.documentToBson = ...?
  243. //TODO: proto.addToBsonObj = ...?
  244. //TODO: proto.addToBsonArray = ...?
  245. //NOTE: in `munge` we're not passing the `Object`s in and allowing `toJSON` (was `documentToBson`) to modify it directly and are instead building and returning a new `Object` since that's the way it's actually used
  246. proto.toJSON = function toJSON(requireExpression){
  247. var o = {};
  248. if (this.excludeId) o[Document.ID_PROPERTY_NAME] = false;
  249. for (var i = 0, l = this._order.length; i < l; i++) {
  250. var fieldName = this._order[i];
  251. if (!this._expressions.hasOwnProperty(fieldName)) throw new Error("internal error: fieldName from _ordered list not found in _expressions");
  252. var fieldValue = this._expressions[fieldName];
  253. if (fieldValue === undefined) {
  254. o[fieldName] = true; // this is inclusion, not an expression
  255. } else {
  256. o[fieldName] = fieldValue.toJSON(requireExpression);
  257. }
  258. }
  259. return o;
  260. };
  261. return klass;
  262. })();