-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
PostgresStorageAdapter.js
2649 lines (2494 loc) · 87.5 KB
/
PostgresStorageAdapter.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
// @flow
import { createClient } from './PostgresClient';
// @flow-disable-next
import Parse from 'parse/node';
// @flow-disable-next
import _ from 'lodash';
// @flow-disable-next
import { v4 as uuidv4 } from 'uuid';
import sql from './sql';
import { StorageAdapter } from '../StorageAdapter';
import type { SchemaType, QueryType, QueryOptions } from '../StorageAdapter';
const Utils = require('../../../Utils');
const PostgresRelationDoesNotExistError = '42P01';
const PostgresDuplicateRelationError = '42P07';
const PostgresDuplicateColumnError = '42701';
const PostgresMissingColumnError = '42703';
const PostgresUniqueIndexViolationError = '23505';
const logger = require('../../../logger');
const debug = function (...args: any) {
args = ['PG: ' + arguments[0]].concat(args.slice(1, args.length));
const log = logger.getLogger();
log.debug.apply(log, args);
};
const parseTypeToPostgresType = type => {
switch (type.type) {
case 'String':
return 'text';
case 'Date':
return 'timestamp with time zone';
case 'Object':
return 'jsonb';
case 'File':
return 'text';
case 'Boolean':
return 'boolean';
case 'Pointer':
return 'text';
case 'Number':
return 'double precision';
case 'GeoPoint':
return 'point';
case 'Bytes':
return 'jsonb';
case 'Polygon':
return 'polygon';
case 'Array':
if (type.contents && type.contents.type === 'String') {
return 'text[]';
} else {
return 'jsonb';
}
default:
throw `no type for ${JSON.stringify(type)} yet`;
}
};
const ParseToPosgresComparator = {
$gt: '>',
$lt: '<',
$gte: '>=',
$lte: '<=',
};
const mongoAggregateToPostgres = {
$dayOfMonth: 'DAY',
$dayOfWeek: 'DOW',
$dayOfYear: 'DOY',
$isoDayOfWeek: 'ISODOW',
$isoWeekYear: 'ISOYEAR',
$hour: 'HOUR',
$minute: 'MINUTE',
$second: 'SECOND',
$millisecond: 'MILLISECONDS',
$month: 'MONTH',
$week: 'WEEK',
$year: 'YEAR',
};
const toPostgresValue = value => {
if (typeof value === 'object') {
if (value.__type === 'Date') {
return value.iso;
}
if (value.__type === 'File') {
return value.name;
}
}
return value;
};
const transformValue = value => {
if (typeof value === 'object' && value.__type === 'Pointer') {
return value.objectId;
}
return value;
};
// Duplicate from then mongo adapter...
const emptyCLPS = Object.freeze({
find: {},
get: {},
count: {},
create: {},
update: {},
delete: {},
addField: {},
protectedFields: {},
});
const defaultCLPS = Object.freeze({
find: { '*': true },
get: { '*': true },
count: { '*': true },
create: { '*': true },
update: { '*': true },
delete: { '*': true },
addField: { '*': true },
protectedFields: { '*': [] },
});
const toParseSchema = schema => {
if (schema.className === '_User') {
delete schema.fields._hashed_password;
}
if (schema.fields) {
delete schema.fields._wperm;
delete schema.fields._rperm;
}
let clps = defaultCLPS;
if (schema.classLevelPermissions) {
clps = { ...emptyCLPS, ...schema.classLevelPermissions };
}
let indexes = {};
if (schema.indexes) {
indexes = { ...schema.indexes };
}
return {
className: schema.className,
fields: schema.fields,
classLevelPermissions: clps,
indexes,
};
};
const toPostgresSchema = schema => {
if (!schema) {
return schema;
}
schema.fields = schema.fields || {};
schema.fields._wperm = { type: 'Array', contents: { type: 'String' } };
schema.fields._rperm = { type: 'Array', contents: { type: 'String' } };
if (schema.className === '_User') {
schema.fields._hashed_password = { type: 'String' };
schema.fields._password_history = { type: 'Array' };
}
return schema;
};
const handleDotFields = object => {
Object.keys(object).forEach(fieldName => {
if (fieldName.indexOf('.') > -1) {
const components = fieldName.split('.');
const first = components.shift();
object[first] = object[first] || {};
let currentObj = object[first];
let next;
let value = object[fieldName];
if (value && value.__op === 'Delete') {
value = undefined;
}
/* eslint-disable no-cond-assign */
while ((next = components.shift())) {
/* eslint-enable no-cond-assign */
currentObj[next] = currentObj[next] || {};
if (components.length === 0) {
currentObj[next] = value;
}
currentObj = currentObj[next];
}
delete object[fieldName];
}
});
return object;
};
const transformDotFieldToComponents = fieldName => {
return fieldName.split('.').map((cmpt, index) => {
if (index === 0) {
return `"${cmpt}"`;
}
return `'${cmpt}'`;
});
};
const transformDotField = fieldName => {
if (fieldName.indexOf('.') === -1) {
return `"${fieldName}"`;
}
const components = transformDotFieldToComponents(fieldName);
let name = components.slice(0, components.length - 1).join('->');
name += '->>' + components[components.length - 1];
return name;
};
const transformAggregateField = fieldName => {
if (typeof fieldName !== 'string') {
return fieldName;
}
if (fieldName === '$_created_at') {
return 'createdAt';
}
if (fieldName === '$_updated_at') {
return 'updatedAt';
}
return fieldName.substr(1);
};
const validateKeys = object => {
if (typeof object == 'object') {
for (const key in object) {
if (typeof object[key] == 'object') {
validateKeys(object[key]);
}
if (key.includes('$') || key.includes('.')) {
throw new Parse.Error(
Parse.Error.INVALID_NESTED_KEY,
"Nested keys should not contain the '$' or '.' characters"
);
}
}
}
};
// Returns the list of join tables on a schema
const joinTablesForSchema = schema => {
const list = [];
if (schema) {
Object.keys(schema.fields).forEach(field => {
if (schema.fields[field].type === 'Relation') {
list.push(`_Join:${field}:${schema.className}`);
}
});
}
return list;
};
interface WhereClause {
pattern: string;
values: Array<any>;
sorts: Array<any>;
}
const buildWhereClause = ({ schema, query, index, caseInsensitive }): WhereClause => {
const patterns = [];
let values = [];
const sorts = [];
schema = toPostgresSchema(schema);
for (const fieldName in query) {
const isArrayField =
schema.fields && schema.fields[fieldName] && schema.fields[fieldName].type === 'Array';
const initialPatternsLength = patterns.length;
const fieldValue = query[fieldName];
// nothing in the schema, it's gonna blow up
if (!schema.fields[fieldName]) {
// as it won't exist
if (fieldValue && fieldValue.$exists === false) {
continue;
}
}
const authDataMatch = fieldName.match(/^_auth_data_([a-zA-Z0-9_]+)$/);
if (authDataMatch) {
// TODO: Handle querying by _auth_data_provider, authData is stored in authData field
continue;
} else if (caseInsensitive && (fieldName === 'username' || fieldName === 'email')) {
patterns.push(`LOWER($${index}:name) = LOWER($${index + 1})`);
values.push(fieldName, fieldValue);
index += 2;
} else if (fieldName.indexOf('.') >= 0) {
let name = transformDotField(fieldName);
if (fieldValue === null) {
patterns.push(`$${index}:raw IS NULL`);
values.push(name);
index += 1;
continue;
} else {
if (fieldValue.$in) {
name = transformDotFieldToComponents(fieldName).join('->');
patterns.push(`($${index}:raw)::jsonb @> $${index + 1}::jsonb`);
values.push(name, JSON.stringify(fieldValue.$in));
index += 2;
} else if (fieldValue.$regex) {
// Handle later
} else if (typeof fieldValue !== 'object') {
patterns.push(`$${index}:raw = $${index + 1}::text`);
values.push(name, fieldValue);
index += 2;
}
}
} else if (fieldValue === null || fieldValue === undefined) {
patterns.push(`$${index}:name IS NULL`);
values.push(fieldName);
index += 1;
continue;
} else if (typeof fieldValue === 'string') {
patterns.push(`$${index}:name = $${index + 1}`);
values.push(fieldName, fieldValue);
index += 2;
} else if (typeof fieldValue === 'boolean') {
patterns.push(`$${index}:name = $${index + 1}`);
// Can't cast boolean to double precision
if (schema.fields[fieldName] && schema.fields[fieldName].type === 'Number') {
// Should always return zero results
const MAX_INT_PLUS_ONE = 9223372036854775808;
values.push(fieldName, MAX_INT_PLUS_ONE);
} else {
values.push(fieldName, fieldValue);
}
index += 2;
} else if (typeof fieldValue === 'number') {
patterns.push(`$${index}:name = $${index + 1}`);
values.push(fieldName, fieldValue);
index += 2;
} else if (['$or', '$nor', '$and'].includes(fieldName)) {
const clauses = [];
const clauseValues = [];
fieldValue.forEach(subQuery => {
const clause = buildWhereClause({
schema,
query: subQuery,
index,
caseInsensitive,
});
if (clause.pattern.length > 0) {
clauses.push(clause.pattern);
clauseValues.push(...clause.values);
index += clause.values.length;
}
});
const orOrAnd = fieldName === '$and' ? ' AND ' : ' OR ';
const not = fieldName === '$nor' ? ' NOT ' : '';
patterns.push(`${not}(${clauses.join(orOrAnd)})`);
values.push(...clauseValues);
}
if (fieldValue.$ne !== undefined) {
if (isArrayField) {
fieldValue.$ne = JSON.stringify([fieldValue.$ne]);
patterns.push(`NOT array_contains($${index}:name, $${index + 1})`);
} else {
if (fieldValue.$ne === null) {
patterns.push(`$${index}:name IS NOT NULL`);
values.push(fieldName);
index += 1;
continue;
} else {
// if not null, we need to manually exclude null
if (fieldValue.$ne.__type === 'GeoPoint') {
patterns.push(
`($${index}:name <> POINT($${index + 1}, $${index + 2}) OR $${index}:name IS NULL)`
);
} else {
if (fieldName.indexOf('.') >= 0) {
const constraintFieldName = transformDotField(fieldName);
patterns.push(
`(${constraintFieldName} <> $${index} OR ${constraintFieldName} IS NULL)`
);
} else if (typeof fieldValue.$ne === 'object' && fieldValue.$ne.$relativeTime) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'$relativeTime can only be used with the $lt, $lte, $gt, and $gte operators'
);
} else {
patterns.push(`($${index}:name <> $${index + 1} OR $${index}:name IS NULL)`);
}
}
}
}
if (fieldValue.$ne.__type === 'GeoPoint') {
const point = fieldValue.$ne;
values.push(fieldName, point.longitude, point.latitude);
index += 3;
} else {
// TODO: support arrays
values.push(fieldName, fieldValue.$ne);
index += 2;
}
}
if (fieldValue.$eq !== undefined) {
if (fieldValue.$eq === null) {
patterns.push(`$${index}:name IS NULL`);
values.push(fieldName);
index += 1;
} else {
if (fieldName.indexOf('.') >= 0) {
values.push(fieldValue.$eq);
patterns.push(`${transformDotField(fieldName)} = $${index++}`);
} else if (typeof fieldValue.$eq === 'object' && fieldValue.$eq.$relativeTime) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'$relativeTime can only be used with the $lt, $lte, $gt, and $gte operators'
);
} else {
values.push(fieldName, fieldValue.$eq);
patterns.push(`$${index}:name = $${index + 1}`);
index += 2;
}
}
}
const isInOrNin = Array.isArray(fieldValue.$in) || Array.isArray(fieldValue.$nin);
if (
Array.isArray(fieldValue.$in) &&
isArrayField &&
schema.fields[fieldName].contents &&
schema.fields[fieldName].contents.type === 'String'
) {
const inPatterns = [];
let allowNull = false;
values.push(fieldName);
fieldValue.$in.forEach((listElem, listIndex) => {
if (listElem === null) {
allowNull = true;
} else {
values.push(listElem);
inPatterns.push(`$${index + 1 + listIndex - (allowNull ? 1 : 0)}`);
}
});
if (allowNull) {
patterns.push(`($${index}:name IS NULL OR $${index}:name && ARRAY[${inPatterns.join()}])`);
} else {
patterns.push(`$${index}:name && ARRAY[${inPatterns.join()}]`);
}
index = index + 1 + inPatterns.length;
} else if (isInOrNin) {
var createConstraint = (baseArray, notIn) => {
const not = notIn ? ' NOT ' : '';
if (baseArray.length > 0) {
if (isArrayField) {
patterns.push(`${not} array_contains($${index}:name, $${index + 1})`);
values.push(fieldName, JSON.stringify(baseArray));
index += 2;
} else {
// Handle Nested Dot Notation Above
if (fieldName.indexOf('.') >= 0) {
return;
}
const inPatterns = [];
values.push(fieldName);
baseArray.forEach((listElem, listIndex) => {
if (listElem != null) {
values.push(listElem);
inPatterns.push(`$${index + 1 + listIndex}`);
}
});
patterns.push(`$${index}:name ${not} IN (${inPatterns.join()})`);
index = index + 1 + inPatterns.length;
}
} else if (!notIn) {
values.push(fieldName);
patterns.push(`$${index}:name IS NULL`);
index = index + 1;
} else {
// Handle empty array
if (notIn) {
patterns.push('1 = 1'); // Return all values
} else {
patterns.push('1 = 2'); // Return no values
}
}
};
if (fieldValue.$in) {
createConstraint(
_.flatMap(fieldValue.$in, elt => elt),
false
);
}
if (fieldValue.$nin) {
createConstraint(
_.flatMap(fieldValue.$nin, elt => elt),
true
);
}
} else if (typeof fieldValue.$in !== 'undefined') {
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad $in value');
} else if (typeof fieldValue.$nin !== 'undefined') {
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad $nin value');
}
if (Array.isArray(fieldValue.$all) && isArrayField) {
if (isAnyValueRegexStartsWith(fieldValue.$all)) {
if (!isAllValuesRegexOrNone(fieldValue.$all)) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'All $all values must be of regex type or none: ' + fieldValue.$all
);
}
for (let i = 0; i < fieldValue.$all.length; i += 1) {
const value = processRegexPattern(fieldValue.$all[i].$regex);
fieldValue.$all[i] = value.substring(1) + '%';
}
patterns.push(`array_contains_all_regex($${index}:name, $${index + 1}::jsonb)`);
} else {
patterns.push(`array_contains_all($${index}:name, $${index + 1}::jsonb)`);
}
values.push(fieldName, JSON.stringify(fieldValue.$all));
index += 2;
} else if (Array.isArray(fieldValue.$all)) {
if (fieldValue.$all.length === 1) {
patterns.push(`$${index}:name = $${index + 1}`);
values.push(fieldName, fieldValue.$all[0].objectId);
index += 2;
}
}
if (typeof fieldValue.$exists !== 'undefined') {
if (typeof fieldValue.$exists === 'object' && fieldValue.$exists.$relativeTime) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'$relativeTime can only be used with the $lt, $lte, $gt, and $gte operators'
);
} else if (fieldValue.$exists) {
patterns.push(`$${index}:name IS NOT NULL`);
} else {
patterns.push(`$${index}:name IS NULL`);
}
values.push(fieldName);
index += 1;
}
if (fieldValue.$containedBy) {
const arr = fieldValue.$containedBy;
if (!(arr instanceof Array)) {
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad $containedBy: should be an array`);
}
patterns.push(`$${index}:name <@ $${index + 1}::jsonb`);
values.push(fieldName, JSON.stringify(arr));
index += 2;
}
if (fieldValue.$text) {
const search = fieldValue.$text.$search;
let language = 'english';
if (typeof search !== 'object') {
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad $text: $search, should be object`);
}
if (!search.$term || typeof search.$term !== 'string') {
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad $text: $term, should be string`);
}
if (search.$language && typeof search.$language !== 'string') {
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad $text: $language, should be string`);
} else if (search.$language) {
language = search.$language;
}
if (search.$caseSensitive && typeof search.$caseSensitive !== 'boolean') {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`bad $text: $caseSensitive, should be boolean`
);
} else if (search.$caseSensitive) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`bad $text: $caseSensitive not supported, please use $regex or create a separate lower case column.`
);
}
if (search.$diacriticSensitive && typeof search.$diacriticSensitive !== 'boolean') {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`bad $text: $diacriticSensitive, should be boolean`
);
} else if (search.$diacriticSensitive === false) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`bad $text: $diacriticSensitive - false not supported, install Postgres Unaccent Extension`
);
}
patterns.push(
`to_tsvector($${index}, $${index + 1}:name) @@ to_tsquery($${index + 2}, $${index + 3})`
);
values.push(language, fieldName, language, search.$term);
index += 4;
}
if (fieldValue.$nearSphere) {
const point = fieldValue.$nearSphere;
const distance = fieldValue.$maxDistance;
const distanceInKM = distance * 6371 * 1000;
patterns.push(
`ST_DistanceSphere($${index}:name::geometry, POINT($${index + 1}, $${
index + 2
})::geometry) <= $${index + 3}`
);
sorts.push(
`ST_DistanceSphere($${index}:name::geometry, POINT($${index + 1}, $${
index + 2
})::geometry) ASC`
);
values.push(fieldName, point.longitude, point.latitude, distanceInKM);
index += 4;
}
if (fieldValue.$within && fieldValue.$within.$box) {
const box = fieldValue.$within.$box;
const left = box[0].longitude;
const bottom = box[0].latitude;
const right = box[1].longitude;
const top = box[1].latitude;
patterns.push(`$${index}:name::point <@ $${index + 1}::box`);
values.push(fieldName, `((${left}, ${bottom}), (${right}, ${top}))`);
index += 2;
}
if (fieldValue.$geoWithin && fieldValue.$geoWithin.$centerSphere) {
const centerSphere = fieldValue.$geoWithin.$centerSphere;
if (!(centerSphere instanceof Array) || centerSphere.length < 2) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; $centerSphere should be an array of Parse.GeoPoint and distance'
);
}
// Get point, convert to geo point if necessary and validate
let point = centerSphere[0];
if (point instanceof Array && point.length === 2) {
point = new Parse.GeoPoint(point[1], point[0]);
} else if (!GeoPointCoder.isValidJSON(point)) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; $centerSphere geo point invalid'
);
}
Parse.GeoPoint._validate(point.latitude, point.longitude);
// Get distance and validate
const distance = centerSphere[1];
if (isNaN(distance) || distance < 0) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; $centerSphere distance invalid'
);
}
const distanceInKM = distance * 6371 * 1000;
patterns.push(
`ST_DistanceSphere($${index}:name::geometry, POINT($${index + 1}, $${
index + 2
})::geometry) <= $${index + 3}`
);
values.push(fieldName, point.longitude, point.latitude, distanceInKM);
index += 4;
}
if (fieldValue.$geoWithin && fieldValue.$geoWithin.$polygon) {
const polygon = fieldValue.$geoWithin.$polygon;
let points;
if (typeof polygon === 'object' && polygon.__type === 'Polygon') {
if (!polygon.coordinates || polygon.coordinates.length < 3) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; Polygon.coordinates should contain at least 3 lon/lat pairs'
);
}
points = polygon.coordinates;
} else if (polygon instanceof Array) {
if (polygon.length < 3) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; $polygon should contain at least 3 GeoPoints'
);
}
points = polygon;
} else {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
"bad $geoWithin value; $polygon should be Polygon object or Array of Parse.GeoPoint's"
);
}
points = points
.map(point => {
if (point instanceof Array && point.length === 2) {
Parse.GeoPoint._validate(point[1], point[0]);
return `(${point[0]}, ${point[1]})`;
}
if (typeof point !== 'object' || point.__type !== 'GeoPoint') {
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad $geoWithin value');
} else {
Parse.GeoPoint._validate(point.latitude, point.longitude);
}
return `(${point.longitude}, ${point.latitude})`;
})
.join(', ');
patterns.push(`$${index}:name::point <@ $${index + 1}::polygon`);
values.push(fieldName, `(${points})`);
index += 2;
}
if (fieldValue.$geoIntersects && fieldValue.$geoIntersects.$point) {
const point = fieldValue.$geoIntersects.$point;
if (typeof point !== 'object' || point.__type !== 'GeoPoint') {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoIntersect value; $point should be GeoPoint'
);
} else {
Parse.GeoPoint._validate(point.latitude, point.longitude);
}
patterns.push(`$${index}:name::polygon @> $${index + 1}::point`);
values.push(fieldName, `(${point.longitude}, ${point.latitude})`);
index += 2;
}
if (fieldValue.$regex) {
let regex = fieldValue.$regex;
let operator = '~';
const opts = fieldValue.$options;
if (opts) {
if (opts.indexOf('i') >= 0) {
operator = '~*';
}
if (opts.indexOf('x') >= 0) {
regex = removeWhiteSpace(regex);
}
}
const name = transformDotField(fieldName);
regex = processRegexPattern(regex);
patterns.push(`$${index}:raw ${operator} '$${index + 1}:raw'`);
values.push(name, regex);
index += 2;
}
if (fieldValue.__type === 'Pointer') {
if (isArrayField) {
patterns.push(`array_contains($${index}:name, $${index + 1})`);
values.push(fieldName, JSON.stringify([fieldValue]));
index += 2;
} else {
patterns.push(`$${index}:name = $${index + 1}`);
values.push(fieldName, fieldValue.objectId);
index += 2;
}
}
if (fieldValue.__type === 'Date') {
patterns.push(`$${index}:name = $${index + 1}`);
values.push(fieldName, fieldValue.iso);
index += 2;
}
if (fieldValue.__type === 'GeoPoint') {
patterns.push(`$${index}:name ~= POINT($${index + 1}, $${index + 2})`);
values.push(fieldName, fieldValue.longitude, fieldValue.latitude);
index += 3;
}
if (fieldValue.__type === 'Polygon') {
const value = convertPolygonToSQL(fieldValue.coordinates);
patterns.push(`$${index}:name ~= $${index + 1}::polygon`);
values.push(fieldName, value);
index += 2;
}
Object.keys(ParseToPosgresComparator).forEach(cmp => {
if (fieldValue[cmp] || fieldValue[cmp] === 0) {
const pgComparator = ParseToPosgresComparator[cmp];
let postgresValue = toPostgresValue(fieldValue[cmp]);
let constraintFieldName;
if (fieldName.indexOf('.') >= 0) {
let castType;
switch (typeof postgresValue) {
case 'number':
castType = 'double precision';
break;
case 'boolean':
castType = 'boolean';
break;
default:
castType = undefined;
}
constraintFieldName = castType
? `CAST ((${transformDotField(fieldName)}) AS ${castType})`
: transformDotField(fieldName);
} else {
if (typeof postgresValue === 'object' && postgresValue.$relativeTime) {
if (schema.fields[fieldName].type !== 'Date') {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'$relativeTime can only be used with Date field'
);
}
const parserResult = Utils.relativeTimeToDate(postgresValue.$relativeTime);
if (parserResult.status === 'success') {
postgresValue = toPostgresValue(parserResult.result);
} else {
console.error('Error while parsing relative date', parserResult);
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`bad $relativeTime (${postgresValue.$relativeTime}) value. ${parserResult.info}`
);
}
}
constraintFieldName = `$${index++}:name`;
values.push(fieldName);
}
values.push(postgresValue);
patterns.push(`${constraintFieldName} ${pgComparator} $${index++}`);
}
});
if (initialPatternsLength === patterns.length) {
throw new Parse.Error(
Parse.Error.OPERATION_FORBIDDEN,
`Postgres doesn't support this query type yet ${JSON.stringify(fieldValue)}`
);
}
}
values = values.map(transformValue);
return { pattern: patterns.join(' AND '), values, sorts };
};
export class PostgresStorageAdapter implements StorageAdapter {
canSortOnJoinTables: boolean;
enableSchemaHooks: boolean;
// Private
_collectionPrefix: string;
_client: any;
_onchange: any;
_pgp: any;
_stream: any;
_uuid: any;
constructor({ uri, collectionPrefix = '', databaseOptions = {} }: any) {
this._collectionPrefix = collectionPrefix;
this.enableSchemaHooks = !!databaseOptions.enableSchemaHooks;
delete databaseOptions.enableSchemaHooks;
const { client, pgp } = createClient(uri, databaseOptions);
this._client = client;
this._onchange = () => {};
this._pgp = pgp;
this._uuid = uuidv4();
this.canSortOnJoinTables = false;
}
watch(callback: () => void): void {
this._onchange = callback;
}
//Note that analyze=true will run the query, executing INSERTS, DELETES, etc.
createExplainableQuery(query: string, analyze: boolean = false) {
if (analyze) {
return 'EXPLAIN (ANALYZE, FORMAT JSON) ' + query;
} else {
return 'EXPLAIN (FORMAT JSON) ' + query;
}
}
handleShutdown() {
if (this._stream) {
this._stream.done();
delete this._stream;
}
if (!this._client) {
return;
}
this._client.$pool.end();
}
async _listenToSchema() {
if (!this._stream && this.enableSchemaHooks) {
this._stream = await this._client.connect({ direct: true });
this._stream.client.on('notification', data => {
const payload = JSON.parse(data.payload);
if (payload.senderId !== this._uuid) {
this._onchange();
}
});
await this._stream.none('LISTEN $1~', 'schema.change');
}
}
_notifySchemaChange() {
if (this._stream) {
this._stream
.none('NOTIFY $1~, $2', ['schema.change', { senderId: this._uuid }])
.catch(error => {
console.log('Failed to Notify:', error); // unlikely to ever happen
});
}
}
async _ensureSchemaCollectionExists(conn: any) {
conn = conn || this._client;
await conn
.none(
'CREATE TABLE IF NOT EXISTS "_SCHEMA" ( "className" varChar(120), "schema" jsonb, "isParseClass" bool, PRIMARY KEY ("className") )'
)
.catch(error => {
throw error;
});
}
async classExists(name: string) {
return this._client.one(
'SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = $1)',
[name],
a => a.exists
);
}
async setClassLevelPermissions(className: string, CLPs: any) {
await this._client.task('set-class-level-permissions', async t => {
const values = [className, 'schema', 'classLevelPermissions', JSON.stringify(CLPs)];
await t.none(
`UPDATE "_SCHEMA" SET $2:name = json_object_set_key($2:name, $3::text, $4::jsonb) WHERE "className" = $1`,
values
);
});
this._notifySchemaChange();
}
async setIndexesWithSchemaFormat(
className: string,
submittedIndexes: any,
existingIndexes: any = {},
fields: any,
conn: ?any
): Promise<void> {
conn = conn || this._client;
const self = this;
if (submittedIndexes === undefined) {
return Promise.resolve();
}
if (Object.keys(existingIndexes).length === 0) {
existingIndexes = { _id_: { _id: 1 } };
}
const deletedIndexes = [];
const insertedIndexes = [];
Object.keys(submittedIndexes).forEach(name => {
const field = submittedIndexes[name];
if (existingIndexes[name] && field.__op !== 'Delete') {
throw new Parse.Error(Parse.Error.INVALID_QUERY, `Index ${name} exists, cannot update.`);
}
if (!existingIndexes[name] && field.__op === 'Delete') {
throw new Parse.Error(
Parse.Error.INVALID_QUERY,
`Index ${name} does not exist, cannot delete.`
);
}
if (field.__op === 'Delete') {
deletedIndexes.push(name);
delete existingIndexes[name];
} else {
Object.keys(field).forEach(key => {
if (!Object.prototype.hasOwnProperty.call(fields, key)) {
throw new Parse.Error(
Parse.Error.INVALID_QUERY,
`Field ${key} does not exist, cannot add index.`
);
}
});
existingIndexes[name] = field;
insertedIndexes.push({
key: field,
name,
});
}
});
await conn.tx('set-indexes-with-schema-format', async t => {
if (insertedIndexes.length > 0) {
await self.createIndexes(className, insertedIndexes, t);
}
if (deletedIndexes.length > 0) {
await self.dropIndexes(className, deletedIndexes, t);
}
await t.none(
'UPDATE "_SCHEMA" SET $2:name = json_object_set_key($2:name, $3::text, $4::jsonb) WHERE "className" = $1',
[className, 'schema', 'indexes', JSON.stringify(existingIndexes)]
);
});
this._notifySchemaChange();
}
async createClass(className: string, schema: SchemaType, conn: ?any) {
conn = conn || this._client;
const parseSchema = await conn
.tx('create-class', async t => {
await this.createTable(className, schema, t);
await t.none(
'INSERT INTO "_SCHEMA" ("className", "schema", "isParseClass") VALUES ($<className>, $<schema>, true)',
{ className, schema }