-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathBaseQuery.js
2165 lines (1931 loc) Β· 74.8 KB
/
BaseQuery.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
/* eslint-disable no-unused-vars,prefer-template */
const R = require('ramda');
const cronParser = require('cron-parser');
const moment = require('moment-timezone');
const inflection = require('inflection');
const UserError = require('../compiler/UserError');
const BaseMeasure = require('./BaseMeasure');
const BaseDimension = require('./BaseDimension');
const BaseSegment = require('./BaseSegment');
const BaseFilter = require('./BaseFilter');
const BaseGroupFilter = require('./BaseGroupFilter');
const BaseTimeDimension = require('./BaseTimeDimension');
const ParamAllocator = require('./ParamAllocator');
const PreAggregations = require('./PreAggregations');
const SqlParser = require('../parser/SqlParser');
const DEFAULT_PREAGGREGATIONS_SCHEMA = 'stb_pre_aggregations';
const standardGranularitiesParents = {
year: 'month',
week: 'day',
month: 'day',
day: 'hour',
hour: 'minute',
minute: 'second'
};
const SecondsDurations = {
week: 60 * 60 * 24 * 7,
day: 60 * 60 * 24,
hour: 60 * 60,
minute: 60,
second: 1
};
class BaseQuery {
constructor(compilers, options) {
this.compilers = compilers;
this.cubeEvaluator = compilers.cubeEvaluator;
this.joinGraph = compilers.joinGraph;
this.options = options || {};
this.orderHashToString = this.orderHashToString.bind(this);
this.defaultOrder = this.defaultOrder.bind(this);
this.initFromOptions();
this.granularityParentHierarchyCache = {};
}
extractDimensionsAndMeasures(filters = []) {
if (!filters) {
return [];
}
let allFilters = [];
filters.forEach(f => {
if (f.and) {
allFilters = allFilters.concat(this.extractDimensionsAndMeasures(f.and));
} else if (f.or) {
allFilters = allFilters.concat(this.extractDimensionsAndMeasures(f.or));
} else if (!f.dimension && !f.member) {
throw new UserError(`member attribute is required for filter ${JSON.stringify(f)}`);
} else if (this.cubeEvaluator.isMeasure(f.member || f.dimension)) {
allFilters.push({ measure: f.member || f.dimension });
} else {
allFilters.push({ dimension: f.member || f.dimension });
}
});
return allFilters;
}
extractFiltersAsTree(filters = []) {
if (!filters) {
return [];
}
return filters.map(f => {
if (f.and || f.or) {
let operator = 'or';
if (f.and) {
operator = 'and';
}
const data = this.extractDimensionsAndMeasures(f[operator]);
const dimension = data.filter(e => !!e.dimension).map(e => e.dimension);
const measure = data.filter(e => !!e.measure).map(e => e.measure);
if (dimension.length && !measure.length) {
return {
values: this.extractFiltersAsTree(f[operator]),
operator,
dimension: dimension[0],
measure: null,
};
}
if (!dimension.length && measure.length) {
return {
values: this.extractFiltersAsTree(f[operator]),
operator,
dimension: null,
measure: measure[0],
};
}
if (!dimension.length && !measure.length) {
return {
values: [],
operator,
dimension: null,
measure: null,
};
}
throw new UserError(`You cannot use dimension and measure in same condition: ${JSON.stringify(f)}`);
}
if (!f.dimension && !f.member) {
throw new UserError(`member attribute is required for filter ${JSON.stringify(f)}`);
}
if (this.cubeEvaluator.isMeasure(f.member || f.dimension)) {
return Object.assign({}, f, {
dimension: null,
measure: f.member || f.dimension
});
}
return Object.assign({}, f, {
measure: null,
dimension: f.member || f.dimension
});
});
}
initFromOptions() {
this.contextSymbols = Object.assign({ userContext: {} }, this.options.contextSymbols || {});
this.paramAllocator = this.options.paramAllocator || this.newParamAllocator();
this.compilerCache = this.compilers.compiler.compilerCache;
this.queryCache = this.compilerCache.getQueryCache({
measures: this.options.measures,
dimensions: this.options.dimensions,
timeDimensions: this.options.timeDimensions,
filters: this.options.filters,
segments: this.options.segments,
order: this.options.order,
contextSymbols: this.options.contextSymbols,
timezone: this.options.timezone,
limit: this.options.limit,
offset: this.options.offset,
rowLimit: this.options.rowLimit,
preAggregationsSchema: this.options.preAggregationsSchema,
className: this.constructor.name,
externalClassName: this.options.externalQueryClass && this.options.externalQueryClass.name,
preAggregationQuery: this.options.preAggregationQuery,
useOriginalSqlPreAggregationsInPreAggregation: this.options.useOriginalSqlPreAggregationsInPreAggregation,
cubeLatticeCache: this.options.cubeLatticeCache, // TODO too heavy for key
historyQueries: this.options.historyQueries, // TODO too heavy for key
ungrouped: this.options.ungrouped
});
this.timezone = this.options.timezone;
this.rowLimit = this.options.rowLimit;
this.offset = this.options.offset;
this.preAggregations = this.newPreAggregations();
this.measures = (this.options.measures || []).map(this.newMeasure.bind(this));
this.dimensions = (this.options.dimensions || []).map(this.newDimension.bind(this));
this.segments = (this.options.segments || []).map(this.newSegment.bind(this));
this.order = this.options.order || [];
const filters = this.extractFiltersAsTree(this.options.filters || []);
// measure_filter (the one extracted from filters parameter on measure and
// used in drill downs) should go to WHERE instead of HAVING
this.filters = filters.filter(f => f.dimension || f.operator === 'measure_filter' || f.operator === 'measureFilter').map(this.initFilter.bind(this));
this.measureFilters = filters.filter(f => f.measure && f.operator !== 'measure_filter' && f.operator !== 'measureFilter').map(this.initFilter.bind(this));
this.timeDimensions = (this.options.timeDimensions || []).map(dimension => {
if (!dimension.dimension) {
const join = this.joinGraph.buildJoin(this.collectCubeNames(true));
if (!join) {
return undefined;
}
// eslint-disable-next-line prefer-destructuring
dimension.dimension = this.cubeEvaluator.timeDimensionPathsForCube(join.root)[0];
if (!dimension.dimension) {
return undefined;
}
}
return dimension;
}).filter(R.identity).map(this.newTimeDimension.bind(this));
this.allFilters = this.timeDimensions.concat(this.segments).concat(this.filters);
this.join = this.joinGraph.buildJoin(this.allCubeNames);
this.cubeAliasPrefix = this.options.cubeAliasPrefix;
this.preAggregationsSchemaOption =
this.options.preAggregationsSchema != null ? this.options.preAggregationsSchema : DEFAULT_PREAGGREGATIONS_SCHEMA;
if (this.order.length === 0) {
this.order = this.defaultOrder();
}
this.externalQueryClass = this.options.externalQueryClass;
this.initUngrouped();
}
cacheValue(key, fn, { contextPropNames, inputProps, cache } = {}) {
const currentContext = this.safeEvaluateSymbolContext();
if (contextPropNames) {
const contextKey = {};
for (let i = 0; i < contextPropNames.length; i++) {
contextKey[contextPropNames[i]] = currentContext[contextPropNames[i]];
}
key = key.concat([JSON.stringify(contextKey)]);
}
const { value, resultProps } = (cache || this.compilerCache).cache(
key,
() => {
if (inputProps) {
return {
value: this.evaluateSymbolSqlWithContext(fn, inputProps),
resultProps: inputProps
};
}
return { value: fn() };
}
);
if (resultProps) {
Object.keys(resultProps).forEach(k => {
if (Array.isArray(currentContext[k])) {
// eslint-disable-next-line prefer-spread
currentContext[k].push.apply(currentContext[k], resultProps[k]);
} else if (currentContext[k]) {
Object.keys(currentContext[k]).forEach(innerKey => {
currentContext[k][innerKey] = resultProps[k][innerKey];
});
}
});
}
return value;
}
get allCubeNames() {
if (!this.collectedCubeNames) {
this.collectedCubeNames = this.collectCubeNames();
}
return this.collectedCubeNames;
}
get dataSource() {
const dataSources = R.uniq(this.allCubeNames.map(c => this.cubeDataSource(c)));
if (dataSources.length > 1) {
throw new UserError(`Joins across data sources aren't supported in community edition. Found data sources: ${dataSources.join(', ')}`);
}
return dataSources[0];
}
cubeDataSource(cube) {
return this.cubeEvaluator.cubeFromPath(cube).dataSource || 'default';
}
get aliasNameToMember() {
return R.fromPairs(
this.measures.map(m => [m.unescapedAliasName(), m.measure]).concat(
this.dimensions.map(m => [m.unescapedAliasName(), m.dimension])
).concat(
this.timeDimensions.filter(m => !!m.granularity)
.map(m => [m.unescapedAliasName(), `${m.dimension}.${m.granularity}`])
)
);
}
initUngrouped() {
this.ungrouped = this.options.ungrouped;
if (this.ungrouped) {
if (!this.options.allowUngroupedWithoutPrimaryKey) {
const cubes = R.uniq([this.join.root].concat(this.join.joins.map(j => j.originalTo)));
const primaryKeyNames = cubes.map(c => this.primaryKeyName(c));
const missingPrimaryKeys = primaryKeyNames.filter(key => !this.dimensions.find(d => d.dimension === key));
if (missingPrimaryKeys.length) {
throw new UserError(`Ungrouped query requires primary keys to be present in dimensions: ${missingPrimaryKeys.map(k => `'${k}'`).join(', ')}. Pass allowUngroupedWithoutPrimaryKey option to disable this check.`);
}
}
if (this.measures.length) {
throw new UserError('Measures aren\'t allowed in ungrouped query');
}
if (this.measureFilters.length) {
throw new UserError('Measure filters aren\'t allowed in ungrouped query');
}
}
}
get subQueryDimensions() {
// eslint-disable-next-line no-underscore-dangle
if (!this._subQueryDimensions) {
// eslint-disable-next-line no-underscore-dangle
this._subQueryDimensions = this.collectFromMembers(
false,
this.collectSubQueryDimensionsFor.bind(this),
'collectSubQueryDimensionsFor'
);
}
// eslint-disable-next-line no-underscore-dangle
return this._subQueryDimensions;
}
get asSyntaxTable() {
return 'AS';
}
get asSyntaxJoin() {
return 'AS';
}
defaultOrder() {
if (this.options.preAggregationQuery) {
return [];
}
const res = [];
const granularity = this.timeDimensions.find(d => d.granularity);
if (granularity) {
res.push({
id: granularity.dimension,
desc: false,
});
} else if (this.measures.length > 0 && this.dimensions.length > 0) {
const firstMeasure = this.measures[0];
let id = firstMeasure.measure;
if (firstMeasure.expressionName) {
id = firstMeasure.expressionName;
}
res.push({ id, desc: true });
} else if (this.dimensions.length > 0) {
res.push({
id: this.dimensions[0].dimension,
desc: false,
});
}
return res;
}
newMeasure(measurePath) {
return new BaseMeasure(this, measurePath);
}
newDimension(dimensionPath) {
return new BaseDimension(this, dimensionPath);
}
newSegment(segmentPath) {
return new BaseSegment(this, segmentPath);
}
initFilter(filter) {
if (filter.operator === 'and' || filter.operator === 'or') {
filter.values = filter.values.map(this.initFilter.bind(this));
return this.newGroupFilter(filter);
}
return this.newFilter(filter);
}
newFilter(filter) {
return new BaseFilter(this, filter);
}
newGroupFilter(filter) {
return new BaseGroupFilter(this, filter);
}
newTimeDimension(timeDimension) {
return new BaseTimeDimension(this, timeDimension);
}
newParamAllocator() {
return new ParamAllocator();
}
newPreAggregations() {
return new PreAggregations(this, this.options.historyQueries || [], this.options.cubeLatticeCache);
}
escapeColumnName(name) {
return `"${name}"`;
}
buildParamAnnotatedSql() {
if (!this.options.preAggregationQuery && !this.ungrouped) {
const preAggregationForQuery = this.preAggregations.findPreAggregationForQuery();
if (preAggregationForQuery) {
return this.preAggregations.rollupPreAggregation(preAggregationForQuery);
}
}
return this.fullKeyQueryAggregate();
}
externalPreAggregationQuery() {
if (!this.options.preAggregationQuery && this.externalQueryClass) {
const preAggregationForQuery = this.preAggregations.findPreAggregationForQuery();
if (preAggregationForQuery && preAggregationForQuery.preAggregation.external) {
return true;
}
const preAggregationsDescription = this.preAggregations.preAggregationsDescription();
return preAggregationsDescription.length && R.all((p) => p.external, preAggregationsDescription);
}
return false;
}
buildSqlAndParams() {
if (!this.options.preAggregationQuery && this.externalQueryClass) {
if (this.externalPreAggregationQuery()) { // TODO performance
return this.externalQuery().buildSqlAndParams();
}
}
return this.compilers.compiler.withQuery(
this,
() => this.cacheValue(
['buildSqlAndParams'],
() => this.paramAllocator.buildSqlAndParams(this.buildParamAnnotatedSql()),
{ cache: this.queryCache }
)
);
}
externalQuery() {
const ExternalQuery = this.externalQueryClass;
return new ExternalQuery(this.compilers, {
...this.options,
externalQueryClass: null
});
}
runningTotalDateJoinCondition() {
return this.timeDimensions.map(
d => [
d,
(dateFrom, dateTo, dateField, dimensionDateFrom, dimensionDateTo) => `${dateField} >= ${dimensionDateFrom} AND ${dateField} <= ${dateTo}`
]
);
}
rollingWindowDateJoinCondition(trailingInterval, leadingInterval, offset) {
offset = offset || 'end';
return this.timeDimensions.map(
d => [d, (dateFrom, dateTo, dateField, dimensionDateFrom, dimensionDateTo, isFromStartToEnd) => {
// dateFrom based window
const conditions = [];
if (trailingInterval !== 'unbounded') {
const startDate = isFromStartToEnd || offset === 'start' ? dateFrom : dateTo;
const trailingStart = trailingInterval ? this.subtractInterval(startDate, trailingInterval) : startDate;
const sign = offset === 'start' ? '>=' : '>';
conditions.push(`${dateField} ${sign} ${trailingStart}`);
}
if (leadingInterval !== 'unbounded') {
const endDate = isFromStartToEnd || offset === 'end' ? dateTo : dateFrom;
const leadingEnd = leadingInterval ? this.addInterval(endDate, leadingInterval) : endDate;
const sign = offset === 'end' ? '<=' : '<';
conditions.push(`${dateField} ${sign} ${leadingEnd}`);
}
return conditions.length ? conditions.join(' AND ') : '1 = 1';
}]
);
}
subtractInterval(date, interval) {
return `${date} - interval '${interval}'`;
}
addInterval(date, interval) {
return `${date} + interval '${interval}'`;
}
addTimestampInterval(timestamp, interval) {
return this.addInterval(timestamp, interval);
}
subtractTimestampInterval(timestamp, interval) {
return this.subtractInterval(timestamp, interval);
}
cumulativeMeasures() {
return this.measures.filter(m => m.isCumulative());
}
isRolling() {
return !!this.measures.find(m => m.isRolling()); // TODO
}
simpleQuery() {
// eslint-disable-next-line prefer-template
const inlineWhereConditions = [];
const commonQuery = this.rewriteInlineWhere(() => this.commonQuery(), inlineWhereConditions);
return `${commonQuery} ${this.baseWhere(this.allFilters.concat(inlineWhereConditions))}` +
this.groupByClause() +
this.baseHaving(this.measureFilters) +
this.orderBy() +
this.groupByDimensionLimit();
}
fullKeyQueryAggregate() {
const { multipliedMeasures, regularMeasures, cumulativeMeasures } = this.fullKeyQueryAggregateMeasures();
if (!multipliedMeasures.length && !cumulativeMeasures.length) {
return this.simpleQuery();
}
const renderedReferenceContext = {
renderedReference: R.pipe(
R.map(m => [m.measure, m.aliasName()]),
R.fromPairs
)(multipliedMeasures.concat(regularMeasures).concat(cumulativeMeasures.map(([multiplied, measure]) => measure)))
};
let toJoin =
(regularMeasures.length ? [
this.withCubeAliasPrefix('main', () => this.regularMeasuresSubQuery(regularMeasures))
] : [])
.concat(
R.pipe(
R.groupBy(m => m.cube().name),
R.toPairs,
R.map(
([keyCubeName, measures]) => this.withCubeAliasPrefix(`${keyCubeName}_key`, () => this.aggregateSubQuery(keyCubeName, measures))
)
)(multipliedMeasures)
).concat(
R.map(
([multiplied, measure]) => this.withCubeAliasPrefix(
`${this.aliasName(measure.measure.replace('.', '_'))}_cumulative`,
() => this.overTimeSeriesQuery(
multiplied ?
(measures, filters) => this.aggregateSubQuery(measures[0].cube().name, measures, filters) :
this.regularMeasuresSubQuery.bind(this),
measure
)
)
)(cumulativeMeasures)
);
// Move regular measures to multiplied ones if there're same cubes to calculate.
// Most of the times it'll be much faster to calculate as there will be only single scan per cube
if (
regularMeasures.length &&
multipliedMeasures.length &&
!cumulativeMeasures.length
) {
const cubeNames = R.pipe(R.map(m => m.cube().name), R.uniq, R.sortBy(R.identity));
const regularMeasuresCubes = cubeNames(regularMeasures);
const multipliedMeasuresCubes = cubeNames(multipliedMeasures);
if (R.equals(regularMeasuresCubes, multipliedMeasuresCubes)) {
toJoin = R.pipe(
R.groupBy(m => m.cube().name),
R.toPairs,
R.map(
([keyCubeName, measures]) => this.withCubeAliasPrefix(`${keyCubeName}_key`, () => this.aggregateSubQuery(keyCubeName, measures))
)
)(regularMeasures.concat(multipliedMeasures));
}
}
const join = R.drop(1, toJoin)
.map(
(q, i) => (this.dimensionAliasNames().length ?
`INNER JOIN (${q}) as q_${i + 1} ON ${this.dimensionsJoinCondition(`q_${i}`, `q_${i + 1}`)}` :
`, (${q}) as q_${i + 1}`)
).join('\n');
const columnsToSelect = this.evaluateSymbolSqlWithContext(
() => this.dimensionColumns('q_0').concat(this.measures.map(m => m.selectColumns())).join(', '),
renderedReferenceContext
);
const havingFilters = this.evaluateSymbolSqlWithContext(
() => this.baseWhere(this.measureFilters),
renderedReferenceContext
);
return `SELECT ${this.topLimit()}${columnsToSelect} FROM (${toJoin[0]}) as q_0 ${join}${havingFilters}${this.orderBy()}${this.groupByDimensionLimit()}`;
}
fullKeyQueryAggregateMeasures() {
const measureToHierarchy = this.collectRootMeasureToHieararchy();
const measuresToRender = (multiplied, cumulative) => R.pipe(
R.values,
R.flatten,
R.filter(
m => m.multiplied === multiplied && this.newMeasure(m.measure).isCumulative() === cumulative
),
R.map(m => m.measure),
R.uniq,
R.map(m => this.newMeasure(m))
);
const multipliedMeasures = measuresToRender(true, false)(measureToHierarchy);
const regularMeasures = measuresToRender(false, false)(measureToHierarchy);
const cumulativeMeasures =
R.pipe(
R.map(multiplied => R.xprod([multiplied], measuresToRender(multiplied, true)(measureToHierarchy))),
R.unnest
)([false, true]);
return { multipliedMeasures, regularMeasures, cumulativeMeasures };
}
dimensionsJoinCondition(leftAlias, rightAlias) {
const dimensionAliases = this.dimensionAliasNames();
if (!dimensionAliases.length) {
return '1 = 1';
}
return dimensionAliases
.map(alias => `(${leftAlias}.${alias} = ${rightAlias}.${alias} OR (${leftAlias}.${alias} IS NULL AND ${rightAlias}.${alias} IS NULL))`)
.join(' AND ');
}
baseWhere(filters) {
const filterClause = filters.map(t => t.filterToWhere()).filter(R.identity).map(f => `(${f})`);
return filterClause.length ? ` WHERE ${filterClause.join(' AND ')}` : '';
}
baseHaving(filters) {
const filterClause = filters.map(t => t.filterToWhere()).filter(R.identity).map(f => `(${f})`);
return filterClause.length ? ` HAVING ${filterClause.join(' AND ')}` : '';
}
timeStampInClientTz(dateParam) {
return this.convertTz(dateParam);
}
granularityHierarchies() {
return R.fromPairs(Object.keys(standardGranularitiesParents).map(k => [k, this.granularityParentHierarchy(k)]));
}
granularityParent(granularity) {
return standardGranularitiesParents[granularity];
}
granularityParentHierarchy(granularity) {
if (!this.granularityParentHierarchyCache[granularity]) {
this.granularityParentHierarchyCache[granularity] = [granularity].concat(
this.granularityParent(granularity) ? this.granularityParentHierarchy(this.granularityParent(granularity)) : []
);
}
return this.granularityParentHierarchyCache[granularity];
}
minGranularity(granularityA, granularityB) {
if (!granularityA) {
return granularityB;
}
if (!granularityB) {
return granularityA;
}
if (granularityA === granularityB) {
return granularityA;
}
const aHierarchy = R.reverse(this.granularityParentHierarchy(granularityA));
const bHierarchy = R.reverse(this.granularityParentHierarchy(granularityB));
let lastIndex = Math.max(
aHierarchy.findIndex((g, i) => g !== bHierarchy[i]),
bHierarchy.findIndex((g, i) => g !== aHierarchy[i])
);
if (lastIndex === -1 && aHierarchy.length === bHierarchy.length) {
lastIndex = aHierarchy.length - 1;
}
if (lastIndex <= 0) {
throw new Error(`Can't find common parent for '${granularityA}' and '${granularityB}'`);
}
return aHierarchy[lastIndex - 1];
}
overTimeSeriesQuery(baseQueryFn, cumulativeMeasure) {
const dateJoinCondition = cumulativeMeasure.dateJoinCondition();
const cumulativeMeasures = [cumulativeMeasure];
const dateFromStartToEndConditionSql =
(isFromStartToEnd) => dateJoinCondition.map(
// TODO these weird conversions to be strict typed for big query.
// TODO Consider adding strict definitions of local and UTC time type
([d, f]) => ({
filterToWhere: () => {
const timeSeries = d.timeSeries();
return f(
isFromStartToEnd ?
this.dateTimeCast(this.paramAllocator.allocateParam(timeSeries[0][0])) :
`${this.timeStampInClientTz(d.dateFromParam())}`,
isFromStartToEnd ?
this.dateTimeCast(this.paramAllocator.allocateParam(timeSeries[timeSeries.length - 1][1])) :
`${this.timeStampInClientTz(d.dateToParam())}`,
`${d.convertedToTz()}`,
`${this.timeStampInClientTz(d.dateFromParam())}`,
`${this.timeStampInClientTz(d.dateToParam())}`,
isFromStartToEnd
);
}
})
);
if (!this.timeDimensions.find(d => d.granularity)) {
const filters = this.segments.concat(this.filters).concat(dateFromStartToEndConditionSql(false));
return baseQueryFn(cumulativeMeasures, filters, false);
}
const dateSeriesSql = this.timeDimensions.map(d => this.dateSeriesSql(d)).join(', ');
const filters = this.segments.concat(this.filters).concat(dateFromStartToEndConditionSql(true));
const baseQuery = this.groupedUngroupedSelect(
() => baseQueryFn(cumulativeMeasures, filters),
cumulativeMeasure.shouldUngroupForCumulative(),
!cumulativeMeasure.shouldUngroupForCumulative() && this.minGranularity(
cumulativeMeasure.windowGranularity(), this.timeDimensions.find(d => d.granularity).granularity
) || undefined
);
const baseQueryAlias = this.cubeAlias('base');
const dateJoinConditionSql =
dateJoinCondition.map(
([d, f]) => f(
`${d.dateSeriesAliasName()}.${this.escapeColumnName('date_from')}`,
`${d.dateSeriesAliasName()}.${this.escapeColumnName('date_to')}`,
`${baseQueryAlias}.${d.aliasName()}`,
`'${d.dateFromFormatted()}'`,
`'${d.dateToFormatted()}'`
)
).join(' AND ');
return this.overTimeSeriesSelect(
cumulativeMeasures,
dateSeriesSql,
baseQuery,
dateJoinConditionSql,
baseQueryAlias
);
}
overTimeSeriesSelect(cumulativeMeasures, dateSeriesSql, baseQuery, dateJoinConditionSql, baseQueryAlias) {
const forSelect = this.dateSeriesSelect().concat(
this.dimensions.concat(cumulativeMeasures).map(s => s.cumulativeSelectColumns())
).filter(c => !!c).join(', ');
return `SELECT ${forSelect} FROM ${dateSeriesSql}` +
` LEFT JOIN (${baseQuery}) ${this.asSyntaxJoin} ${baseQueryAlias} ON ${dateJoinConditionSql}` +
this.groupByClause();
}
dateSeriesSelect() {
return this.timeDimensions.map(d => d.dateSeriesSelectColumn());
}
dateSeriesSql(timeDimension) {
return `(${this.seriesSql(timeDimension)}) ${this.asSyntaxTable} ${timeDimension.dateSeriesAliasName()}`;
}
seriesSql(timeDimension) {
const values = timeDimension.timeSeries().map(
([from, to]) => `('${from}', '${to}')`
);
return `SELECT ${this.dateTimeCast('date_from')}, ${this.dateTimeCast('date_to')} FROM (VALUES ${values}) ${this.asSyntaxTable} dates (date_from, date_to)`;
}
timeStampParam(timeDimension) {
return timeDimension.dateFieldType() === 'string' ? '?' : this.timeStampCast('?');
}
timeRangeFilter(dimensionSql, fromTimeStampParam, toTimeStampParam) {
return `${dimensionSql} >= ${fromTimeStampParam} AND ${dimensionSql} <= ${toTimeStampParam}`;
}
timeNotInRangeFilter(dimensionSql, fromTimeStampParam, toTimeStampParam) {
return `${dimensionSql} < ${fromTimeStampParam} OR ${dimensionSql} > ${toTimeStampParam}`;
}
beforeDateFilter(dimensionSql, timeStampParam) {
return `${dimensionSql} < ${timeStampParam}`;
}
afterDateFilter(dimensionSql, timeStampParam) {
return `${dimensionSql} > ${timeStampParam}`;
}
timeStampCast(value) {
return `${value}::timestamptz`;
}
dateTimeCast(value) {
return `${value}::timestamp`;
}
commonQuery() {
return `SELECT${this.topLimit()}
${this.baseSelect()}
FROM
${this.query()}`;
}
collectRootMeasureToHieararchy() {
const notAddedMeasureFilters = R.flatten(this.measureFilters.map(f => f.getMembers()))
.filter(f => R.none(m => m.measure === f.measure, this.measures));
return R.fromPairs(this.measures.concat(notAddedMeasureFilters).map(m => {
const collectedMeasures = this.collectFrom(
[m],
this.collectMultipliedMeasures.bind(this),
'collectMultipliedMeasures',
this.queryCache
);
if (m.expressionName && !collectedMeasures.length) {
throw new UserError(`Subquery dimension ${m.expressionName} should reference at least one measure`);
}
return [m.measure, collectedMeasures];
}));
}
query() {
return this.joinQuery(this.join, this.collectFromMembers(
false,
this.collectSubQueryDimensionsFor.bind(this),
'collectSubQueryDimensionsFor'
));
}
rewriteInlineCubeSql(cube, isLeftJoinCondition) {
const sql = this.cubeSql(cube);
const cubeAlias = this.cubeAlias(cube);
// TODO params independent sql caching
const parser = this.queryCache.cache(['SqlParser', sql], () => new SqlParser(sql));
if (
this.cubeEvaluator.cubeFromPath(cube).rewriteQueries &&
parser.isSimpleAsteriskQuery()
) {
const conditions = parser.extractWhereConditions(cubeAlias);
if (!isLeftJoinCondition && this.safeEvaluateSymbolContext().inlineWhereConditions) {
this.safeEvaluateSymbolContext().inlineWhereConditions.push({ filterToWhere: () => conditions });
}
return [parser.extractTableFrom(), cubeAlias, conditions];
} else {
return [sql, cubeAlias];
}
}
joinQuery(join, subQueryDimensions) {
const joins = join.joins.map(
j => {
const [cubeSql, cubeAlias, conditions] = this.rewriteInlineCubeSql(j.originalTo, true);
return `LEFT JOIN ${cubeSql} ${this.asSyntaxJoin} ${cubeAlias}
ON ${this.evaluateSql(j.originalFrom, j.join.sql)}${conditions ? ` AND (${conditions})` : ''}`;
}
).concat(subQueryDimensions.map(d => this.subQueryJoin(d)));
const [cubeSql, cubeAlias] = this.rewriteInlineCubeSql(join.root);
return `${cubeSql} ${this.asSyntaxJoin} ${cubeAlias}\n${joins.join('\n')}`;
}
subQueryJoin(dimension) {
const { prefix, subQuery, cubeName } = this.subQueryDescription(dimension);
const primaryKey = this.newDimension(this.primaryKeyName(cubeName));
const subQueryAlias = this.escapeColumnName(this.aliasName(prefix));
const { collectOriginalSqlPreAggregations } = this.safeEvaluateSymbolContext();
const sql = subQuery.evaluateSymbolSqlWithContext(() => subQuery.buildParamAnnotatedSql(), {
collectOriginalSqlPreAggregations
});
return `LEFT JOIN (${sql}) ${this.asSyntaxJoin} ${subQueryAlias}
ON ${subQueryAlias}.${primaryKey.aliasName()} = ${this.primaryKeySql(this.cubeEvaluator.primaryKeys[cubeName], cubeName)}`;
}
get filtersWithoutSubQueries() {
if (!this.filtersWithoutSubQueriesValue) {
this.filtersWithoutSubQueriesValue = this.allFilters.filter(
f => this.collectFrom([f], this.collectSubQueryDimensionsFor.bind(this), 'collectSubQueryDimensionsFor').length === 0
);
}
return this.filtersWithoutSubQueriesValue;
}
subQueryDescription(dimension) {
const symbol = this.cubeEvaluator.dimensionByPath(dimension);
const [cubeName, name] = this.cubeEvaluator.parsePath('dimensions', dimension);
const prefix = this.subQueryName(cubeName, name);
let filters;
let segments;
let timeDimensions;
if (symbol.propagateFiltersToSubQuery) {
filters = this.filtersWithoutSubQueries.filter(
f => f instanceof BaseFilter && !(f instanceof BaseTimeDimension)
).map(f => ({
dimension: f.dimension,
operator: f.operator,
values: f.values
}));
timeDimensions = this.filtersWithoutSubQueries.filter(
f => f instanceof BaseTimeDimension
).map(f => ({
dimension: f.dimension,
dateRange: f.dateRange
}));
segments = this.filtersWithoutSubQueries.filter(
f => f instanceof BaseSegment
).map(f => f.segment);
}
const subQuery = this.newSubQuery({
cubeAliasPrefix: prefix,
rowLimit: null,
measures: [{
expression: symbol.sql,
cubeName,
name
}],
dimensions: [this.primaryKeyName(cubeName)],
filters,
segments,
timeDimensions
});
return { prefix, subQuery, cubeName };
}
subQueryName(cubeName, name) {
return `${cubeName}_${name}_subquery`;
}
regularMeasuresSubQuery(measures, filters) {
filters = filters || this.allFilters;
const inlineWhereConditions = [];
const query = this.rewriteInlineWhere(() => this.joinQuery(
this.join,
this.collectFrom(
this.dimensionsForSelect().concat(measures).concat(this.allFilters),
this.collectSubQueryDimensionsFor.bind(this),
'collectSubQueryDimensionsFor'
)
), inlineWhereConditions);
return `SELECT ${this.selectAllDimensionsAndMeasures(measures)} FROM ${
query
} ${this.baseWhere(filters.concat(inlineWhereConditions))}` +
(!this.safeEvaluateSymbolContext().ungrouped && this.groupByClause() || '');
}
aggregateSubQuery(keyCubeName, measures, filters) {
filters = filters || this.allFilters;
const primaryKeyDimension = this.newDimension(this.primaryKeyName(keyCubeName));
const shouldBuildJoinForMeasureSelect = this.checkShouldBuildJoinForMeasureSelect(measures, keyCubeName);
let keyCubeSql;
let keyCubeAlias;
let keyCubeInlineLeftJoinConditions;
const measureSubQueryDimensions = this.collectFrom(
measures,
this.collectSubQueryDimensionsFor.bind(this),
'collectSubQueryDimensionsFor'
);
if (shouldBuildJoinForMeasureSelect) {
const cubes = this.collectFrom(measures, this.collectCubeNamesFor.bind(this), 'collectCubeNamesFor');
const measuresJoin = this.joinGraph.buildJoin(cubes);
if (measuresJoin.multiplicationFactor[keyCubeName]) {
throw new UserError(
`'${measures.map(m => m.measure).join(', ')}' reference cubes that lead to row multiplication.`
);
}
keyCubeSql = `(${this.aggregateSubQueryMeasureJoin(keyCubeName, measures, measuresJoin, primaryKeyDimension, measureSubQueryDimensions)})`;
keyCubeAlias = this.cubeAlias(keyCubeName);
} else {
[keyCubeSql, keyCubeAlias, keyCubeInlineLeftJoinConditions] = this.rewriteInlineCubeSql(keyCubeName);
}
const measureSelectFn = () => measures.map(m => m.selectColumns());
const selectedMeasures = shouldBuildJoinForMeasureSelect ? this.evaluateSymbolSqlWithContext(
measureSelectFn,
{
ungroupedAliases: R.fromPairs(measures.map(m => [m.measure, m.aliasName()]))
}
) : measureSelectFn();
const columnsForSelect =
this.dimensionColumns(this.escapeColumnName('keys')).concat(selectedMeasures).filter(s => !!s).join(', ');
const keyInMeasureSelect = shouldBuildJoinForMeasureSelect ?
`${this.cubeAlias(keyCubeName)}.${primaryKeyDimension.aliasName()}` :
this.dimensionSql(primaryKeyDimension);
const subQueryJoins =
shouldBuildJoinForMeasureSelect ? '' : measureSubQueryDimensions.map(d => this.subQueryJoin(d)).join('\n');
return `SELECT ${columnsForSelect} FROM (${this.keysQuery(primaryKeyDimension, filters)}) ${this.asSyntaxTable} ${this.escapeColumnName('keys')} ` +
`LEFT OUTER JOIN ${keyCubeSql} ${this.asSyntaxJoin} ${keyCubeAlias} ON
${this.escapeColumnName('keys')}.${primaryKeyDimension.aliasName()} = ${keyInMeasureSelect}
${keyCubeInlineLeftJoinConditions ? ` AND (${keyCubeInlineLeftJoinConditions})` : ''}` +
subQueryJoins +
(!this.safeEvaluateSymbolContext().ungrouped && this.groupByClause() || '');
}
checkShouldBuildJoinForMeasureSelect(measures, keyCubeName) {
return measures.map(measure => {
const cubeNames = this.collectFrom([measure], this.collectCubeNamesFor.bind(this), 'collectCubeNamesFor');
if (R.any(cubeName => keyCubeName !== cubeName, cubeNames)) {
const measuresJoin = this.joinGraph.buildJoin(cubeNames);
if (measuresJoin.multiplicationFactor[keyCubeName]) {
throw new UserError(
`'${measure.measure}' references cubes that lead to row multiplication. Please rewrite it using sub query.`
);
}
return true;
}
return false;
}).reduce((a, b) => a || b);
}