/
alter_table.c
1917 lines (1662 loc) · 59.2 KB
/
alter_table.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
/*-------------------------------------------------------------------------
*
* alter_table.c
* Routines related to the altering of tables.
*
* There are three UDFs defined in this file:
* undistribute_table:
* Turns a distributed table to a local table
* alter_distributed_table:
* Alters distribution_column, shard_count or colocate_with
* properties of a distributed table
* alter_table_set_access_method:
* Changes the access method of a table
*
* All three methods work in similar steps:
* - Create a new table the required way (with a different
* shard count, distribution column, colocate with value,
* access method or local)
* - Move everything to the new table
* - Drop the old one
*
* Copyright (c) Citus Data, Inc.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "fmgr.h"
#include "access/hash.h"
#include "access/xact.h"
#include "catalog/dependency.h"
#include "catalog/pg_am.h"
#include "columnar/columnar.h"
#include "columnar/columnar_tableam.h"
#include "commands/defrem.h"
#include "distributed/colocation_utils.h"
#include "distributed/commands.h"
#include "distributed/commands/utility_hook.h"
#include "distributed/coordinator_protocol.h"
#include "distributed/deparser.h"
#include "distributed/distribution_column.h"
#include "distributed/listutils.h"
#include "distributed/local_executor.h"
#include "distributed/metadata/dependency.h"
#include "distributed/metadata/distobject.h"
#include "distributed/metadata_cache.h"
#include "distributed/metadata_sync.h"
#include "distributed/multi_executor.h"
#include "distributed/multi_logical_planner.h"
#include "distributed/multi_partitioning_utils.h"
#include "distributed/reference_table_utils.h"
#include "distributed/relation_access_tracking.h"
#include "distributed/shard_utils.h"
#include "distributed/worker_protocol.h"
#include "distributed/worker_transaction.h"
#include "executor/spi.h"
#include "nodes/pg_list.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
/* Table Conversion Types */
#define UNDISTRIBUTE_TABLE 'u'
#define ALTER_DISTRIBUTED_TABLE 'a'
#define ALTER_TABLE_SET_ACCESS_METHOD 'm'
#define UNDISTRIBUTE_TABLE_CASCADE_HINT \
"Use cascade option to undistribute all the relations involved in " \
"a foreign key relationship with %s by executing SELECT " \
"undistribute_table($$%s$$, cascade_via_foreign_keys=>true)"
typedef TableConversionReturn *(*TableConversionFunction)(struct
TableConversionParameters *);
/*
* TableConversionState objects are used for table conversion functions:
* UndistributeTable, AlterDistributedTable, AlterTableSetAccessMethod.
*
* They can be created using TableConversionParameters objects with
* CreateTableConversion function.
*
* TableConversionState objects include everything TableConversionParameters
* objects do and some extra to be used in the conversion process.
*/
typedef struct TableConversionState
{
/*
* Determines type of conversion: UNDISTRIBUTE_TABLE,
* ALTER_DISTRIBUTED_TABLE, ALTER_TABLE_SET_ACCESS_METHOD.
*/
char conversionType;
/* Oid of the table to do conversion on */
Oid relationId;
/*
* Options to do conversions on the table
* distributionColumn is the name of the new distribution column,
* shardCountIsNull is if the shardCount variable is not given
* shardCount is the new shard count,
* colocateWith is the name of the table to colocate with, 'none', or
* 'default'
* accessMethod is the name of the new accessMethod for the table
*/
char *distributionColumn;
bool shardCountIsNull;
int shardCount;
char *colocateWith;
char *accessMethod;
/*
* cascadeToColocated determines whether the shardCount and
* colocateWith will be cascaded to the currently colocated tables
*/
CascadeToColocatedOption cascadeToColocated;
/*
* cascadeViaForeignKeys determines if the conversion operation
* will be cascaded to the graph connected with foreign keys
* to the table
*/
bool cascadeViaForeignKeys;
/* schema of the table */
char *schemaName;
Oid schemaId;
/* name of the table */
char *relationName;
/* new relation oid after the conversion */
Oid newRelationId;
/* temporary name for intermediate table */
char *tempName;
/*hash that is appended to the name to create tempName */
uint32 hashOfName;
/* shard count of the table before conversion */
int originalShardCount;
/* list of the table oids of tables colocated with the table before conversion */
List *colocatedTableList;
/* new distribution key, if distributionColumn variable is given */
Var *distributionKey;
/* distribution key of the table before conversion */
Var *originalDistributionKey;
/* access method name of the table before conversion */
char *originalAccessMethod;
/*
* The function that will be used for the conversion
* Must comply with conversionType
* UNDISTRIBUTE_TABLE -> UndistributeTable
* ALTER_DISTRIBUTED_TABLE -> AlterDistributedTable
* ALTER_TABLE_SET_ACCESS_METHOD -> AlterTableSetAccessMethod
*/
TableConversionFunction function;
/*
* suppressNoticeMessages determines if we want to suppress NOTICE
* messages that we explicitly issue
*/
bool suppressNoticeMessages;
} TableConversionState;
static TableConversionReturn * AlterDistributedTable(TableConversionParameters *params);
static TableConversionReturn * AlterTableSetAccessMethod(
TableConversionParameters *params);
static TableConversionReturn * ConvertTable(TableConversionState *con);
static bool SwitchToSequentialAndLocalExecutionIfShardNameTooLong(char *relationName,
char *longestShardName);
static void DropIndexesNotSupportedByColumnar(Oid relationId,
bool suppressNoticeMessages);
static char * GetIndexAccessMethodName(Oid indexId);
static void DropConstraintRestrict(Oid relationId, Oid constraintId);
static void DropIndexRestrict(Oid indexId);
static void EnsureTableNotReferencing(Oid relationId, char conversionType);
static void EnsureTableNotReferenced(Oid relationId, char conversionType);
static void EnsureTableNotForeign(Oid relationId);
static void EnsureTableNotPartition(Oid relationId);
static TableConversionState * CreateTableConversion(TableConversionParameters *params);
static void CreateDistributedTableLike(TableConversionState *con);
static void CreateCitusTableLike(TableConversionState *con);
static List * GetViewCreationCommandsOfTable(Oid relationId);
static void ReplaceTable(Oid sourceId, Oid targetId, List *justBeforeDropCommands,
bool suppressNoticeMessages);
static bool HasAnyGeneratedStoredColumns(Oid relationId);
static List * GetNonGeneratedStoredColumnNameList(Oid relationId);
static void CheckAlterDistributedTableConversionParameters(TableConversionState *con);
static char * CreateWorkerChangeSequenceDependencyCommand(char *sequenceSchemaName,
char *sequenceName,
char *sourceSchemaName,
char *sourceName,
char *targetSchemaName,
char *targetName);
static char * GetAccessMethodForMatViewIfExists(Oid viewOid);
static bool WillRecreateForeignKeyToReferenceTable(Oid relationId,
CascadeToColocatedOption cascadeOption);
static void WarningsForDroppingForeignKeysWithDistributedTables(Oid relationId);
PG_FUNCTION_INFO_V1(undistribute_table);
PG_FUNCTION_INFO_V1(alter_distributed_table);
PG_FUNCTION_INFO_V1(alter_table_set_access_method);
PG_FUNCTION_INFO_V1(worker_change_sequence_dependency);
/*
* undistribute_table gets a distributed table name and
* udistributes it.
*/
Datum
undistribute_table(PG_FUNCTION_ARGS)
{
CheckCitusVersion(ERROR);
Oid relationId = PG_GETARG_OID(0);
bool cascadeViaForeignKeys = PG_GETARG_BOOL(1);
TableConversionParameters params = {
.relationId = relationId,
.cascadeViaForeignKeys = cascadeViaForeignKeys
};
UndistributeTable(¶ms);
PG_RETURN_VOID();
}
/*
* alter_distributed_table gets a distributed table and some other
* parameters and alters some properties of the table according to
* the parameters.
*/
Datum
alter_distributed_table(PG_FUNCTION_ARGS)
{
CheckCitusVersion(ERROR);
Oid relationId = PG_GETARG_OID(0);
char *distributionColumn = NULL;
if (!PG_ARGISNULL(1))
{
text *distributionColumnText = PG_GETARG_TEXT_P(1);
distributionColumn = text_to_cstring(distributionColumnText);
}
int shardCount = 0;
bool shardCountIsNull = true;
if (!PG_ARGISNULL(2))
{
shardCount = PG_GETARG_INT32(2);
shardCountIsNull = false;
}
char *colocateWith = NULL;
if (!PG_ARGISNULL(3))
{
text *colocateWithText = PG_GETARG_TEXT_P(3);
colocateWith = text_to_cstring(colocateWithText);
}
CascadeToColocatedOption cascadeToColocated = CASCADE_TO_COLOCATED_UNSPECIFIED;
if (!PG_ARGISNULL(4))
{
if (PG_GETARG_BOOL(4) == true)
{
cascadeToColocated = CASCADE_TO_COLOCATED_YES;
}
else
{
cascadeToColocated = CASCADE_TO_COLOCATED_NO;
}
}
TableConversionParameters params = {
.relationId = relationId,
.distributionColumn = distributionColumn,
.shardCountIsNull = shardCountIsNull,
.shardCount = shardCount,
.colocateWith = colocateWith,
.cascadeToColocated = cascadeToColocated
};
AlterDistributedTable(¶ms);
PG_RETURN_VOID();
}
/*
* alter_table_set_access_method gets a distributed table and an access
* method and changes table's access method into that.
*/
Datum
alter_table_set_access_method(PG_FUNCTION_ARGS)
{
CheckCitusVersion(ERROR);
Oid relationId = PG_GETARG_OID(0);
text *accessMethodText = PG_GETARG_TEXT_P(1);
char *accessMethod = text_to_cstring(accessMethodText);
TableConversionParameters params = {
.relationId = relationId,
.accessMethod = accessMethod
};
AlterTableSetAccessMethod(¶ms);
PG_RETURN_VOID();
}
/*
* worker_change_sequence_dependency is a wrapper UDF for
* changeDependencyFor function
*/
Datum
worker_change_sequence_dependency(PG_FUNCTION_ARGS)
{
Oid sequenceOid = PG_GETARG_OID(0);
Oid sourceRelationOid = PG_GETARG_OID(1);
Oid targetRelationOid = PG_GETARG_OID(2);
changeDependencyFor(RelationRelationId, sequenceOid,
RelationRelationId, sourceRelationOid, targetRelationOid);
PG_RETURN_VOID();
}
/*
* UndistributeTable undistributes the given table. It uses ConvertTable function to
* create a new local table and move everything to that table.
*
* The local tables, tables with references, partition tables and foreign tables are
* not supported. The function gives errors in these cases.
*/
TableConversionReturn *
UndistributeTable(TableConversionParameters *params)
{
EnsureCoordinator();
EnsureRelationExists(params->relationId);
EnsureTableOwner(params->relationId);
if (!IsCitusTable(params->relationId))
{
ereport(ERROR, (errmsg("cannot undistribute table "
"because the table is not distributed")));
}
if (!params->cascadeViaForeignKeys)
{
EnsureTableNotReferencing(params->relationId, UNDISTRIBUTE_TABLE);
EnsureTableNotReferenced(params->relationId, UNDISTRIBUTE_TABLE);
}
EnsureTableNotForeign(params->relationId);
EnsureTableNotPartition(params->relationId);
if (PartitionedTable(params->relationId))
{
List *partitionList = PartitionList(params->relationId);
/*
* This is a less common pattern where foreing key is directly from/to
* the partition relation as we already handled inherited foreign keys
* on partitions either by erroring out or cascading via foreign keys.
* It seems an acceptable limitation for now to ask users to drop such
* foreign keys manually.
*/
ErrorIfAnyPartitionRelationInvolvedInNonInheritedFKey(partitionList);
}
params->conversionType = UNDISTRIBUTE_TABLE;
params->shardCountIsNull = true;
TableConversionState *con = CreateTableConversion(params);
return ConvertTable(con);
}
/*
* AlterDistributedTable changes some properties of the given table. It uses
* ConvertTable function to create a new local table and move everything to that table.
*
* The local and reference tables, tables with references, partition tables and foreign
* tables are not supported. The function gives errors in these cases.
*/
TableConversionReturn *
AlterDistributedTable(TableConversionParameters *params)
{
EnsureCoordinator();
EnsureRelationExists(params->relationId);
EnsureTableOwner(params->relationId);
if (!IsCitusTableType(params->relationId, DISTRIBUTED_TABLE))
{
ereport(ERROR, (errmsg("cannot alter table because the table "
"is not distributed")));
}
EnsureTableNotForeign(params->relationId);
EnsureTableNotPartition(params->relationId);
EnsureHashDistributedTable(params->relationId);
params->conversionType = ALTER_DISTRIBUTED_TABLE;
TableConversionState *con = CreateTableConversion(params);
CheckAlterDistributedTableConversionParameters(con);
if (WillRecreateForeignKeyToReferenceTable(con->relationId, con->cascadeToColocated))
{
ereport(DEBUG1, (errmsg("setting multi shard modify mode to sequential")));
SetLocalMultiShardModifyModeToSequential();
}
return ConvertTable(con);
}
/*
* AlterTableSetAccessMethod changes the access method of the given table. It uses
* ConvertTable function to create a new table with the access method and move everything
* to that table.
*
* The local and references tables, tables with references, partition tables and foreign
* tables are not supported. The function gives errors in these cases.
*/
TableConversionReturn *
AlterTableSetAccessMethod(TableConversionParameters *params)
{
EnsureRelationExists(params->relationId);
EnsureTableOwner(params->relationId);
if (IsCitusTable(params->relationId))
{
EnsureCoordinator();
}
EnsureTableNotReferencing(params->relationId, ALTER_TABLE_SET_ACCESS_METHOD);
EnsureTableNotReferenced(params->relationId, ALTER_TABLE_SET_ACCESS_METHOD);
EnsureTableNotForeign(params->relationId);
if (IsCitusTableType(params->relationId, DISTRIBUTED_TABLE))
{
EnsureHashDistributedTable(params->relationId);
}
if (PartitionedTable(params->relationId))
{
ereport(ERROR, (errmsg("you cannot alter access method of a partitioned table")));
}
if (PartitionTable(params->relationId) &&
IsCitusTableType(params->relationId, DISTRIBUTED_TABLE))
{
Oid parentRelationId = PartitionParentOid(params->relationId);
if (HasForeignKeyToReferenceTable(parentRelationId))
{
ereport(DEBUG1, (errmsg("setting multi shard modify mode to sequential")));
SetLocalMultiShardModifyModeToSequential();
}
}
params->conversionType = ALTER_TABLE_SET_ACCESS_METHOD;
params->shardCountIsNull = true;
TableConversionState *con = CreateTableConversion(params);
if (strcmp(con->originalAccessMethod, con->accessMethod) == 0)
{
ereport(ERROR, (errmsg("the access method of %s is already %s",
generate_qualified_relation_name(con->relationId),
con->accessMethod)));
}
return ConvertTable(con);
}
/*
* ConvertTable is used for converting a table into a new table with different properties.
* The conversion is done by creating a new table, moving everything to the new table and
* dropping the old one. So the oid of the table is not preserved.
*
* The new table will have the same name, columns and rows. It will also have partitions,
* views, sequences of the old table. Finally it will have everything created by
* GetPostLoadTableCreationCommands function, which include indexes. These will be
* re-created during conversion, so their oids are not preserved either (except for
* sequences). However, their names are preserved.
*
* The dropping of old table is done with CASCADE. Anything not mentioned here will
* be dropped.
*
* The function returns a TableConversionReturn object that can stores variables that
* can be used at the caller operations.
*/
TableConversionReturn *
ConvertTable(TableConversionState *con)
{
/*
* We undistribute citus local tables that are not chained with any reference
* tables via foreign keys at the end of the utility hook.
* Here we temporarily set the related GUC to off to disable the logic for
* internally executed DDL's that might invoke this mechanism unnecessarily.
*/
bool oldEnableLocalReferenceForeignKeys = EnableLocalReferenceForeignKeys;
SetLocalEnableLocalReferenceForeignKeys(false);
/* switch to sequential execution if shard names will be too long */
SwitchToSequentialAndLocalExecutionIfRelationNameTooLong(con->relationId,
con->relationName);
if (con->conversionType == UNDISTRIBUTE_TABLE && con->cascadeViaForeignKeys &&
(TableReferencing(con->relationId) || TableReferenced(con->relationId)))
{
/*
* Acquire ExclusiveLock as UndistributeTable does in order to
* make sure that no modifications happen on the relations.
*/
CascadeOperationForFkeyConnectedRelations(con->relationId, ExclusiveLock,
CASCADE_FKEY_UNDISTRIBUTE_TABLE);
/*
* Undistributed every foreign key connected relation in our foreign key
* subgraph including itself, so return here.
*/
SetLocalEnableLocalReferenceForeignKeys(oldEnableLocalReferenceForeignKeys);
return NULL;
}
char *newAccessMethod = con->accessMethod ? con->accessMethod :
con->originalAccessMethod;
IncludeSequenceDefaults includeSequenceDefaults = NEXTVAL_SEQUENCE_DEFAULTS;
List *preLoadCommands = GetPreLoadTableCreationCommands(con->relationId,
includeSequenceDefaults,
newAccessMethod);
if (con->accessMethod && strcmp(con->accessMethod, "columnar") == 0)
{
DropIndexesNotSupportedByColumnar(con->relationId,
con->suppressNoticeMessages);
}
/*
* Since we already dropped unsupported indexes, we can safely pass
* includeIndexes to be true.
*/
bool includeIndexes = true;
bool includeReplicaIdentity = true;
List *postLoadCommands = GetPostLoadTableCreationCommands(con->relationId,
includeIndexes,
includeReplicaIdentity);
List *justBeforeDropCommands = NIL;
List *attachPartitionCommands = NIL;
postLoadCommands = list_concat(postLoadCommands,
GetViewCreationCommandsOfTable(con->relationId));
List *foreignKeyCommands = NIL;
if (con->conversionType == ALTER_DISTRIBUTED_TABLE)
{
foreignKeyCommands = GetForeignConstraintToReferenceTablesCommands(
con->relationId);
if (con->cascadeToColocated == CASCADE_TO_COLOCATED_YES ||
con->cascadeToColocated == CASCADE_TO_COLOCATED_NO_ALREADY_CASCADED)
{
List *foreignKeyToDistributedTableCommands =
GetForeignConstraintToDistributedTablesCommands(con->relationId);
foreignKeyCommands = list_concat(foreignKeyCommands,
foreignKeyToDistributedTableCommands);
List *foreignKeyFromDistributedTableCommands =
GetForeignConstraintFromDistributedTablesCommands(con->relationId);
foreignKeyCommands = list_concat(foreignKeyCommands,
foreignKeyFromDistributedTableCommands);
}
else
{
WarningsForDroppingForeignKeysWithDistributedTables(con->relationId);
}
}
bool isPartitionTable = false;
char *attachToParentCommand = NULL;
if (PartitionTable(con->relationId))
{
isPartitionTable = true;
char *detachFromParentCommand = GenerateDetachPartitionCommand(con->relationId);
attachToParentCommand = GenerateAlterTableAttachPartitionCommand(con->relationId);
justBeforeDropCommands = lappend(justBeforeDropCommands, detachFromParentCommand);
}
if (PartitionedTable(con->relationId))
{
if (!con->suppressNoticeMessages)
{
ereport(NOTICE, (errmsg("converting the partitions of %s",
quote_qualified_identifier(con->schemaName,
con->relationName))));
}
List *partitionList = PartitionList(con->relationId);
Oid partitionRelationId = InvalidOid;
foreach_oid(partitionRelationId, partitionList)
{
char *detachPartitionCommand = GenerateDetachPartitionCommand(
partitionRelationId);
char *attachPartitionCommand = GenerateAlterTableAttachPartitionCommand(
partitionRelationId);
/*
* We first detach the partitions to be able to convert them separately.
* After this they are no longer partitions, so they will not be caught by
* the checks.
*/
ExecuteQueryViaSPI(detachPartitionCommand, SPI_OK_UTILITY);
attachPartitionCommands = lappend(attachPartitionCommands,
attachPartitionCommand);
CascadeToColocatedOption cascadeOption = CASCADE_TO_COLOCATED_NO;
if (con->cascadeToColocated == CASCADE_TO_COLOCATED_YES ||
con->cascadeToColocated == CASCADE_TO_COLOCATED_NO_ALREADY_CASCADED)
{
cascadeOption = CASCADE_TO_COLOCATED_NO_ALREADY_CASCADED;
}
TableConversionParameters partitionParam = {
.relationId = partitionRelationId,
.distributionColumn = con->distributionColumn,
.shardCountIsNull = con->shardCountIsNull,
.shardCount = con->shardCount,
.cascadeToColocated = cascadeOption,
.colocateWith = con->colocateWith,
.suppressNoticeMessages = con->suppressNoticeMessages,
/*
* Even if we called UndistributeTable with cascade option, we
* shouldn't cascade via foreign keys on partitions. Otherwise,
* we might try to undistribute partitions of other tables in
* our foreign key subgraph more than once.
*/
.cascadeViaForeignKeys = false
};
TableConversionReturn *partitionReturn = con->function(&partitionParam);
if (cascadeOption == CASCADE_TO_COLOCATED_NO_ALREADY_CASCADED)
{
foreignKeyCommands = list_concat(foreignKeyCommands,
partitionReturn->foreignKeyCommands);
}
}
}
if (!con->suppressNoticeMessages)
{
ereport(NOTICE, (errmsg("creating a new table for %s",
quote_qualified_identifier(con->schemaName,
con->relationName))));
}
TableDDLCommand *tableCreationCommand = NULL;
foreach_ptr(tableCreationCommand, preLoadCommands)
{
Assert(CitusIsA(tableCreationCommand, TableDDLCommand));
char *tableCreationSql = GetTableDDLCommand(tableCreationCommand);
Node *parseTree = ParseTreeNode(tableCreationSql);
RelayEventExtendNames(parseTree, con->schemaName, con->hashOfName);
ProcessUtilityParseTree(parseTree, tableCreationSql, PROCESS_UTILITY_QUERY,
NULL, None_Receiver, NULL);
}
/* set columnar options */
if (con->accessMethod == NULL && con->originalAccessMethod &&
strcmp(con->originalAccessMethod, "columnar") == 0)
{
ColumnarOptions options = { 0 };
ReadColumnarOptions(con->relationId, &options);
ColumnarTableDDLContext *context = (ColumnarTableDDLContext *) palloc0(
sizeof(ColumnarTableDDLContext));
/* build the context */
context->schemaName = con->schemaName;
context->relationName = con->relationName;
context->options = options;
char *columnarOptionsSql = GetShardedTableDDLCommandColumnar(con->hashOfName,
context);
ExecuteQueryViaSPI(columnarOptionsSql, SPI_OK_SELECT);
}
con->newRelationId = get_relname_relid(con->tempName, con->schemaId);
if (con->conversionType == ALTER_DISTRIBUTED_TABLE)
{
CreateDistributedTableLike(con);
}
else if (con->conversionType == ALTER_TABLE_SET_ACCESS_METHOD)
{
CreateCitusTableLike(con);
}
/* preserve colocation with procedures/functions */
if (con->conversionType == ALTER_DISTRIBUTED_TABLE)
{
/*
* Updating the colocationId of functions is always desirable for
* the following scenario:
* we have shardCount or colocateWith change
* AND entire co-location group is altered
* The reason for the second condition is because we currently don't
* remember the original table specified in the colocateWith when
* distributing the function. We only remember the colocationId in
* pg_dist_object table.
*/
if ((!con->shardCountIsNull || con->colocateWith != NULL) &&
(con->cascadeToColocated == CASCADE_TO_COLOCATED_YES || list_length(
con->colocatedTableList) == 1) && con->distributionColumn == NULL)
{
/*
* Update the colocationId from the one of the old relation to the one
* of the new relation for all tuples in citus.pg_dist_object
*/
UpdateDistributedObjectColocationId(TableColocationId(con->relationId),
TableColocationId(con->newRelationId));
}
}
ReplaceTable(con->relationId, con->newRelationId, justBeforeDropCommands,
con->suppressNoticeMessages);
TableDDLCommand *tableConstructionCommand = NULL;
foreach_ptr(tableConstructionCommand, postLoadCommands)
{
Assert(CitusIsA(tableConstructionCommand, TableDDLCommand));
char *tableConstructionSQL = GetTableDDLCommand(tableConstructionCommand);
ExecuteQueryViaSPI(tableConstructionSQL, SPI_OK_UTILITY);
}
char *attachPartitionCommand = NULL;
foreach_ptr(attachPartitionCommand, attachPartitionCommands)
{
Node *parseTree = ParseTreeNode(attachPartitionCommand);
ProcessUtilityParseTree(parseTree, attachPartitionCommand,
PROCESS_UTILITY_QUERY,
NULL, None_Receiver, NULL);
}
if (isPartitionTable)
{
ExecuteQueryViaSPI(attachToParentCommand, SPI_OK_UTILITY);
}
if (con->cascadeToColocated == CASCADE_TO_COLOCATED_YES)
{
Oid colocatedTableId = InvalidOid;
/* For now we only support cascade to colocation for alter_distributed_table UDF */
Assert(con->conversionType == ALTER_DISTRIBUTED_TABLE);
foreach_oid(colocatedTableId, con->colocatedTableList)
{
if (colocatedTableId == con->relationId)
{
continue;
}
char *qualifiedRelationName = quote_qualified_identifier(con->schemaName,
con->relationName);
TableConversionParameters cascadeParam = {
.relationId = colocatedTableId,
.shardCountIsNull = con->shardCountIsNull,
.shardCount = con->shardCount,
.colocateWith = qualifiedRelationName,
.cascadeToColocated = CASCADE_TO_COLOCATED_NO_ALREADY_CASCADED,
.suppressNoticeMessages = con->suppressNoticeMessages
};
TableConversionReturn *colocatedReturn = con->function(&cascadeParam);
foreignKeyCommands = list_concat(foreignKeyCommands,
colocatedReturn->foreignKeyCommands);
}
}
/* recreate foreign keys */
TableConversionReturn *ret = NULL;
if (con->conversionType == ALTER_DISTRIBUTED_TABLE)
{
if (con->cascadeToColocated != CASCADE_TO_COLOCATED_NO_ALREADY_CASCADED)
{
char *foreignKeyCommand = NULL;
foreach_ptr(foreignKeyCommand, foreignKeyCommands)
{
ExecuteQueryViaSPI(foreignKeyCommand, SPI_OK_UTILITY);
}
}
else
{
ret = palloc0(sizeof(TableConversionReturn));
ret->foreignKeyCommands = foreignKeyCommands;
}
}
/* increment command counter so that next command can see the new table */
CommandCounterIncrement();
SetLocalEnableLocalReferenceForeignKeys(oldEnableLocalReferenceForeignKeys);
return ret;
}
/*
* DropIndexesNotSupportedByColumnar is a helper function used during accces
* method conversion to drop the indexes that are not supported by columnarAM.
*/
static void
DropIndexesNotSupportedByColumnar(Oid relationId, bool suppressNoticeMessages)
{
Relation columnarRelation = RelationIdGetRelation(relationId);
List *indexIdList = RelationGetIndexList(columnarRelation);
/*
* Immediately close the relation since we might execute ALTER TABLE
* for that relation.
*/
RelationClose(columnarRelation);
Oid indexId = InvalidOid;
foreach_oid(indexId, indexIdList)
{
char *indexAmName = GetIndexAccessMethodName(indexId);
if (ColumnarSupportsIndexAM(indexAmName))
{
continue;
}
if (!suppressNoticeMessages)
{
ereport(NOTICE, (errmsg("unsupported access method for index %s "
"on columnar table %s, given index and "
"the constraint depending on the index "
"(if any) will be dropped",
get_rel_name(indexId),
generate_qualified_relation_name(relationId))));
}
Oid constraintId = get_index_constraint(indexId);
if (OidIsValid(constraintId))
{
/* index is implied by a constraint, so drop the constraint itself */
DropConstraintRestrict(relationId, constraintId);
}
else
{
DropIndexRestrict(indexId);
}
}
}
/*
* GetIndexAccessMethodName returns access method name of index with indexId.
* If there is no such index, then errors out.
*/
static char *
GetIndexAccessMethodName(Oid indexId)
{
/* fetch pg_class tuple of the index relation */
HeapTuple indexTuple = SearchSysCache1(RELOID, ObjectIdGetDatum(indexId));
if (!HeapTupleIsValid(indexTuple))
{
ereport(ERROR, (errmsg("index with oid %u does not exist", indexId)));
}
Form_pg_class indexForm = (Form_pg_class) GETSTRUCT(indexTuple);
Oid indexAMId = indexForm->relam;
ReleaseSysCache(indexTuple);
char *indexAmName = get_am_name(indexAMId);
if (!indexAmName)
{
ereport(ERROR, (errmsg("access method with oid %u does not exist", indexAMId)));
}
return indexAmName;
}
/*
* DropConstraintRestrict drops the constraint with constraintId by using spi.
*/
static void
DropConstraintRestrict(Oid relationId, Oid constraintId)
{
char *qualifiedRelationName = generate_qualified_relation_name(relationId);
char *constraintName = get_constraint_name(constraintId);
const char *quotedConstraintName = quote_identifier(constraintName);
StringInfo dropConstraintCommand = makeStringInfo();
appendStringInfo(dropConstraintCommand, "ALTER TABLE %s DROP CONSTRAINT %s RESTRICT;",
qualifiedRelationName, quotedConstraintName);
ExecuteQueryViaSPI(dropConstraintCommand->data, SPI_OK_UTILITY);
}
/*
* DropIndexRestrict drops the index with indexId by using spi.
*/
static void
DropIndexRestrict(Oid indexId)
{
char *qualifiedIndexName = generate_qualified_relation_name(indexId);
StringInfo dropIndexCommand = makeStringInfo();
appendStringInfo(dropIndexCommand, "DROP INDEX %s RESTRICT;", qualifiedIndexName);
ExecuteQueryViaSPI(dropIndexCommand->data, SPI_OK_UTILITY);
}
/*
* EnsureTableNotReferencing checks if the table has a reference to another
* table and errors if it is.
*/
void
EnsureTableNotReferencing(Oid relationId, char conversionType)
{
if (TableReferencing(relationId))
{
if (conversionType == UNDISTRIBUTE_TABLE)
{
char *qualifiedRelationName = generate_qualified_relation_name(relationId);
ereport(ERROR, (errmsg("cannot complete operation "
"because table %s has a foreign key",
get_rel_name(relationId)),
errhint(UNDISTRIBUTE_TABLE_CASCADE_HINT,
qualifiedRelationName,
qualifiedRelationName)));
}
else
{
ereport(ERROR, (errmsg("cannot complete operation "
"because table %s has a foreign key",
get_rel_name(relationId))));
}
}
}
/*
* EnsureTableNotReferenced checks if the table is referenced by another
* table and errors if it is.
*/
void
EnsureTableNotReferenced(Oid relationId, char conversionType)
{
if (TableReferenced(relationId))
{
if (conversionType == UNDISTRIBUTE_TABLE)
{
char *qualifiedRelationName = generate_qualified_relation_name(relationId);
ereport(ERROR, (errmsg("cannot complete operation "
"because table %s is referenced by a foreign key",
get_rel_name(relationId)),
errhint(UNDISTRIBUTE_TABLE_CASCADE_HINT,
qualifiedRelationName,
qualifiedRelationName)));
}
else
{
ereport(ERROR, (errmsg("cannot complete operation "
"because table %s is referenced by a foreign key",
get_rel_name(relationId))));
}
}
}
/*
* EnsureTableNotForeign checks if the table is a foreign table and errors
* if it is.
*/
void
EnsureTableNotForeign(Oid relationId)
{
char relationKind = get_rel_relkind(relationId);
if (relationKind == RELKIND_FOREIGN_TABLE)
{
ereport(ERROR, (errmsg("cannot complete operation "