forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.c
More file actions
2122 lines (1908 loc) · 58.5 KB
/
Copy pathcommon.c
File metadata and controls
2122 lines (1908 loc) · 58.5 KB
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
/*
* This file and its contents are licensed under the Timescale License.
* Please see the included NOTICE for copyright information and
* LICENSE-TIMESCALE for a copy of the license.
*/
#include "common.h"
#include <utils/acl.h>
#include <utils/date.h>
#include <utils/timestamp.h>
#include <utils/uuid.h>
#include "extension.h"
#include "guc.h"
static Const *check_time_bucket_argument(Node *arg, char *position, bool process_checks,
StringInfo msg, bool for_rewrites);
static void process_additional_timebucket_parameter(ContinuousAggBucketFunction *bf, Const *arg,
bool *custom_origin);
static void process_timebucket_parameters(FuncExpr *fe, ContinuousAggBucketFunction *bf,
bool process_checks, bool is_cagg_create,
AttrNumber htpartcolno, StringInfo msg,
bool for_rewrites);
static void caggtimebucket_validate(ContinuousAggTimeBucketInfo *tbinfo, List *groupClause,
List *targetList, List *rtable, bool is_cagg_create);
static Datum get_bucket_width_datum(ContinuousAggTimeBucketInfo bucket_info);
static int64 get_bucket_width(ContinuousAggTimeBucketInfo bucket_info);
static FuncExpr *build_conversion_call(Oid type, FuncExpr *boundary);
static FuncExpr *build_boundary_call(int32 ht_id, Oid type);
static Const *cagg_boundary_make_lower_bound(Oid type);
static Node *build_union_query_quals(int32 ht_id, Oid partcoltype, Oid opno, int varno,
AttrNumber attno);
static RangeTblEntry *makeRangeTblEntry(Query *subquery, const char *aliasname);
#define INTERNAL_TO_DATE_FUNCTION "to_date"
#define INTERNAL_TO_TSTZ_FUNCTION "to_timestamp"
#define INTERNAL_TO_TS_FUNCTION "to_timestamp_without_timezone"
#define BOUNDARY_FUNCTION "cagg_watermark"
static Const *
check_time_bucket_argument(Node *arg, char *position, bool process_checks, StringInfo msg,
bool for_rewrites)
{
if (IsA(arg, NamedArgExpr))
{
arg = (Node *) castNode(NamedArgExpr, arg)->arg;
}
Node *expr = eval_const_expressions(NULL, arg);
if (process_checks && !IsA(expr, Const))
{
if (!for_rewrites)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("only immutable expressions allowed in time bucket function"),
errhint("Use an immutable expression as %s argument to the time bucket "
"function.",
position)));
}
else if (msg)
{
appendStringInfo(msg,
"non-immutable expression as %s argument to the time bucket function",
position);
}
return NULL;
}
return castNode(Const, expr);
}
/*
* Initialize caggtimebucket.
*/
void
caggtimebucketinfo_init(ContinuousAggTimeBucketInfo *src, int32 hypertable_id, Oid hypertable_oid,
AttrNumber hypertable_partition_colno, Oid hypertable_partition_coltype,
int64 hypertable_partition_col_interval, int32 parent_mat_hypertable_id)
{
src->htid = hypertable_id;
src->parent_mat_hypertable_id = parent_mat_hypertable_id;
src->htoid = hypertable_oid;
src->htoidparent = InvalidOid;
src->htpartcolno = hypertable_partition_colno;
src->htpartcoltype = hypertable_partition_coltype;
src->htpartcol_interval_len = hypertable_partition_col_interval;
/* Initialize bucket function data structure */
src->bf = palloc0(sizeof(ContinuousAggBucketFunction));
src->bf->bucket_function = InvalidOid;
src->bf->bucket_width_type = InvalidOid;
/* Time based buckets */
src->bf->bucket_time_width = NULL; /* not specified by default */
src->bf->bucket_time_timezone = NULL; /* not specified by default */
src->bf->bucket_time_offset = NULL; /* not specified by default */
TIMESTAMP_NOBEGIN(src->bf->bucket_time_origin); /* origin is not specified by default */
/* Integer based buckets */
src->bf->bucket_integer_width = 0; /* invalid value */
src->bf->bucket_integer_offset = 0; /* invalid value */
}
/*
* Check if the supplied OID belongs to a valid bucket function
* for continuous aggregates.
*/
bool
function_allowed_in_cagg_definition(Oid funcid)
{
FuncInfo *finfo = ts_func_cache_get_bucketing_func(funcid);
if (finfo == NULL)
{
return false;
}
if (finfo->allowed_in_cagg_definition)
{
return true;
}
return false;
}
/*
* When a view is created (StoreViewQuery), 2 dummy rtable entries corresponding to "old" and
* "new" are prepended to the rtable list. We remove these and adjust the varnos to recreate
* the user or direct view query.
*/
void
RemoveRangeTableEntries(Query *query)
{
#if PG16_LT
List *rtable = query->rtable;
Assert(list_length(rtable) >= 3);
rtable = list_delete_first(rtable);
query->rtable = list_delete_first(rtable);
OffsetVarNodes((Node *) query, -2, 0);
Assert(list_length(query->rtable) >= 1);
#endif
}
/*
* Extract the final view from the UNION ALL query.
*
* q1 is the query on the materialization hypertable with the finalize call
* q2 is the query on the raw hypertable which was supplied in the initial CREATE VIEW statement
* returns q1 from:
* SELECT * from ( SELECT * from q1 where <coale_qual>
* UNION ALL
* SELECT * from q2 where existing_qual and <coale_qual>
* where coale_qual is: time < ----> (or >= )
* COALESCE(_timescaledb_functions.to_timestamp(_timescaledb_functions.cagg_watermark( <htid>)),
* '-infinity'::timestamp with time zone)
* The WHERE clause of the final view is removed.
*/
Query *
destroy_union_query(Query *q)
{
Assert(q->commandType == CMD_SELECT &&
((SetOperationStmt *) q->setOperations)->op == SETOP_UNION &&
((SetOperationStmt *) q->setOperations)->all == true);
/* Get RTE of the left-hand side of UNION ALL. */
RangeTblEntry *rte = linitial(q->rtable);
Assert(rte->rtekind == RTE_SUBQUERY);
Query *query = copyObject(rte->subquery);
/* Delete the WHERE clause from the final view. */
query->jointree->quals = NULL;
return query;
}
/*
* Handle additional parameter of the timebucket function such as timezone, offset, or origin
*/
static void
process_additional_timebucket_parameter(ContinuousAggBucketFunction *bf, Const *arg,
bool *custom_origin)
{
char *tz_name;
switch (exprType((Node *) arg))
{
/* Timezone as text */
case TEXTOID:
if (!arg->constisnull)
{
tz_name = TextDatumGetCString(arg->constvalue);
if (!ts_is_valid_timezone_name(tz_name))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid timezone name \"%s\"", tz_name)));
}
bf->bucket_time_timezone = tz_name;
}
break;
case INTERVALOID:
/* Bucket offset as interval */
if (!arg->constisnull)
{
bf->bucket_time_offset = DatumGetIntervalP(arg->constvalue);
}
break;
case DATEOID:
/* Bucket origin as Date */
if (!arg->constisnull)
{
bf->bucket_time_origin =
date2timestamptz_opt_overflow(DatumGetDateADT(arg->constvalue), NULL);
}
*custom_origin = true;
break;
case TIMESTAMPOID:
/* Bucket origin as Timestamp */
bf->bucket_time_origin = DatumGetTimestamp(arg->constvalue);
*custom_origin = true;
break;
case TIMESTAMPTZOID:
/* Bucket origin as TimestampTZ */
bf->bucket_time_origin = DatumGetTimestampTz(arg->constvalue);
*custom_origin = true;
break;
case INT2OID:
/* Bucket offset as smallint */
bf->bucket_integer_offset = DatumGetInt16(arg->constvalue);
break;
case INT4OID:
/* Bucket offset as int */
bf->bucket_integer_offset = DatumGetInt32(arg->constvalue);
break;
case INT8OID:
/* Bucket offset as bigint */
bf->bucket_integer_offset = DatumGetInt64(arg->constvalue);
break;
default:
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("unable to handle time_bucket parameter of type: %s",
format_type_be(exprType((Node *) arg)))));
pg_unreachable();
}
}
/*
* Process the FuncExpr node to fill the bucket function data structure. The other
* parameters are used when `process_check` is true that means we need to raise errors
* when invalid parameters are passed to the time bucket function when creating a cagg.
*/
static void
process_timebucket_parameters(FuncExpr *fe, ContinuousAggBucketFunction *bf, bool process_checks,
bool is_cagg_create, AttrNumber htpartcolno, StringInfo msg,
bool for_rewrites)
{
Node *width_arg;
Node *col_arg;
bool custom_origin = false;
TIMESTAMP_NOBEGIN(bf->bucket_time_origin);
int nargs;
nargs = list_length(fe->args);
if (nargs < 2 || nargs > 5)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unsupported time bucket function signature")));
}
/* Only column allowed : time_bucket('1day', <column> ) */
col_arg = lsecond(fe->args);
/* Could be a named argument */
if (IsA(col_arg, NamedArgExpr))
{
col_arg = (Node *) castNode(NamedArgExpr, col_arg)->arg;
}
if (process_checks && htpartcolno != InvalidAttrNumber &&
(!(IsA(col_arg, Var)) || castNode(Var, col_arg)->varattno != htpartcolno))
{
if (!for_rewrites)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("time bucket function must reference the primary hypertable "
"dimension column")));
}
else if (msg)
{
appendStringInfoString(msg,
"time bucket function must reference the primary hypertable "
"dimension column");
}
return;
}
/*
* Process the third argument of the time bucket function. This could be `timezone`, `offset`,
* or `origin`.
*
* Time bucket function variations with 3 and 5 arguments:
* - time_bucket(width SMALLINT, ts SMALLINT, offset SMALLINT)
* - time_bucket(width INTEGER, ts INTEGER, offset INTEGER)
* - time_bucket(width BIGINT, ts BIGINT, offset BIGINT)
* - time_bucket(width INTERVAL, ts DATE, offset INTERVAL)
* - time_bucket(width INTERVAL, ts DATE, origin DATE)
* - time_bucket(width INTERVAL, ts TIMESTAMPTZ, offset INTERVAL)
* - time_bucket(width INTERVAL, ts TIMESTAMPTZ, origin TIMESTAMPTZ)
* - time_bucket(width INTERVAL, ts TIMESTAMPTZ, timezone TEXT, origin TIMESTAMPTZ,
* offset INTERVAL)
* - time_bucket(width INTERVAL, ts TIMESTAMP, offset INTERVAL)
* - time_bucket(width INTERVAL, ts TIMESTAMP, origin TIMESTAMP)
*/
if (nargs >= 3)
{
Const *arg = check_time_bucket_argument(lthird(fe->args),
"third",
process_checks,
msg,
for_rewrites);
if (!arg)
{
return;
}
process_additional_timebucket_parameter(bf, arg, &custom_origin);
}
/*
* Process the fourth and fifth arguments of the time bucket function. This could be `origin` or
* `offset`.
*
* Time bucket function variation with 5 arguments:
* - time_bucket(width INTERVAL, ts TIMESTAMPTZ, timezone TEXT, origin TIMESTAMPTZ,
* offset INTERVAL)
*/
if (nargs >= 4)
{
Const *arg = check_time_bucket_argument(lfourth(fe->args),
"fourth",
process_checks,
msg,
for_rewrites);
if (!arg)
{
return;
}
process_additional_timebucket_parameter(bf, arg, &custom_origin);
}
if (nargs == 5)
{
Const *arg = check_time_bucket_argument(lfifth(fe->args),
"fifth",
process_checks,
msg,
for_rewrites);
if (!arg)
{
return;
}
process_additional_timebucket_parameter(bf, arg, &custom_origin);
}
if (process_checks && custom_origin && TIMESTAMP_NOT_FINITE(bf->bucket_time_origin))
{
if (!for_rewrites)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid origin value: infinity")));
}
else if (msg)
{
appendStringInfoString(msg, "invalid time bucket origin value: infinity");
}
return;
}
/*
* We constify width expression here so any immutable expression will be allowed.
* Otherwise it would make it harder to create caggs for hypertables with e.g. int8
* partitioning column as int constants default to int4 and so expression would
* have a cast and not be a Const.
*/
width_arg = linitial(fe->args);
if (IsA(width_arg, NamedArgExpr))
{
width_arg = (Node *) castNode(NamedArgExpr, width_arg)->arg;
}
width_arg = eval_const_expressions(NULL, width_arg);
if (IsA(width_arg, Const))
{
Const *width = castNode(Const, width_arg);
bf->bucket_width_type = width->consttype;
if (width->constisnull)
{
if (process_checks && !for_rewrites)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid bucket width for time bucket function")));
}
return;
}
if (width->consttype == INTERVALOID)
{
bf->bucket_time_width = DatumGetIntervalP(width->constvalue);
}
if (!IS_TIME_BUCKET_INFO_TIME_BASED(bf))
{
bf->bucket_integer_width =
ts_interval_value_to_internal(width->constvalue, width->consttype);
}
}
else if (process_checks)
{
if (!for_rewrites)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("only immutable expressions allowed in time bucket function"),
errhint("Use an immutable expression as first argument to the time bucket "
"function.")));
}
else if (msg)
{
appendStringInfoString(msg,
"non-immutable expression as first argument to the time bucket "
"function");
}
return;
}
bf->bucket_function = fe->funcid;
bf->bucket_time_based = ts_continuous_agg_bucket_on_interval(bf->bucket_function);
bf->bucket_fixed_interval = time_bucket_info_has_fixed_width(bf);
if (process_checks && is_cagg_create && ts_continuous_agg_bucket_width(bf) <= 0)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("time bucket width must be greater than zero")));
}
}
/*
* Check if the group-by clauses has exactly 1 time_bucket(.., <col>) where
* <col> is the hypertable's partitioning column and other invariants. Then fill
* the `bucket_width` and other fields of `tbinfo`.
*/
bool
caggtimebucket_validate_common(ContinuousAggBucketFunction *bf, List *groupClause, List *targetList,
List *rtable, int ht_partcolno, StringInfo msg, bool is_cagg_create,
const bool for_rewrites)
{
ListCell *l;
bool found = false;
/* Make sure tbinfo was initialized. This assumption is used below. */
Assert(bf->bucket_integer_width == 0);
Assert(bf->bucket_time_timezone == NULL);
Assert(TIMESTAMP_NOT_FINITE(bf->bucket_time_origin));
List *group_exprs = get_sortgrouplist_exprs(groupClause, targetList);
#if PG18_GE
/* PG18 introduced RTEs for group clauses so
* we can just use rtable to look for GROUP BY expressions.
*
* https://github.com/postgres/postgres/commit/247dea89
*/
List *group_rte_exprs = NIL;
foreach (l, rtable)
{
RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
if (rte->rtekind == RTE_GROUP)
{
group_rte_exprs = list_concat(group_rte_exprs, rte->groupexprs);
}
}
group_exprs = group_rte_exprs;
#endif
foreach (l, group_exprs)
{
Expr *expr = (Expr *) lfirst(l);
if (IsA(expr, FuncExpr))
{
FuncExpr *fe = castNode(FuncExpr, expr);
/* Filter any non bucketing functions */
FuncInfo *finfo = ts_func_cache_get_bucketing_func(fe->funcid);
if (finfo == NULL || !finfo->is_bucketing_func)
{
continue;
}
/* Do we have a bucketing function that is not allowed in the CAgg definition?
*
* This is only validated upon creation. If an older TSDB version has allowed us to use
* the function and it's now removed from the list of allowed functions, we should not
* error out (e.g., materialized_only setting is changed on a CAgg that uses the
* deprecated time_bucket_ng function). */
if (!function_allowed_in_cagg_definition(fe->funcid))
{
continue;
}
if (found)
{
if (!for_rewrites)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("continuous aggregate view cannot contain"
" multiple time bucket functions")));
}
else if (msg)
{
appendStringInfoString(msg,
"multiple time bucket functions are not supported with "
"CAggs");
}
return false;
}
else
{
found = true;
}
process_timebucket_parameters(fe,
bf,
true,
is_cagg_create,
ht_partcolno,
msg,
for_rewrites);
if (!OidIsValid(bf->bucket_function))
{
return false;
}
}
}
if (bf->bucket_time_offset != NULL && TIMESTAMP_NOT_FINITE(bf->bucket_time_origin) == false)
{
if (!for_rewrites)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("using offset and origin in a time_bucket function at the same time is "
"not "
"supported")));
}
else if (msg)
{
appendStringInfoString(msg,
"using offset and origin in a time_bucket function at the same "
"time is "
"not "
"supported");
}
return false;
}
if (!time_bucket_info_has_fixed_width(bf))
{
/* Variable-sized buckets can be used only with intervals. */
Assert(bf->bucket_time_width != NULL);
Assert(IS_TIME_BUCKET_INFO_TIME_BASED(bf));
if ((bf->bucket_time_width->month != 0) &&
((bf->bucket_time_width->day != 0) || (bf->bucket_time_width->time != 0)))
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid interval specified"),
errhint("Use either months or days and hours, but not months, days and hours "
"together")));
}
}
if (!found)
{
if (!for_rewrites)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg(
"continuous aggregate view must include a valid time bucket function")));
}
else if (msg)
{
appendStringInfoString(msg, "should be a valid time bucket function in the query");
}
return false;
}
return true;
}
static void
caggtimebucket_validate(ContinuousAggTimeBucketInfo *tbinfo, List *groupClause, List *targetList,
List *rtable, bool is_cagg_create)
{
bool for_rewrite = false;
caggtimebucket_validate_common(tbinfo->bf,
groupClause,
targetList,
rtable,
tbinfo->htpartcolno,
NULL,
is_cagg_create,
for_rewrite);
}
/*
* Check query for Cagg support, extract error details and error hints.
*
* Returns:
* True if the query is supported
* (either for Cagg view or for query rewrite with Cagg, see for_rewrites),
* false otherwise with hints and errors added
* if hint and error string buffers are provided.
*/
bool
cagg_query_supported(const Query *query, StringInfo hint, StringInfo detail,
const bool for_rewrites)
{
if (!query->jointree->fromlist)
{
if (!for_rewrites)
{
appendStringInfoString(hint, "FROM clause missing in the query");
}
else if (hint)
{
appendStringInfoString(hint, "FROM clause missing in the query");
}
return false;
}
if (query->commandType != CMD_SELECT)
{
if (!for_rewrites)
{
appendStringInfoString(hint, "Use a SELECT query in the continuous aggregate view.");
}
else if (hint)
{
appendStringInfoString(hint, "not a SELECT query");
}
return false;
}
if (query->hasWindowFuncs)
{
if (ts_guc_enable_cagg_window_functions)
{
if (!for_rewrites)
{
elog(WARNING,
"window function support is experimental and may result in unexpected results "
"depending on the functions used.");
}
else if (hint)
{
appendStringInfoString(hint, "Window function in a query");
}
}
else
{
if (!for_rewrites)
{
appendStringInfoString(detail, "Window function support not enabled.");
appendStringInfoString(hint,
"Enable experimental window function support by setting "
"timescaledb.enable_cagg_window_functions.");
}
else if (hint)
{
appendStringInfoString(hint, "Window function in a query");
}
return false;
}
}
if (query->hasDistinctOn || query->distinctClause)
{
if (!for_rewrites)
{
appendStringInfoString(detail,
"DISTINCT / DISTINCT ON queries are not supported by continuous "
"aggregates.");
}
else if (hint)
{
appendStringInfoString(hint,
"DISTINCT / DISTINCT ON queries are not supported by continuous "
"aggregates.");
}
return false;
}
/* Can apply LIMIT to queries rewritten with Caggs */
if (!for_rewrites && (query->limitOffset || query->limitCount))
{
appendStringInfoString(detail,
"LIMIT and LIMIT OFFSET are not supported in queries defining "
"continuous aggregates.");
appendStringInfoString(hint,
"Use LIMIT and LIMIT OFFSET in SELECTS from the continuous "
"aggregate view instead.");
return false;
}
if (query->hasRecursive || query->hasSubLinks || query->cteList)
{
if (!for_rewrites)
{
appendStringInfoString(detail,
"CTEs and subqueries are not supported by "
"continuous aggregates.");
}
else if (hint)
{
appendStringInfoString(hint,
"CTEs and sublinks are not supported by "
"continuous aggregates.");
}
return false;
}
if (query->hasForUpdate || query->hasModifyingCTE)
{
if (!for_rewrites)
{
appendStringInfoString(detail,
"Data modification is not allowed in continuous aggregate view "
"definitions.");
}
else if (hint)
{
appendStringInfoString(hint,
"Data modification is not allowed in continuous aggregates");
}
return false;
}
if (query->hasRowSecurity)
{
if (!for_rewrites)
{
appendStringInfoString(detail,
"Row level security is not supported by continuous aggregate "
"views.");
}
else if (hint)
{
appendStringInfoString(hint,
"Row level security is not supported by continuous aggregates");
}
return false;
}
if (query->groupingSets)
{
if (!for_rewrites)
{
appendStringInfoString(detail,
"GROUP BY GROUPING SETS, ROLLUP and CUBE are not supported by "
"continuous aggregates");
appendStringInfoString(hint,
"Define multiple continuous aggregates with different grouping "
"levels.");
}
else if (hint)
{
appendStringInfoString(hint,
"GROUP BY GROUPING SETS, ROLLUP and CUBE are not supported by "
"continuous aggregates");
}
return false;
}
if (query->setOperations)
{
if (!for_rewrites)
{
appendStringInfoString(detail,
"UNION, EXCEPT & INTERSECT are not supported by continuous "
"aggregates");
}
else if (hint)
{
appendStringInfoString(hint,
"UNION, EXCEPT & INTERSECT are not supported by continuous "
"aggregates");
}
return false;
}
if (!query->groupClause)
{
/*
* Query can have aggregate without group by, so look
* for groupClause.
*/
if (!for_rewrites)
{
appendStringInfoString(hint,
"Include at least one aggregate function"
" and a GROUP BY clause with time bucket.");
}
else if (hint)
{
appendStringInfoString(hint, "no GROUP BY clause in the query");
}
return false;
}
return true; /* Query was OK and is supported. */
}
bool
cagg_query_rtes_supported(RangeTblEntry *rte, RangeTblEntry **ht_rte, StringInfo detail,
const bool for_rewrites)
{
if (rte->rtekind == RTE_RELATION
/* Allow for processed views in Caggs used in a query */
|| (for_rewrites && rte->relkind == RELKIND_VIEW))
{
bool is_hypertable =
ts_is_hypertable(rte->relid) || ts_continuous_agg_find_by_relid(rte->relid);
if (is_hypertable && !(*ht_rte))
{
*ht_rte = rte;
}
else if (is_hypertable && (*ht_rte))
{
if (!for_rewrites)
{
appendStringInfoString(detail,
"Only one hypertable is allowed in continuous aggregate "
"view.");
}
else if (detail)
{
appendStringInfo(detail,
"More than one hypertable in the query: \"%s\" and \"%s\"",
rte->eref->aliasname,
(*ht_rte)->eref->aliasname);
}
return false;
}
if (is_hypertable && rte->inh == false && !(for_rewrites && rte->relkind == RELKIND_VIEW))
{
if (!for_rewrites)
{
appendStringInfoString(detail,
"FROM ONLY on hypertables is not allowed in continuous "
"aggregate.");
}
else if (detail)
{
appendStringInfo(detail,
"FROM ONLY on hypertable \"%s\" is not allowed in continuous "
"aggregate.",
rte->eref->aliasname);
}
return false;
}
}
/* Only inner joins are allowed. */
if (rte->jointype != JOIN_INNER && rte->jointype != JOIN_LEFT)
{
if (detail)
{
appendStringInfoString(detail,
"only INNER or LEFT joins are supported in continuous "
"aggregates");
}
return false;
}
/* Subquery only using LATERAL */
if (rte->subquery && !rte->lateral && !(for_rewrites && rte->relkind == RELKIND_VIEW))
{
if (!for_rewrites)
{
appendStringInfoString(detail, "Sub-queries are not supported in FROM clause.");
}
else if (detail)
{
appendStringInfoString(detail,
"only LATERAL subqueries in FROM clause are supported in "
"continuous aggregates.");
}
return false;
}
/* TABLESAMPLE not allowed */
if (rte->tablesample)
{
if (detail)
{
appendStringInfoString(detail, "TABLESAMPLE is not supported in continuous aggregate.");
}
return false;
}
return true;
}
const Dimension *
cagg_hypertable_dim_supported(RangeTblEntry *ht_rte, Hypertable *ht, StringInfo msg,
StringInfo detail, StringInfo hint, const bool for_rewrites)
{
if (TS_HYPERTABLE_IS_INTERNAL_COMPRESSION_TABLE(ht))
{
if (!for_rewrites)
{
appendStringInfoString(msg, "hypertable is an internal compressed hypertable");
}
else if (msg)
{
appendStringInfo(msg,
"hypertable \"%s.%s\" is an internal compressed hypertable",
NameStr(ht->fd.schema_name),
NameStr(ht->fd.table_name));
}
return NULL;
}
if (ht_rte->relkind == RELKIND_RELATION)
{
ContinuousAggHypertableStatus status = ts_continuous_agg_hypertable_status(ht->fd.id);
/* Prevent create a CAGG over an existing materialization hypertable. */
if (status == HypertableIsMaterialization || status == HypertableIsMaterializationAndRaw)
{
const ContinuousAgg *cagg =
ts_continuous_agg_find_by_mat_hypertable_id(ht->fd.id, false);
Assert(cagg != NULL);
if (!for_rewrites)
{
appendStringInfoString(msg,
"hypertable is a continuous aggregate materialization "
"table");
appendStringInfo(detail,
"Materialization hypertable \"%s.%s\".",
NameStr(ht->fd.schema_name),
NameStr(ht->fd.table_name));
appendStringInfo(hint,
"Do you want to use continuous aggregate \"%s.%s\" instead?",
NameStr(cagg->data.user_view_schema),
NameStr(cagg->data.user_view_name));
}
else if (msg)
{
appendStringInfo(msg,
"hypertable \"%s.%s\" is a continuous aggregate materialization "
"table",
NameStr(ht->fd.schema_name),
NameStr(ht->fd.table_name));
}
return NULL;
}
}
/* Get primary partitioning column information. */
const Dimension *part_dimension = hyperspace_get_open_dimension(ht->space, 0);
/*
* NOTE: if we ever allow custom partitioning functions we'll need to
* change part_dimension->fd.column_type to partitioning_type
* below, along with any other fallout.
*/
if (part_dimension == NULL || part_dimension->partitioning != NULL)
{
if (msg)
{
appendStringInfoString(msg,
"custom partitioning functions not supported with continuous "
"aggregates");
}