Skip to content

Commit 512251e

Browse files
drew-grossflovilmart
authored andcommitted
Move field deletion logic into mongo adapter (#1471)
1 parent f312f81 commit 512251e

File tree

4 files changed

+86
-40
lines changed

4 files changed

+86
-40
lines changed

spec/Schema.spec.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -684,12 +684,13 @@ describe('Schema', () => {
684684
.then(() => schema.deleteField('relationField', 'NewClass', config.database))
685685
.then(() => schema.reloadData())
686686
.then(() => {
687-
expect(schema['data']['NewClass']).toEqual({
687+
const expectedSchema = {
688688
objectId: { type: 'String' },
689689
updatedAt: { type: 'Date' },
690690
createdAt: { type: 'Date' },
691691
ACL: { type: 'ACL' }
692-
});
692+
};
693+
expect(dd(schema.data.NewClass, expectedSchema)).toEqual(undefined);
693694
done();
694695
});
695696
});
@@ -716,6 +717,10 @@ describe('Schema', () => {
716717
done();
717718
Parse.Object.enableSingleInstance();
718719
});
720+
})
721+
.catch(error => {
722+
fail(error);
723+
done();
719724
});
720725
});
721726

src/Adapters/Storage/Mongo/MongoCollection.js

-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ export default class MongoCollection {
2828

2929
var index = {};
3030
index[key] = '2d';
31-
//TODO: condiser moving index creation logic into Schema.js
3231
return this._mongoCollection.createIndex(index)
3332
// Retry, but just once.
3433
.then(() => this._rawFind(query, { skip, limit, sort }));

src/Adapters/Storage/Mongo/MongoStorageAdapter.js

+49-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
2-
import MongoCollection from './MongoCollection';
3-
import MongoSchemaCollection from './MongoSchemaCollection';
1+
import MongoCollection from './MongoCollection';
2+
import MongoSchemaCollection from './MongoSchemaCollection';
43
import {parse as parseUrl, format as formatUrl} from '../../../vendor/mongodbUrl';
4+
import _ from 'lodash';
55

66
let mongodb = require('mongodb');
77
let MongoClient = mongodb.MongoClient;
@@ -78,6 +78,52 @@ export class MongoStorageAdapter {
7878
});
7979
});
8080
}
81+
82+
// Remove the column and all the data. For Relations, the _Join collection is handled
83+
// specially, this function does not delete _Join columns. It should, however, indicate
84+
// that the relation fields does not exist anymore. In mongo, this means removing it from
85+
// the _SCHEMA collection. There should be no actual data in the collection under the same name
86+
// as the relation column, so it's fine to attempt to delete it. If the fields listed to be
87+
// deleted do not exist, this function should return successfully anyways. Checking for
88+
// attempts to delete non-existent fields is the responsibility of Parse Server.
89+
90+
// Pointer field names are passed for legacy reasons: the original mongo
91+
// format stored pointer field names differently in the database, and therefore
92+
// needed to know the type of the field before it could delete it. Future database
93+
// adatpers should ignore the pointerFieldNames argument. All the field names are in
94+
// fieldNames, they show up additionally in the pointerFieldNames database for use
95+
// by the mongo adapter, which deals with the legacy mongo format.
96+
97+
// This function is not obligated to delete fields atomically. It is given the field
98+
// names in a list so that databases that are capable of deleting fields atomically
99+
// may do so.
100+
101+
// Returns a Promise.
102+
103+
// This function currently accepts the collectionPrefix and adaptive collection as a paramater because it isn't
104+
// actually capable of determining the location of it's own _SCHEMA collection without having
105+
// the collectionPrefix. Also, Schemas.js, the caller of this function, only stores the collection
106+
// itself, and not the prefix. Eventually Parse Server won't care what a SchemaCollection is and
107+
// will just tell the DB adapter to do things and it will do them.
108+
deleteFields(className: string, fieldNames, pointerFieldNames, collectionPrefix, adaptiveCollection) {
109+
const nonPointerFieldNames = _.difference(fieldNames, pointerFieldNames);
110+
const mongoFormatNames = nonPointerFieldNames.concat(pointerFieldNames.map(name => `_p_${name}`));
111+
const collectionUpdate = { '$unset' : {} };
112+
mongoFormatNames.forEach(name => {
113+
collectionUpdate['$unset'][name] = null;
114+
});
115+
116+
const schemaUpdate = { '$unset' : {} };
117+
fieldNames.forEach(name => {
118+
schemaUpdate['$unset'][name] = null;
119+
});
120+
121+
return adaptiveCollection.updateMany({}, collectionUpdate)
122+
.then(updateResult => {
123+
return this.schemaCollection(collectionPrefix)
124+
})
125+
.then(schemaCollection => schemaCollection.updateSchema(className, schemaUpdate));
126+
}
81127
}
82128

