-
Notifications
You must be signed in to change notification settings - Fork 869
/
common.c
1622 lines (1437 loc) · 50.5 KB
/
common.c
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/date.h>
#include <utils/timestamp.h>
#include "guc.h"
static Const *check_time_bucket_argument(Node *arg, char *position, bool process_checks);
static void caggtimebucketinfo_init(CAggTimebucketInfo *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);
static void process_additional_timebucket_parameter(ContinuousAggsBucketFunction *bf, Const *arg);
static void process_timebucket_parameters(FuncExpr *fe, ContinuousAggsBucketFunction *bf,
bool process_checks, bool is_cagg_create,
AttrNumber htpartcolno);
static void caggtimebucket_validate(CAggTimebucketInfo *tbinfo, List *groupClause, List *targetList,
bool is_cagg_create);
static bool cagg_query_supported(const Query *query, StringInfo hint, StringInfo detail,
const bool finalized);
static Datum get_bucket_width_datum(CAggTimebucketInfo bucket_info);
static int64 get_bucket_width(CAggTimebucketInfo 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);
static bool time_bucket_info_has_fixed_width(const ContinuousAggsBucketFunction *bf);
#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)
{
if (IsA(arg, NamedArgExpr))
arg = (Node *) castNode(NamedArgExpr, arg)->arg;
Node *expr = eval_const_expressions(NULL, arg);
if (process_checks && !IsA(expr, Const))
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)));
return castNode(Const, expr);
}
/*
* Initialize caggtimebucket.
*/
static void
caggtimebucketinfo_init(CAggTimebucketInfo *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->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(ContinuousAggsBucketFunction));
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;
/* Allow creation of CAggs with deprecated bucket function in debug builds for testing purposes
*/
if (ts_guc_debug_allow_cagg_with_deprecated_funcs && IS_DEPRECATED_TIME_BUCKET_NG_FUNC(finfo))
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(ContinuousAggsBucketFunction *bf, Const *arg)
{
char *tz_name;
switch (exprType((Node *) arg))
{
/* Timezone as text */
case TEXTOID:
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 */
bf->bucket_time_offset = DatumGetIntervalP(arg->constvalue);
break;
case DATEOID:
/* Bucket origin as Date */
bf->bucket_time_origin =
date2timestamptz_opt_overflow(DatumGetDateADT(arg->constvalue), NULL);
break;
case TIMESTAMPOID:
/* Bucket origin as Timestamp */
bf->bucket_time_origin = DatumGetTimestamp(arg->constvalue);
break;
case TIMESTAMPTZOID:
/* Bucket origin as TimestampTZ */
bf->bucket_time_origin = DatumGetTimestampTz(arg->constvalue);
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_TS_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, ContinuousAggsBucketFunction *bf, bool process_checks,
bool is_cagg_create, AttrNumber htpartcolno)
{
Node *width_arg;
Node *col_arg;
bool custom_origin = false;
Const *const_arg;
/* 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))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("time bucket function must reference the primary hypertable "
"dimension column")));
if (list_length(fe->args) >= 3)
{
Const *arg = check_time_bucket_argument(lthird(fe->args), "third", process_checks);
process_additional_timebucket_parameter(bf, arg);
}
if (list_length(fe->args) >= 4)
{
Const *arg = check_time_bucket_argument(lfourth(fe->args), "fourth", process_checks);
process_additional_timebucket_parameter(bf, arg);
}
/* Check for custom origin. */
switch (exprType(col_arg))
{
case DATEOID:
/* Origin is always 3rd arg for date variants. */
if (list_length(fe->args) == 3 && exprType(lthird(fe->args)) == DATEOID)
{
Node *arg = lthird(fe->args);
custom_origin = true;
/* this function also takes care of named arguments */
const_arg = check_time_bucket_argument(arg, "third", process_checks);
bf->bucket_time_origin =
DatumGetTimestamp(DirectFunctionCall1(date_timestamp, const_arg->constvalue));
}
break;
case TIMESTAMPOID:
/* Origin is always 3rd arg for timestamp variants. */
if (list_length(fe->args) == 3 && exprType(lthird(fe->args)) == TIMESTAMPOID)
{
Node *arg = lthird(fe->args);
custom_origin = true;
const_arg = check_time_bucket_argument(arg, "third", process_checks);
bf->bucket_time_origin = DatumGetTimestamp(const_arg->constvalue);
}
break;
case TIMESTAMPTZOID:
/* Origin can be 3rd or 4th arg for timestamptz variants. */
if (list_length(fe->args) >= 3 && exprType(lthird(fe->args)) == TIMESTAMPTZOID)
{
Node *arg = lthird(fe->args);
custom_origin = true;
Const *constval = check_time_bucket_argument(arg, "third", process_checks);
bf->bucket_time_origin = DatumGetTimestampTz(constval->constvalue);
}
else if (list_length(fe->args) >= 4 && exprType(lfourth(fe->args)) == TIMESTAMPTZOID)
{
custom_origin = true;
if (IsA(lfourth(fe->args), Const))
{
bf->bucket_time_origin =
DatumGetTimestampTz(castNode(Const, lfourth(fe->args))->constvalue);
}
/* could happen in a statement like time_bucket('1h', .., 'utc', origin =>
* ...) */
else if (IsA(lfourth(fe->args), NamedArgExpr))
{
Const *constval =
check_time_bucket_argument(lfourth(fe->args), "fourth", process_checks);
bf->bucket_time_origin = DatumGetTimestampTz(constval->constvalue);
}
}
}
if (process_checks && custom_origin && TIMESTAMP_NOT_FINITE(bf->bucket_time_origin))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid origin value: infinity")));
}
/*
* 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 && is_cagg_create)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid bucket width for time bucket function")));
}
else
{
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)
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.")));
}
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);
}
/*
* 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`.
*/
static void
caggtimebucket_validate(CAggTimebucketInfo *tbinfo, List *groupClause, List *targetList,
bool is_cagg_create)
{
ListCell *l;
bool found = false;
/* Make sure tbinfo was initialized. This assumption is used below. */
Assert(tbinfo->bf->bucket_integer_width == 0);
Assert(tbinfo->bf->bucket_time_timezone == NULL);
Assert(TIMESTAMP_NOT_FINITE(tbinfo->bf->bucket_time_origin));
foreach (l, groupClause)
{
SortGroupClause *sgc = (SortGroupClause *) lfirst(l);
TargetEntry *tle = get_sortgroupclause_tle(sgc, targetList);
if (IsA(tle->expr, FuncExpr))
{
FuncExpr *fe = castNode(FuncExpr, tle->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))
{
if (IS_DEPRECATED_TIME_BUCKET_NG_FUNC(finfo))
{
if (is_cagg_create)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("experimental bucket functions are not supported inside a "
"CAgg "
"definition"),
errhint("Use a function from the %s schema instead.",
FUNCTIONS_SCHEMA_NAME)));
}
}
else
{
continue;
}
}
if (found)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("continuous aggregate view cannot contain"
" multiple time bucket functions")));
else
found = true;
process_timebucket_parameters(fe,
tbinfo->bf,
true,
is_cagg_create,
tbinfo->htpartcolno);
}
}
if (tbinfo->bf->bucket_time_offset != NULL &&
TIMESTAMP_NOT_FINITE(tbinfo->bf->bucket_time_origin) == false)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("using offset and origin in a time_bucket function at the same time is not "
"supported")));
}
if (!time_bucket_info_has_fixed_width(tbinfo->bf))
{
/* Variable-sized buckets can be used only with intervals. */
Assert(tbinfo->bf->bucket_time_width != NULL);
Assert(IS_TIME_BUCKET_INFO_TIME_BASED(tbinfo->bf));
if ((tbinfo->bf->bucket_time_width->month != 0) &&
((tbinfo->bf->bucket_time_width->day != 0) ||
(tbinfo->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)
elog(ERROR, "continuous aggregate view must include a valid time bucket function");
}
/*
* Check query and extract error details and error hints.
*
* Returns:
* True if the query is supported, false otherwise with hints and errors
* added.
*/
static bool
cagg_query_supported(const Query *query, StringInfo hint, StringInfo detail, const bool finalized)
{
if (!finalized)
{
/* continuous aggregates with old format will not be allowed */
appendStringInfoString(detail,
"Continuous Aggregates with partials is not supported anymore.");
appendStringInfoString(hint,
"Define the Continuous Aggregate with \"finalized\" parameter set "
"to true.");
return false;
}
if (!query->jointree->fromlist)
{
appendStringInfoString(hint, "FROM clause missing in the query");
return false;
}
if (query->commandType != CMD_SELECT)
{
appendStringInfoString(hint, "Use a SELECT query in the continuous aggregate view.");
return false;
}
if (query->hasWindowFuncs)
{
appendStringInfoString(detail,
"Window functions are not supported by continuous aggregates.");
return false;
}
if (query->hasDistinctOn || query->distinctClause)
{
appendStringInfoString(detail,
"DISTINCT / DISTINCT ON queries are not supported by continuous "
"aggregates.");
return false;
}
if (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->hasTargetSRFs || query->cteList)
{
appendStringInfoString(detail,
"CTEs, subqueries and set-returning functions are not supported by "
"continuous aggregates.");
return false;
}
if (query->hasForUpdate || query->hasModifyingCTE)
{
appendStringInfoString(detail,
"Data modification is not allowed in continuous aggregate view "
"definitions.");
return false;
}
if (query->hasRowSecurity)
{
appendStringInfoString(detail,
"Row level security is not supported by continuous aggregate "
"views.");
return false;
}
if (query->groupingSets)
{
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.");
return false;
}
if (query->setOperations)
{
appendStringInfoString(detail,
"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.
*/
appendStringInfoString(hint,
"Include at least one aggregate function"
" and a GROUP BY clause with time bucket.");
return false;
}
return true; /* Query was OK and is supported. */
}
static Datum
get_bucket_width_datum(CAggTimebucketInfo bucket_info)
{
Datum width = (Datum) 0;
switch (bucket_info.bf->bucket_width_type)
{
case INT8OID:
case INT4OID:
case INT2OID:
width = ts_internal_to_interval_value(bucket_info.bf->bucket_integer_width,
bucket_info.bf->bucket_width_type);
break;
case INTERVALOID:
width = IntervalPGetDatum(bucket_info.bf->bucket_time_width);
break;
default:
Assert(false);
}
return width;
}
static int64
get_bucket_width(CAggTimebucketInfo bucket_info)
{
int64 width = 0;
/* Calculate the width. */
switch (bucket_info.bf->bucket_width_type)
{
case INT8OID:
case INT4OID:
case INT2OID:
width = bucket_info.bf->bucket_integer_width;
break;
case INTERVALOID:
{
/*
* Original interval should not be changed, hence create a local copy
* for this check.
*/
Interval interval = *bucket_info.bf->bucket_time_width;
/*
* epoch will treat year as 365.25 days. This leads to the unexpected
* result that year is not multiple of day or month, which is perceived
* as a bug. For that reason, we treat all months as 30 days regardless of year
*/
if (interval.month && !interval.day && !interval.time)
{
interval.day = interval.month * DAYS_PER_MONTH;
interval.month = 0;
}
/* Convert Interval to int64 */
width = ts_interval_value_to_internal(IntervalPGetDatum(&interval), INTERVALOID);
break;
}
default:
Assert(false);
}
return width;
}
CAggTimebucketInfo
cagg_validate_query(const Query *query, const bool finalized, const char *cagg_schema,
const char *cagg_name, const bool is_cagg_create)
{
CAggTimebucketInfo bucket_info = { 0 };
CAggTimebucketInfo bucket_info_parent = { 0 };
Hypertable *ht = NULL, *ht_parent = NULL;
RangeTblRef *rtref = NULL, *rtref_other = NULL;
RangeTblEntry *rte = NULL, *rte_other = NULL;
JoinType jointype = JOIN_FULL;
OpExpr *op = NULL;
List *fromList = NIL;
StringInfo hint = makeStringInfo();
StringInfo detail = makeStringInfo();
bool is_hierarchical = false;
Query *prev_query = NULL;
ContinuousAgg *cagg_parent = NULL;
Oid normal_table_id = InvalidOid;
if (!cagg_query_supported(query, hint, detail, finalized))
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate query"),
hint->len > 0 ? errhint("%s", hint->data) : 0,
detail->len > 0 ? errdetail("%s", detail->data) : 0));
}
/* Check if there are only two tables in the from list. */
fromList = query->jointree->fromlist;
if (list_length(fromList) > CONTINUOUS_AGG_MAX_JOIN_RELATIONS)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("only two tables with one hypertable and one normal table "
"are allowed in continuous aggregate view")));
}
/* Extra checks for joins in Caggs. */
if (list_length(fromList) == CONTINUOUS_AGG_MAX_JOIN_RELATIONS ||
!IsA(linitial(query->jointree->fromlist), RangeTblRef))
{
if (list_length(fromList) == CONTINUOUS_AGG_MAX_JOIN_RELATIONS)
{
if (!IsA(linitial(fromList), RangeTblRef) || !IsA(lsecond(fromList), RangeTblRef))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate view"),
errdetail(
"From clause can only have one hypertable and one normal table.")));
rtref = linitial_node(RangeTblRef, query->jointree->fromlist);
rte = list_nth(query->rtable, rtref->rtindex - 1);
rtref_other = lsecond_node(RangeTblRef, query->jointree->fromlist);
rte_other = list_nth(query->rtable, rtref_other->rtindex - 1);
jointype = rte->jointype || rte_other->jointype;
if (query->jointree->quals != NULL && IsA(query->jointree->quals, OpExpr))
op = (OpExpr *) query->jointree->quals;
}
else
{
ListCell *l;
foreach (l, query->jointree->fromlist)
{
Node *jtnode = (Node *) lfirst(l);
JoinExpr *join = NULL;
if (IsA(jtnode, JoinExpr))
{
join = castNode(JoinExpr, jtnode);
jointype = join->jointype;
op = (OpExpr *) join->quals;
rte = list_nth(query->rtable, ((RangeTblRef *) join->larg)->rtindex - 1);
rte_other = list_nth(query->rtable, ((RangeTblRef *) join->rarg)->rtindex - 1);
if (rte->subquery != NULL || rte_other->subquery != NULL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate view"),
errdetail("Sub-queries are not supported in FROM clause.")));
RangeTblEntry *jrte = rt_fetch(join->rtindex, query->rtable);
if (jrte->joinaliasvars == NIL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate view")));
}
}
}
/*
* Error out if there is aynthing else than one normal table and one hypertable
* in the from clause, e.g. sub-query, lateral, two hypertables, etc.
*/
if (rte->lateral || rte_other->lateral)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate view"),
errdetail("Lateral joins are not supported in FROM clause.")));
if ((rte->relkind == RELKIND_VIEW && ts_is_hypertable(rte_other->relid)) ||
(rte_other->relkind == RELKIND_VIEW && ts_is_hypertable(rte->relid)))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate view"),
errdetail("Views are not supported in FROM clause.")));
if (rte->relkind != RELKIND_VIEW && rte_other->relkind != RELKIND_VIEW &&
(ts_is_hypertable(rte->relid) == ts_is_hypertable(rte_other->relid)))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate view"),
errdetail("Multiple hypertables or normal tables are not supported in FROM "
"clause.")));
/* Only inner joins are allowed. */
if (jointype != JOIN_INNER)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("only inner joins are supported in continuous aggregates")));
/* Only equality conditions are permitted on joins. */
if (op && IsA(op, OpExpr) &&
list_length(castNode(OpExpr, op)->args) == CONTINUOUS_AGG_MAX_JOIN_RELATIONS)
{
Oid left_type = exprType(linitial(op->args));
Oid right_type = exprType(lsecond(op->args));
if (!ts_is_equality_operator(op->opno, left_type, right_type))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate view"),
errdetail(
"Only equality conditions are supported in continuous aggregates.")));
}
else
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate view"),
errdetail("Unsupported expression in join clause."),
errhint("Only equality conditions are supported in continuous aggregates.")));
/*
* Record the table oid of the normal table. This is required so
* that we know which one is hypertable to carry out the related
* processing in later parts of code.
*/
if (rte->relkind == RELKIND_VIEW)
normal_table_id = rte_other->relid;
else if (rte_other->relkind == RELKIND_VIEW)
normal_table_id = rte->relid;
else
normal_table_id = ts_is_hypertable(rte->relid) ? rte_other->relid : rte->relid;
if (normal_table_id == rte->relid)
rte = rte_other;
}
else
{
/* Check if we have a hypertable in the FROM clause. */
rtref = linitial_node(RangeTblRef, query->jointree->fromlist);
rte = list_nth(query->rtable, rtref->rtindex - 1);
}
/* FROM only <tablename> sets rte->inh to false. */
if (rte->rtekind != RTE_JOIN)
{
if ((rte->relkind != RELKIND_RELATION && rte->relkind != RELKIND_VIEW) ||
rte->tablesample || rte->inh == false)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate view")));
}
Ensure(rte->relkind == RELKIND_RELATION || rte->relkind == RELKIND_VIEW,
"invalid continuous aggregate view");
const Dimension *part_dimension = NULL;
int32 parent_mat_hypertable_id = INVALID_HYPERTABLE_ID;
Cache *hcache = ts_hypertable_cache_pin();
if (rte->relkind == RELKIND_RELATION)
{
ht = ts_hypertable_cache_get_entry(hcache, rte->relid, CACHE_FLAG_MISSING_OK);
if (!ht)
{
ts_cache_release(hcache);
ereport(ERROR,
(errcode(ERRCODE_TS_HYPERTABLE_NOT_EXIST),
errmsg("table \"%s\" is not a hypertable", get_rel_name(rte->relid))));
}
}
else
{
cagg_parent = ts_continuous_agg_find_by_relid(rte->relid);
if (!cagg_parent)
{
ts_cache_release(hcache);
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid continuous aggregate query"),
errhint("Continuous aggregate needs to query hypertable or another "
"continuous aggregate.")));
}
if (!ContinuousAggIsFinalized(cagg_parent))
{
ts_cache_release(hcache);
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("old format of continuous aggregate is not supported"),
errhint("Run \"CALL cagg_migrate('%s.%s');\" to migrate to the new "
"format.",
NameStr(cagg_parent->data.user_view_schema),
NameStr(cagg_parent->data.user_view_name))));
}
parent_mat_hypertable_id = cagg_parent->data.mat_hypertable_id;
ht = ts_hypertable_cache_get_entry_by_id(hcache, cagg_parent->data.mat_hypertable_id);
/* If parent cagg is hierarchical then we should get the matht otherwise the rawht. */
if (ContinuousAggIsHierarchical(cagg_parent))
ht_parent =
ts_hypertable_cache_get_entry_by_id(hcache, cagg_parent->data.mat_hypertable_id);
else
ht_parent =
ts_hypertable_cache_get_entry_by_id(hcache, cagg_parent->data.raw_hypertable_id);
/* Get the querydef for the source cagg. */
is_hierarchical = true;
prev_query = ts_continuous_agg_get_query(cagg_parent);
}
if (TS_HYPERTABLE_IS_INTERNAL_COMPRESSION_TABLE(ht))
{
ts_cache_release(hcache);
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hypertable is an internal compressed hypertable")));
}
if (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);
ts_cache_release(hcache);
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hypertable is a continuous aggregate materialization table"),
errdetail("Materialization hypertable \"%s.%s\".",
NameStr(ht->fd.schema_name),
NameStr(ht->fd.table_name)),
errhint("Do you want to use continuous aggregate \"%s.%s\" instead?",
NameStr(cagg->data.user_view_schema),
NameStr(cagg->data.user_view_name))));
}
}
/* Get primary partitioning column information. */
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)
{
ts_cache_release(hcache);
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("custom partitioning functions not supported"
" with continuous aggregates")));
}
if (IS_INTEGER_TYPE(ts_dimension_get_partition_type(part_dimension)) &&
rte->relkind == RELKIND_RELATION)
{
const char *funcschema = NameStr(part_dimension->fd.integer_now_func_schema);
const char *funcname = NameStr(part_dimension->fd.integer_now_func);
if (strlen(funcschema) == 0 || strlen(funcname) == 0)
{
ts_cache_release(hcache);
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("custom time function required on hypertable \"%s\"",
get_rel_name(ht->main_table_relid)),
errdetail("An integer-based hypertable requires a custom time function to "
"support continuous aggregates."),
errhint("Set a custom time function on the hypertable.")));
}
}
caggtimebucketinfo_init(&bucket_info,
ht->fd.id,
ht->main_table_relid,
part_dimension->column_attno,
part_dimension->fd.column_type,
part_dimension->fd.interval_length,
parent_mat_hypertable_id);
if (is_hierarchical)
{
const Dimension *part_dimension_parent = hyperspace_get_open_dimension(ht_parent->space, 0);
caggtimebucketinfo_init(&bucket_info_parent,
ht_parent->fd.id,
ht_parent->main_table_relid,
part_dimension_parent->column_attno,
part_dimension_parent->fd.column_type,
part_dimension_parent->fd.interval_length,
INVALID_HYPERTABLE_ID);
}
ts_cache_release(hcache);
/*
* We need a GROUP By clause with time_bucket on the partitioning
* column of the hypertable
*/
Assert(query->groupClause);
caggtimebucket_validate(&bucket_info, query->groupClause, query->targetList, is_cagg_create);
/* Check row security settings for the table. */
if (ts_has_row_security(rte->relid))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot create continuous aggregate on hypertable with row security")));
/* At this point, we should have a valid bucket function. Otherwise, we have errored out before.
*/
Ensure(OidIsValid(bucket_info.bf->bucket_function), "unable to find valid bucket function");
/* Ignore time_bucket_ng in this check, since offset and origin were allowed in the past */
FuncInfo *func_info = ts_func_cache_get_bucketing_func(bucket_info.bf->bucket_function);
Ensure(func_info != NULL, "bucket function is not found in function cache");