Expression.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. "use strict";
  2. /**
  3. * A base class for all pipeline expressions; Performs common expressions within an Op.
  4. *
  5. * NOTE: An object expression can take any of the following forms:
  6. *
  7. * f0: {f1: ..., f2: ..., f3: ...}
  8. * f0: {$operator:[operand1, operand2, ...]}
  9. *
  10. * @class Expression
  11. * @namespace mungedb-aggregate.pipeline.expressions
  12. * @module mungedb-aggregate
  13. * @constructor
  14. */
  15. var Expression = module.exports = function Expression() {
  16. if (arguments.length !== 0) throw new Error("zero args expected");
  17. }, klass = Expression, proto = klass.prototype;
  18. var Value = require("../Value"),
  19. Document = require("../Document"),
  20. Variables = require("./Variables");
  21. /**
  22. * Reference to the `mungedb-aggregate.pipeline.expressions.Expression.ObjectCtx` class
  23. * @static
  24. * @property ObjectCtx
  25. */
  26. var ObjectCtx = Expression.ObjectCtx = (function() {
  27. // CONSTRUCTOR
  28. /**
  29. * Utility class for parseObject() below. isDocumentOk indicates that it is OK to use a Document in the current context.
  30. *
  31. * NOTE: deviation from Mongo code: accepts an `Object` of settings rather than a bitmask to help simplify the interface a little bit
  32. *
  33. * @class ObjectCtx
  34. * @namespace mungedb-aggregate.pipeline.expressions.Expression
  35. * @module mungedb-aggregate
  36. * @constructor
  37. * @param opts
  38. * @param [opts.isDocumentOk] {Boolean}
  39. * @param [opts.isTopLevel] {Boolean}
  40. * @param [opts.isInclusionOk] {Boolean}
  41. */
  42. var klass = function ObjectCtx(opts /*= {isDocumentOk:..., isTopLevel:..., isInclusionOk:...}*/ ) {
  43. if (!(opts instanceof Object && opts.constructor === Object)) throw new Error("opts is required and must be an Object containing named args");
  44. for (var k in opts) { // assign all given opts to self so long as they were part of klass.prototype as undefined properties
  45. if (opts.hasOwnProperty(k) && proto.hasOwnProperty(k) && proto[k] === undefined) this[k] = opts[k];
  46. }
  47. }, proto = klass.prototype;
  48. // PROTOTYPE MEMBERS
  49. proto.isDocumentOk =
  50. proto.isTopLevel =
  51. proto.isInclusionOk = undefined;
  52. return klass;
  53. })();
  54. //
  55. // Diagram of relationship between parse functions when parsing a $op:
  56. //
  57. // { someFieldOrArrayIndex: { $op: [ARGS] } }
  58. // ^ parseExpression on inner $op BSONElement
  59. // ^ parseObject on BSONObject
  60. // ^ parseOperand on outer BSONElement wrapping the $op Object
  61. //
  62. /**
  63. * Parses a JSON Object that could represent a functional expression or a Document expression.
  64. * @method parseObject
  65. * @static
  66. * @param obj the element representing the object
  67. * @param ctx a MiniCtx representing the options above
  68. * @param vps Variables Parse State
  69. * @returns the parsed Expression
  70. */
  71. klass.parseObject = function parseObject(obj, ctx, vps) {
  72. if (!(ctx instanceof ObjectCtx)) throw new Error("ctx must be ObjectCtx");
  73. /*
  74. An object expression can take any of the following forms:
  75. f0: {f1: ..., f2: ..., f3: ...}
  76. f0: {$operator:[operand1, operand2, ...]}
  77. */
  78. var expression, // the result
  79. expressionObject, // the alt result
  80. UNKNOWN = 0,
  81. NOTOPERATOR = 1,
  82. OPERATOR = 2,
  83. kind = UNKNOWN;
  84. if (obj === undefined || obj === null || (obj instanceof Object && Object.keys(obj).length === 0)) return new ObjectExpression();
  85. var fieldNames = Object.keys(obj);
  86. for (var fieldCount = 0, n = fieldNames.length; fieldCount < n; ++fieldCount) {
  87. var fieldName = fieldNames[fieldCount];
  88. if (fieldName[0] === "$") {
  89. if (fieldCount !== 0)
  90. throw new Error("the operator must be the only field in a pipeline object (at '" + fieldName + "'.; uassert code 15983");
  91. if (ctx.isTopLevel)
  92. throw new Error("$expressions are not allowed at the top-level of $project; uassert code 16404");
  93. // we've determined this "object" is an operator expression
  94. kind = OPERATOR;
  95. expression = Expression.parseExpression(fieldName, obj[fieldName], vps); //NOTE: DEVIATION FROM MONGO: c++ code uses 2 arguments. See #parseExpression
  96. } else {
  97. if (kind === OPERATOR)
  98. throw new Error("this object is already an operator expression, and can't be used as a document expression (at '" + fieldName + "'.; uassert code 15990");
  99. if (!ctx.isTopLevel && fieldName.indexOf(".") !== -1)
  100. throw new Error("dotted field names are only allowed at the top level; uassert code 16405");
  101. // if it's our first time, create the document expression
  102. if (expression === undefined) {
  103. if (!ctx.isDocumentOk) throw new Error("Assertion failure");
  104. // CW TODO error: document not allowed in this context
  105. expressionObject = ctx.isTopLevel ? ObjectExpression.createRoot() : ObjectExpression.create();
  106. expression = expressionObject;
  107. // this "object" is not an operator expression
  108. kind = NOTOPERATOR;
  109. }
  110. var fieldValue = obj[fieldName];
  111. switch (typeof(fieldValue)) {
  112. case "object":
  113. // it's a nested document
  114. var subCtx = new ObjectCtx({
  115. isDocumentOk: ctx.isDocumentOk,
  116. isInclusionOk: ctx.isInclusionOk
  117. });
  118. expressionObject.addField(fieldName, Expression.parseObject(fieldValue, subCtx, vps));
  119. break;
  120. case "string":
  121. // it's a renamed field
  122. // CW TODO could also be a constant
  123. expressionObject.addField(fieldName, FieldPathExpression.parse(fieldValue, vps));
  124. break;
  125. case "boolean":
  126. case "number":
  127. // it's an inclusion specification
  128. if (fieldValue) {
  129. if (!ctx.isInclusionOk)
  130. throw new Error("field inclusion is not allowed inside of $expressions; uassert code 16420");
  131. expressionObject.includePath(fieldName);
  132. } else {
  133. if (!(ctx.isTopLevel && fieldName === Document.ID_PROPERTY_NAME))
  134. throw new Error("The top-level " + Document.ID_PROPERTY_NAME + " field is the only field currently supported for exclusion; uassert code 16406");
  135. expressionObject.excludeId = true;
  136. }
  137. break;
  138. default:
  139. throw new Error("disallowed field type " + Value.getType(fieldValue) + " in object expression (at '" + fieldName + "') uassert code 15992");
  140. }
  141. }
  142. }
  143. return expression;
  144. };
  145. klass.expressionParserMap = {};
  146. /**
  147. * Registers an ExpressionParser so it can be called from parseExpression and friends.
  148. * As an example, if your expression looks like {"$foo": [1,2,3]} you would add this line:
  149. * REGISTER_EXPRESSION("$foo", ExpressionFoo::parse);
  150. */
  151. klass.registerExpression = function registerExpression(key, parserFunc) {
  152. if (key in klass.expressionParserMap)
  153. throw new Error("Duplicate expression (" + key + ") detected; massert code 17064");
  154. klass.expressionParserMap[key] = parserFunc;
  155. return 1;
  156. };
  157. //NOTE: DEVIATION FROM MONGO: the c++ version has 2 arguments, not 3. //TODO: could easily fix this inconsistency
  158. /**
  159. * Parses a BSONElement which has already been determined to be functional expression.
  160. * @static
  161. * @method parseExpression
  162. * @param exprElement should be the only element inside the expression object.
  163. * That is the field name should be the $op for the expression.
  164. * @param vps the variable parse state
  165. * @returns the parsed Expression
  166. */
  167. klass.parseExpression = function parseExpression(exprElementKey, exprElementValue, vps) {
  168. var opName = exprElementKey,
  169. op = Expression.expressionParserMap[opName];
  170. if (!op) throw new Error("invalid operator : " + exprElementKey + "; uassert code 15999");
  171. // make the expression node
  172. return op(exprElementValue, vps);
  173. };
  174. /**
  175. * Parses a BSONElement which is an operand in an Expression.
  176. *
  177. * This is the most generic parser and can parse ExpressionFieldPath, a literal, or a $op.
  178. * If it is a $op, exprElement should be the outer element whose value is an Object
  179. * containing the $op.
  180. *
  181. * @method parseOperand
  182. * @static
  183. * @param exprElement should be the only element inside the expression object.
  184. * That is the field name should be the $op for the expression.
  185. * @param vps the variable parse state
  186. * @returns the parsed operand, as an Expression
  187. */
  188. klass.parseOperand = function parseOperand(exprElement, vps) {
  189. var t = typeof(exprElement);
  190. if (t === "string" && exprElement[0] === "$") {
  191. //if we got here, this is a field path expression
  192. return FieldPathExpression.parse(exprElement, vps);
  193. } else if (t === "object" && exprElement && exprElement.constructor === Object) {
  194. var oCtx = new ObjectCtx({
  195. isDocumentOk: true
  196. });
  197. return Expression.parseObject(exprElement, oCtx, vps);
  198. } else {
  199. return ConstantExpression.parse(exprElement, vps);
  200. }
  201. };
  202. /**
  203. * Optimize the Expression.
  204. *
  205. * This provides an opportunity to do constant folding, or to collapse nested
  206. * operators that have the same precedence, such as $add, $and, or $or.
  207. *
  208. * The Expression should be replaced with the return value, which may or may
  209. * not be the same object. In the case of constant folding, a computed
  210. * expression may be replaced by a constant.
  211. *
  212. * @method optimize
  213. * @returns the optimized Expression
  214. */
  215. proto.optimize = function optimize() {
  216. return this;
  217. };
  218. /**
  219. * Add this expression's field dependencies to the set.
  220. * Expressions are trees, so this is often recursive.
  221. *
  222. * @method addDependencies
  223. * @param deps Fully qualified paths to depended-on fields are added to this set.
  224. * Empty string means need full document.
  225. * @param path path to self if all ancestors are ExpressionObjects.
  226. * Top-level ExpressionObject gets pointer to empty vector.
  227. * If any other Expression is an ancestor, or in other cases
  228. * where {a:1} inclusion objects aren't allowed, they get
  229. * NULL.
  230. */
  231. proto.addDependencies = function addDependencies(deps, path) { //jshint ignore:line
  232. throw new Error("WAS NOT IMPLEMENTED BY INHERITOR!");
  233. };
  234. /**
  235. * simple expressions are just inclusion exclusion as supported by ExpressionObject
  236. * @method isSimple
  237. */
  238. proto.isSimple = function isSimple() {
  239. return false;
  240. };
  241. /**
  242. * Serialize the Expression tree recursively.
  243. * If explain is false, returns a Value parsable by parseOperand().
  244. * @method serialize
  245. */
  246. proto.serialize = function serialize(explain) { //jshint ignore:line
  247. throw new Error("WAS NOT IMPLEMENTED BY INHERITOR!");
  248. };
  249. /**
  250. * Evaluate expression with specified inputs and return result.
  251. *
  252. * While vars is non-const, if properly constructed, subexpressions modifications to it
  253. * should not effect outer expressions due to unique variable Ids.
  254. *
  255. * @method evaluate
  256. * @param vars
  257. */
  258. proto.evaluate = function evaluate(vars) {
  259. if (vars instanceof Object && vars.constructor === Object) vars = new Variables(0, vars); /// Evaluate expression with specified inputs and return result. (only used by tests)
  260. return this.evaluateInternal(vars);
  261. };
  262. /**
  263. * Produce a field path string with the field prefix removed.
  264. * Throws an error if the field prefix is not present.
  265. * @method removeFieldPrefix
  266. * @static
  267. * @param prefixedField the prefixed field
  268. * @returns the field path with the prefix removed
  269. */
  270. klass.removeFieldPrefix = function removeFieldPrefix(prefixedField) {
  271. if (prefixedField.indexOf("\0") !== -1) throw new Error("field path must not contain embedded null characters; uassert code 16419");
  272. if (prefixedField[0] !== "$") throw new Error("field path references must be prefixed with a '$' ('" + prefixedField + "'); uassert code 15982");
  273. return prefixedField.substr(1);
  274. };
  275. /**
  276. * Evaluate the subclass Expression using the given Variables as context and return result.
  277. * @method evaluate
  278. * @returns the computed value
  279. */
  280. proto.evaluateInternal = function evaluateInternal(vars) { //jshint ignore:line
  281. throw new Error("WAS NOT IMPLEMENTED BY INHERITOR!");
  282. };
  283. var ObjectExpression = require("./ObjectExpression"),
  284. FieldPathExpression = require("./FieldPathExpression"),
  285. ConstantExpression = require("./ConstantExpression");