From 8db119479d2adc313051adaeb7672b564f9353cb Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Thu, 30 May 2013 12:44:53 +0200 Subject: [PATCH] ensureIndex can be called whenever --- lib/datastore.js | 17 +++++++++++++---- test/db.test.js | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/lib/datastore.js b/lib/datastore.js index cc0499b..8c41e00 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -1,6 +1,3 @@ -/** - * TODO: make ensureIndex work whenever it is called, not just right after loadDatabase - */ var fs = require('fs') , path = require('path') , customUtils = require('./customUtils') @@ -31,7 +28,18 @@ function Datastore (filename) { /** - * TODO: make it work whenever ensureIndex is called + * Reset all currently defined indexes + */ +Datastore.prototype.resetIndexes = function (newData) { + var self = this; + + Object.keys(this.indexes).forEach(function (i) { + self.indexes[i].reset(newData); + }); +}; + + +/** * Ensure an index is kept for this field. Same parameters as lib/indexes * For now this function is synchronous, we need to test how much time it takes * @param {String} options.fieldName @@ -144,6 +152,7 @@ Datastore.prototype._loadDatabase = function (cb) { if (err) { return callback(err); } self.data = Datastore.treatRawData(rawData); self.datafileSize = self.data.length; + self.resetIndexes(self.data); self.persistCachedDatabase(callback); }); } diff --git a/test/db.test.js b/test/db.test.js index de9dae3..a43f541 100644 --- a/test/db.test.js +++ b/test/db.test.js @@ -1189,8 +1189,43 @@ describe('Database', function () { }); }); + it('ensureIndex can be called before a loadDatabase and still be initialized and filled correctly', function (done) { + var now = new Date() + , rawData = model.serialize({ _id: "aaa", z: "1", a: 2, ages: [1, 5, 12] }) + '\n' + + model.serialize({ _id: "bbb", z: "2", hello: 'world' }) + '\n' + + model.serialize({ _id: "ccc", z: "3", nested: { today: now } }) + ; + + d.data.length.should.equal(0); + d.datafileSize.should.equal(0); + + d.ensureIndex({ fieldName: 'z' }); + d.indexes.z.fieldName.should.equal('z'); + d.indexes.z.unique.should.equal(false); + d.indexes.z.sparse.should.equal(false); + d.indexes.z.tree.getNumberOfKeys().should.equal(0); + + fs.writeFile(testDb, rawData, 'utf8', function () { + d.loadDatabase(function () { + d.data.length.should.equal(3); + d.datafileSize.should.equal(3); + + d.indexes.z.tree.getNumberOfKeys().should.equal(3); + d.indexes.z.tree.search('1')[0].should.equal(d.data[0]); + d.indexes.z.tree.search('2')[0].should.equal(d.data[1]); + d.indexes.z.tree.search('3')[0].should.equal(d.data[2]); + + done(); + }); + }); + }); + }); + + + + }); // ==== End of 'Using indexes' ==== //