ObjectExpression.js 12 KB

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