FieldPathExpression.js 5.5 KB

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