forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess_utility.c
4708 lines (4031 loc) · 129 KB
/
process_utility.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 Apache License 2.0.
* Please see the included NOTICE for copyright information and
* LICENSE-APACHE for a copy of the license.
*/
#include <postgres.h>
#include <access/htup_details.h>
#include <access/xact.h>
#include <catalog/index.h>
#include <catalog/namespace.h>
#include <catalog/objectaddress.h>
#include <catalog/pg_authid.h>
#include <catalog/pg_class_d.h>
#include <catalog/pg_constraint.h>
#include <catalog/pg_inherits.h>
#include <catalog/pg_trigger.h>
#include <commands/alter.h>
#include <commands/cluster.h>
#include <commands/copy.h>
#include <commands/defrem.h>
#include <commands/event_trigger.h>
#include <commands/prepare.h>
#include <commands/tablecmds.h>
#include <commands/tablespace.h>
#include <commands/trigger.h>
#include <commands/user.h>
#include <commands/vacuum.h>
#include <miscadmin.h>
#include <nodes/makefuncs.h>
#include <nodes/nodes.h>
#include <nodes/parsenodes.h>
#include <parser/parse_type.h>
#include <parser/parse_utilcmd.h>
#include <storage/lmgr.h>
#include <tcop/utility.h>
#include <utils/acl.h>
#include <utils/builtins.h>
#include <utils/guc.h>
#include <utils/inval.h>
#include <utils/lsyscache.h>
#include <utils/rel.h>
#include <utils/snapmgr.h>
#include <utils/syscache.h>
#include "compat/compat.h"
#include "annotations.h"
#include "chunk.h"
#include "chunk_index.h"
#include "compression_with_clause.h"
#include "copy.h"
#include "cross_module_fn.h"
#include "debug_assert.h"
#include "debug_point.h"
#include "dimension_vector.h"
#include "errors.h"
#include "event_trigger.h"
#include "export.h"
#include "extension.h"
#include "extension_constants.h"
#include "foreign_key.h"
#include "hypercube.h"
#include "hypertable.h"
#include "hypertable_cache.h"
#include "indexing.h"
#include "partitioning.h"
#include "process_utility.h"
#include "scan_iterator.h"
#include "time_utils.h"
#include "trigger.h"
#include "ts_catalog/array_utils.h"
#include "ts_catalog/catalog.h"
#include "ts_catalog/chunk_column_stats.h"
#include "ts_catalog/compression_settings.h"
#include "ts_catalog/continuous_agg.h"
#include "ts_catalog/continuous_aggs_watermark.h"
#include "tss_callbacks.h"
#include "utils.h"
#include "with_clause_parser.h"
#ifdef USE_TELEMETRY
#include "telemetry/functions.h"
#endif
void _process_utility_init(void);
void _process_utility_fini(void);
static ProcessUtility_hook_type prev_ProcessUtility_hook;
static bool expect_chunk_modification = false;
static DDLResult process_altertable_set_options(AlterTableCmd *cmd, Hypertable *ht);
static DDLResult process_altertable_reset_options(AlterTableCmd *cmd, Hypertable *ht);
/* Call the default ProcessUtility and handle PostgreSQL version differences */
static void
prev_ProcessUtility(ProcessUtilityArgs *args)
{
ProcessUtility_hook_type hook =
prev_ProcessUtility_hook ? prev_ProcessUtility_hook : standard_ProcessUtility;
hook(args->pstmt,
args->query_string,
args->readonly_tree,
args->context,
args->params,
args->queryEnv,
args->dest,
args->completion_tag);
}
static void
check_chunk_alter_table_operation_allowed(Oid relid, AlterTableStmt *stmt)
{
if (expect_chunk_modification)
return;
if (ts_chunk_exists_relid(relid))
{
bool all_allowed = true;
ListCell *lc;
/* only allow if all commands are allowed */
foreach (lc, stmt->cmds)
{
AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lc);
switch (cmd->subtype)
{
case AT_SetOptions:
case AT_ResetOptions:
case AT_SetRelOptions:
case AT_ResetRelOptions:
case AT_ReplaceRelOptions:
case AT_SetStatistics:
case AT_SetStorage:
case AT_DropCluster:
case AT_ClusterOn:
case AT_EnableRowSecurity:
case AT_DisableRowSecurity:
case AT_SetTableSpace:
case AT_ReAddStatistics:
case AT_SetCompression:
/* allowed on chunks */
break;
case AT_AddConstraint:
{
/* if this is an OSM chunk, block the operation */
Chunk *chunk = ts_chunk_get_by_relid(relid, false /* fail_if_not_found */);
if (chunk && chunk->fd.osm_chunk)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("operation not supported on OSM chunk tables")));
}
break;
}
case AT_DropConstraint:
{
/* if this is an OSM chunk, block the operation */
Chunk *chunk = ts_chunk_get_by_relid(relid, false /* fail_if_not_found */);
if (chunk && chunk->fd.osm_chunk)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("operation not supported on OSM chunk tables")));
}
break;
}
default:
/* disable by default */
all_allowed = false;
break;
}
}
if (!all_allowed)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("operation not supported on chunk tables")));
}
}
/* we block some ALTER commands on continuous aggregate materialization tables
*/
static void
check_continuous_agg_alter_table_allowed(Hypertable *ht, AlterTableStmt *stmt)
{
ListCell *lc;
ContinuousAggHypertableStatus status = ts_continuous_agg_hypertable_status(ht->fd.id);
if ((status & HypertableIsMaterialization) == 0)
return;
/* only allow if all commands are allowed */
foreach (lc, stmt->cmds)
{
AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lc);
switch (cmd->subtype)
{
case AT_AddIndex:
case AT_ReAddIndex:
case AT_SetRelOptions:
case AT_ReplicaIdentity:
/* allowed on materialization tables */
continue;
default:
/* disable by default */
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("operation not supported on materialization tables")));
break;
}
}
}
static void
check_alter_table_allowed_on_ht_with_compression(Hypertable *ht, AlterTableStmt *stmt)
{
ListCell *lc;
if (!TS_HYPERTABLE_HAS_COMPRESSION_ENABLED(ht))
return;
/* only allow if all commands are allowed */
foreach (lc, stmt->cmds)
{
AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lc);
switch (cmd->subtype)
{
/*
* ALLOWED:
*
* This is a whitelist of allowed commands.
*/
case AT_AddIndex:
case AT_ReAddIndex:
case AT_ResetRelOptions:
case AT_ReplaceRelOptions:
case AT_SetRelOptions:
case AT_ClusterOn:
case AT_DropCluster:
case AT_ChangeOwner:
/* this is passed down in `process_altertable_change_owner` */
case AT_SetTableSpace:
/* this is passed down in `process_altertable_set_tablespace_end` */
case AT_SetStatistics: /* should this be pushed down in some way? */
case AT_AddColumn: /* this is passed down */
case AT_ColumnDefault: /* this is passed down */
case AT_DropColumn: /* this is passed down */
case AT_DropConstraint: /* this is passed down */
case AT_ReplicaIdentity:
case AT_ReAddStatistics:
case AT_SetCompression:
continue;
/*
* BLOCKED:
*
* List things that we want to explicitly block for documentation purposes
* But also block everything else as well.
*/
case AT_EnableRowSecurity:
case AT_DisableRowSecurity:
case AT_ForceRowSecurity:
case AT_NoForceRowSecurity:
default:
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("operation not supported on hypertables that have compression "
"enabled")));
break;
}
}
}
static void
check_altertable_add_column_for_compressed(Hypertable *ht, ColumnDef *col)
{
if (col->constraints)
{
bool has_default = false;
bool has_notnull = col->is_not_null;
ListCell *lc;
bool is_bool = false;
foreach (lc, col->constraints)
{
Constraint *constraint = lfirst_node(Constraint, lc);
switch (constraint->contype)
{
/*
* We can safelly ignore NULL constraints because it does nothing
* and according to Postgres docs is useless and exist just for
* compatibility with other database systems
* https://www.postgresql.org/docs/current/ddl-constraints.html#id-1.5.4.6.6
*/
case CONSTR_NULL:
continue;
case CONSTR_NOTNULL:
has_notnull = true;
continue;
case CONSTR_DEFAULT:
/*
* Since default expressions might trigger a table rewrite we
* only allow Const here for now.
*/
if (!IsA(constraint->raw_expr, A_Const))
{
if (IsA(constraint->raw_expr, TypeCast) &&
IsA(castNode(TypeCast, constraint->raw_expr)->arg, A_Const))
{
/*
* Ignore error only for boolean column, as values like
* 'True' or 'False' are treated as TypeCast.
*/
char *name =
strVal(llast(((TypeCast *) constraint->raw_expr)->typeName->names));
is_bool = strstr(name, "bool") ? true : false;
}
if (!is_bool)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg(
"cannot add column with non-constant default expression "
"to a hypertable that has compression enabled")));
}
has_default = true;
continue;
default:
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot add column with constraints "
"to a hypertable that has compression enabled")));
break;
}
}
/* require a default for columns added with NOT NULL */
if (has_notnull && !has_default)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot add column with NOT NULL constraint without default "
"to a hypertable that has compression enabled")));
}
}
if (col->is_not_null || col->identitySequence != NULL)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot add column with constraints to a hypertable that has "
"compression enabled")));
}
/* not possible to get non-null value here this is set when
* ALTER TABLE ALTER COLUMN ... SET TYPE < > USING ...
* but check anyway.
*/
Assert(col->raw_default == NULL && col->cooked_default == NULL);
}
static void
relation_not_only(RangeVar *rv)
{
if (!rv->inh)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("ONLY option not supported on hypertable operations")));
}
static void
add_hypertable_to_process_args(ProcessUtilityArgs *args, const Hypertable *ht)
{
args->hypertable_list = lappend_oid(args->hypertable_list, ht->main_table_relid);
}
static bool
check_table_in_rangevar_list(List *rvlist, Name schema_name, Name table_name)
{
ListCell *l;
foreach (l, rvlist)
{
RangeVar *rvar = lfirst_node(RangeVar, l);
if (strcmp(rvar->relname, NameStr(*table_name)) == 0 &&
strcmp(rvar->schemaname, NameStr(*schema_name)) == 0)
return true;
}
return false;
}
static void
add_chunk_oid(Hypertable *ht, Oid chunk_relid, void *vargs)
{
ProcessUtilityArgs *args = vargs;
GrantStmt *stmt = castNode(GrantStmt, args->parsetree);
Chunk *chunk = ts_chunk_get_by_relid(chunk_relid, true);
/*
* If chunk is in the same schema as the hypertable it could already be part of
* the objects list in the case of "GRANT ALL IN SCHEMA" for example
*/
if (!check_table_in_rangevar_list(stmt->objects, &chunk->fd.schema_name, &chunk->fd.table_name))
{
RangeVar *rv =
makeRangeVar(NameStr(chunk->fd.schema_name), NameStr(chunk->fd.table_name), -1);
stmt->objects = lappend(stmt->objects, rv);
}
}
static void
process_drop_trigger_start(ProcessUtilityArgs *args, DropStmt *stmt)
{
Cache *hcache = ts_hypertable_cache_pin();
ListCell *lc;
foreach (lc, stmt->objects)
{
Node *object = lfirst(lc);
Relation rel = NULL;
ObjectAddress objaddr;
/* Get the relation of the trigger */
objaddr =
get_object_address(stmt->removeType, object, &rel, AccessShareLock, stmt->missing_ok);
if (OidIsValid(objaddr.objectId))
{
const Hypertable *ht;
Assert(NULL != rel);
Assert(objaddr.classId == TriggerRelationId);
ht =
ts_hypertable_cache_get_entry(hcache, RelationGetRelid(rel), CACHE_FLAG_MISSING_OK);
if (NULL != ht)
add_hypertable_to_process_args(args, ht);
/* Lock from get_object_address must be held until transaction end */
table_close(rel, NoLock);
}
}
ts_cache_release(hcache);
}
/* We use this for both materialized views and views. */
static void
process_alterviewschema(ProcessUtilityArgs *args)
{
AlterObjectSchemaStmt *stmt = (AlterObjectSchemaStmt *) args->parsetree;
Oid relid;
char *schema;
char *name;
Assert(stmt->objectType == OBJECT_MATVIEW || stmt->objectType == OBJECT_VIEW);
if (NULL == stmt->relation)
return;
relid = RangeVarGetRelid(stmt->relation, NoLock, true);
if (!OidIsValid(relid))
return;
schema = get_namespace_name(get_rel_namespace(relid));
name = get_rel_name(relid);
ts_continuous_agg_rename_view(schema, name, stmt->newschema, name, &stmt->objectType);
}
static void
process_altertableschema(ProcessUtilityArgs *args)
{
AlterObjectSchemaStmt *alterstmt = (AlterObjectSchemaStmt *) args->parsetree;
Oid relid;
Cache *hcache;
Hypertable *ht;
Assert(alterstmt->objectType == OBJECT_TABLE);
if (NULL == alterstmt->relation)
return;
relid = RangeVarGetRelid(alterstmt->relation, NoLock, true);
if (!OidIsValid(relid))
return;
ht = ts_hypertable_cache_get_cache_and_entry(relid, CACHE_FLAG_MISSING_OK, &hcache);
if (ht == NULL)
{
ContinuousAgg *cagg = ts_continuous_agg_find_by_relid(relid);
if (cagg)
{
alterstmt->objectType = OBJECT_MATVIEW;
process_alterviewschema(args);
ts_cache_release(hcache);
return;
}
Chunk *chunk = ts_chunk_get_by_relid(relid, false);
if (NULL != chunk)
ts_chunk_set_schema(chunk, alterstmt->newschema);
}
else
{
ts_hypertable_set_schema(ht, alterstmt->newschema);
add_hypertable_to_process_args(args, ht);
}
ts_cache_release(hcache);
}
/* Change the schema of a hypertable or a chunk */
static DDLResult
process_alterobjectschema(ProcessUtilityArgs *args)
{
AlterObjectSchemaStmt *alterstmt = (AlterObjectSchemaStmt *) args->parsetree;
switch (alterstmt->objectType)
{
case OBJECT_TABLE:
process_altertableschema(args);
break;
case OBJECT_MATVIEW:
case OBJECT_VIEW:
process_alterviewschema(args);
break;
default:
break;
}
return DDL_CONTINUE;
}
static DDLResult
process_copy(ProcessUtilityArgs *args)
{
CopyStmt *stmt = (CopyStmt *) args->parsetree;
ts_begin_tss_store_callback();
/*
* Needed to add the appropriate number of tuples to the completion tag
*/
uint64 processed;
Hypertable *ht = NULL;
Cache *hcache = NULL;
Oid relid;
if (stmt->relation)
{
relid = RangeVarGetRelid(stmt->relation, NoLock, true);
if (!OidIsValid(relid))
return DDL_CONTINUE;
ht = ts_hypertable_cache_get_cache_and_entry(relid, CACHE_FLAG_MISSING_OK, &hcache);
if (ht == NULL)
{
ts_cache_release(hcache);
return DDL_CONTINUE;
}
}
/* We only copy for COPY FROM (which copies into a hypertable). Since
* hypertable data are in the hypertable chunks and no data would be
* copied, we skip the copy for COPY TO, but print an informative
* message. */
if (!stmt->is_from || NULL == stmt->relation)
{
if (ht && stmt->relation)
ereport(NOTICE,
(errmsg("hypertable data are in the chunks, no data will be copied"),
errdetail("Data for hypertables are stored in the chunks of a hypertable so "
"COPY TO of a hypertable will not copy any data."),
errhint("Use \"COPY (SELECT * FROM <hypertable>) TO ...\" to copy all data in "
"hypertable, or copy each chunk individually.")));
if (hcache)
ts_cache_release(hcache);
return DDL_CONTINUE;
}
PreventCommandIfReadOnly("COPY FROM");
/* Performs acl check in here inside `copy_security_check` */
timescaledb_DoCopy(stmt, args->query_string, &processed, ht);
args->completion_tag->commandTag = CMDTAG_COPY;
args->completion_tag->nprocessed = processed;
add_hypertable_to_process_args(args, ht);
ts_cache_release(hcache);
ts_end_tss_store_callback(args->query_string,
args->pstmt->stmt_location,
args->pstmt->stmt_len,
args->pstmt->queryId,
args->completion_tag->nprocessed);
return DDL_DONE;
}
typedef void (*process_chunk_t)(Hypertable *ht, Oid chunk_relid, void *arg);
typedef void (*mt_process_chunk_t)(int32 hypertable_id, Oid chunk_relid, void *arg);
/*
* Applies a function to each chunk of a hypertable.
*
* Returns the number of processed chunks, or -1 if the table was not a
* hypertable.
*/
static int
foreach_chunk(Hypertable *ht, process_chunk_t process_chunk, void *arg)
{
List *chunks;
ListCell *lc;
int n = 0;
if (NULL == ht)
return -1;
chunks = find_inheritance_children(ht->main_table_relid, NoLock);
foreach (lc, chunks)
{
process_chunk(ht, lfirst_oid(lc), arg);
n++;
}
return n;
}
static int
foreach_chunk_multitransaction(Oid relid, MemoryContext mctx, mt_process_chunk_t process_chunk,
void *arg)
{
Cache *hcache;
Hypertable *ht;
int32 hypertable_id;
List *chunks;
ListCell *lc;
int num_chunks = -1;
StartTransactionCommand();
MemoryContextSwitchTo(mctx);
LockRelationOid(relid, AccessShareLock);
ht = ts_hypertable_cache_get_cache_and_entry(relid, CACHE_FLAG_MISSING_OK, &hcache);
if (NULL == ht)
{
ts_cache_release(hcache);
CommitTransactionCommand();
return -1;
}
hypertable_id = ht->fd.id;
chunks = find_inheritance_children(ht->main_table_relid, NoLock);
ts_cache_release(hcache);
CommitTransactionCommand();
num_chunks = list_length(chunks);
foreach (lc, chunks)
{
process_chunk(hypertable_id, lfirst_oid(lc), arg);
}
list_free(chunks);
return num_chunks;
}
typedef struct VacuumCtx
{
VacuumRelation *ht_vacuum_rel;
List *chunk_rels;
} VacuumCtx;
/* Adds a chunk to the list of tables to be vacuumed */
static void
add_chunk_to_vacuum(Hypertable *ht, Oid chunk_relid, void *arg)
{
VacuumCtx *ctx = (VacuumCtx *) arg;
Chunk *chunk = ts_chunk_get_by_relid(chunk_relid, true);
VacuumRelation *chunk_vacuum_rel;
RangeVar *chunk_range_var;
chunk_range_var = copyObject(ctx->ht_vacuum_rel->relation);
chunk_range_var->relname = NameStr(chunk->fd.table_name);
chunk_range_var->schemaname = NameStr(chunk->fd.schema_name);
chunk_vacuum_rel =
makeVacuumRelation(chunk_range_var, chunk_relid, ctx->ht_vacuum_rel->va_cols);
ctx->chunk_rels = lappend(ctx->chunk_rels, chunk_vacuum_rel);
/* If we have a compressed chunk, make sure to analyze it as well */
if (chunk->fd.compressed_chunk_id != INVALID_CHUNK_ID)
{
Chunk *comp_chunk = ts_chunk_get_by_id(chunk->fd.compressed_chunk_id, false);
/* Compressed chunk might be missing due to concurrent operations */
if (comp_chunk)
{
chunk_vacuum_rel = makeVacuumRelation(NULL, comp_chunk->table_id, NIL);
ctx->chunk_rels = lappend(ctx->chunk_rels, chunk_vacuum_rel);
}
}
}
/*
* Construct a list of VacuumRelations for all vacuumable rels in
* the current database. This is similar to the PostgresQL get_all_vacuum_rels
* from vacuum.c.
*/
static List *
ts_get_all_vacuum_rels(bool is_vacuumcmd)
{
List *vacrels = NIL;
Relation pgclass;
TableScanDesc scan;
HeapTuple tuple;
Cache *hcache = ts_hypertable_cache_pin();
pgclass = table_open(RelationRelationId, AccessShareLock);
scan = table_beginscan_catalog(pgclass, 0, NULL);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
Oid relid;
relid = classform->oid;
/* check permissions of relation */
if (!vacuum_is_permitted_for_relation_compat(relid,
classform,
is_vacuumcmd ? VACOPT_VACUUM : VACOPT_ANALYZE))
continue;
/*
* We include partitioned tables here; depending on which operation is
* to be performed, caller will decide whether to process or ignore
* them.
*/
if (classform->relkind != RELKIND_RELATION && classform->relkind != RELKIND_MATVIEW &&
classform->relkind != RELKIND_PARTITIONED_TABLE)
continue;
/*
* Build VacuumRelation(s) specifying the table OIDs to be processed.
* We omit a RangeVar since it wouldn't be appropriate to complain
* about failure to open one of these relations later.
*/
vacrels = lappend(vacrels, makeVacuumRelation(NULL, relid, NIL));
}
table_endscan(scan);
table_close(pgclass, AccessShareLock);
ts_cache_release(hcache);
return vacrels;
}
/* Vacuums/Analyzes a hypertable and all of it's chunks */
static DDLResult
process_vacuum(ProcessUtilityArgs *args)
{
VacuumStmt *stmt = (VacuumStmt *) args->parsetree;
bool is_toplevel = (args->context == PROCESS_UTILITY_TOPLEVEL);
VacuumCtx ctx = {
.ht_vacuum_rel = NULL,
.chunk_rels = NIL,
};
ListCell *lc;
Hypertable *ht;
List *vacuum_rels = NIL;
bool is_vacuumcmd;
/* save original VacuumRelation list */
List *saved_stmt_rels = stmt->rels;
is_vacuumcmd = stmt->is_vacuumcmd;
#if PG16_GE
if (is_vacuumcmd)
{
/* Look for new option ONLY_DATABASE_STATS */
foreach (lc, stmt->options)
{
DefElem *opt = (DefElem *) lfirst(lc);
/* if "only_database_stats" is defined then don't execute our custom code and return to
* the postgres execution for the proper validations */
if (strcmp(opt->defname, "only_database_stats") == 0)
return DDL_CONTINUE;
}
}
#endif
if (stmt->rels == NIL)
vacuum_rels = ts_get_all_vacuum_rels(is_vacuumcmd);
else
{
Cache *hcache = ts_hypertable_cache_pin();
foreach (lc, stmt->rels)
{
VacuumRelation *vacuum_rel = lfirst_node(VacuumRelation, lc);
Oid table_relid = vacuum_rel->oid;
if (!OidIsValid(table_relid) && vacuum_rel->relation != NULL)
table_relid = RangeVarGetRelid(vacuum_rel->relation, NoLock, true);
if (OidIsValid(table_relid))
{
ht = ts_hypertable_cache_get_entry(hcache, table_relid, CACHE_FLAG_MISSING_OK);
if (ht)
{
add_hypertable_to_process_args(args, ht);
ctx.ht_vacuum_rel = vacuum_rel;
foreach_chunk(ht, add_chunk_to_vacuum, &ctx);
}
}
vacuum_rels = lappend(vacuum_rels, vacuum_rel);
}
ts_cache_release(hcache);
}
stmt->rels = list_concat(ctx.chunk_rels, vacuum_rels);
/* The list of rels to vacuum could be empty if we are only vacuuming a
* distributed hypertable. In that case, we don't want to vacuum locally. */
if (list_length(stmt->rels) > 0)
{
PreventCommandDuringRecovery(is_vacuumcmd ? "VACUUM" : "ANALYZE");
/* ACL permission checks inside vacuum_rel and analyze_rel called by this ExecVacuum */
ExecVacuum(args->parse_state, stmt, is_toplevel);
}
/*
Restore original list. stmt->rels which has references to
VacuumRelation list is freed up, however VacuumStmt is not
cleaned up because of which there is a crash.
*/
stmt->rels = saved_stmt_rels;
return DDL_DONE;
}
static void
process_truncate_chunk(Hypertable *ht, Oid chunk_relid, void *arg)
{
TruncateStmt *stmt = arg;
ObjectAddress objaddr = {
.classId = RelationRelationId,
.objectId = chunk_relid,
};
performDeletion(&objaddr, stmt->behavior, 0);
}
static bool
relation_should_recurse(RangeVar *rv)
{
return rv->inh;
}
/* handle forwarding TRUNCATEs to the chunks of a hypertable */
static void
handle_truncate_hypertable(ProcessUtilityArgs *args, TruncateStmt *stmt, Hypertable *ht)
{
add_hypertable_to_process_args(args, ht);
/* Delete the metadata */
ts_chunk_delete_by_hypertable_id(ht->fd.id);
/* Drop the chunk tables */
foreach_chunk(ht, process_truncate_chunk, stmt);
}
/*
* Truncate a hypertable.
*/
static DDLResult
process_truncate(ProcessUtilityArgs *args)
{
TruncateStmt *stmt = (TruncateStmt *) args->parsetree;
Cache *hcache = ts_hypertable_cache_pin();
ListCell *cell;
List *hypertables = NIL, *mat_hypertables = NIL;
List *relations = NIL;
bool list_changed = false;
MemoryContext oldctx, parsetreectx = GetMemoryChunkContext(args->parsetree);
/* For all hypertables, we drop the now empty chunks. We also propagate the
* TRUNCATE call to the compressed version of the hypertable, if it exists.
*/
/* Preprocess and filter out distributed hypertables */
foreach (cell, stmt->relations)
{
RangeVar *rv = lfirst(cell);
Oid relid;
bool list_append = false;
if (!rv)
continue;
/* Grab AccessExclusiveLock, same as regular TRUNCATE processing grabs
* below. We just do it preemptively here. */
relid = RangeVarGetRelid(rv, AccessExclusiveLock, true);
if (!OidIsValid(relid))
{
/* We should add invalid relations to the list to raise error on the
* standard_ProcessUtility when we're trying to TRUNCATE a nonexistent relation */
list_append = true;
}
else
{
switch (get_rel_relkind(relid))
{
case RELKIND_VIEW:
{
ContinuousAgg *cagg = ts_continuous_agg_find_by_relid(relid);
if (cagg)
{
Hypertable *mat_ht, *raw_ht;
if (!relation_should_recurse(rv))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot truncate only a continuous aggregate")));
mat_ht = ts_hypertable_get_by_id(cagg->data.mat_hypertable_id);
Assert(mat_ht != NULL);
/* Create list item into the same context of the list */
oldctx = MemoryContextSwitchTo(parsetreectx);
rv = makeRangeVar(NameStr(mat_ht->fd.schema_name),
NameStr(mat_ht->fd.table_name),
-1);
MemoryContextSwitchTo(oldctx);
/* Invalidate the entire continuous aggregate since it no
* longer has any data */
raw_ht = ts_hypertable_get_by_id(cagg->data.raw_hypertable_id);
Assert(raw_ht != NULL);
ts_cm_functions->continuous_agg_invalidate_mat_ht(raw_ht,
mat_ht,
TS_TIME_NOBEGIN,
TS_TIME_NOEND);
/* Additionally, this cagg's materialization hypertable could be the
* underlying hypertable for other caggs defined on top of it, in that case
* we must update the hypertable invalidation log */
ContinuousAggHypertableStatus agg_status;
agg_status = ts_continuous_agg_hypertable_status(mat_ht->fd.id);
if (agg_status & HypertableIsRawTable)
ts_cm_functions->continuous_agg_invalidate_raw_ht(mat_ht,
TS_TIME_NOBEGIN,
TS_TIME_NOEND);
/* mark list as changed because we'll add the materialization hypertable */
list_changed = true;
/* list of materialization hypertables to reset the watermark */
mat_hypertables = lappend(mat_hypertables, mat_ht);
/* include the materialization hypertable to the list to be handled by the
* proper hypertable and chunk truncate code-path later */
hypertables = lappend(hypertables, mat_ht);
}
list_append = true;
break;
}
case RELKIND_RELATION:
/* TRUNCATE for foreign tables not implemented yet. This will raise an error. */
case RELKIND_FOREIGN_TABLE:
{
list_append = true;
Hypertable *ht =
ts_hypertable_cache_get_entry(hcache, relid, CACHE_FLAG_MISSING_OK);
if (ht)
{
ContinuousAggHypertableStatus agg_status;
agg_status = ts_continuous_agg_hypertable_status(ht->fd.id);
if ((agg_status & HypertableIsMaterialization) != 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),