83129
export default MongoStorageAdapter;

src/Schema.js

+30-34
Original file line numberDiff line numberDiff line change
@@ -514,40 +514,36 @@ class Schema {
514514
}
515515

516516
return this.reloadData()
517-
.then(() => {
518-
return this.hasClass(className)
519-
.then(hasClass => {
520-
if (!hasClass) {
521-
throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, `Class ${className} does not exist.`);
522-
}
523-
if (!this.data[className][fieldName]) {
524-
throw new Parse.Error(255, `Field ${fieldName} does not exist, cannot delete.`);
525-
}
526-
527-
if (this.data[className][fieldName].type == 'Relation') {
528-
//For relations, drop the _Join table
529-
return database.dropCollection(`_Join:${fieldName}:${className}`)
530-
.then(() => {
531-
return Promise.resolve();
532-
}, error => {
533-
if (error.message == 'ns not found') {
534-
return Promise.resolve();
535-
}
536-
return Promise.reject(error);
537-
});
538-
}
539-
540-
// for non-relations, remove all the data.
541-
// This is necessary to ensure that the data is still gone if they add the same field.
542-
return database.adaptiveCollection(className)
543-
.then(collection => {
544-
let mongoFieldName = this.data[className][fieldName].type === 'Pointer' ? `_p_${fieldName}` : fieldName;
545-
return collection.updateMany({}, { "$unset": { [mongoFieldName]: null } });
546-
});
547-
})
548-
// Save the _SCHEMA object
549-
.then(() => this._collection.updateSchema(className, { $unset: { [fieldName]: null } }));
550-
});
517+
.then(() => this.hasClass(className))
518+
.then(hasClass => {
519+
if (!hasClass) {
520+
throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, `Class ${className} does not exist.`);
521+
}
522+
if (!this.data[className][fieldName]) {
523+
throw new Parse.Error(255, `Field ${fieldName} does not exist, cannot delete.`);
524+
}
525+
526+
if (this.data[className][fieldName].type == 'Relation') {
527+
//For relations, drop the _Join table
528+
return database.adaptiveCollection(className).then(collection => {
529+
return database.adapter.deleteFields(className, [fieldName], [], database.collectionPrefix, collection);
530+
})
531+
.then(() => database.dropCollection(`_Join:${fieldName}:${className}`))
532+
.catch(error => {
533+
// 'ns not found' means collection was already gone. Ignore deletion attempt.
534+
// TODO: 'ns not found' is a mongo implementation detail. Move it into mongo adapter.
535+
if (error.message == 'ns not found') {
536+
return Promise.resolve();
537+
}
538+
return Promise.reject(error);
539+
});
540+
}
541+
542+
const fieldNames = [fieldName];
543+
const pointerFieldNames = this.data[className][fieldName].type === 'Pointer' ? [fieldName] : [];
544+
return database.adaptiveCollection(className)
545+
.then(collection => database.adapter.deleteFields(className, fieldNames, pointerFieldNames, database.collectionPrefix, collection));
546+
});
551547
}
552548

553549
// Validates an object provided in REST format.

0 commit comments

Comments
 (0)