feat: Add support for MongoDB query comment (#8928)

This commit is contained in:
Oussama Meglali
2024-03-03 02:27:57 +01:00
committed by GitHub
parent afcafdba1e
commit 2170962a50
9 changed files with 173 additions and 12 deletions

View File

@@ -0,0 +1,99 @@
'use strict';
const Config = require('../lib/Config');
const TestUtils = require('../lib/TestUtils');
const { MongoClient } = require('mongodb');
const databaseURI = 'mongodb://localhost:27017/';
const request = require('../lib/request');
let config, client, database;
const masterKeyHeaders = {
'X-Parse-Application-Id': 'test',
'X-Parse-Rest-API-Key': 'rest',
'X-Parse-Master-Key': 'test',
'Content-Type': 'application/json',
};
const masterKeyOptions = {
headers: masterKeyHeaders,
json: true,
};
describe_only_db('mongo')('Parse.Query with comment testing', () => {
beforeEach(async () => {
config = Config.get('test');
client = await MongoClient.connect(databaseURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
database = client.db('parseServerMongoAdapterTestDatabase');
const level = 2;
const profiling = await database.command({ profile: level });
console.log(`profiling ${JSON.stringify(profiling)}`);
});
afterEach(async () => {
await client.close();
await TestUtils.destroyAllDataPermanently(false);
});
it('send comment with query through REST', async () => {
const comment = 'Hello Parse';
const object = new TestObject();
object.set('name', 'object');
await object.save();
const options = Object.assign({}, masterKeyOptions, {
url: Parse.serverURL + '/classes/TestObject',
qs: {
explain: true,
comment: comment,
},
});
await request(options);
const result = await database.collection('system.profile').findOne({}, { sort: { ts: -1 } });
expect(result.command.explain.comment).toBe(comment);
});
it('send comment with query', async () => {
const comment = 'Hello Parse';
const object = new TestObject();
object.set('name', 'object');
await object.save();
const collection = await config.database.adapter._adaptiveCollection('TestObject');
await collection._rawFind({ name: 'object' }, { comment: comment });
const result = await database.collection('system.profile').findOne({}, { sort: { ts: -1 } });
expect(result.command.comment).toBe(comment);
});
it('send a comment with a count query', async () => {
const comment = 'Hello Parse';
const object = new TestObject();
object.set('name', 'object');
await object.save();
const object2 = new TestObject();
object2.set('name', 'object');
await object2.save();
const collection = await config.database.adapter._adaptiveCollection('TestObject');
const countResult = await collection.count({ name: 'object' }, { comment: comment });
expect(countResult).toEqual(2);
const result = await database.collection('system.profile').findOne({}, { sort: { ts: -1 } });
expect(result.command.comment).toBe(comment);
});
it('attach a comment to an aggregation', async () => {
const comment = 'Hello Parse';
const object = new TestObject();
object.set('name', 'object');
await object.save();
const collection = await config.database.adapter._adaptiveCollection('TestObject');
await collection.aggregate([{ $group: { _id: '$name' } }], {
explain: true,
comment: comment,
});
const result = await database.collection('system.profile').findOne({}, { sort: { ts: -1 } });
expect(result.command.explain.comment).toBe(comment);
});
});

View File

@@ -15,7 +15,18 @@ export default class MongoCollection {
// idea. Or even if this behavior is a good idea. // idea. Or even if this behavior is a good idea.
find( find(
query, query,
{ skip, limit, sort, keys, maxTimeMS, readPreference, hint, caseInsensitive, explain } = {} {
skip,
limit,
sort,
keys,
maxTimeMS,
readPreference,
hint,
caseInsensitive,
explain,
comment,
} = {}
) { ) {
// Support for Full Text Search - $text // Support for Full Text Search - $text
if (keys && keys.$score) { if (keys && keys.$score) {
@@ -32,6 +43,7 @@ export default class MongoCollection {
hint, hint,
caseInsensitive, caseInsensitive,
explain, explain,
comment,
}).catch(error => { }).catch(error => {
// Check for "no geoindex" error // Check for "no geoindex" error
if (error.code != 17007 && !error.message.match(/unable to find index for .geoNear/)) { if (error.code != 17007 && !error.message.match(/unable to find index for .geoNear/)) {
@@ -60,6 +72,7 @@ export default class MongoCollection {
hint, hint,
caseInsensitive, caseInsensitive,
explain, explain,
comment,
}) })
) )
); );
@@ -75,7 +88,18 @@ export default class MongoCollection {
_rawFind( _rawFind(
query, query,
{ skip, limit, sort, keys, maxTimeMS, readPreference, hint, caseInsensitive, explain } = {} {
skip,
limit,
sort,
keys,
maxTimeMS,
readPreference,
hint,
caseInsensitive,
explain,
comment,
} = {}
) { ) {
let findOperation = this._mongoCollection.find(query, { let findOperation = this._mongoCollection.find(query, {
skip, skip,
@@ -83,6 +107,7 @@ export default class MongoCollection {
sort, sort,
readPreference, readPreference,
hint, hint,
comment,
}); });
if (keys) { if (keys) {
@@ -100,7 +125,7 @@ export default class MongoCollection {
return explain ? findOperation.explain(explain) : findOperation.toArray(); return explain ? findOperation.explain(explain) : findOperation.toArray();
} }
count(query, { skip, limit, sort, maxTimeMS, readPreference, hint } = {}) { count(query, { skip, limit, sort, maxTimeMS, readPreference, hint, comment } = {}) {
// If query is empty, then use estimatedDocumentCount instead. // If query is empty, then use estimatedDocumentCount instead.
// This is due to countDocuments performing a scan, // This is due to countDocuments performing a scan,
// which greatly increases execution time when being run on large collections. // which greatly increases execution time when being run on large collections.
@@ -118,6 +143,7 @@ export default class MongoCollection {
maxTimeMS, maxTimeMS,
readPreference, readPreference,
hint, hint,
comment,
}); });
return countOperation; return countOperation;
@@ -127,9 +153,9 @@ export default class MongoCollection {
return this._mongoCollection.distinct(field, query); return this._mongoCollection.distinct(field, query);
} }
aggregate(pipeline, { maxTimeMS, readPreference, hint, explain } = {}) { aggregate(pipeline, { maxTimeMS, readPreference, hint, explain, comment } = {}) {
return this._mongoCollection return this._mongoCollection
.aggregate(pipeline, { maxTimeMS, readPreference, hint, explain }) .aggregate(pipeline, { maxTimeMS, readPreference, hint, explain, comment })
.toArray(); .toArray();
} }

View File

@@ -603,7 +603,17 @@ export class MongoStorageAdapter implements StorageAdapter {
className: string, className: string,
schema: SchemaType, schema: SchemaType,
query: QueryType, query: QueryType,
{ skip, limit, sort, keys, readPreference, hint, caseInsensitive, explain }: QueryOptions {
skip,
limit,
sort,
keys,
readPreference,
hint,
caseInsensitive,
explain,
comment,
}: QueryOptions
): Promise<any> { ): Promise<any> {
validateExplainValue(explain); validateExplainValue(explain);
schema = convertParseSchemaToMongoSchema(schema); schema = convertParseSchemaToMongoSchema(schema);
@@ -646,6 +656,7 @@ export class MongoStorageAdapter implements StorageAdapter {
hint, hint,
caseInsensitive, caseInsensitive,
explain, explain,
comment,
}) })
) )
.then(objects => { .then(objects => {
@@ -735,7 +746,9 @@ export class MongoStorageAdapter implements StorageAdapter {
schema: SchemaType, schema: SchemaType,
query: QueryType, query: QueryType,
readPreference: ?string, readPreference: ?string,
hint: ?mixed _estimate: ?boolean,
hint: ?mixed,
comment: ?string
) { ) {
schema = convertParseSchemaToMongoSchema(schema); schema = convertParseSchemaToMongoSchema(schema);
readPreference = this._parseReadPreference(readPreference); readPreference = this._parseReadPreference(readPreference);
@@ -745,6 +758,7 @@ export class MongoStorageAdapter implements StorageAdapter {
maxTimeMS: this._maxTimeMS, maxTimeMS: this._maxTimeMS,
readPreference, readPreference,
hint, hint,
comment,
}) })
) )
.catch(err => this.handleError(err)); .catch(err => this.handleError(err));
@@ -777,7 +791,8 @@ export class MongoStorageAdapter implements StorageAdapter {
pipeline: any, pipeline: any,
readPreference: ?string, readPreference: ?string,
hint: ?mixed, hint: ?mixed,
explain?: boolean explain?: boolean,
comment: ?string
) { ) {
validateExplainValue(explain); validateExplainValue(explain);
let isPointerField = false; let isPointerField = false;
@@ -811,6 +826,7 @@ export class MongoStorageAdapter implements StorageAdapter {
maxTimeMS: this._maxTimeMS, maxTimeMS: this._maxTimeMS,
hint, hint,
explain, explain,
comment,
}) })
) )
.then(results => { .then(results => {

View File

@@ -19,6 +19,7 @@ export type QueryOptions = {
caseInsensitive?: boolean, caseInsensitive?: boolean,
action?: string, action?: string,
addsField?: boolean, addsField?: boolean,
comment?: string,
}; };
export type UpdateQueryOptions = { export type UpdateQueryOptions = {
@@ -97,7 +98,8 @@ export interface StorageAdapter {
query: QueryType, query: QueryType,
readPreference?: string, readPreference?: string,
estimate?: boolean, estimate?: boolean,
hint?: mixed hint?: mixed,
comment?: string
): Promise<number>; ): Promise<number>;
distinct( distinct(
className: string, className: string,
@@ -111,7 +113,8 @@ export interface StorageAdapter {
pipeline: any, pipeline: any,
readPreference: ?string, readPreference: ?string,
hint: ?mixed, hint: ?mixed,
explain?: boolean explain?: boolean,
comment?: string
): Promise<any>; ): Promise<any>;
performInitialization(options: ?any): Promise<void>; performInitialization(options: ?any): Promise<void>;
watch(callback: () => void): void; watch(callback: () => void): void;

View File

@@ -1188,6 +1188,7 @@ class DatabaseController {
hint, hint,
caseInsensitive = false, caseInsensitive = false,
explain, explain,
comment,
}: any = {}, }: any = {},
auth: any = {}, auth: any = {},
validSchemaController: SchemaController.SchemaController validSchemaController: SchemaController.SchemaController
@@ -1237,6 +1238,7 @@ class DatabaseController {
hint, hint,
caseInsensitive: this.options.enableCollationCaseComparison ? false : caseInsensitive, caseInsensitive: this.options.enableCollationCaseComparison ? false : caseInsensitive,
explain, explain,
comment,
}; };
Object.keys(sort).forEach(fieldName => { Object.keys(sort).forEach(fieldName => {
if (fieldName.match(/^authData\.([a-zA-Z0-9_]+)\.id$/)) { if (fieldName.match(/^authData\.([a-zA-Z0-9_]+)\.id$/)) {
@@ -1306,7 +1308,8 @@ class DatabaseController {
query, query,
readPreference, readPreference,
undefined, undefined,
hint hint,
comment
); );
} }
} else if (distinct) { } else if (distinct) {
@@ -1325,7 +1328,8 @@ class DatabaseController {
pipeline, pipeline,
readPreference, readPreference,
hint, hint,
explain explain,
comment
); );
} }
} else if (explain) { } else if (explain) {

View File

@@ -212,6 +212,7 @@ function _UnsafeRestQuery(
case 'skip': case 'skip':
case 'limit': case 'limit':
case 'readPreference': case 'readPreference':
case 'comment':
this.findOptions[option] = restOptions[option]; this.findOptions[option] = restOptions[option];
break; break;
case 'order': case 'order':

View File

@@ -19,6 +19,10 @@ export class AggregateRouter extends ClassesRouter {
options.explain = body.explain; options.explain = body.explain;
delete body.explain; delete body.explain;
} }
if (body.comment) {
options.comment = body.comment;
delete body.comment;
}
if (body.readPreference) { if (body.readPreference) {
options.readPreference = body.readPreference; options.readPreference = body.readPreference;
delete body.readPreference; delete body.readPreference;

View File

@@ -166,6 +166,7 @@ export class ClassesRouter extends PromiseRouter {
'subqueryReadPreference', 'subqueryReadPreference',
'hint', 'hint',
'explain', 'explain',
'comment',
]; ];
for (const key of Object.keys(body)) { for (const key of Object.keys(body)) {
@@ -215,6 +216,9 @@ export class ClassesRouter extends PromiseRouter {
if (body.explain) { if (body.explain) {
options.explain = body.explain; options.explain = body.explain;
} }
if (body.comment && typeof body.comment === 'string') {
options.comment = body.comment;
}
return options; return options;
} }

View File

@@ -576,6 +576,10 @@ export function maybeRunQueryTrigger(
restOptions = restOptions || {}; restOptions = restOptions || {};
restOptions.hint = jsonQuery.hint; restOptions.hint = jsonQuery.hint;
} }
if (jsonQuery.comment) {
restOptions = restOptions || {};
restOptions.comment = jsonQuery.comment;
}
if (requestObject.readPreference) { if (requestObject.readPreference) {
restOptions = restOptions || {}; restOptions = restOptions || {};
restOptions.readPreference = requestObject.readPreference; restOptions.readPreference = requestObject.readPreference;