FieldPathExpression.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. "use strict";
  2. var Expression = require("./Expression"),
  3. Variables = require("./Variables"),
  4. Value = require("../Value"),
  5. FieldPath = require("../FieldPath");
  6. /**
  7. * Create a field path expression.
  8. *
  9. * Evaluation will extract the value associated with the given field
  10. * path from the source document.
  11. *
  12. * @class FieldPathExpression
  13. * @namespace mungedb-aggregate.pipeline.expressions
  14. * @module mungedb-aggregate
  15. * @extends mungedb-aggregate.pipeline.expressions.Expression
  16. * @constructor
  17. * @param {String} theFieldPath the field path string, without any leading document indicator
  18. */
  19. var FieldPathExpression = module.exports = function FieldPathExpression(theFieldPath, variable) {
  20. if (arguments.length != 2) throw new Error(klass.name + ": expected args: theFieldPath[, variable]");
  21. this._fieldPath = new FieldPath(theFieldPath);
  22. this._variable = variable;
  23. }, klass = FieldPathExpression, base = Expression, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  24. /**
  25. * Create a field path expression using old semantics (rooted off of CURRENT).
  26. *
  27. * // NOTE: this method is deprecated and only used by tests
  28. * // TODO remove this method in favor of parse()
  29. *
  30. * Evaluation will extract the value associated with the given field
  31. * path from the source document.
  32. *
  33. * @param fieldPath the field path string, without any leading document
  34. * indicator
  35. * @returns the newly created field path expression
  36. **/
  37. klass.create = function create(fieldPath) {
  38. return new FieldPathExpression("CURRENT." + fieldPath, Variables.ROOT_ID);
  39. };
  40. // this is the new version that supports every syntax
  41. /**
  42. * Like create(), but works with the raw string from the user with the "$" prefixes.
  43. * @param raw raw string fieldpath
  44. * @param vps variablesParseState
  45. * @returns a new FieldPathExpression
  46. */
  47. klass.parse = function parse(raw, vps) {
  48. if (raw[0] !== "$") throw new Error("FieldPath: '" + raw + "' doesn't start with a $; uassert code 16873");
  49. if (raw.length < 2) throw new Error("'$' by itself is not a valid FieldPath; uassert code 16872"); // need at least "$" and either "$" or a field name
  50. if (raw[1] === "$") {
  51. var fieldPath = raw.substr(2), // strip off $$
  52. varName = fieldPath.substr(0, fieldPath.indexOf("."));
  53. Variables.uassertValidNameForUserRead(varName);
  54. return new FieldPathExpression(raw.slice(2), vps.getVariableName(varName));
  55. } else {
  56. return new FieldPathExpression("CURRENT." + raw.substr(1), vps.getVariable("CURRENT"));
  57. }
  58. };
  59. proto.optimize = function optimize() {
  60. // nothing can be done for these
  61. return this;
  62. };
  63. proto.addDependencies = function addDependencies(deps) {
  64. if (this._variable === Variables.ROOT_ID) {
  65. if (this._fieldPath.fieldNames.length === 1) {
  66. deps.needWholeDocument = true; // need full doc if just "$$ROOT"
  67. } else {
  68. deps.fields[this._fieldPath.tail().getPath(false)] = 1;
  69. }
  70. }
  71. };
  72. /**
  73. * Helper for evaluatePath to handle Array case
  74. */
  75. proto._evaluatePathArray = function _evaluatePathArray(index, input) {
  76. if (!(input instanceof Array)) throw new Error("must be array; dassert");
  77. // Check for remaining path in each element of array
  78. var result = [];
  79. for (var i = 0, l = input.length; i < l; i++) {
  80. if (!(input[i] instanceof Object))
  81. continue;
  82. var nested = this._evaluatePath(index, input[i]);
  83. if (nested !== undefined)
  84. result.push(nested);
  85. }
  86. return result;
  87. };
  88. /**
  89. * Internal implementation of evaluateInternal(), used recursively.
  90. *
  91. * The internal implementation doesn't just use a loop because of
  92. * the possibility that we need to skip over an array. If the path
  93. * is "a.b.c", and a is an array, then we fan out from there, and
  94. * traverse "b.c" for each element of a:[...]. This requires that
  95. * a be an array of objects in order to navigate more deeply.
  96. *
  97. * @param index current path field index to extract
  98. * @param input current document traversed to (not the top-level one)
  99. * @returns the field found; could be an array
  100. */
  101. proto._evaluatePath = function _evaluatePath(index, input) {
  102. // Note this function is very hot so it is important that is is well optimized.
  103. // In particular, all return paths should support RVO.
  104. // if we've hit the end of the path, stop
  105. if (index == this._fieldPath.fieldNames.length - 1)
  106. return input[this._fieldPath.fieldNames[index]];
  107. // Try to dive deeper
  108. var val = input[this._fieldPath.fieldNames[index]];
  109. if (val instanceof Object && val.constructor === Object) {
  110. return this._evaluatePath(index + 1, val);
  111. } else if (val instanceof Array) {
  112. return this._evaluatePathArray(index + 1, val);
  113. } else {
  114. return undefined;
  115. }
  116. };
  117. proto.evaluateInternal = function evaluateInternal(vars) {
  118. if (this._fieldPath.fieldNames.length === 1) // get the whole variable
  119. return vars.getValue(this._variable);
  120. if (this._variable === Variables.ROOT_ID) {
  121. // ROOT is always a document so use optimized code path
  122. return this._evaluatePath(1, vars.getRoot());
  123. }
  124. var val = vars.getValue(this._variable);
  125. if (val instanceof Object && val.constructor === Object) {
  126. return this._evaluatePath(1, val);
  127. } else if(val instanceof Array) {
  128. return this._evaluatePathArray(1,val);
  129. } else {
  130. return undefined;
  131. }
  132. };
  133. proto.serialize = function serialize(){
  134. if(this._fieldPath.fieldNames[0] === "CURRENT" && this._fieldPath.fieldNames.length > 1) {
  135. // use short form for "$$CURRENT.foo" but not just "$$CURRENT"
  136. return "$" + this._fieldPath.tail().getPath(false);
  137. } else {
  138. return "$$" + this._fieldPath.getPath(false);
  139. }
  140. };
  141. proto.getFieldPath = function getFieldPath(){
  142. return this._fieldPath;
  143. };