diff --git a/lib/datastore.js b/lib/datastore.js index d35f81b..fbda4fe 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -58,7 +58,13 @@ Datastore.prototype.ensureIndex = function (options, cb) { options.datastore = this; this.indexes[options.fieldName] = new Index(options); - this.indexes[options.fieldName].insert(this.data); + + try { + this.indexes[options.fieldName].insert(this.data); + } catch (e) { + delete this.indexes[options.fieldName]; + return callback(e); + } return callback(); }; diff --git a/lib/indexes.js b/lib/indexes.js index 39bd5c8..bc19c97 100644 --- a/lib/indexes.js +++ b/lib/indexes.js @@ -39,6 +39,7 @@ function Index (options) { /** * Reset an index * @param {Document or Array of documents} newData Optional, data to initialize the index with + * If an error is thrown during insertion, the index is not modified */ Index.prototype.reset = function (newData) { this.tree = new BinarySearchTree(this.treeOptions); @@ -50,7 +51,7 @@ Index.prototype.reset = function (newData) { /** * Insert a new document in the index - * If an array is passed, we insert all its elements + * If an array is passed, we insert all its elements (if one insertion fails the index is not modified) * O(log(n)) */ Index.prototype.insert = function (doc) { diff --git a/test/db.test.js b/test/db.test.js index 3f18589..1ee8935 100644 --- a/test/db.test.js +++ b/test/db.test.js @@ -1282,7 +1282,23 @@ describe('Database', function () { }); }); - it.skip('If a unique constraint is not respected, ensureIndex will return an error', function (done) { + it('If a unique constraint is not respected, ensureIndex will return an error', function (done) { + d.insert({ a: 1, b: 4 }, function () { + d.insert({ a: 2, b: 45 }, function () { + d.insert({ a: 1, b: 3 }, function () { + d.ensureIndex({ fieldName: 'b' }, function (err) { + assert.isUndefined(err); + + d.ensureIndex({ fieldName: 'a', unique: true }, function (err) { + err.errorType.should.equal('uniqueViolated'); + assert.deepEqual(Object.keys(d.indexes), ['b']); + + done(); + }); + }); + }); + }); + }); }); }); // ==== End of 'ensureIndex' ==== //