ObjectExpression.js 12 KB

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