ensureIndex can be called whenever

pull/2/head
Louis Chatriot 12 years ago
parent c5e5bbbeea
commit 8db119479d
  1. 17
      lib/datastore.js
  2. 35
      test/db.test.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);
});
}

@ -1189,7 +1189,42 @@ 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' ==== //

Loading…
Cancel
Save