If ensureIndex cant create a new index because a unique constraint is not met, nothing done

pull/2/head
Louis Chatriot 12 years ago
parent d223e4733d
commit a369d1b110
  1. 8
      lib/datastore.js
  2. 3
      lib/indexes.js
  3. 18
      test/db.test.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();
};

@ -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) {

@ -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' ==== //

Loading…
Cancel
Save