/
query-builder.ts
1180 lines (1112 loc) · 33.2 KB
/
query-builder.ts
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
import { mapKeys, snakeCase } from 'lodash';
import { createQueryBuilder, SelectQueryBuilder } from 'typeorm';
import { Constructor } from './types/typings';
import { FilterHelper, QueryConditionService } from './utils/filter.helper';
import { isNum, isUniqueFields } from './utils/common.helper';
import { isArray, isString } from 'class-validator';
import {
QueryBuilderPart,
QueryComparableProp,
QueryPropsDef,
} from './model/repository.model';
import { ReadStream } from 'typeorm/platform/PlatformTools';
import { LookupFilter } from './constants/filter.constant';
const UNDEFINED_CONST = undefined;
// QueryBuilder helpers
export class QueryBuilder<
T,
R = T | T[],
P = QueryPropsDef<T>
> {
constructor(
private entityType: Constructor<T> | string | Function,
entityAlias: string,
private queryObject?,
) {
if (queryObject && queryObject.page && isNum(queryObject.page)) {
this.page = Number(queryObject.page);
}
if (queryObject && queryObject.limit && isNum(queryObject.limit)) {
this.limit = Number(queryObject.limit);
}
if (entityAlias) {
this.qb = createQueryBuilder(entityType, entityAlias);
}
}
public queryBuilderParts = new Array<QueryBuilderPart<T>>();
public havingQueryBuilderParts = new Array<QueryBuilderPart<T>>();
private page: number = 1;
private limit: number = 10;
public fieldResolverMap: { [key: string]: string } = {};
public qb: SelectQueryBuilder<any>;
public joinHistory: { [key: string]: string } = {};
/**
* Transform key to snake_case and optionally with alias.
*
* @param {string} key Field key from query params.
* @param {string} alias Alias, ex. t1, optional.
* @return {*} {string}
*/
private transformKey(key: string, alias?: string): string {
let tKey = snakeCase(key);
if (alias || this.qb.alias) {
tKey = `${alias ? alias : this.qb.alias}.${tKey}`;
}
return tKey;
}
/**
* Transform Property Selector
*
* @param propertySelector Property Selector.
*/
private transformProperty<JR extends Object>(
propertySelector: ((obj: P) => QueryComparableProp | JR) | string,
) {
if (!propertySelector) {
throw new Error('Property Selector not provided.');
}
let property = '';
if (typeof propertySelector !== 'string') {
const mainAlias = this.qb.alias;
const selectors = propertySelector.toString().split('.');
property = `${selectors[selectors.length - 1]}`;
if (selectors.length > 2) {
const selector = selectors[selectors.length - 2];
const history = Object.keys(this.joinHistory);
const historyKey = history.find((h) => h.includes(selector));
const relationAlias = this.joinHistory[historyKey];
if (relationAlias) {
property = `${relationAlias}.${selectors[selectors.length - 1]}`;
}
} else if (mainAlias) {
property = `${mainAlias}.${selectors[selectors.length - 1]}`;
}
} else {
property = propertySelector;
}
return property;
}
/**
* Transform Property Selector and Relation
*
* @param propertySelector Property Selector.
*/
private transformPropertyAndRelation<JR extends Object>(
propertySelector: ((obj: P) => JR) | string,
) {
let property = '';
let relation = '';
let relationEntityType = '';
if (typeof propertySelector !== 'string') {
const mainAlias = this.qb.alias;
const selectors = propertySelector.toString().split('.');
relation = selectors[selectors.length - 1];
property = `ptc_${selectors[selectors.length - 1]}`;
if (selectors.length > 2) {
const selector = selectors[selectors.length - 2];
const history = Object.keys(this.joinHistory);
const historyKey = history.find((h) => h.includes(selector));
const relationAlias = this.joinHistory[historyKey];
if (relationAlias) {
property = `${relationAlias}.${selectors[selectors.length - 1]}`;
}
relationEntityType = selector;
} else if (mainAlias) {
property = `${mainAlias}.${selectors[selectors.length - 1]}`;
}
} else {
property = propertySelector;
relation = propertySelector.split('.')[1];
}
if (!property || !relation) {
throw new Error('Property Selector not defined.');
}
if (!relationEntityType && !this.qb.hasRelation(this.entityType, relation)) {
const entityTypeClass = this.entityType as Constructor<T>;
throw new Error(
`${entityTypeClass.name} does not have relation with ${relation}`,
);
}
return { property, relation };
}
/**
* Transform Aggregate Property Selector
*
* @param propertySelector Property Selector
* @param type AVG | SUM | MIN | MAX
*/
private transformAggregateProp(
propertySelector: ((obj: P) => number) | string,
type,
) {
if (!propertySelector) {
throw new Error('Property Selector not provided.');
}
let transformedProp = '';
if (typeof propertySelector !== 'string') {
const mainAlias = this.qb.alias;
const selectors = propertySelector.toString().split('.');
if (selectors.length > 2) {
const history = Object.keys(this.joinHistory);
const historyKey = history.find((h) => h.includes(selectors[selectors.length - 2]));
const relationAlias = this.joinHistory[historyKey];
transformedProp = `${relationAlias}.${selectors[selectors.length - 1]}`;
} else {
transformedProp = `${mainAlias}.${selectors[selectors.length - 1]}`;
}
} else {
transformedProp = propertySelector;
}
const prop =
transformedProp.split('.').length > 1
? transformedProp.split('.')[1]
: transformedProp;
const entityMetadata = this.qb.connection.getMetadata(this.entityType);
const property = entityMetadata.findColumnWithPropertyName(prop);
if (property && property.type != 'numeric') {
throw new Error(
`Type of ${property.propertyName} field is ${property.type} not assignable to type number in ${type} method. Please provide only numeric type field.`,
);
}
return {
prop,
transformedProp,
};
}
/**
* Get Query.
*/
public getQuery(): string {
this.compileQueryBuilderParts();
return this.qb.getQuery();
}
/**
* Select one or multiple fields with each Alias field
*
* @param args Array of Array of field with alias, e.g: ['t1.id', 'id'], ...
*/
public selectRaw(...args: Array<string | string[]>) {
const expressionArgs = args.filter(
arg => isString(arg) || (isArray(arg) && arg.length <= 2),
);
if (!expressionArgs.length) {
throw new Error(`String expression is required for the selectRaw method`);
}
for (const arg of args) {
if (args.indexOf(arg) === 0) {
if (arg[1]) {
this.qb.select(arg[0], arg[1]);
} else {
this.qb.select(arg[0]);
}
} else {
if (arg[1]) {
this.qb.addSelect(arg[0], arg[1]);
} else {
this.qb.addSelect(arg[0]);
}
}
}
return this;
}
/**
* SELECT Sub Query
*
* @param entity Entity Target used in Sub Query.
* @param selection Selection Sub Query.
* @param selectionAlias Alias for Sub Query.
*/
public selectSubQuery<JR extends Object>(
entity: Constructor<P> | Function,
selectionAlias: string,
selection: (qb: QueryBuilder<JR, P>) => QueryBuilder<any>,
) {
const initQueryBuilder = new QueryBuilder<JR, P>(
entity,
selectionAlias,
{},
);
const queryBuilder = selection(initQueryBuilder);
this.qb.addSelect(`(${queryBuilder.qb.getQuery()})`, selectionAlias);
return this;
}
/**
* FROM query
*
* @param entity Entity Target
* @param aliasName Alias
* @param subQuery Query Builder
*/
public from<JR extends Object>(
entity: Constructor<P> | Function,
aliasName: string,
subQuery?: (qb: QueryBuilder<JR, P>) => QueryBuilder<any>,
) {
const initQueryBuilder = new QueryBuilder<JR, P>(
entity,
aliasName,
{},
);
if (subQuery) {
const queryBuilder = subQuery(initQueryBuilder);
this.qb.from(`(${queryBuilder.getQuery()})`, aliasName);
} else {
this.qb.from(entity, aliasName);
}
return this;
}
/**
* Create Sub Query.
*/
private createSubQuery(isMain: boolean = false) {
const queryBuilder: SelectQueryBuilder<T> = this.qb
.createQueryBuilder()
.subQuery()
if (isMain) {
queryBuilder.from(this.entityType, this.qb.alias);
}
const query = new QueryBuilder<T, T>(
this.entityType,
this.queryObject,
this.qb.alias,
);
query.qb = queryBuilder;
return query;
}
/**
* Sets whether the selection is DISTINCT.
* Remember set distinct after joining your relation.
*
* @param {boolean} distinct Is Distinct argument.
*/
public setDistinct(distinct?: boolean) {
this.qb.distinct(distinct ? distinct : true);
return this;
}
/**
* Sets the distinct on clause for Postgres.
* Remember set distinct after joining your relation.
*
* @param args Array of field to set distinct on them.
*/
public setDistinctOn(
...args: Array<((obj: P) => any) | string>
) {
if (!args.length) {
throw new Error(
`Property selector is required in ${this.setDistinctOn.name}`,
);
}
if (!isUniqueFields(args)) {
throw new Error(
`Fields have to be unique in ${this.setDistinctOn.name}`,
);
}
const props = [];
for (const propertySelector of args) {
const property = this.transformProperty(
propertySelector,
);
props.push(property);
}
this.qb.distinctOn(props);
return this;
}
/**
* Group By Query.
*
* @param args Array of field to set distinct on them.
*/
public groupBy(
...args: Array<((obj: P) => any) | string>
) {
if (!args.length) {
throw new Error(
`Property selector is required in ${this.groupBy.name}`,
);
}
if (!isUniqueFields(args)) {
throw new Error(
`Fields have to be unique in ${this.groupBy.name}`,
);
}
for (const propertySelector of args) {
const property = this.transformProperty(
propertySelector,
);
if (args.indexOf(propertySelector) === 0) {
this.qb.groupBy(property);
} else {
this.qb.addGroupBy(property);
}
}
return this;
}
/**
* Apply Where Condition
*
* @param whereQueryBuilderFn Condition Type.
* @param condition Condition value from exec method (optional).
*/
private applyWhere(whereQueryBuilderFn: 'AND' | 'OR', condition: any) {
if (whereQueryBuilderFn === 'AND') {
this.qb.andWhere(condition);
} else {
this.qb.orWhere(condition);
}
return this;
}
/**
* Compile Isolated Where Query.
*
* @param conditions Isolated Conditions.
* @param conditionFn Condition Type : AND | OR.
*/
private isolatedConditions(
conditions: (query: QueryBuilder<T, P>) => QueryBuilder<T, P>,
conditionFn: '' | 'AND' | 'OR',
) {
const query = this.createSubQuery(true);
query.joinHistory = this.joinHistory;
const queryBuilder = conditions(query);
const whereConditionParts = queryBuilder.queryBuilderParts;
let condition = '';
if (whereConditionParts.length) {
for (const queryPart of whereConditionParts) {
if (queryPart && queryPart.partAction[0]) {
const whereQueryBuilderFn = queryPart.partAction[0];
const whereCondition = queryPart.partParams[0];
if (whereConditionParts.indexOf(queryPart) === 0) {
condition += `${whereCondition}`;
} else {
condition += ` ${whereQueryBuilderFn} ${whereCondition}`;
}
}
}
}
this.queryBuilderParts.push(
new QueryBuilderPart([conditionFn], [
`(${condition})`,
]),
);
return this;
}
/**
* AND Where
*
* @param propertySelector Property Selector.
* @param whereFn Where Base to define its operator, condition type, etc into Query Builder Parts.
*/
public andWhere(
propertySelector: ((obj: P) => QueryComparableProp) | string,
whereFn: (queryCondition: QueryConditionService<T>, subQuery?: QueryBuilder<T, P>) => void,
) {
whereFn(
new QueryConditionService<T>(
this.transformProperty(propertySelector),
this.qb,
this.queryBuilderParts,
'AND',
),
this.createSubQuery(),
);
return this;
}
/**
* AND Isolated Where.
*
* @param and Isolated condition.
*/
public andWhereIsolated(and: (query: QueryBuilder<T, P>) => QueryBuilder<T, P>) {
return this.isolatedConditions(and, 'AND');
}
/**
* OR Where
*
* @param propertySelector Property Selector.
* @param whereFn Where Base to define its operator, condition type, etc into Query Builder Parts.
*/
public orWhere(
propertySelector: ((obj: P) => QueryComparableProp) | string,
whereFn: (queryCondition: QueryConditionService<T>, subQuery?: QueryBuilder<T, P>) => void,
) {
whereFn(
new QueryConditionService<T>(
this.transformProperty(propertySelector),
this.qb,
this.queryBuilderParts,
'OR',
),
this.createSubQuery(),
);
return this;
}
/**
* OR Isolated Where.
*
* @param or Isolated condition.
*/
public orWhereIsolated(or: (query: QueryBuilder<T, P>) => QueryBuilder<T, P>) {
return this.isolatedConditions(or, 'OR');
}
/**
* Apply Having
*
* @param havingQueryBuilderFn Condition Type.
* @param params Condition value from exec method (optional).
*/
private applyHaving(havingQueryBuilderFn: 'AND' | 'OR', condition: any) {
if (havingQueryBuilderFn === 'AND') {
this.qb.andHaving(condition);
} else {
this.qb.orHaving(condition);
}
return this;
}
/**
* AND Having
*
* @param propertySelector Property Selector.
* @param havingFn Where Base to define its operator, condition type, etc into Having Query Builder Parts.
*/
public andHaving(
propertySelector: ((obj: P) => QueryComparableProp) | string,
havingFn: (queryCondition: QueryConditionService<T>) => void,
) {
havingFn(
new QueryConditionService<T>(
this.transformProperty(propertySelector),
this.qb,
this.havingQueryBuilderParts,
'AND',
),
);
return this;
}
/**
* OR Having
*
* @param propertySelector Property Selector.
* @param havingFn Where Base to define its operator, condition type, etc into Having Query Builder Parts.
*/
public orHaving(
propertySelector: ((obj: P) => QueryComparableProp) | string,
havingFn: (queryCondition: QueryConditionService<T>) => void,
) {
havingFn(
new QueryConditionService<T>(
this.transformProperty(propertySelector),
this.qb,
this.havingQueryBuilderParts,
'OR',
),
);
return this;
}
/**
* Apply Join
*
* @param propertySelector Property Selector.
* @param joinAlias Alias for relation table.
* @param joinQueryBuilderFn Type of Join.
* @param joinCondition Condition when join.
*/
private applyJoin<JR extends Object>(
propertySelector: ((obj: P) => JR) | string,
joinAlias: string,
joinQueryBuilderFn: 'INNER' | 'LEFT',
joinCondition?: (qb: QueryBuilder<JR, P>) => QueryBuilder<JR, P>,
) {
const { property, relation } = this.transformPropertyAndRelation(
propertySelector,
);
this.joinHistory[property] = joinAlias;
if (joinCondition && typeof joinCondition === 'function') {
const entityMetadata = this.qb.connection.getMetadata(this.entityType);
const relationMetadata = entityMetadata.findRelationWithPropertyPath(
relation,
);
let etyMetadata = relationMetadata && relationMetadata.inverseEntityMetadata;
if (!relationMetadata) {
for (const etyMd of this.qb.connection.entityMetadatas) {
if (etyMd.name.toLowerCase() === relation) {
etyMetadata = etyMd;
}
}
}
const RelationEntityType = etyMetadata.target;
const queryBuilder = new QueryBuilder<JR, P>(
RelationEntityType,
joinAlias,
{},
);
queryBuilder.joinHistory = this.joinHistory;
const qb = joinCondition(queryBuilder);
let condition = '';
if (qb.queryBuilderParts) {
for (const part of qb.queryBuilderParts) {
const condWhere = part.partParams[0];
const whereQueryBuilderFn = part.partAction[0];
if (qb.queryBuilderParts.indexOf(part) === 0) {
condition += condWhere;
} else {
condition += ` ${whereQueryBuilderFn} ${condWhere}`;
}
}
}
if (condition) {
if (joinQueryBuilderFn === 'INNER') {
this.qb.innerJoin(property, joinAlias, condition);
} else {
this.qb.leftJoin(property, joinAlias, condition);
}
}
} else {
if (joinQueryBuilderFn === 'INNER') {
this.qb.innerJoin(property, joinAlias);
} else {
this.qb.leftJoin(property, joinAlias);
}
}
return this;
}
/**
* Inner Join
*
* @param propertySelector Property Selector.
* @param joinAlias Alias for relation table.
* @param joinCondition Condition when join.
*/
public innerJoin<JR extends Object>(
propertySelector: ((obj: P) => JR) | string,
joinAlias: string,
joinCondition?: (qb: QueryBuilder<JR, P>) => QueryBuilder<JR, P>,
) {
return this.applyJoin(propertySelector, joinAlias, 'INNER', joinCondition);
}
/**
* Left Join
*
* @param propertySelector Property Selector.
* @param joinAlias Alias for relation table.
* @param joinCondition Condition when join.
*/
public leftJoin<JR extends Object>(
propertySelector: ((obj: P) => JR) | string,
joinAlias: string,
joinCondition?: (qb: QueryBuilder<JR, P>) => QueryBuilder<JR, P>,
) {
return this.applyJoin(propertySelector, joinAlias, 'LEFT', joinCondition);
}
/**
* Apply Join
*
* @param propertySelector Property Selector.
* @param joinAlias Alias for relation table.
* @param joinQueryBuilderFn Type of Join.
* @param joinCondition Condition when join.
*/
private applyJoinSubQuery(
subQuery: SelectQueryBuilder<T>,
joinAlias: string,
joinQueryBuilderFn: 'INNER' | 'LEFT',
joinCondition?: (qb: QueryBuilder<T, P>) => QueryBuilder<T, P>,
) {
if (joinCondition && typeof joinCondition === 'function') {
const query = this.createSubQuery(true);
const qb = joinCondition(query);
let condition = '';
if (qb.queryBuilderParts) {
for (const part of qb.queryBuilderParts) {
const condWhere = part.partParams[0];
const whereQueryBuilderFn = part.partAction[0];
if (qb.queryBuilderParts.indexOf(part) === 0) {
condition += condWhere;
} else {
condition += ` ${whereQueryBuilderFn} ${condWhere}`;
}
}
}
if (condition) {
if (joinQueryBuilderFn === 'INNER') {
this.qb.innerJoin(sb => subQuery, joinAlias, condition);
} else {
this.qb.leftJoin(sb => subQuery, joinAlias, condition);
}
}
} else {
if (joinQueryBuilderFn === 'INNER') {
this.qb.innerJoin(sb => subQuery, joinAlias);
} else {
this.qb.leftJoin(sb => subQuery, joinAlias);
}
}
return this;
}
/**
* Inner Join Sub Query
*
* @param subQuery Property Selector.
* @param joinAlias Alias for relation table.
* @param joinCondition Condition when join.
*/
public innerJoinSubQuery<JR extends Object>(
subQuery: ((qb: QueryBuilder<T, P>) => QueryBuilder<T, P>),
joinAlias: string,
joinCondition?: (qb: QueryBuilder<JR, P>) => QueryBuilder<JR, P>,
) {
return this.applyJoinSubQuery(subQuery(this.createSubQuery()).qb, joinAlias, 'INNER', joinCondition);
}
/**
* Left Join Sub Query
*
* @param subQuery Property Selector.
* @param joinAlias Alias for relation table.
* @param joinCondition Condition when join.
*/
public leftJoinSubQuery<JR extends Object>(
subQuery: ((qb: QueryBuilder<T, P>) => QueryBuilder<T, P>),
joinAlias: string,
joinCondition?: (qb: QueryBuilder<JR, P>) => QueryBuilder<JR, P>,
) {
return this.applyJoinSubQuery(subQuery(this.createSubQuery()).qb, joinAlias, 'LEFT', joinCondition);
}
/**
* Apply Query Builder with Filter and Pagination.
*
* @param {any} query Query params.
* @param {string} alias Alias, ex. t1, optional.
* @return {*} {QueryBuilder}
*/
public applyFilterPagination(alias?: string) {
// pagination
this.applyPagination(alias);
// filter
this.applyFilterQueries();
return this;
}
/**
* Apply Query Builder with Pagination.
*
* @param {any} query Query params.
* @param {string} alias Alias, ex. t1, optional.
* @return {*} {QueryBuilder}
*/
private applyPagination(alias?: string) {
// sort
this.applyOrder(alias);
// paginate
this.applyPaginate();
return this;
}
/**
* Paginate method.
*
* @param {any} query Query params.
* @return {*} {QueryBuilder}
*/
private applyPaginate() {
let { page } = this;
if (page > 0) {
page -= 1;
}
this.qb.offset(page * this.limit);
this.qb.limit(this.limit);
return this;
}
/**
* Get Order Criteria.
*
* @param field Order field.
*/
private getOrderCriteria(field) {
if (field.startsWith('^')) {
return 'ASC';
} else if (field.startsWith('-')) {
return 'DESC';
} else {
throw new Error(`No order set for <${field}>. Prefix with one of these: [^, -]`);
}
}
/**
* Apply Query Builder with Order.
*
* @param {string} alias Alias, ex. t1, optional.
* @return {*} {QueryBuilder}
*/
private applyOrder(alias?: string) {
if (!this.queryObject['order']) return this;
const order = {};
const orderFields = this.queryObject['order'].split(',');
for (const field of orderFields) {
const orderCriteria = this.getOrderCriteria(field);
order[field.substr(1, field.length)] = orderCriteria;
}
if (order) {
const orderObject = mapKeys(order, (value, key) => {
return this.transformKey(key, alias);
});
const orders = Object.keys(orderObject);
for (const orderKey of orders) {
if (orders.indexOf(orderKey) === 0) {
this.qb.orderBy(orderKey, orderObject[orderKey]);
} else {
this.qb.addOrderBy(orderKey, orderObject[orderKey]);
}
}
}
return this;
}
/**
* Set Locking.
*
* @param type Type of Locking.
*/
public setLocking(
type:
"pessimistic_read" | "pessimistic_write"
| "dirty_read" | "pessimistic_partial_write"
| "pessimistic_write_or_fail" | "for_no_key_update"
| "optimistic",
version?: number,
) {
if (type !== 'optimistic') {
this.qb.setLock(type);
} else {
if (!version) {
throw new Error("Version is not provided for optimistic locking");
}
this.qb.setLock(type, version);
}
return this;
}
/**
* Apply Query Builder with Filter Query.
*
* @param {any} query Query params.
* @return {*} {QueryBuilder}
*/
public applyFilterQueries() {
const { fieldResolverMap, queryObject } = this;
if (fieldResolverMap) {
mapKeys(fieldResolverMap, (field, key) => {
if (queryObject[key]) {
const operator = FilterHelper.getOperator(key);
const value = queryObject[key];
switch (operator) {
case LookupFilter.CONTAINS:
this.qb.andWhere(`${field} LIKE '%${value}%'`);
break;
case LookupFilter.I_CONTAINS:
this.qb.andWhere(`${field} ILIKE '%${value}%'`);
break;
case LookupFilter.STARTS_WITH:
this.qb.andWhere(`${field} LIKE '${value}%'`);
break;
case LookupFilter.I_STARTS_WITH:
this.qb.andWhere(`${field} ILIKE '${value}%'`);
break;
case LookupFilter.ENDS_WITH:
this.qb.andWhere(`${field} LIKE '%${value}'`);
break;
case LookupFilter.I_ENDS_WITH:
this.qb.andWhere(`${field} ILIKE '%${value}'`);
break;
case LookupFilter.IS_NULL:
this.qb.andWhere(`${field} IS NULL`);
break;
case LookupFilter.LT:
this.qb.andWhere(`${field} < '${value}'`);
break;
case LookupFilter.LTE:
this.qb.andWhere(`${field} <= '${value}'`);
break;
case LookupFilter.GT:
this.qb.andWhere(`${field} > '${value}'`);
break;
case LookupFilter.GTE:
this.qb.andWhere(`${field} >= '${value}'`);
break;
case LookupFilter.IN:
this.qb.andWhere(`${field} IN ('${value}')`);
break;
case LookupFilter.BETWEEN:
this.qb.andWhere(`${field} BETWEEN '${value[0]}' AND '${value[1]}'`);
break;
case LookupFilter.NOT_EQUAL:
this.qb.andWhere(`${field} <> '${value}'`);
break;
default:
this.qb.andWhere(`${field} = '${value}'`);
break;
}
}
});
}
return this;
}
/**
* Compile Query Builder Parts
*
* @private
* @memberof QueryBuilder
*/
private compileQueryBuilderParts() {
// Apply Where Condition
for (const part of this.queryBuilderParts) {
if (part && part.partAction[0]) {
this.applyWhere(part.partAction[0], part.partParams[0]);
}
}
// Apply Having Condition
for (const part of this.havingQueryBuilderParts) {
if (part && part.partAction[0]) {
this.applyHaving(part.partAction[0], part.partParams[0]);
}
}
}
/**
* Get Raw SQL from Compiled QueryBuilder.
*
* @returns string
* @memberof QueryBuilder
*/
public getSql() {
this.compileQueryBuilderParts();
return this.qb.getSql();
}
/**
* Gets all raw results.
*
* @return {*} {Promise<any[]>}
*/
public exec(): Promise<any[]> {
this.compileQueryBuilderParts();
return this.qb.getRawMany();
}
/**
* Executes built SQL query and returns raw data stream.
*
* @param output Writeable data for output.
* @param transformer Transform data before write to the output.
*/
public async stream(output: any, transformer: (data: any) => string): Promise<ReadStream> {
this.compileQueryBuilderParts();
const stream = await this.qb.stream();
stream
.pipe(QueryBuilder.parser(transformer))
.pipe(output);
return stream;
}
/**
* Parser for transform data
*
* @param transformer Transformer.
*/
private static parser(transformer) {
const through = require('through');
const stream = through(
function(data) {
try {
const json = transformer(data);
stream.queue(json);
} catch (err) {
return stream.emit('error', err);
}
},
function() {
// reach the end.
stream.queue(null);
},
);
return stream;
}
/**
* Apply Aggregate Method - SUM, MAX, MIN, and AVG.
*
* @return {*} {Promise<number>}
*/
private async applyOneAggregate(
propertySelector: ((obj: P) => number) | string,
type: 'SUM' | 'AVG' | 'MAX' | 'MIN',
): Promise<number> {
const { transformedProp } = this.transformAggregateProp(
propertySelector,
type,
);
const { result } = await this.qb
.clone()
.select(`${type}(${transformedProp})`, 'result')
.groupBy()
.orderBy()
.limit(UNDEFINED_CONST)
.offset(UNDEFINED_CONST)
.getRawOne();