generated from oracle/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
OracleCollection.js
1402 lines (1302 loc) · 46 KB
/
OracleCollection.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 Parse from 'parse/node';
import logger from '../../../logger.js';
import _ from 'lodash';
import OracleStorageAdapter from './OracleStorageAdapter';
const oracledb = require('oracledb');
oracledb.autoCommit = true;
const Collection = oracledb.SodaCollection;
const SodaDB = oracledb.SodaDB;
const DB_VERSION = process.env.ORACLEDB_VERSION;
const ddlTimeOut = `
BEGIN
EXECUTE IMMEDIATE ('
alter session set ddl_lock_timeout=1000
');
END;`;
export default class OracleCollection {
_oracleSodaDB: SodaDB;
_oracleCollection: Collection;
_oracleStorageAdapter: OracleStorageAdapter;
_name: string;
indexes = new Array();
idIndexCreating = false;
jsonSQLtype = 'JSON'; //DBVersion 23c default
constructor(oracleStorageAdapter: OracleStorageAdapter, collectionName: String) {
this._oracleStorageAdapter = oracleStorageAdapter;
this._name = collectionName;
this._oracleCollection = undefined;
logger.verbose('Oracle Database Version = ' + DB_VERSION);
// To support backwards compatibility with instant clients
if (typeof DB_VERSION !== 'undefined' && DB_VERSION !== '23') {
this.jsonSQLtype = 'BLOB';
}
}
async getCollectionConnection() {
const mymetadata = {
keyColumn: { name: 'ID', assignmentMethod: 'UUID' },
contentColumn: { name: 'JSON_DOCUMENT', sqlType: this.jsonSQLtype },
versionColumn: { name: 'VERSION', method: 'UUID' },
lastModifiedColumn: { name: 'LAST_MODIFIED' },
creationTimeColumn: { name: 'CREATED_ON' },
};
logger.verbose('getCollectionConnection about to connect for collection ' + this._name);
let localConn;
this._oracleCollection = await this._oracleStorageAdapter
.connect()
.then(p => {
logger.verbose('getCollectionConnection about to get connection from pool ');
logger.verbose(' statistics: ' + JSON.stringify(p.getStatistics()));
return p.getConnection();
})
.then(conn => {
logger.verbose('getCollectionConnection about to get SodaDB');
localConn = conn;
return conn.getSodaDatabase();
})
.then(sodadb => {
logger.verbose('getCollectionConnection open collection for ' + this._name);
this._oracleSodaDB = sodadb;
return sodadb.openCollection(this._name);
})
.then(async coll => {
if (!coll) {
logger.verbose('getCollectionConnection create NEW collection for ' + this._name);
const newCollection = await this._oracleSodaDB.createCollection(this._name, {
metaData: mymetadata,
});
/*
Create index on _id for every new collection
This imitates Mongo behavior which happens automatically
Index names MUST be unique in a schema, append table name
cannot have two indexes with the same name in a single schema.
*/
if (!this.idIndexCreating) {
this.idIndexCreating = true;
const indexName = 'ididx' + this._name;
const indexSpec = { name: indexName, unique: true, fields: [{ path: '_id' }] };
await newCollection.createIndex(indexSpec);
logger.verbose(
'getCollectionConnection successfully create _id index for ' + this._name
);
// Add _id if it doesn't exist to indexes array
const found = this.indexes.find(item => {
return Object.keys(item)[0] === '_id_';
});
if (typeof found === 'undefined') {
this.indexes.push({ _id_: { _id: 1 } });
}
}
return newCollection;
}
return coll;
})
.catch(error => {
logger.error('getCollectionConnection ERROR: ' + error);
throw error;
});
logger.verbose(
'getCollectionConnection returning collection for ' +
this._name +
' returned ' +
this._oracleCollection
);
return localConn;
}
// Atomically updates data in the database for a single (first) object that matched the query
// If there is nothing that matches the query - does insert
// Postgres Note: `INSERT ... ON CONFLICT UPDATE` that is available since 9.5.
async upsertOne(query, update, session) {
/*
UpsertOne is of the form
where query =
{"_id": "HasAllPOD"}
and update = the new document
{"_id": "HasAllPOD","numPODs": 17"}
in this case if update fails becuase no document existed then
rerunning the query would return 0 and indicate an insert
*/
logger.verbose('in upsertOne query = ' + JSON.stringify(query));
logger.verbose('use session to make linter happy ' + JSON.stringify(session));
// TODO need to use save(), which is the SODA equivalent of upsert() andit takes a SodaDocument
let docs;
let promise;
try {
promise = await this.findOneAndUpdate(query, update, null);
logger.verbose('Upsert Promise = ' + promise);
if (promise === false) {
logger.verbose('Upsert Insert for query ' + JSON.stringify(query));
promise = await this._rawFind(query, { type: 'sodadocs' }).then(d => (docs = d));
if (docs && docs.length == 0) {
// Its an insert so merge query into update
_.merge(update, query);
promise = await this.insertOne(update);
}
}
return promise;
} catch (error) {
logger.error('Collection UpsertOne throws ' + error);
throw error;
}
}
async findOneAndUpdate(query, update, transactionalSession) {
try {
logger.verbose('in Collection findOneAndUpdate query = ' + JSON.stringify(query));
logger.verbose(
'use transactionalSession to make linter happy ' + JSON.stringify(transactionalSession)
);
// TODO: Fix updatedAt, it should be _updatedAt because its an internal field
// and updatedAt doesn't get updated for Schemas
let updateObj;
let result = await this._rawFind(query, { type: 'one' }).then(result => {
return result;
});
//************************************************************************************************/
// Modify Update based on Mongo operators
//
// Look for $unset, Mongo's deleteField
// Create array of fieldNames to be deleted
const newUpdate = new Object();
const fieldNames = new Array();
Object.keys(update).forEach(item => {
if (item === '$unset') {
Object.keys(update[item]).forEach(item => {
fieldNames.push(item);
});
} else {
if (item === '_updated_at') {
newUpdate['updatedAt'] = update[item];
} else {
newUpdate[item] = update[item];
}
}
});
// if FieldNames > 0, delete those fields and
// repalce update with newUpdate that has the $unset pairs removed
// Don't move deletefields to update transform code
if (fieldNames.length > 0) {
await this.deleteFields(fieldNames).then(result => {
update = newUpdate;
return result;
});
// Ya changed the key values get them again
result = await this._rawFind(query, { type: 'one' }).then(result => {
return result;
});
}
// Process Increments $inc
const newIncUpdate = new Object();
let incUpdt = false;
Object.keys(update).forEach(item => {
if (item === '$inc') {
Object.keys(update[item]).forEach(it2 => {
incUpdt = true;
_.set(result.content, it2, _.result(result.content, it2) + update[item][it2]);
});
} else {
if (item === '_updated_at') {
newIncUpdate['updatedAt'] = update[item];
} else {
newIncUpdate[item] = update[item];
}
}
});
if (incUpdt) {
update = newIncUpdate;
}
// Process $AddToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.
const newAddToSetUpdate = new Object();
let addToSetUpdt = false;
Object.keys(update).forEach(item => {
if (item === '$addToSet') {
Object.keys(update[item]).forEach(it2 => {
Object.keys(update[item][it2]).forEach(it3 => {
if (it3 === '$each') {
const updtArray = update[item][it2][it3];
// Check for dot notation
const temp = it2.split('.');
let newArray;
if (temp.length > 1) {
newArray = result.content[temp[0]][temp[1]];
} else {
newArray = result.content[it2];
}
updtArray.forEach(updt => {
if (typeof updt === 'object') {
if (!newArray.some(entry => Object.keys(entry)[0] === Object.keys(updt)[0])) {
addToSetUpdt = true;
newArray.push(updt);
}
} else {
if (!newArray.includes(updt)) {
addToSetUpdt = true;
newArray.push(updt);
}
}
});
}
});
});
} else {
if (item === '_updated_at') {
newAddToSetUpdate['updatedAt'] = update[item];
} else {
newAddToSetUpdate[item] = update[item];
}
}
});
if (addToSetUpdt) {
update = newAddToSetUpdate;
}
// Process $pullAll operator removes all instances of the specified values from an existing array.
const newPullAllUpdate = new Object();
let pullAllUpdt = false;
Object.keys(update).forEach(item => {
if (item === '$pullAll') {
Object.keys(update[item]).forEach(it2 => {
const updtArray = update[item][it2];
const rsltArray = result.content[it2];
const newArray = new Array();
updtArray.forEach(updt => {
if (typeof updt === 'object') {
rsltArray.forEach(entry => {
if (Object.keys(entry)[0] != Object.keys(updt)[0]) {
newArray.push(entry);
pullAllUpdt = true;
}
});
}
newPullAllUpdate[it2] = newArray;
});
});
} else {
if (item === '_updated_at') {
newPullAllUpdate['updatedAt'] = update[item];
} else {
newPullAllUpdate[item] = update[item];
}
}
});
if (pullAllUpdt) {
update = newPullAllUpdate;
}
// End of Transform Update
//************************************************************************************************/
if (result && Object.keys(result).length > 0) {
// found the doc, so we need to update it
const key = result.key;
logger.verbose('key = ' + key);
const version = result.version;
logger.verbose('version = ' + version);
const oldContent = result.content;
logger.verbose('oldContent = ' + JSON.stringify(oldContent));
logger.verbose('update = ' + JSON.stringify(update));
// Check for empty object and remove it from original, no merging, replacing
Object.keys(update).forEach(item => {
if (
typeof update[item] === 'object' &&
update[item] !== null &&
item !== 'updatedAt' &&
Object.keys(update[item]).length === 0
) {
_.unset(oldContent, item);
}
});
if (update.fieldName) {
const theUpdate = { [update.fieldName]: update.theFieldType };
logger.verbose('theUpdate = ' + JSON.stringify(theUpdate));
updateObj = { ...oldContent, ...theUpdate };
} else {
if (pullAllUpdt || update['_metadata']) {
// Handle set or merge for _metadata in Schema
Object.keys(update).forEach(item => {
const found = Object.keys(oldContent).find(item => {
return item === '_metadata';
});
if (item === '_metadata') {
if (found) {
if (
Object.prototype.hasOwnProperty.call(oldContent[item], 'class_permissions') &&
Object.prototype.hasOwnProperty.call(update[item], 'class_permissions')
) {
// Just reset class_permissions to update
_.set(oldContent[item], 'class_permissions', update[item]['class_permissions']);
} else {
_.merge(oldContent['_metadata'], update[item]);
}
} else {
_.set(oldContent, item, update[item]);
}
} else {
_.set(oldContent, item, update[item]);
}
});
updateObj = oldContent;
} else {
updateObj = _.merge(oldContent, update);
}
}
logger.verbose('Updated Object = ' + JSON.stringify(updateObj));
let localConn = null;
return this.getCollectionConnection()
.then(conn => {
localConn = conn;
return this._oracleCollection.find().key(key).version(version).replaceOne(updateObj);
})
.then(result => {
if (result.replaced == true) {
return updateObj;
} else {
return 'retry';
}
})
.finally(async () => {
if (localConn) {
await localConn.close();
localConn = null;
}
})
.catch(error => {
logger.error('Find One and Update replaceOne ERROR = ', error);
throw error;
});
} else {
logger.verbose('No Docs, nothing to update, return false');
return false;
}
} catch (error) {
logger.error('Find One and Update ERROR = ', error);
throw error;
}
}
async updateSchemaIndexes(query, update) {
// This method just updates Schema _metadata.indexes
// It is laways a set (replace), never a merge
logger.verbose('in Collection updateSchemaIndexes query = ' + JSON.stringify(query));
logger.verbose('update = ' + JSON.stringify(update));
const result = await this._rawFind(query, { type: 'one' }).then(result => {
return result;
});
if (Object.keys(result).length > 0) {
// found the doc, so we need to update it
const key = result.key;
logger.verbose('key = ' + key);
const version = result.version;
logger.verbose('version = ' + version);
const oldContent = result.content;
logger.verbose('oldContent = ' + JSON.stringify(oldContent));
logger.verbose('update = ' + JSON.stringify(update));
// Either set or merge _metadata depending on if it existed before
Object.keys(update).forEach(item => {
if (item === '_metadata') {
if (Object.prototype.hasOwnProperty.call(oldContent, item)) {
if (Object.prototype.hasOwnProperty.call(oldContent[item], 'indexes')) {
if (
Object.keys(update).length <= Object.keys(oldContent['_metadata']['indexes']).length
) {
// Its a delete. Parse deletes by sending an update with the deleted index
// Set Indexes w Update only
_.set(oldContent[item], 'indexes', update[item]['indexes']);
} else {
_.merge(oldContent['_metadata'], update[item]);
}
} else {
_.merge(oldContent['_metadata'], update[item]);
}
} else {
_.set(oldContent, item, update[item]);
}
}
});
const updateObj = oldContent;
logger.verbose('Updated Object = ' + JSON.stringify(updateObj));
let localConn = null;
return this.getCollectionConnection()
.then(conn => {
localConn = conn;
return this._oracleCollection.find().key(key).version(version).replaceOne(updateObj);
})
.then(result => {
if (result.replaced == true) {
return update;
} else {
return 'retry';
}
})
.finally(async () => {
if (localConn) {
await localConn.close();
localConn = null;
}
})
.catch(error => {
logger.error('updateSchemaIndexes update ERROR: ', error);
throw error;
});
} else {
logger.verbose('updateSchemaIndexes No record found for query: ' + JSON.stringify(query));
return false;
}
}
catch(error) {
logger.error('updateSchemaIndexes ERROR: ', error);
throw error;
}
async findOneAndDelete(query: string) {
try {
logger.verbose('in Collection findOneAndDelete query = ' + JSON.stringify(query));
const result = await this._rawFind(query, { type: 'one' }).then(result => {
return result;
});
if (Object.keys(result).length > 0) {
// found the doc, so we need to update it
const key = result.key;
logger.verbose('key = ' + key);
const version = result.version;
logger.verbose('version = ' + version);
let localConn = null;
return this.getCollectionConnection()
.then(conn => {
localConn = conn;
return this._oracleCollection.find().key(key).version(version).remove();
})
.finally(async () => {
if (localConn) {
await localConn.close();
localConn = null;
}
})
.catch(error => {
logger.error('Find One and Delete remove ERROR: ', error);
throw error;
});
} else {
logger.verbose('Find One and Delete No record found for query: ' + JSON.stringify(query));
}
} catch (error) {
logger.error('Find One and Delete ERROR: ', error);
throw error;
}
}
async deleteObjectsByQuery(query, transactionalSession) {
try {
logger.verbose('in Collection deleteObjectsByQuery query = ' + JSON.stringify(query));
logger.verbose(
'use transactionalSession to make linter happy ' + JSON.stringify(transactionalSession)
);
const result = await this._rawFind(query, { type: 'all' }).then(result => {
return result;
});
if (result.length > 0) {
for (let i = 0; i < result.length; i++) {
// found the doc, so we need to update it
const key = result[i].key;
logger.verbose('key = ' + key);
const version = result[i].version;
logger.verbose('version = ' + version);
let localConn = null;
return this.getCollectionConnection()
.then(conn => {
localConn = conn;
return this._oracleCollection.find().key(key).version(version).remove();
})
.finally(async () => {
if (localConn) {
await localConn.close();
localConn = null;
}
})
.catch(error => {
logger.error('Delete Objects By Query remove ERROR: ', error);
throw error;
});
}
} else {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.');
}
} catch (error) {
logger.error('Delete Objects By Query ERROR: ', error);
throw error;
}
}
// Delete fields from all documents in a collection
async deleteFields(fieldNames: Array<string>) {
try {
var promises = Array();
// Rewriting like createIndexes, Collection method will just delete a field
logger.verbose(
'DeleteFields ' + JSON.stringify(fieldNames) + ' for Collection ' + this._name
);
for (let idx = 0; idx < fieldNames.length; idx++) {
const fieldName = fieldNames[idx];
logger.verbose('about to delete field' + fieldName);
const promise = this.deleteFieldFromCollection(fieldName)
.then(promise => {
if (promise === 'retry') {
return this.deleteFieldFromCollection(fieldName);
}
return promise;
})
.catch(error => {
logger.error('Collection deleteFields caught error ' + error.message);
throw error;
});
promises.push(promise);
}
const results = await Promise.all(promises);
logger.verbose('DeleteFields returns ' + results);
return results;
} catch (error) {
logger.error('Delete Fields ERROR: ', error);
throw error;
}
}
// deleteField from all docs in a collection that has it
async deleteFieldFromCollection(fieldName: string) {
try {
logger.verbose('deleteFieldFromCollection fieldName to delete is ' + fieldName);
const query = JSON.parse(`{"${fieldName}":{"$exists":true}}`);
const result = await this._rawFind(query, { type: 'all' }).then(result => {
return result;
});
if (result.length > 0) {
// found the doc, so we need to update it
var promises = Array();
for (let i = 0; i < result.length; i++) {
const promise = this.deleteField(
fieldName,
result[i].key,
result[i].version,
result[i].content
)
.then(promise => {
if (promise === 'retry') {
return this.deleteFieldFromCollection(fieldName);
}
return promise;
})
.catch(error => {
logger.error('deleteFieldFromConnection caught error ' + error.message);
throw error;
});
promises.push(promise);
}
const results = await Promise.all(promises);
logger.verbose('DeleteFieldFromCollection returns ' + results);
return results;
} else {
logger.verbose('Field ' + fieldName + ' Not Found In DeleteFieldFromCollection');
return false;
}
} catch (error) {
logger.error('Delete Field ERROR: ', error);
throw error;
}
}
// deleteField from a specific document containing it
async deleteField(fieldName: string, key: string, version: string, oldContent: string) {
logger.verbose('key = ' + key);
logger.verbose('version = ' + version);
logger.verbose('oldContent before delete = ' + JSON.stringify(oldContent));
delete oldContent[fieldName];
logger.verbose('oldContent after delete update = ' + JSON.stringify(oldContent));
let localConn = null;
return this.getCollectionConnection()
.then(conn => {
localConn = conn;
return this._oracleCollection.find().key(key).version(version).replaceOne(oldContent);
})
.then(result => {
if (result.replaced == true) {
return oldContent;
} else {
return 'retry';
}
})
.finally(async () => {
if (localConn) {
await localConn.close();
localConn = null;
}
})
.catch(error => {
logger.error('DeleteFieldFromCollection replaceOne ERROR: ', error);
throw error;
});
}
// Delete a field in a specific SCHEMA doc
async deleteSchemaField(query: string, fieldName: string) {
try {
logger.verbose('fieldName to delete is ' + fieldName);
const existobj = JSON.parse(`{"${fieldName}":{"$exists":true}}`);
const newquery = { ...query, ...existobj };
const result = await this._rawFind(newquery, { type: 'one' }).then(result => {
return result;
});
if (result) {
// found the doc, so we need to update it
const key = result.key;
logger.verbose('key = ' + key);
const version = result.version;
logger.verbose('version = ' + version);
const oldContent = result.content;
logger.verbose('oldContent before delete = ' + JSON.stringify(oldContent));
delete oldContent[fieldName];
logger.verbose('oldContent after delete update = ' + JSON.stringify(oldContent));
let localConn = null;
return this.getCollectionConnection()
.then(conn => {
localConn = conn;
return this._oracleCollection.find().key(key).version(version).replaceOne(oldContent);
})
.then(result => {
if (result.replaced == true) {
return oldContent;
} else {
return 'retry';
}
})
.finally(async () => {
if (localConn) {
await localConn.close();
localConn = null;
}
})
.catch(error => {
logger.error('Delete SCHEMA Field replaceOne ERROR: ', error.message);
throw error;
});
} else {
logger.verbose('Field ' + fieldName + ' Not Found In DeleteSchemaField');
return false;
}
} catch (error) {
logger.error('Delete SCHEMA Field ERROR: ', error);
throw error;
}
}
// Does a find with "smart indexing".
// Currently this just means, if it needs a geoindex and there is
// none, then build the geoindex.
// This could be improved a lot but it's not clear if that's a good
// idea. Or even if this behavior is a good idea.
async find(
query,
{
skip,
limit,
sort,
keys,
maxTimeMS,
readPreference,
hint,
caseInsensitive,
explain,
sortTypes,
} = {}
) {
try {
logger.verbose('entering find()');
// Support for Full Text Search - $text
if (keys && keys.$score) {
delete keys.$score;
keys.score = { $meta: 'textScore' };
}
return this._rawFind(
query,
{ type: 'content' },
{
skip,
limit,
sort,
keys,
maxTimeMS,
readPreference,
hint,
caseInsensitive,
explain,
sortTypes,
}
).then(result => {
return result;
});
} catch (error) {
logger.verbose("in find()'s error block");
// Check for "no geoindex" error
if (error.code != 17007 && !error.message.match(/unable to find index for .geoNear/)) {
throw error;
}
// Figure out what key needs an index
const key = error.message.match(/field=([A-Za-z_0-9]+) /)[1];
if (!key) {
throw error;
}
// TODO: Need to fix up this call to DB
// TODO: MUST FIX
var index = {};
index[key] = '2d';
await this.getCollectionConnection();
const result = await this._oracleCollection
.createIndex(index)
// Retry, but just once.
.then(() =>
this._rawFind(query, {
skip,
limit,
sort,
keys,
maxTimeMS,
readPreference,
hint,
caseInsensitive,
explain,
})
);
this.closeConnection();
return result.map(i => i.getContent());
}
}
async _rawFind(
query,
retval,
{
skip,
limit,
sort,
keys,
maxTimeMS,
readPreference,
hint,
caseInsensitive,
explain,
sortTypes,
} = {}
) {
logger.verbose('_rawFind: collection = ' + JSON.stringify(this._oracleCollection));
logger.verbose('query = ' + JSON.stringify(query));
logger.verbose('limit = ' + limit);
// use these so the linter will not complain - until i actually use them properly
logger.verbose(
'TODO: not using these: ' + sort,
maxTimeMS,
readPreference,
caseInsensitive,
explain
);
let localConn = null;
try {
let findOperation;
await this.getCollectionConnection()
.then(conn => {
localConn = conn;
findOperation = this._oracleCollection.find();
})
.catch(async error => {
logger.error('Error getting connection in _rawFind, ERROR =' + error);
if (localConn) {
await localConn.close();
localConn = null;
}
throw error;
});
// let findOperation = this._oracleCollection.find(); // find() is sync and returns SodaOperation
// All this below is to handle empty array in $in selection
// Node APIs fail for empty array error
// The fix will be in a future release of instant client
// https://orahub.oci.oraclecorp.com/ora-microservices-dev/mbaas-parse-server/-/wikis/ORA-40676:-invalid-Query-By-Example-(QBE)-filter-specification-JZN-00305:-Array-of-values-was-empty
const myObj = JSON.parse(JSON.stringify(query));
for (const x in myObj) {
if (typeof myObj[x] === 'object') {
const json = JSON.parse(JSON.stringify(myObj[x]));
//CDB
//to manage EqualTo() with null
// when an input query is like
// {"foo":null,"$or":[{"_rperm":{"$in":["*","*"]}},{"_rperm":null},{"_rperm":{"$exists":false}}]}
// and need to generate a $or for null check, need to wrap the whole thing with a $and
// It looks like null = non-existance or null
if (json == null) {
let newQuery = {};
if (Object.prototype.hasOwnProperty.call(myObj, '$or')) {
// This whole not handling null is getting ugly
const originalOr = JSON.stringify(myObj['$or']);
const queryOr = JSON.stringify({ $or: [{ [x]: { $exists: false } }, { [x]: null }] });
const andString = `[${queryOr},{"$or":${originalOr}}]`;
newQuery['$and'] = JSON.parse(andString);
delete myObj['$or'];
} else {
newQuery = { $or: [{ [x]: { $exists: false } }, { [x]: null }] };
}
query = newQuery;
}
//CDB-END
//CDB
//to manage notEqualTo() with null
if (json != null) {
if (Object.keys(json)[0] == '$ne') {
if (json['$ne'] == null) {
const newQuery = { $and: [{ [x]: { $exists: true } }, { [x]: { $ne: null } }] };
query = newQuery;
}
}
}
//CDB-END
//CDD
// Remove empty objects from $and clause
// ORA-40676: invalid Query-By-Example (QBE) filter specification
// JZN-00315: Empty objects not allowed
//
// fix up queries like
// { '$and': [ {}, { _p_user: '_User$EYTVvcG4j9' } ] }
if (json != null && x == '$and') {
if (Array.isArray(json)) {
const condList = new Array();
json.forEach(item => {
if (!(Object.keys(item).length === 0)) {
condList.push(item);
}
});
query = {
$and: condList,
};
}
}
//CDD
for (const y in json) {
//query should not match on array when searching for null
if (y === '$all' && Array.isArray(json[y]) && json[y][0] == null) {
if (localConn) {
await localConn.close();
localConn = null;
}
return [];
} else {
// to manage $all of normal expression for query match on array with multiple objects
if (
y === '$all' &&
Array.isArray(json[y]) &&
json[y][0]['__FIELD__!!__'] === undefined
) {
const newCondList = Array();
for (var ass in myObj[x]['$all']) {
if (typeof myObj[x]['$all'][ass] === 'object') {
// ???
const condList = myObj[x]['$all'][0];
Object.keys(condList).forEach(function (key) {
// key: the name of the object key
// index: the ordinal position of the key within the object
const newField = x + '[*].' + key;
newCondList.push({
[newField]: condList[key],
});
});
}
}
// For 'containsAll date array queries','containsAll string array queries','containsAll number array queries'
// no 'objects' in array: doesn't need a query re-write in $and:[] 'for query match on array with multiple objects'
// newCondList == []
if (newCondList.length != 0) {
query = {
$and: newCondList,
};
}
} //CDB
}
if (y === '$in' || y === '$nin' || y === '$all') {
if (json[y].length > 0 && json[y][0] !== null) {
//TO MANAGE 'containsAllStartingWith single empty value returns empty results' test
if (
Object.keys(json[y][0]).length == 0 &&
y === '$all' &&
typeof json[y][0] == 'object'
) {
if (localConn) {
await localConn.close();
localConn = null;
}
return [];
}
}
if (json[y].length == 0) {
if (y === '$in' || y === '$all') {
if (localConn) {
await localConn.close();
localConn = null;
}
return [];
} else {
query = JSON.parse('{}');
}
}
}
// to manage $all of $regex expression
//To exclude a $all on $regex array to be transformed in $and
/* CDD Commented this code out becuase it broke this query
{"numbers":{"$all":[1,2,3]}