Expression.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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, base = Object, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  18. // DEPENDENCIES
  19. var Document = require("../Document");
  20. // NESTED CLASSES
  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. }, base = Object, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  48. // PROTOTYPE MEMBERS
  49. proto.isDocumentOk =
  50. proto.isTopLevel =
  51. proto.isInclusionOk = undefined;
  52. return klass;
  53. })();
  54. proto.removeFieldPrefix = function removeFieldPrefix( prefixedField ) {
  55. if(prefixedField.indexOf("\0") !== -1 ) {
  56. // field path must not contain embedded null characters - 16419
  57. }
  58. if(prefixedField[0] !== '$') {
  59. // "field path references must be prefixed with a '$'"
  60. }
  61. return prefixedField.slice(1);
  62. };
  63. var KIND_UNKNOWN = 0,
  64. KIND_NOTOPERATOR = 1,
  65. KIND_OPERATOR = 2;
  66. /**
  67. * Parse an Object. The object could represent a functional expression or a Document expression.
  68. *
  69. * An object expression can take any of the following forms:
  70. *
  71. * f0: {f1: ..., f2: ..., f3: ...}
  72. * f0: {$operator:[operand1, operand2, ...]}
  73. *
  74. * @static
  75. * @method parseObject
  76. * @param obj the element representing the object
  77. * @param ctx a MiniCtx representing the options above
  78. * @returns the parsed Expression
  79. **/
  80. klass.parseObject = function parseObject(obj, ctx, vps){
  81. if(!(ctx instanceof ObjectCtx)) throw new Error("ctx must be ObjectCtx");
  82. var kind = KIND_UNKNOWN,
  83. pExpression, // the result
  84. pExpressionObject; // the alt result
  85. if (obj === undefined || obj == {}) return new ObjectExpression();
  86. var fieldNames = Object.keys(obj);
  87. if(fieldNames.length === 0) { //NOTE: Added this for mongo 2.5 port of document sources. Should reconsider when porting the expressions themselves
  88. return new ObjectExpression();
  89. }
  90. for (var fieldCount = 0, n = fieldNames.length; fieldCount < n; ++fieldCount) {
  91. var pFieldName = fieldNames[fieldCount];
  92. if (pFieldName[0] === "$") {
  93. if (fieldCount !== 0)
  94. throw new Error("the operator must be the only field in a pipeline object (at '" + pFieldName + "'.; code 16410");
  95. if(ctx.isTopLevel)
  96. throw new Error("$expressions are not allowed at the top-level of $project; code 16404");
  97. kind = KIND_OPERATOR; //we've determined this "object" is an operator expression
  98. pExpression = Expression.parseExpression(pFieldName, obj[pFieldName], vps);
  99. } else {
  100. if (kind === KIND_OPERATOR)
  101. throw new Error("this object is already an operator expression, and can't be used as a document expression (at '" + pFieldName + "'.; code 15990");
  102. if (!ctx.isTopLevel && pFieldName.indexOf(".") != -1)
  103. throw new Error("dotted field names are only allowed at the top level; code 16405");
  104. if (pExpression === undefined) { // if it's our first time, create the document expression
  105. if (!ctx.isDocumentOk)
  106. throw new Error("document not allowed in this context"); // CW TODO error: document not allowed in this context
  107. pExpression = pExpressionObject = new ObjectExpression(); //check for top level?
  108. kind = kinds.NOT_OPERATOR; //this "object" is not an operator expression
  109. }
  110. var fieldValue = obj[pFieldName];
  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. pExpressionObject.addField(pFieldName, Expression.parseObject(fieldValue, subCtx, vps));
  119. break;
  120. case "string":
  121. // it's a renamed field // CW TODO could also be a constant
  122. var pathExpr = new FieldPathExpression.parse(fieldValue);
  123. pExpressionObject.addField(pFieldName, pathExpr);
  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; code 16420");
  131. pExpressionObject.includePath(pFieldName);
  132. } else {
  133. if (!(ctx.isTopLevel && fn == Document.ID_PROPERTY_NAME))
  134. throw new Error("The top-level " + Document.ID_PROPERTY_NAME + " field is the only field currently supported for exclusion; code 16406");
  135. pExpressionObject.excludeId = true;
  136. }
  137. break;
  138. default:
  139. throw new Error("disallowed field type " + (fieldValue ? fieldValue.constructor.name + ":" : "") + typeof(fieldValue) + " in object expression (at '" + pFieldName + "')");
  140. }
  141. }
  142. }
  143. return pExpression;
  144. };
  145. klass.expressionParserMap = {};
  146. klass.registerExpression = function registerExpression(key, parserFunc) {
  147. if( key in klass.expressionParserMap ) {
  148. throw new Error("Duplicate expression registrarion for " + key);
  149. }
  150. klass.expressionParserMap[key] = parserFunc;
  151. return 0; // Should
  152. };
  153. /**
  154. * Parse a BSONElement Object which has already been determined to be functional expression.
  155. *
  156. * @static
  157. * @method parseExpression
  158. * @param opName the name of the (prefix) operator
  159. * @param obj the BSONElement to parse
  160. * @returns the parsed Expression
  161. **/
  162. klass.parseExpression = function parseExpression(exprKey, exprValue, vps) {
  163. if( !(exprKey in Expression.expressionParserMap) ) {
  164. throw new Error("Invalid operator : " + exprKey);
  165. }
  166. return Expression.expressionParserMap[exprKey](exprValue, vps);
  167. };
  168. /**
  169. * Parse a BSONElement which is an operand in an Expression.
  170. *
  171. * @static
  172. * @param pBsonElement the expected operand's BSONElement
  173. * @returns the parsed operand, as an Expression
  174. **/
  175. klass.parseOperand = function parseOperand(exprElement, vps){
  176. var t = typeof(exprElement);
  177. if (t === "string" && exprElement[0] == "$") { //if we got here, this is a field path expression
  178. return new FieldPathExpression.parse(exprElement, vps);
  179. }
  180. else
  181. if (t === "object" && exprElement && exprElement.constructor === Object)
  182. return Expression.parseObject(exprElement, new ObjectCtx({isDocumentOk: true}), vps);
  183. else return ConstantExpression.parse(exprElement, vps);
  184. };
  185. /**
  186. * Produce a field path string with the field prefix removed.
  187. * Throws an error if the field prefix is not present.
  188. *
  189. * @static
  190. * @param prefixedField the prefixed field
  191. * @returns the field path with the prefix removed
  192. **/
  193. klass.removeFieldPrefix = function removeFieldPrefix(prefixedField) {
  194. if (prefixedField.indexOf("\0") != -1) throw new Error("field path must not contain embedded null characters; code 16419");
  195. if (prefixedField[0] !== "$") throw new Error("field path references must be prefixed with a '$' ('" + prefixedField + "'); code 15982");
  196. return prefixedField.substr(1);
  197. };
  198. // PROTOTYPE MEMBERS
  199. /**
  200. * Evaluate the Expression using the given document as input.
  201. *
  202. * @method evaluate
  203. * @returns the computed value
  204. **/
  205. proto.evaluate = function evaluate(obj) {
  206. throw new Error("WAS NOT IMPLEMENTED BY INHERITOR!");
  207. };
  208. /**
  209. * Optimize the Expression.
  210. *
  211. * This provides an opportunity to do constant folding, or to collapse nested
  212. * operators that have the same precedence, such as $add, $and, or $or.
  213. *
  214. * The Expression should be replaced with the return value, which may or may
  215. * not be the same object. In the case of constant folding, a computed
  216. * expression may be replaced by a constant.
  217. *
  218. * @method optimize
  219. * @returns the optimized Expression
  220. **/
  221. proto.optimize = function optimize() {
  222. throw new Error("WAS NOT IMPLEMENTED BY INHERITOR!");
  223. };
  224. /**
  225. * Add this expression's field dependencies to the set Expressions are trees, so this is often recursive.
  226. *
  227. * Top-level ExpressionObject gets pointer to empty vector.
  228. * If any other Expression is an ancestor, or in other cases where {a:1} inclusion objects aren't allowed, they get NULL.
  229. *
  230. * @method addDependencies
  231. * @param deps output parameter
  232. * @param path path to self if all ancestors are ExpressionObjects.
  233. **/
  234. proto.addDependencies = function addDependencies(deps, path) {
  235. throw new Error("WAS NOT IMPLEMENTED BY INHERITOR!");
  236. };
  237. /**
  238. * simple expressions are just inclusion exclusion as supported by ExpressionObject
  239. * @method getIsSimple
  240. **/
  241. proto.getIsSimple = function getIsSimple() {
  242. return false;
  243. };
  244. proto.toMatcherBson = function toMatcherBson(){
  245. throw new Error("WAS NOT IMPLEMENTED BY INHERITOR!"); //verify(false && "Expression::toMatcherBson()");
  246. };