generated from oracle/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
OracleStorageAdapter.js
1303 lines (1199 loc) · 44.5 KB
/
OracleStorageAdapter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023, Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import OracleSchemaCollection from './OracleSchemaCollection';
import OracleCollection from './OracleCollection';
import { StorageAdapter } from '../StorageAdapter';
import type { SchemaType, StorageClass, QueryType, QueryOptions } from '../StorageAdapter';
// @flow-disable-next
import Parse from 'parse/node';
// @flow-disable-next
import _ from 'lodash';
import logger from '../../../logger.js';
import {
transformKey,
transformWhere,
transformUpdate,
parseObjectToOracleObjectForCreate,
oracleObjectToParseObject,
transformPointerString,
} from './OracleTransform';
import { Pool } from 'oracledb';
const oracledb = require('oracledb');
const OracleSchemaCollectionName = '_SCHEMA';
const storageAdapterAllCollections = oracleAdapter => {
const collections = oracleAdapter.listAllCollections(oracleAdapter._collectionPrefix);
logger.verbose('collections is ' + JSON.stringify(collections));
return collections;
};
//CDB
//to preserve the original query to hack for $containedBy
var queryBackup = '';
//CDB-END
var initialized = false;
var createConnPool = true;
var schemaCollection = null;
const convertParseSchemaToOracleSchema = ({ ...schema }) => {
delete schema.fields._rperm;
delete schema.fields._wperm;
if (schema.className === '_User') {
// Legacy mongo adapter knows about the difference between password and _hashed_password.
// Future database adapters will only know about _hashed_password.
// Note: Parse Server will bring back password with injectDefaultSchema, so we don't need
// to add _hashed_password back ever.
delete schema.fields._hashed_password;
}
return schema;
};
// Returns { code, error } if invalid, or { result }, an object
// suitable for inserting into _SCHEMA collection, otherwise.
const oracleSchemaFromFieldsAndClassNameAndCLP = (
fields,
className,
classLevelPermissions,
indexes
) => {
const oracleObject = {
_id: className,
// TODO: I'm not sure we need objectId
objectId: 'string',
updatedAt: 'string',
createdAt: 'string',
_metadata: undefined,
};
for (const fieldName in fields) {
const { type, targetClass, ...fieldOptions } = fields[fieldName];
oracleObject[fieldName] = OracleSchemaCollection.parseFieldTypeToOracleFieldType({
type,
targetClass,
});
if (fieldOptions && Object.keys(fieldOptions).length > 0) {
oracleObject._metadata = oracleObject._metadata || {};
oracleObject._metadata.fields_options = oracleObject._metadata.fields_options || {};
oracleObject._metadata.fields_options[fieldName] = fieldOptions;
}
}
if (typeof classLevelPermissions !== 'undefined') {
oracleObject._metadata = oracleObject._metadata || {};
if (!classLevelPermissions) {
delete oracleObject._metadata.class_permissions;
} else {
oracleObject._metadata.class_permissions = classLevelPermissions;
}
}
if (indexes && typeof indexes === 'object' && Object.keys(indexes).length > 0) {
oracleObject._metadata = oracleObject._metadata || {};
oracleObject._metadata.indexes = indexes;
}
if (!oracleObject._metadata) {
// cleanup the unused _metadata
delete oracleObject._metadata;
}
return oracleObject;
};
function validateExplainValue(explain) {
if (explain) {
// The list of allowed explain values is from node-mongodb-native/lib/explain.js
const explainAllowedValues = [
'queryPlanner',
'queryPlannerExtended',
'executionStats',
'allPlansExecution',
false,
true,
];
if (!explainAllowedValues.includes(explain)) {
throw new Parse.Error(Parse.Error.INVALID_QUERY, 'Invalid value for explain');
}
}
}
export class OracleStorageAdapter implements StorageAdapter {
// private
_onchange: any;
_collectionPrefix: string;
_connectionPool: Pool;
_collections: Map<String, OracleCollection>;
constructor(options: any) {
logger.verbose(
'OracleStorageAdapter constructor, uri = ' +
options.databaseURI +
' collectionPrefix = ' +
options.collectionPrefix
);
this._uri = options.databaseURI;
this._collectionPrefix = options.collectionPrefix;
this._connectionPool = null;
this._collections = new Map();
}
_schemaCollection(): Promise<OracleSchemaCollection> {
try {
const collection = this._adaptiveCollection(OracleSchemaCollectionName);
if (schemaCollection === null) {
if (!this._stream && this.enableSchemaHooks) {
// TODO make sure these are all defined
this._stream = collection._orcaleCollection.watch();
this._stream.on('change', () => this._onchange());
}
schemaCollection = new OracleSchemaCollection(collection);
}
return schemaCollection;
} catch (error) {
this.handleError(error);
}
}
listAllCollections(prefix) {
const result = new Array();
this._collections.forEach(function (value, key) {
if (key.includes(prefix)) {
const array = key.split(prefix);
if (array.length == 2) {
result.push(array[1]);
} else {
result.push(array[0]);
}
}
});
return result;
}
async _truncate(collectionName) {
logger.verbose('Storage Adapter _truncate for ' + collectionName);
try {
const collection = this._adaptiveCollection(collectionName);
const result = await collection.truncate();
logger.verbose(
'Storage Adapter _truncate for collection ' +
collectionName +
' returns ' +
JSON.stringify(result)
);
return result;
} catch (error) {
logger.error(
'Storage Adapter _truncate Error for collection' + collectionName + ' ERROR = ' + error
);
this.handleError(error);
}
}
async _drop(collectionName) {
logger.verbose('StorageAdapter _drop ' + collectionName);
try {
const collection = this._adaptiveCollection(collectionName);
const result = await collection.drop();
if (result) {
// Remove Collection
logger.verbose('Dropping ' + this._collectionPrefix + collection + ' from collectionMap');
this._collections.delete(this._collectionPrefix + collectionName);
if (collectionName.includes(OracleSchemaCollectionName)) {
schemaCollection = null;
}
}
logger.verbose('StorageAdapter _drop returns ' + result);
return result;
} catch (error) {
logger.error('Storage Adapter _drop Error for ' + collectionName);
this.handleError(error);
}
}
_adaptiveCollection(name: string): OracleCollection {
let realName;
if (name.includes(this._collectionPrefix)) {
realName = name;
} else {
realName = this._collectionPrefix + name;
}
// first check if we already have this collection, and if so, just return it
// this will reuse the same collection and its embedded connection, so we don't
// create a connection starvation scenario
if (this._collections.get(realName)) {
logger.verbose('Adaptive Collection returning Existing collection ' + realName);
return this._collections.get(realName);
}
const collection = new OracleCollection(this, realName);
this._collections.set(realName, collection);
logger.verbose('Adaptive Collection returning Created collection ' + realName);
return collection;
}
async initialize() {
if (initialized === false) {
const wallet_location = process.env.ORACLE_WALLET_LOCATION;
const client_location = process.env.ORACLE_CLIENT_LOCATION;
if (typeof client_location === 'undefined') {
throw 'Required Environment Variable, ORACLE_CLIENT_LOCATION, is not defined';
}
logger.verbose('wallet location = ' + process.env.ORACLE_WALLET_LOCATION);
logger.verbose('oracle client = ' + process.env.ORACLE_CLIENT_LOCATION);
try {
if (typeof wallet_location === 'undefined') {
logger.info(
'No Wallet location specified. Intializing Oracle Client to access Local Database Docker Image'
);
oracledb.initOracleClient({
libDir: client_location,
});
} else {
logger.info(
'Wallet location specified. Intializing Oracle Client to access Cloud Database Instance'
);
oracledb.initOracleClient({
libDir: client_location,
configDir: wallet_location,
});
}
} catch (error) {
if (error.message.includes('NJS-077')) {
// already initialized - so ignore the error
logger.verbose('oracledb already initialized');
} else {
logger.error('Error Initalizing Oracle Client: ' + error);
// if we get here, probably should exit the whole server process
process.exit(1);
}
}
initialized = true;
}
}
async connect() {
if (this.connectionPromise) {
logger.verbose('reusing connection pool ' + JSON.stringify(this._connectionPool));
logger.verbose(' statistics: ' + JSON.stringify(this._connectionPool.getStatistics()));
return this._connectionPool;
}
this.initialize();
var re = new RegExp('oracledb://[a-zA-Z0-9_]*:[^@:]*@[a-zA-Z0-9_.:/]*$');
if (!re.test(this._uri)) {
throw 'Incorrect Connection String Format. Format is oracledb://user:password@tnsname';
}
const user = this.getUserFromUri(this._uri);
const pw = this.getPasswordFromUri(this._uri);
const tnsname = this.getTnsNameFromUri(this._uri);
logger.info('creating a connection pool');
try {
if (createConnPool) {
createConnPool = false;
this.connectionPromise = await oracledb.createPool({
poolAlias: 'parse',
user: user,
password: pw,
connectString: tnsname,
poolIncrement: 5,
poolMax: 100,
poolMin: 3,
poolTimeout: 10,
// Use default of 60000 ms
// queueTimeout: 10,
enableStatistics: true,
});
logger.info('connection pool successfully created');
this._connectionPool = oracledb.getPool('parse');
return Promise.resolve(this._connectionPool);
} else {
logger.verbose('Returning connection promise while connecting');
return this.connectionPromise;
}
} catch (error) {
logger.error('Error Creating Connection Pool: ', error);
throw error;
}
}
getUserFromUri(uri) {
const myArray = uri.split('//');
const myArray2 = myArray[1].split(':');
return myArray2[0];
}
getPasswordFromUri(uri) {
const myArray = uri.split(':');
const myArray2 = myArray[2].split('@');
return myArray2[0];
}
getTnsNameFromUri(uri) {
const myArray = uri.split('@');
return myArray[1];
}
handleError<T>(error: ?(Error | Parse.Error)): Promise<T> {
if (error && error.code === 13) {
// Unauthorized error
delete this.client;
delete this.database;
delete this.connectionPromise;
logger.error('Received unauthorized error', { error: error });
}
if (typeof error === 'object' && error.code !== 101 && error.code != 137) {
console.log(JSON.stringify(error));
if (error.errorNum === 0) {
console.trace();
}
}
// What to throw? Maybe need to map ORA msgs to Parse msgs
// throw error.message;
throw error;
}
classExists(className: string): Promise<boolean> {
return new Promise(resolve => {
logger.verbose('classExists name = ' + className);
const collections = storageAdapterAllCollections(this);
resolve(collections.includes(className));
});
}
async setClassLevelPermissions(className, CLPs) {
try {
logger.verbose('StorageAdapter setClassLevelPermissions for ' + className);
logger.verbose('setClassLevelPermissions permissions = ' + JSON.stringify(CLPs));
const newCLPS = '{"_metadata": {"class_permissions":' + JSON.stringify(CLPs) + '}}';
const newCLPSObj = JSON.parse(newCLPS);
const result = await this._schemaCollection().updateSchema(className, newCLPSObj);
logger.verbose('StorageAdapter setClassLevelPermissions returns ' + result);
return result;
} catch (error) {
logger.error('StorageAdapter setClassLevelPermissions Error for ' + className);
this.handleError(error);
}
}
async createClass(className: string, schema: SchemaType): Promise<void> {
try {
logger.verbose('StorageAdapter createClass for ' + className);
schema = convertParseSchemaToOracleSchema(schema);
const oracleObject = oracleSchemaFromFieldsAndClassNameAndCLP(
schema.fields,
className,
schema.classLevelPermissions,
schema.indexes
);
oracleObject._id = className;
const result = await this._schemaCollection().insertSchema(oracleObject);
logger.verbose('StorageAdapter createClass insertSchema result = ' + result);
if (typeof schema.indexes !== 'undefined' && Object.keys(schema.indexes).length > 0) {
if (Array.isArray(schema.indexes)) {
await this.createIndexes(className, schema.indexes);
} else {
const indexes = new Array(schema.indexes);
await this.createIndexes(className, indexes);
}
}
return result;
} catch (error) {
logger.error('StorageAdapter createClass Error for ' + className);
this.handleError(error);
}
}
async addFieldIfNotExists(className: string, fieldName: string, type: any): Promise<void> {
try {
logger.verbose('StorageAdapter addFieldIfNotExists for ' + className);
const result = await this._schemaCollection().addFieldIfNotExists(className, fieldName, type);
logger.verbose('StorageAdapter addFieldIfNotExists returns ' + result);
await this.createIndexesIfNeeded(className, fieldName, type);
return result;
} catch (error) {
logger.error('StorageAdapter addFieldIfNotExists Error for ' + className);
this.handleError(error);
}
}
async updateFieldOptions(className: string, fieldName: string, type: any): Promise<void> {
const schemaCollection = this._schemaCollection();
await schemaCollection.updateFieldOptions(className, fieldName, type);
}
async deleteClass(className: string): Promise<void> {
try {
logger.verbose('StorageAdapter deleteClass for ' + className);
const result1 = await this._drop(className);
logger.verbose('StorageAdapter deleteClass drop returns ' + result1);
const result = await this._schemaCollection().findAndDeleteSchema(className);
logger.verbose('StorageAdapter deleteClass deleteSchema returns ' + result);
return result;
} catch (error) {
logger.error('StorageAdapter deleteClass Error for ' + className);
this.handleError(error);
}
}
async deleteAllClasses(fast: boolean) {
// let result;
logger.verbose('entering deleteAllClasses fast = ' + fast);
const collections = storageAdapterAllCollections(this);
return Promise.all(
collections.map(collection => (fast ? this._truncate(collection) : this._drop(collection)))
);
}
async deleteFields(
className: string,
schema: SchemaType,
fieldNames: Array<string>
): Promise<void> {
logger.verbose('StorageAdapter deleteFields for className: ' + className);
logger.verbose('StorageAdapter deleteFields for schema: ' + schema);
logger.verbose('StorageAdapter deleteFields oracleFormatNames = ' + fieldNames);
try {
const collection = this._adaptiveCollection(className);
const result = await collection.deleteFields(fieldNames);
const result1 = await this._schemaCollection().deleteSchemaFields(className, fieldNames);
logger.verbose('StorageAdapter deleteFields collection result = ' + result);
logger.verbose('StorageAdapter deleteFields schemacollection result = ' + result1);
} catch (error) {
logger.error('StorageAdapter deleteFields Error for ' + className);
this.handleError(error);
}
}
async getAllClasses(): Promise<StorageClass[]> {
try {
const schemaCollection = this._schemaCollection();
const result = await schemaCollection._fetchAllSchemasFrom_SCHEMA();
logger.verbose('StorageAdapter getAllClasses returns ' + result);
return result;
} catch (error) {
logger.error('StorageAdapter getAllClasses Error');
this.handleError(error);
}
}
// getClass(className: string): Promise<StorageClass>;
// TODO: As yet not particularly well specified. Creates an object. Maybe shouldn't even need the schema,
// and should infer from the type. Or maybe does need the schema for validations. Or maybe needs
// the schema only for the legacy mongo format. We'll figure that out later.
async createObject(
className: string,
schema: SchemaType,
object: any,
transactionalSession: ?any
) {
logger.verbose('StorageAdapter createObject for className: ' + className);
try {
schema = convertParseSchemaToOracleSchema(schema);
const oracleObject = parseObjectToOracleObjectForCreate(className, object, schema);
const collection = this._adaptiveCollection(className);
const result = await collection.insertOne(oracleObject, transactionalSession);
logger.verbose('StorageAdapter createObject insertOne returns: ' + result);
return { ops: [oracleObject] };
} catch (error) {
// "ORA-00001: unique constraint (ADMIN.index_name) violated"
if (error.errorNum === 1) {
// Duplicate value
const err = new Parse.Error(
Parse.Error.DUPLICATE_VALUE,
'A duplicate value for a field with unique values was provided'
);
err.underlyingError = error;
if (error.message) {
const matches = error.message.match(/index:[\sa-zA-Z0-9_\-\.]+\$?([a-zA-Z_-]+)_1/);
if (matches && Array.isArray(matches)) {
err.userInfo = { duplicated_field: matches[1] };
}
}
this.handleError(err);
}
this.handleError(error);
}
}
async findOneAndUpdate(className, schema, query, update, transactionalSession) {
try {
logger.verbose('StorageAdapter findOneAndUpdate for ' + className);
let oraWhere = transformWhere(className, query, schema);
const oraUpdate = transformUpdate(className, update, schema);
// Check if this query needs Oracle Storage Adapter _wperm syntax
oraWhere = this.checkUserQuery(oraWhere);
const collection = this._adaptiveCollection(className);
const result = await collection.findOneAndUpdate(oraWhere, oraUpdate, transactionalSession);
logger.verbose('StorageAdapter findOneAndUpdate returns ' + JSON.stringify(result));
return result;
} catch (error) {
logger.error('StorageAdapter indOneAndUpdate Error for ' + className);
this.handleError(error);
}
}
/*
Parse has ACL formats that are part of a query which causes an error which was fixed in
https://bug.oraclecorp.com/pls/bug/webbug_print.show?c_rptno=34596223
Basically, Oracle cannot handle a null as part of an in operator clause
{_id: "TV5CazXRtP",_wperm: {$in: [null,"*","tE8wEhXmJg","role:Admins",],},}
This needs to be modified to
{_id: "tE8wEhXmJg",$or : [{_wperm: {"$in": [ "*", "tE8wEhXmJg" ]}}, {_wperm : null}]}
to work with Oracle SODA
Waiting on maintenance update to pick up the fix.
In the meantime, checkUserQuery will fix up the query
More here
https://orahub.oci.oraclecorp.com/ora-microservices-dev/mbaas-parse-server/-/wikis/Error:-ORA-40596:-error-occurred-in-JSON-processing-jznEngValCmpWithTypCnv:invTyp
*/
checkUserQuery(query) {
logger.verbose('in StorageAdapter checkUserQuery');
logger.verbose('Input query = ' + JSON.stringify(query));
const newObj = new Object();
const queryObj = JSON.parse(JSON.stringify(query));
let checkNull = false;
for (const x in queryObj) {
if (x === '_wperm' && typeof queryObj[x] === 'object') {
const myArray = [];
const json = JSON.parse(JSON.stringify(queryObj[x]));
for (const y in json) {
if (y === '$in') {
if (json[y].length >= 2) {
for (let i = 0; i < json[y].length; i++) {
if (json[y][i] === null) {
checkNull = true;
} else {
myArray.push(json[y][i]);
}
}
}
}
if (json[y].length !== myArray.length) {
let temp;
if (checkNull) {
// Case where no Perms exists on the document
temp = `[{"_wperm":{"$in":${JSON.stringify(
myArray
)}}},{"_wperm":null},{"_wperm":{"$exists":false}}]`;
} else {
temp = `[{"_wperm":{"$in":${JSON.stringify(myArray)}}},{"_wperm":null}]`;
}
delete queryObj['_wperm'];
newObj['$or'] = JSON.parse(temp);
} else {
newObj[x] = queryObj[x];
}
}
} else {
newObj[x] = queryObj[x];
}
if (x === '_rperm' && typeof queryObj[x] === 'object') {
const myArray = [];
const json = JSON.parse(JSON.stringify(queryObj[x]));
for (const y in json) {
if (y === '$in') {
if (json[y].length >= 2) {
for (let i = 0; i < json[y].length; i++) {
if (json[y][i] === null) {
checkNull = true;
} else {
myArray.push(json[y][i]);
}
}
}
}
if (json[y].length !== myArray.length) {
let rpermOr;
delete newObj['_rperm'];
if (checkNull) {
// Case where no Perms exists on the document
rpermOr = `[{"_rperm":{"$in":${JSON.stringify(
myArray
)}}},{"_rperm":null},{"_rperm":{"$exists":false}}]`;
} else {
rpermOr = `[{"_rperm":{"$in":${JSON.stringify(myArray)}}},{"_rperm":null}]`;
}
if (Object.prototype.hasOwnProperty.call(newObj, '$or')) {
// $and the existing $or with the _rperm $or
const originalOr = JSON.stringify(newObj['$or']);
const andString = `[{"$or":${originalOr}},{"$or":${rpermOr}}]`;
// TODO: replacing the $and without checking if it existed
// look at lodash to merge
newObj['$and'] = JSON.parse(andString);
delete newObj['$or'];
} else {
newObj['$or'] = JSON.parse(rpermOr);
}
} else {
newObj[x] = queryObj[x];
}
}
} else {
newObj[x] = queryObj[x];
}
}
logger.verbose('Return query = ' + JSON.stringify(newObj));
return newObj;
}
async upsertOneObject(className, schema, query, update, transactionalSession) {
try {
logger.verbose('StorageAdapter upsertOneObject for Collection ' + className);
schema = convertParseSchemaToOracleSchema(schema);
const oraWhere = transformWhere(className, query, schema);
const oraUpdate = transformUpdate(className, update, schema);
const collection = this._adaptiveCollection(className);
const result = await collection.upsertOne(oraWhere, oraUpdate, transactionalSession);
logger.verbose('StorageAdapter upsertOneObject returns ' + result);
return result;
} catch (error) {
logger.error('StorageAdapter upsertOneObject Error for ' + className);
this.handleError(error);
}
}
async deleteObjectsByQuery(className, schema, query, transactionalSession) {
try {
logger.verbose('StorageAdapter deleteObjectsByQuery for ' + className);
schema = convertParseSchemaToOracleSchema(schema);
let oraWhere = transformWhere(className, query, schema);
// Check if query needs Oracle Storage Adapter _wperm syntax
oraWhere = this.checkUserQuery(oraWhere);
const collection = this._adaptiveCollection(className);
const result = await collection.deleteObjectsByQuery(oraWhere, transactionalSession);
logger.verbose('StorageAdapter deleteObjectsByQuery returns ' + result);
return result;
} catch (error) {
logger.error('StorageAdapter deleteObjectsByQuery Error for ' + className);
this.handleError(error);
}
}
// Executes a find. Accepts: className, query in Parse format, and { skip, limit, sort }.
find(
className: string,
schema: SchemaType,
query: QueryType,
{ skip, limit, sort, keys, readPreference, hint, caseInsensitive, explain }: QueryOptions
): Promise<any> {
// try {
logger.verbose('StorageAdapter find for ' + className);
validateExplainValue(explain);
schema = convertParseSchemaToOracleSchema(schema);
logger.verbose('query = ' + JSON.stringify(query));
// start hack
// this is a temporary hack while i work on the _rperm stuff
// remove that from the query if present
//CDB
//to preserve the original query to hack for $containedBy
queryBackup = query;
//CDB-END
// end hack
let oracleWhere = transformWhere(className, query, schema);
// Check if this query needs Oracle Storage Adapter _wperm syntax
oracleWhere = this.checkUserQuery(oracleWhere);
logger.verbose('oracleWhere = ' + JSON.stringify(oracleWhere));
// fix 15-11
const oracleSort = _.mapKeys(sort, (value, fieldName) =>
transformKey(className, fieldName, schema)
);
const sortTypes = new Object();
for (const s in sort) {
let schemaFieldName;
let sortType = 'string';
if (s.split('.').length > 1) {
schemaFieldName = s.split('.')[0];
} else {
schemaFieldName = s;
}
const schemaTypeEntry = schema.fields[schemaFieldName];
const schemaType = schemaTypeEntry[Object.keys(schemaTypeEntry)[0]];
if (schemaType === 'Number') {
sortType = 'number';
}
sortTypes[s] = sortType;
}
logger.verbose('Make linter happy by using keys = ' + keys);
const oracleKeys = keys;
logger.verbose('oracleKeys = ' + JSON.stringify(oracleKeys));
logger.verbose('make linter ignore ' + readPreference);
const collection = this._adaptiveCollection(className);
return collection
.find(oracleWhere, {
skip,
limit,
sort: oracleSort,
keys: oracleKeys,
maxTimeMS: this._maxTimeMS,
readPreference: null,
hint,
caseInsensitive,
explain,
sortTypes,
})
.then(objects => {
logger.verbose('after the find, objects = ' + JSON.stringify(objects));
logger.verbose('about to map oracleObjectToParseObject');
let result = objects.map(object => oracleObjectToParseObject(className, object, schema));
logger.verbose('result = ' + JSON.stringify(result));
//CDB
//$containedBy issue: remove extra documents from the collection with Diff between two Sets
if (JSON.stringify(queryBackup).indexOf('$containedBy') > -1) {
for (var prop in queryBackup) {
if (!(/*typeof*/ (queryBackup[prop].$containedBy === undefined))) {
//let arr = queryBackup[prop].$containedBy;
//11-11fix for 'containedBy number array'
var filteredResult = result.filter(function (myObject) {
const diff = myObject[prop].filter(
x => !queryBackup[prop].$containedBy.includes(x)
);
return diff.length == 0;
});
result = filteredResult;
/*
for (const r in result) {
const myObject = result[r];
const diff = myObject[prop].filter(x => !queryBackup[prop].$containedBy.includes(x));
if (diff.length > 0) {
//remove document
result.splice(r, 1);
}
}
*/
//END11-11 fix
}
}
}
//CDB-END
//CDB
//Delete all fields not in oracleKeys
if (!(typeof oracleKeys === 'undefined')) {
for (const r in result) {
logger.verbose('oracleKeys to mantain = ' + JSON.stringify(oracleKeys));
//to be cleaned
const myObject = result[r];
var oracleKeysSet = new Set(oracleKeys);
oracleKeysSet.add('createdAt');
oracleKeysSet.add('updatedAt');
oracleKeysSet.add('objectId');
var keysResult = new Set(Object.keys(myObject));
logger.verbose('keys remained = ' + JSON.stringify(keysResult));
const diff = new Set([...keysResult].filter(element => !oracleKeysSet.has(element)));
logger.verbose('keys toDel = ' + JSON.stringify(diff));
for (var iter = diff.values(), toDel = null; (toDel = iter.next().value);) {
// Do NOT remove _rperm and _wperm. DatabaseController uses them to value ParseObject.ACL
if (!(toDel === '_rperm' || toDel === '_wperm')) {
delete myObject[toDel];
}
}
logger.verbose('properties remained = ' + JSON.stringify(myObject));
}
}
//CDB-END
logger.verbose('StorageAdapter find returns ' + result);
return result;
})
.catch(err => this.handleError(err));
}
async setIndexesFromOracle(className: string) {
try {
logger.verbose('StorageAdapter setIndexesFromOracle for ' + className);
const indexes = await this.getIndexes(className);
const result = await this._schemaCollection().updateSchema(className, {
_metadata: { indexes: indexes },
});
logger.verbose('StorageAdapter setIndexesFromOracle returns ' + result);
return result;
} catch (error) {
logger.error('StorageAdapter setIndexesFromOracle throws for className ' + className);
this.handleError(error);
}
}
createTextIndexesIfNeeded(className: string, query: QueryType, schema: any): Promise<void> {
logger.verbose('entered createTextIndexesIfNeeded query = ' + JSON.stringify(query));
for (const fieldName in query) {
logger.verbose('processing field ' + fieldName);
if (!query[fieldName] || !query[fieldName].$text) {
continue;
}
const existingIndexes = schema.indexes;
logger.verbose('existingIndexes = ' + existingIndexes);
for (const key in existingIndexes) {
const index = existingIndexes[key];
if (Object.prototype.hasOwnProperty.call(index, fieldName)) {
return Promise.resolve();
}
}
const indexName = `${fieldName}_text`;
const textIndex = {
[indexName]: { [fieldName]: 'text' },
};
return this.setIndexesWithSchemaFormat(
className,
textIndex,
existingIndexes,
schema.fields
).catch(error => {
logger.error('got error ' + JSON.stringify(error));
if (error.code === 85) {
// Index exist with different options
return this.setIndexesFromOracle(className);
}
throw error;
});
}
return Promise.resolve();
}
/*
TODO:
Are multiple indexes processed? I think not because of
const fieldName = Object.keys(indexCreationRequest)[0];
Also, can the code creating the indexspec in
ensureIndex and ensureUniqueness
be combined into 1 method
https://orahub.oci.oraclecorp.com/ora-microservices-dev/mbaas-parse-server/-/issues/35
*/
async ensureIndex(
className: string,
schema: SchemaType,
fieldNames: string[],
indexName: ?string,
caseInsensitive: boolean = false,
options?: Object = {}
): Promise<any> {
try {
logger.verbose('StorageAdapter ensureIndex for ' + className);
schema = convertParseSchemaToOracleSchema(schema);
const indexCreationRequest = {};
const oracleFieldNames = fieldNames.map(fieldName =>
transformKey(className, fieldName, schema)
);
oracleFieldNames.forEach(fieldName => {
indexCreationRequest[fieldName] = options.indexType !== undefined ? options.indexType : 1;
});
logger.verbose(
'use these to make linter happy ' +
JSON.stringify(indexName) +
' ' +
JSON.stringify(caseInsensitive)
);
const fieldName = Object.keys(indexCreationRequest)[0];
const indexRequest = {
name: fieldName,
fields: [
{
path: fieldName,
},
],
unique: true,
};
const collection = this._adaptiveCollection(className);
const result = await collection._createIndex(indexRequest);
logger.verbose('StorageAdapter ensureIndex returns ' + result);
return result;
} catch (error) {
logger.error('StorageAdapter ensureIndex throws for className ' + className);
this.handleError(error);
}
}
// Create a unique index. Unique indexes on nullable fields are not allowed. Since we don't
// currently know which fields are nullable and which aren't, we ignore that criteria.
// As such, we shouldn't expose this function to users of parse until we have an out-of-band
// Way of determining if a field is nullable. Undefined doesn't count against uniqueness,
// which is why we use sparse indexes.
async ensureUniqueness(className: string, schema: SchemaType, fieldNames: string[]) {
try {
logger.verbose('StorageAdapter ensureUniqueness for ' + className);
schema = convertParseSchemaToOracleSchema(schema);
const indexCreationRequest = {};
const oracleFieldNames = fieldNames.map(fieldName =>
transformKey(className, fieldName, schema)
);
oracleFieldNames.forEach(fieldName => {
indexCreationRequest[fieldName] = 1;
});
const fieldName = Object.keys(indexCreationRequest)[0];
const indexRequest = {
name: fieldName,
fields: [
{
path: fieldName,
},
],
unique: true,
};
const collection = this._adaptiveCollection(className);
const result = await collection._ensureSparseUniqueIndexInBackground(indexRequest);
logger.verbose('StorageAdapter ensureUniqueness returns ' + result);
return result;
} catch (error) {
logger.error('StorageAdapter ensureUniqueness throws for className ' + className);
this.handleError(error);
}
}
async count(className, schema, query, readPreference, hint) {
const skip = 0;
const limit = 0;
const sort = {};
let keys;
const caseInsensitive = false;
const explain = false;
// See line 1183 in DatabaseController, it passes null in query
if (query === null) {
query = {};
}
return this.find(className, schema, query, {
skip,
limit,
sort,
keys,
readPreference,
hint,
caseInsensitive,
explain,
})
.then(collection => {
return collection.length;