diff --git a/lib/datastore.js b/lib/datastore.js index 1d2dffe..53a1ed4 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -23,7 +23,10 @@ function Datastore (filename) { this.datafileSize = 0; // Indexed by field name, dot notation can be used + // _id is always indexed and since _ids are generated randomly the underlying + // binary is always well-balanced this.indexes = {}; + this.ensureIndex({ fieldName: '_id', unique: true }); } @@ -114,6 +117,7 @@ Datastore.prototype.removeFromIndexes = function (doc) { /** * Update a document in all indexes + * TODO: enable rollback if an update fails */ Datastore.prototype.updateIndexes = function (doc, newDoc) { var self = this; diff --git a/lib/indexes.js b/lib/indexes.js index bc19c97..92434dc 100644 --- a/lib/indexes.js +++ b/lib/indexes.js @@ -134,12 +134,33 @@ Index.prototype.update = function (oldDoc, newDoc) { * For now only works with field equality (i.e. can't use the index for $lt query for example) * And doesn't return non indexed docs * @param {Thing} value Value to match the key against - * @return {Array od documents} + * @return {Array of documents} */ Index.prototype.getMatching = function (value) { return this.tree.search(value); }; +/** + * Get all elements in the index + * @return {Array of documents} + */ +Index.prototype.getAll = function () { + var res = []; + + this.tree.executeOnEveryNode(function (node) { + var i; + + for (i = 0; i < node.data.length; i += 1) { + res.push(node.data[i]); + } + }); + + return res; +}; + + + + // Interface module.exports = Index; diff --git a/package.json b/package.json index b487c89..660afb6 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "dependencies": { "async": "~0.2.8", "underscore": "~1.4.4", - "binary-search-tree": "0.1.2" + "binary-search-tree": "0.1.3" }, "devDependencies": { "chai": "1.0.x", diff --git a/test/indexes.test.js b/test/indexes.test.js index 16f62f5..11705fb 100644 --- a/test/indexes.test.js +++ b/test/indexes.test.js @@ -363,4 +363,19 @@ describe('Indexes', function () { }); // ==== End of 'Resetting' ==== // + it('Get all elements in the index', function () { + var idx = new Index({ fieldName: 'a' }) + , doc1 = { a: 5, tf: 'hello' } + , doc2 = { a: 8, tf: 'world' } + , doc3 = { a: 2, tf: 'bloup' } + ; + + idx.insert(doc1); + idx.insert(doc2); + idx.insert(doc3); + + assert.deepEqual(idx.getAll(), [{ a: 2, tf: 'bloup' }, { a: 5, tf: 'hello' }, { a: 8, tf: 'world' }]); + }); + + });