ObjectExpression.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. var ObjectExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /** Create an empty expression. Until fields are added, this will evaluate to an empty document (object). **/
  4. var klass = function ObjectExpression(){
  5. if(arguments.length !== 0) throw new Error("zero args expected");
  6. this._excludeId = false; /// <Boolean> for if _id is to be excluded
  7. this._expressions = {}; /// <Object<Expression>> mapping from fieldname to Expression to generate the value NULL expression means include from source document
  8. this._order = []; /// <Array<String>> this is used to maintain order for generated fields not in the source document
  9. }, base = require("./Expression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  10. // DEPENDENCIES
  11. var Value = require("../Value");
  12. // INSTANCE VARIABLES
  13. /** <Boolean> for if _id is to be excluded **/
  14. proto._excludeId = undefined;
  15. /** <Object<Expression>> mapping from fieldname to Expression to generate the value NULL expression means include from source document **/
  16. proto._expressions = undefined;
  17. /** <Array<String>> this is used to maintain order for generated fields not in the source document **/
  18. proto._order = [];
  19. // PROTOTYPE MEMBERS
  20. /** evaluate(), but return a Document instead of a Value-wrapped Document.
  21. | @param pDocument the input Document
  22. | @returns the result document
  23. **/
  24. proto.evaluateDocument = function evaluateDocument(doc){
  25. throw new Error("FINISH evaluateDocument"); //TODO:...
  26. /*
  27. intrusive_ptr<Document> ExpressionObject::evaluateDocument(
  28. const intrusive_ptr<Document> &pDocument) const {
  29. // create and populate the result
  30. intrusive_ptr<Document> pResult(
  31. Document::create(getSizeHint()));
  32. addToDocument(pResult,
  33. Document::create(), // No inclusion field matching.
  34. pDocument);
  35. return pResult;
  36. }
  37. */
  38. };
  39. proto.evaluate = function evaluate(doc){
  40. throw new Error("FINISH evaluate"); //TODO:...
  41. //return Value::createDocument(evaluateDocument(pDocument));
  42. };
  43. proto.optimize = function optimize(){
  44. for (var key in this._expressions) {
  45. var expr = this._expressions[key];
  46. if (expr !== undefined && expr !== null) this._expressions[key] = expr.optimize();
  47. }
  48. return this;
  49. };
  50. proto.getIsSimple = function getIsSimple(){
  51. for (var key in this._expressions) {
  52. var expr = this._expressions[key];
  53. if (expr !== undefined && expr !== null && !expr.getIsSimple()) return false;
  54. }
  55. return true;
  56. };
  57. proto.addDependencies = function addDependencies(deps, path){
  58. var pathStr;
  59. if (path instanceof Array) {
  60. if (path.length === 0) {
  61. // we are in the top level of a projection so _id is implicit
  62. if (!this._excludeId) deps.insert("_id");
  63. } else {
  64. pathStr = new FieldPath(path).getPath() + ".";
  65. }
  66. } else {
  67. if (this._excludeId) throw new Error("_excludeId is true!");
  68. }
  69. for (var key in this._expressions) {
  70. var expr = this._expressions[key];
  71. if (expr !== undefined && expr !== null){
  72. if (path instanceof Array) path.push(key);
  73. expr.addDependencies(deps, path);
  74. if (path instanceof Array) path.pop();
  75. }else{ // inclusion
  76. if(path === undefined || path === null) throw new Error("inclusion not supported in objects nested in $expressions; code 16407");
  77. deps.insert(pathStr + key);
  78. }
  79. }
  80. return deps;
  81. };
  82. /** evaluate(), but add the evaluated fields to a given document instead of creating a new one.
  83. | @param pResult the Document to add the evaluated expressions to
  84. | @param pDocument the input Document for this level
  85. | @param rootDoc the root of the whole input document
  86. **/
  87. proto.addToDocument = function addToDocument(result, document, rootDoc){
  88. throw new Error("FINISH addToDocument"); //TODO:...
  89. /*
  90. void ExpressionObject::addToDocument(
  91. const intrusive_ptr<Document> &pResult,
  92. const intrusive_ptr<Document> &pDocument,
  93. const intrusive_ptr<Document> &rootDoc
  94. ) const
  95. {
  96. const bool atRoot = (pDocument == rootDoc);
  97. ExpressionMap::const_iterator end = _expressions.end();
  98. // This is used to mark fields we've done so that we can add the ones we haven't
  99. set<string> doneFields;
  100. FieldIterator fields(pDocument);
  101. while(fields.more()) {
  102. Document::FieldPair field (fields.next());
  103. ExpressionMap::const_iterator exprIter = _expressions.find(field.first);
  104. // This field is not supposed to be in the output (unless it is _id)
  105. if (exprIter == end) {
  106. if (!_excludeId && atRoot && field.first == Document::idName) {
  107. // _id from the root doc is always included (until exclusion is supported)
  108. // not updating doneFields since "_id" isn't in _expressions
  109. pResult->addField(field.first, field.second);
  110. }
  111. continue;
  112. }
  113. // make sure we don't add this field again
  114. doneFields.insert(exprIter->first);
  115. Expression* expr = exprIter->second.get();
  116. if (!expr) {
  117. // This means pull the matching field from the input document
  118. pResult->addField(field.first, field.second);
  119. continue;
  120. }
  121. ExpressionObject* exprObj = dynamic_cast<ExpressionObject*>(expr);
  122. BSONType valueType = field.second->getType();
  123. if ((valueType != Object && valueType != Array) || !exprObj ) {
  124. // This expression replace the whole field
  125. intrusive_ptr<const Value> pValue(expr->evaluate(rootDoc));
  126. // don't add field if nothing was found in the subobject
  127. if (exprObj && pValue->getDocument()->getFieldCount() == 0)
  128. continue;
  129. // 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.
  130. // TODO make missing distinct from Undefined
  131. if (pValue->getType() != Undefined)
  132. pResult->addField(field.first, pValue);
  133. continue;
  134. }
  135. // 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.
  136. if (valueType == Object) {
  137. intrusive_ptr<Document> doc = Document::create(exprObj->getSizeHint());
  138. exprObj->addToDocument(doc,
  139. field.second->getDocument(),
  140. rootDoc);
  141. pResult->addField(field.first, Value::createDocument(doc));
  142. }
  143. else if (valueType == Array) {
  144. // 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.
  145. vector<intrusive_ptr<const Value> > result;
  146. intrusive_ptr<ValueIterator> pVI(field.second->getArray());
  147. while(pVI->more()) {
  148. intrusive_ptr<const Value> next = pVI->next();
  149. // can't look for a subfield in a non-object value.
  150. if (next->getType() != Object)
  151. continue;
  152. intrusive_ptr<Document> doc = Document::create(exprObj->getSizeHint());
  153. exprObj->addToDocument(doc,
  154. next->getDocument(),
  155. rootDoc);
  156. result.push_back(Value::createDocument(doc));
  157. }
  158. pResult->addField(field.first,
  159. Value::createArray(result));
  160. }
  161. else {
  162. verify( false );
  163. }
  164. }
  165. if (doneFields.size() == _expressions.size())
  166. return;
  167. // add any remaining fields we haven't already taken care of
  168. for (vector<string>::const_iterator i(_order.begin()); i!=_order.end(); ++i) {
  169. ExpressionMap::const_iterator it = _expressions.find(*i);
  170. string fieldName(it->first);
  171. // if we've already dealt with this field, above, do nothing
  172. if (doneFields.count(fieldName))
  173. continue;
  174. // this is a missing inclusion field
  175. if (!it->second)
  176. continue;
  177. intrusive_ptr<const Value> pValue(it->second->evaluate(rootDoc));
  178. // 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.
  179. if (pValue->getType() == Undefined)
  180. continue;
  181. // don't add field if nothing was found in the subobject
  182. if (dynamic_cast<ExpressionObject*>(it->second.get())
  183. && pValue->getDocument()->getFieldCount() == 0)
  184. continue;
  185. pResult->addField(fieldName, pValue);
  186. }
  187. }
  188. */
  189. };
  190. /** estimated number of fields that will be output **/
  191. proto.getSizeHint = function getSizeHint(){
  192. throw new Error("FINISH getSizeHint"); //TODO:...
  193. /*
  194. // Note: this can overestimate, but that is better than underestimating
  195. return _expressions.size() + (_excludeId ? 0 : 1);
  196. */
  197. };
  198. /** Add a field to the document expression.
  199. | @param fieldPath the path the evaluated expression will have in the result Document
  200. | @param pExpression the expression to evaluate obtain this field's Value in the result Document
  201. **/
  202. proto.addField = function addField(path, pExpression){
  203. var fieldPart = path.fields[0],
  204. haveExpr = this._expressions.hasOwnProperty(fieldPart),
  205. expr = this._expressions[fieldPart];
  206. var subObj = expr instanceof ObjectExpression ? expr : undefined;
  207. if(!haveExpr){
  208. this._order.push(fieldPart);
  209. }
  210. throw new Error("FINISH addField"); //TODO:...
  211. /*
  212. void ExpressionObject::addField(const FieldPath &fieldPath, const intrusive_ptr<Expression> &pExpression) {
  213. const string fieldPart = fieldPath.getFieldName(0);
  214. const bool haveExpr = _expressions.count(fieldPart);
  215. intrusive_ptr<Expression>& expr = _expressions[fieldPart]; // inserts if !haveExpr
  216. intrusive_ptr<ExpressionObject> subObj = dynamic_cast<ExpressionObject*>(expr.get());
  217. if (!haveExpr) {
  218. _order.push_back(fieldPart);
  219. }
  220. else { // we already have an expression or inclusion for this field
  221. if (fieldPath.getPathLength() == 1) {
  222. // This expression is for right here
  223. ExpressionObject* newSubObj = dynamic_cast<ExpressionObject*>(pExpression.get());
  224. uassert(16400, str::stream()
  225. << "can't add an expression for field " << fieldPart
  226. << " because there is already an expression for that field"
  227. << " or one of its sub-fields.",
  228. subObj && newSubObj); // we can merge them
  229. // Copy everything from the newSubObj to the existing subObj
  230. // This is for cases like { $project:{ 'b.c':1, b:{ a:1 } } }
  231. for (vector<string>::const_iterator it (newSubObj->_order.begin());
  232. it != newSubObj->_order.end();
  233. ++it) {
  234. // asserts if any fields are dupes
  235. subObj->addField(*it, newSubObj->_expressions[*it]);
  236. }
  237. return;
  238. }
  239. else {
  240. // This expression is for a subfield
  241. uassert(16401, str::stream()
  242. << "can't add an expression for a subfield of " << fieldPart
  243. << " because there is already an expression that applies to"
  244. << " the whole field",
  245. subObj);
  246. }
  247. }
  248. if (fieldPath.getPathLength() == 1) {
  249. verify(!haveExpr); // haveExpr case handled above.
  250. expr = pExpression;
  251. return;
  252. }
  253. if (!haveExpr)
  254. expr = subObj = ExpressionObject::create();
  255. subObj->addField(fieldPath.tail(), pExpression);
  256. }
  257. */
  258. };
  259. /** Add a field path to the set of those to be included.
  260. | Note that including a nested field implies including everything on the path leading down to it.
  261. | @param fieldPath the name of the field to be included
  262. **/
  263. proto.includePath = function includePath(path){
  264. this.addField(path);
  265. };
  266. /** Get a count of the added fields.
  267. | @returns how many fields have been added
  268. **/
  269. proto.getFieldCount = function getFieldCount(){
  270. var e; console.warn(e=new Error("CALLER SHOULD BE USING #expressions.length instead!")); console.log(e.stack);
  271. return this._expressions.length;
  272. };
  273. /*TODO: ... remove this?
  274. inline ExpressionObject::BuilderPathSink::BuilderPathSink(
  275. BSONObjBuilder *pB):
  276. pBuilder(pB) {
  277. }
  278. */
  279. /*TODO: ... remove this?
  280. inline ExpressionObject::PathPusher::PathPusher(
  281. vector<string> *pTheVPath, const string &s):
  282. pvPath(pTheVPath) {
  283. pvPath->push_back(s);
  284. }
  285. inline ExpressionObject::PathPusher::~PathPusher() {
  286. pvPath->pop_back();
  287. }
  288. */
  289. /** Specialized BSON conversion that allows for writing out a $project specification.
  290. | This creates a standalone object, which must be added to a containing object with a name
  291. | @param pBuilder where to write the object to
  292. | @param requireExpression see Expression::addToBsonObj
  293. **/
  294. //TODO: proto.documentToBson = ...?
  295. //TODO: proto.addToBsonObj = ...?
  296. //TODO: proto.addToBsonArray = ...?
  297. /*
  298. /// Visitor abstraction used by emitPaths(). Each path is recorded by calling path().
  299. class PathSink {
  300. public:
  301. virtual ~PathSink() {};
  302. /// Record a path.
  303. /// @param path the dotted path string
  304. /// @param include if true, the path is included; if false, the path is excluded
  305. virtual void path(const string &path, bool include) = 0;
  306. };
  307. /// Utility object for collecting emitPaths() results in a BSON object.
  308. class BuilderPathSink :
  309. public PathSink {
  310. public:
  311. // virtuals from PathSink
  312. virtual void path(const string &path, bool include);
  313. /// Create a PathSink that writes paths to a BSONObjBuilder, to create an object in the form of { path:is_included,...}
  314. /// This object uses a builder pointer that won't guarantee the lifetime of the builder, so make sure it outlasts the use of this for an emitPaths() call.
  315. /// @param pBuilder to the builder to write paths to
  316. BuilderPathSink(BSONObjBuilder *pBuilder);
  317. private:
  318. BSONObjBuilder *pBuilder;
  319. };
  320. /// utility class used by emitPaths()
  321. class PathPusher :
  322. boost::noncopyable {
  323. public:
  324. PathPusher(vector<string> *pvPath, const string &s);
  325. ~PathPusher();
  326. private:
  327. vector<string> *pvPath;
  328. };
  329. */
  330. //void excludeId(bool b) { _excludeId = b; }
  331. return klass;
  332. })();