ObjectExpression.js 12 KB

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