-
Notifications
You must be signed in to change notification settings - Fork 658
/
citus_ruleutils.c
1640 lines (1376 loc) · 43.8 KB
/
citus_ruleutils.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
/*-------------------------------------------------------------------------
*
* citus_ruleutils.c
* Version independent ruleutils wrapper
*
* Copyright (c) Citus Data, Inc.
*-------------------------------------------------------------------------
*/
#include <stddef.h>
#include "postgres.h"
#include "miscadmin.h"
#include "access/attnum.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup.h"
#include "access/htup_details.h"
#include "access/skey.h"
#include "access/stratnum.h"
#include "access/sysattr.h"
#include "access/toast_compression.h"
#include "access/tupdesc.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_attribute.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_class.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_foreign_data_wrapper.h"
#include "catalog/pg_index.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/extension.h"
#include "commands/sequence.h"
#include "foreign/foreign.h"
#include "lib/stringinfo.h"
#include "nodes/nodeFuncs.h"
#include "nodes/nodes.h"
#include "nodes/parsenodes.h"
#include "nodes/pg_list.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "storage/lock.h"
#include "utils/acl.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/errcodes.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/palloc.h"
#include "utils/rel.h"
#include "utils/relcache.h"
#include "utils/ruleutils.h"
#include "utils/syscache.h"
#include "pg_version_constants.h"
#include "distributed/citus_ruleutils.h"
#include "distributed/commands.h"
#include "distributed/listutils.h"
#include "distributed/metadata_cache.h"
#include "distributed/metadata_sync.h"
#include "distributed/metadata_utility.h"
#include "distributed/multi_partitioning_utils.h"
#include "distributed/namespace_utils.h"
#include "distributed/relay_utility.h"
#include "distributed/version_compat.h"
#include "distributed/worker_protocol.h"
static void deparse_index_columns(StringInfo buffer, List *indexParameterList,
List *deparseContext);
static void AppendStorageParametersToString(StringInfo stringBuffer,
List *optionList);
static const char * convert_aclright_to_string(int aclright);
static void simple_quote_literal(StringInfo buf, const char *val);
static void AddVacuumParams(ReindexStmt *reindexStmt, StringInfo buffer);
/*
* pg_get_extensiondef_string finds the foreign data wrapper that corresponds to
* the given foreign tableId, and checks if an extension owns this foreign data
* wrapper. If it does, the function returns the extension's definition. If not,
* the function returns null.
*/
char *
pg_get_extensiondef_string(Oid tableRelationId)
{
ForeignTable *foreignTable = GetForeignTable(tableRelationId);
ForeignServer *server = GetForeignServer(foreignTable->serverid);
ForeignDataWrapper *foreignDataWrapper = GetForeignDataWrapper(server->fdwid);
StringInfoData buffer = { NULL, 0, 0, 0 };
Oid classId = ForeignDataWrapperRelationId;
Oid objectId = server->fdwid;
Oid extensionId = getExtensionOfObject(classId, objectId);
if (OidIsValid(extensionId))
{
char *extensionName = get_extension_name(extensionId);
Oid extensionSchemaId = get_extension_schema(extensionId);
char *extensionSchema = get_namespace_name(extensionSchemaId);
initStringInfo(&buffer);
appendStringInfo(&buffer, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s",
quote_identifier(extensionName),
quote_identifier(extensionSchema));
}
else
{
ereport(NOTICE, (errmsg("foreign-data wrapper \"%s\" does not have an "
"extension defined", foreignDataWrapper->fdwname)));
}
return (buffer.data);
}
/*
* get_extension_version - given an extension OID, fetch its extversion
* or NULL if not found.
*/
char *
get_extension_version(Oid extensionId)
{
char *versionName = NULL;
Relation relation = table_open(ExtensionRelationId, AccessShareLock);
ScanKeyData entry[1];
ScanKeyInit(&entry[0],
Anum_pg_extension_oid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(extensionId));
SysScanDesc scanDesc = systable_beginscan(relation, ExtensionOidIndexId, true,
NULL, 1, entry);
HeapTuple tuple = systable_getnext(scanDesc);
/* We assume that there can be at most one matching tuple */
if (HeapTupleIsValid(tuple))
{
bool isNull = false;
Datum versionDatum = heap_getattr(tuple, Anum_pg_extension_extversion,
RelationGetDescr(relation), &isNull);
if (!isNull)
{
versionName = text_to_cstring(DatumGetTextPP(versionDatum));
}
}
systable_endscan(scanDesc);
table_close(relation, AccessShareLock);
return versionName;
}
/*
* get_extension_schema - given an extension OID, fetch its extnamespace
*
* Returns InvalidOid if no such extension.
*/
Oid
get_extension_schema(Oid ext_oid)
{
/* *INDENT-OFF* */
Oid result;
Relation rel;
HeapTuple tuple;
ScanKeyData entry[1];
rel = table_open(ExtensionRelationId, AccessShareLock);
ScanKeyInit(&entry[0],
Anum_pg_extension_oid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(ext_oid));
SysScanDesc scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
NULL, 1, entry);
tuple = systable_getnext(scandesc);
/* We assume that there can be at most one matching tuple */
if (HeapTupleIsValid(tuple))
result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
else
result = InvalidOid;
systable_endscan(scandesc);
table_close(rel, AccessShareLock);
return result;
/* *INDENT-ON* */
}
/*
* pg_get_serverdef_string finds the foreign server that corresponds to the
* given foreign tableId, and returns this server's definition.
*/
char *
pg_get_serverdef_string(Oid tableRelationId)
{
ForeignTable *foreignTable = GetForeignTable(tableRelationId);
ForeignServer *server = GetForeignServer(foreignTable->serverid);
ForeignDataWrapper *foreignDataWrapper = GetForeignDataWrapper(server->fdwid);
StringInfoData buffer = { NULL, 0, 0, 0 };
initStringInfo(&buffer);
appendStringInfo(&buffer, "CREATE SERVER IF NOT EXISTS %s",
quote_identifier(server->servername));
if (server->servertype != NULL)
{
appendStringInfo(&buffer, " TYPE %s",
quote_literal_cstr(server->servertype));
}
if (server->serverversion != NULL)
{
appendStringInfo(&buffer, " VERSION %s",
quote_literal_cstr(server->serverversion));
}
appendStringInfo(&buffer, " FOREIGN DATA WRAPPER %s",
quote_identifier(foreignDataWrapper->fdwname));
/* append server options, if any */
AppendOptionListToString(&buffer, server->options);
return (buffer.data);
}
/*
* pg_get_sequencedef_string returns the definition of a given sequence. This
* definition includes explicit values for all CREATE SEQUENCE options.
*/
char *
pg_get_sequencedef_string(Oid sequenceRelationId)
{
Form_pg_sequence pgSequenceForm = pg_get_sequencedef(sequenceRelationId);
/* build our DDL command */
char *qualifiedSequenceName = generate_qualified_relation_name(sequenceRelationId);
char *typeName = format_type_be(pgSequenceForm->seqtypid);
char *sequenceDef = psprintf(CREATE_SEQUENCE_COMMAND,
#if (PG_VERSION_NUM >= PG_VERSION_15)
get_rel_persistence(sequenceRelationId) ==
RELPERSISTENCE_UNLOGGED ? "UNLOGGED " : "",
#endif
qualifiedSequenceName,
typeName,
pgSequenceForm->seqincrement, pgSequenceForm->seqmin,
pgSequenceForm->seqmax, pgSequenceForm->seqstart,
pgSequenceForm->seqcache,
pgSequenceForm->seqcycle ? "" : "NO ");
return sequenceDef;
}
/*
* pg_get_sequencedef returns the Form_pg_sequence data about the sequence with the given
* object id.
*/
Form_pg_sequence
pg_get_sequencedef(Oid sequenceRelationId)
{
HeapTuple heapTuple = SearchSysCache1(SEQRELID, sequenceRelationId);
if (!HeapTupleIsValid(heapTuple))
{
elog(ERROR, "cache lookup failed for sequence %u", sequenceRelationId);
}
Form_pg_sequence pgSequenceForm = (Form_pg_sequence) GETSTRUCT(heapTuple);
ReleaseSysCache(heapTuple);
return pgSequenceForm;
}
/*
* pg_get_tableschemadef_string returns the definition of a given table. This
* definition includes table's schema, default column values, not null and check
* constraints. The definition does not include constraints that trigger index
* creations; specifically, unique and primary key constraints are excluded.
* When includeSequenceDefaults is NEXTVAL_SEQUENCE_DEFAULTS, the function also creates
* DEFAULT clauses for columns getting their default values from a sequence.
* When it's WORKER_NEXTVAL_SEQUENCE_DEFAULTS, the function creates the DEFAULT
* clause using worker_nextval('sequence') and not nextval('sequence')
* When IncludeIdentities is NO_IDENTITY, the function does not include identity column
* specifications. When it's INCLUDE_IDENTITY it creates GENERATED .. AS IDENTIY clauses.
*/
char *
pg_get_tableschemadef_string(Oid tableRelationId, IncludeSequenceDefaults
includeSequenceDefaults, IncludeIdentities
includeIdentityDefaults, char *accessMethod)
{
bool firstAttributePrinted = false;
AttrNumber defaultValueIndex = 0;
AttrNumber constraintIndex = 0;
AttrNumber constraintCount = 0;
StringInfoData buffer = { NULL, 0, 0, 0 };
/*
* Instead of retrieving values from system catalogs as other functions in
* ruleutils.c do, we follow an unusual approach here: we open the relation,
* and fetch the relation's tuple descriptor. We do this because the tuple
* descriptor already contains information harnessed from pg_attrdef,
* pg_attribute, pg_constraint, and pg_class; and therefore using the
* descriptor saves us from a lot of additional work.
*/
Relation relation = relation_open(tableRelationId, AccessShareLock);
char *relationName = generate_relation_name(tableRelationId, NIL);
EnsureRelationKindSupported(tableRelationId);
initStringInfo(&buffer);
if (RegularTable(tableRelationId))
{
appendStringInfoString(&buffer, "CREATE ");
if (relation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
{
appendStringInfoString(&buffer, "UNLOGGED ");
}
appendStringInfo(&buffer, "TABLE %s (", relationName);
}
else
{
appendStringInfo(&buffer, "CREATE FOREIGN TABLE %s (", relationName);
}
/*
* Iterate over the table's columns. If a particular column is not dropped
* and is not inherited from another table, print the column's name and its
* formatted type.
*/
TupleDesc tupleDescriptor = RelationGetDescr(relation);
TupleConstr *tupleConstraints = tupleDescriptor->constr;
for (int attributeIndex = 0; attributeIndex < tupleDescriptor->natts;
attributeIndex++)
{
Form_pg_attribute attributeForm = TupleDescAttr(tupleDescriptor, attributeIndex);
/*
* We disregard the inherited attributes (i.e., attinhcount > 0) here. The
* reasoning behind this is that Citus implements declarative partitioning
* by creating the partitions first and then sending
* "ALTER TABLE parent_table ATTACH PARTITION .." command. This may not play
* well with regular inherited tables, which isn't a big concern from Citus'
* perspective.
*/
if (!attributeForm->attisdropped)
{
if (firstAttributePrinted)
{
appendStringInfoString(&buffer, ", ");
}
firstAttributePrinted = true;
const char *attributeName = NameStr(attributeForm->attname);
appendStringInfo(&buffer, "%s ", quote_identifier(attributeName));
const char *attributeTypeName = format_type_with_typemod(
attributeForm->atttypid,
attributeForm->
atttypmod);
appendStringInfoString(&buffer, attributeTypeName);
if (CompressionMethodIsValid(attributeForm->attcompression))
{
appendStringInfo(&buffer, " COMPRESSION %s",
GetCompressionMethodName(attributeForm->attcompression));
}
if (attributeForm->attidentity && includeIdentityDefaults)
{
bool missing_ok = false;
Oid seqOid = getIdentitySequence(RelationGetRelid(relation),
attributeForm->attnum, missing_ok);
if (includeIdentityDefaults == INCLUDE_IDENTITY)
{
Form_pg_sequence pgSequenceForm = pg_get_sequencedef(seqOid);
char *sequenceDef = psprintf(
" GENERATED %s AS IDENTITY (INCREMENT BY " INT64_FORMAT \
" MINVALUE " INT64_FORMAT " MAXVALUE "
INT64_FORMAT \
" START WITH " INT64_FORMAT " CACHE "
INT64_FORMAT " %sCYCLE)",
attributeForm->attidentity == ATTRIBUTE_IDENTITY_ALWAYS ?
"ALWAYS" : "BY DEFAULT",
pgSequenceForm->seqincrement,
pgSequenceForm->seqmin,
pgSequenceForm->seqmax,
pgSequenceForm->seqstart,
pgSequenceForm->seqcache,
pgSequenceForm->seqcycle ? "" : "NO ");
appendStringInfo(&buffer, "%s", sequenceDef);
}
}
/* if this column has a default value, append the default value */
if (attributeForm->atthasdef)
{
List *defaultContext = NULL;
char *defaultString = NULL;
Assert(tupleConstraints != NULL);
AttrDefault *defaultValueList = tupleConstraints->defval;
Assert(defaultValueList != NULL);
AttrDefault *defaultValue = &(defaultValueList[defaultValueIndex]);
defaultValueIndex++;
Assert(defaultValue->adnum == (attributeIndex + 1));
Assert(defaultValueIndex <= tupleConstraints->num_defval);
/* convert expression to node tree, and prepare deparse context */
Node *defaultNode = (Node *) stringToNode(defaultValue->adbin);
/*
* if column default value is explicitly requested, or it is
* not set from a sequence then we include DEFAULT clause for
* this column.
*/
if (includeSequenceDefaults ||
!contain_nextval_expression_walker(defaultNode, NULL))
{
defaultContext = deparse_context_for(relationName, tableRelationId);
/* deparse default value string */
defaultString = deparse_expression(defaultNode, defaultContext,
false, false);
if (attributeForm->attgenerated == ATTRIBUTE_GENERATED_STORED)
{
appendStringInfo(&buffer, " GENERATED ALWAYS AS (%s) STORED",
defaultString);
}
else
{
Oid seqOid = GetSequenceOid(tableRelationId, defaultValue->adnum);
if (includeSequenceDefaults == WORKER_NEXTVAL_SEQUENCE_DEFAULTS &&
seqOid != InvalidOid &&
pg_get_sequencedef(seqOid)->seqtypid != INT8OID)
{
/*
* We use worker_nextval for int and smallint types.
* Check issue #5126 and PR #5254 for details.
* https://github.com/citusdata/citus/issues/5126
*/
char *sequenceName = generate_qualified_relation_name(
seqOid);
appendStringInfo(&buffer,
" DEFAULT worker_nextval(%s::regclass)",
quote_literal_cstr(sequenceName));
}
else
{
appendStringInfo(&buffer, " DEFAULT %s", defaultString);
}
}
}
}
/* if this column has a not null constraint, append the constraint */
if (attributeForm->attnotnull)
{
appendStringInfoString(&buffer, " NOT NULL");
}
if (attributeForm->attcollation != InvalidOid &&
attributeForm->attcollation != DEFAULT_COLLATION_OID)
{
appendStringInfo(&buffer, " COLLATE %s", generate_collation_name(
attributeForm->attcollation));
}
}
}
/*
* Now check if the table has any constraints. If it does, set the number of
* check constraints here. Then iterate over all check constraints and print
* them.
*/
if (tupleConstraints != NULL)
{
constraintCount = tupleConstraints->num_check;
}
for (constraintIndex = 0; constraintIndex < constraintCount; constraintIndex++)
{
ConstrCheck *checkConstraintList = tupleConstraints->check;
ConstrCheck *checkConstraint = &(checkConstraintList[constraintIndex]);
/* if an attribute or constraint has been printed, format properly */
if (firstAttributePrinted || constraintIndex > 0)
{
appendStringInfoString(&buffer, ", ");
}
appendStringInfo(&buffer, "CONSTRAINT %s CHECK ",
quote_identifier(checkConstraint->ccname));
/* convert expression to node tree, and prepare deparse context */
Node *checkNode = (Node *) stringToNode(checkConstraint->ccbin);
List *checkContext = deparse_context_for(relationName, tableRelationId);
/* deparse check constraint string */
char *checkString = deparse_expression(checkNode, checkContext, false, false);
appendStringInfoString(&buffer, "(");
appendStringInfoString(&buffer, checkString);
appendStringInfoString(&buffer, ")");
}
/* close create table's outer parentheses */
appendStringInfoString(&buffer, ")");
/*
* If the relation is a foreign table, append the server name and options to
* the create table statement.
*/
char relationKind = relation->rd_rel->relkind;
if (relationKind == RELKIND_FOREIGN_TABLE)
{
ForeignTable *foreignTable = GetForeignTable(tableRelationId);
ForeignServer *foreignServer = GetForeignServer(foreignTable->serverid);
char *serverName = foreignServer->servername;
appendStringInfo(&buffer, " SERVER %s", quote_identifier(serverName));
AppendOptionListToString(&buffer, foreignTable->options);
}
else if (relationKind == RELKIND_PARTITIONED_TABLE)
{
char *partitioningInformation = GeneratePartitioningInformation(tableRelationId);
appendStringInfo(&buffer, " PARTITION BY %s ", partitioningInformation);
}
/*
* Add table access methods when the table is configured with an
* access method
*/
if (accessMethod)
{
appendStringInfo(&buffer, " USING %s", quote_identifier(accessMethod));
}
else if (OidIsValid(relation->rd_rel->relam))
{
HeapTuple amTup = SearchSysCache1(AMOID, ObjectIdGetDatum(
relation->rd_rel->relam));
if (!HeapTupleIsValid(amTup))
{
elog(ERROR, "cache lookup failed for access method %u",
relation->rd_rel->relam);
}
Form_pg_am amForm = (Form_pg_am) GETSTRUCT(amTup);
appendStringInfo(&buffer, " USING %s", quote_identifier(NameStr(amForm->amname)));
ReleaseSysCache(amTup);
}
/*
* Add any reloptions (storage parameters) defined on the table in a WITH
* clause.
*/
{
char *reloptions = flatten_reloptions(tableRelationId);
if (reloptions)
{
appendStringInfo(&buffer, " WITH (%s)", reloptions);
pfree(reloptions);
}
}
relation_close(relation, AccessShareLock);
return (buffer.data);
}
/*
* EnsureRelationKindSupported errors out if the given relation is not supported
* as a distributed relation.
*/
void
EnsureRelationKindSupported(Oid relationId)
{
char relationKind = get_rel_relkind(relationId);
if (!relationKind)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation with OID %d does not exist",
relationId)));
}
bool supportedRelationKind = RegularTable(relationId) ||
relationKind == RELKIND_FOREIGN_TABLE;
/*
* Citus doesn't support bare inherited tables (i.e., not a partition or
* partitioned table)
*/
supportedRelationKind = supportedRelationKind && !(IsChildTable(relationId) ||
IsParentTable(relationId));
if (!supportedRelationKind)
{
char *relationName = get_rel_name(relationId);
ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("%s is not a regular, foreign or partitioned table",
relationName)));
}
}
/*
* pg_get_tablecolumnoptionsdef_string returns column storage type and column
* statistics definitions for given table, _if_ these definitions differ from
* their default values. The function returns null if all columns use default
* values for their storage types and statistics.
*/
char *
pg_get_tablecolumnoptionsdef_string(Oid tableRelationId)
{
List *columnOptionList = NIL;
ListCell *columnOptionCell = NULL;
bool firstOptionPrinted = false;
StringInfoData buffer = { NULL, 0, 0, 0 };
/*
* Instead of retrieving values from system catalogs, we open the relation,
* and use the relation's tuple descriptor to access attribute information.
* This is primarily to maintain symmetry with pg_get_tableschemadef.
*/
Relation relation = relation_open(tableRelationId, AccessShareLock);
EnsureRelationKindSupported(tableRelationId);
/*
* Iterate over the table's columns. If a particular column is not dropped
* and is not inherited from another table, check if column storage or
* statistics statements need to be printed.
*/
TupleDesc tupleDescriptor = RelationGetDescr(relation);
if (tupleDescriptor->natts > MaxAttrNumber)
{
ereport(ERROR, (errmsg("bad number of tuple descriptor attributes")));
}
AttrNumber natts = tupleDescriptor->natts;
for (AttrNumber attributeIndex = 0;
attributeIndex < natts;
attributeIndex++)
{
Form_pg_attribute attributeForm = TupleDescAttr(tupleDescriptor, attributeIndex);
char *attributeName = NameStr(attributeForm->attname);
char defaultStorageType = get_typstorage(attributeForm->atttypid);
if (!attributeForm->attisdropped && attributeForm->attinhcount == 0)
{
/*
* If the user changed the column's default storage type, create
* alter statement and add statement to a list for later processing.
*/
if (attributeForm->attstorage != defaultStorageType)
{
char *storageName = 0;
StringInfoData statement = { NULL, 0, 0, 0 };
initStringInfo(&statement);
switch (attributeForm->attstorage)
{
case 'p':
{
storageName = "PLAIN";
break;
}
case 'e':
{
storageName = "EXTERNAL";
break;
}
case 'm':
{
storageName = "MAIN";
break;
}
case 'x':
{
storageName = "EXTENDED";
break;
}
default:
{
ereport(ERROR, (errmsg("unrecognized storage type: %c",
attributeForm->attstorage)));
break;
}
}
appendStringInfo(&statement, "ALTER COLUMN %s ",
quote_identifier(attributeName));
appendStringInfo(&statement, "SET STORAGE %s", storageName);
columnOptionList = lappend(columnOptionList, statement.data);
}
/*
* If the user changed the column's statistics target, create
* alter statement and add statement to a list for later processing.
*/
if (attributeForm->attstattarget >= 0)
{
StringInfoData statement = { NULL, 0, 0, 0 };
initStringInfo(&statement);
appendStringInfo(&statement, "ALTER COLUMN %s ",
quote_identifier(attributeName));
appendStringInfo(&statement, "SET STATISTICS %d",
attributeForm->attstattarget);
columnOptionList = lappend(columnOptionList, statement.data);
}
}
}
/*
* Iterate over column storage and statistics statements that we created,
* and append them to a single alter table statement.
*/
foreach(columnOptionCell, columnOptionList)
{
if (!firstOptionPrinted)
{
initStringInfo(&buffer);
appendStringInfo(&buffer, "ALTER TABLE ONLY %s ",
generate_relation_name(tableRelationId, NIL));
}
else
{
appendStringInfoString(&buffer, ", ");
}
firstOptionPrinted = true;
char *columnOptionStatement = (char *) lfirst(columnOptionCell);
appendStringInfoString(&buffer, columnOptionStatement);
pfree(columnOptionStatement);
}
list_free(columnOptionList);
relation_close(relation, AccessShareLock);
return (buffer.data);
}
/*
* deparse_shard_index_statement uses the provided CREATE INDEX node, dist.
* relation, and shard identifier to populate a provided buffer with a string
* representation of a shard-extended version of that command.
*/
void
deparse_shard_index_statement(IndexStmt *origStmt, Oid distrelid, int64 shardid,
StringInfo buffer)
{
IndexStmt *indexStmt = copyObject(origStmt); /* copy to avoid modifications */
/* extend relation and index name using shard identifier */
AppendShardIdToName(&(indexStmt->relation->relname), shardid);
AppendShardIdToName(&(indexStmt->idxname), shardid);
char *relationName = indexStmt->relation->relname;
char *indexName = indexStmt->idxname;
/* use extended shard name and transformed stmt for deparsing */
List *deparseContext = deparse_context_for(relationName, distrelid);
indexStmt = transformIndexStmt(distrelid, indexStmt, NULL);
appendStringInfo(buffer, "CREATE %s INDEX %s %s %s ON %s %s USING %s ",
(indexStmt->unique ? "UNIQUE" : ""),
(indexStmt->concurrent ? "CONCURRENTLY" : ""),
(indexStmt->if_not_exists ? "IF NOT EXISTS" : ""),
quote_identifier(indexName),
(indexStmt->relation->inh ? "" : "ONLY"),
quote_qualified_identifier(indexStmt->relation->schemaname,
relationName),
indexStmt->accessMethod);
/*
* Switch to empty search_path to deparse_index_columns to produce fully-
* qualified names in expressions.
*/
int saveNestLevel = PushEmptySearchPath();
/* index column or expression list begins here */
appendStringInfoChar(buffer, '(');
deparse_index_columns(buffer, indexStmt->indexParams, deparseContext);
appendStringInfoString(buffer, ") ");
/* column/expressions for INCLUDE list */
if (indexStmt->indexIncludingParams != NIL)
{
appendStringInfoString(buffer, "INCLUDE (");
deparse_index_columns(buffer, indexStmt->indexIncludingParams, deparseContext);
appendStringInfoString(buffer, ") ");
}
#if PG_VERSION_NUM >= PG_VERSION_15
if (indexStmt->nulls_not_distinct)
{
appendStringInfoString(buffer, "NULLS NOT DISTINCT ");
}
#endif /* PG_VERSION_15 */
if (indexStmt->options != NIL)
{
appendStringInfoString(buffer, "WITH (");
AppendStorageParametersToString(buffer, indexStmt->options);
appendStringInfoString(buffer, ") ");
}
if (indexStmt->whereClause != NULL)
{
appendStringInfo(buffer, "WHERE %s", deparse_expression(indexStmt->whereClause,
deparseContext, false,
false));
}
/* revert back to original search_path */
PopEmptySearchPath(saveNestLevel);
}
/*
* deparse_shard_reindex_statement uses the provided REINDEX node, dist.
* relation, and shard identifier to populate a provided buffer with a string
* representation of a shard-extended version of that command.
*/
void
deparse_shard_reindex_statement(ReindexStmt *origStmt, Oid distrelid, int64 shardid,
StringInfo buffer)
{
ReindexStmt *reindexStmt = copyObject(origStmt); /* copy to avoid modifications */
char *relationName = NULL;
const char *concurrentlyString =
IsReindexWithParam_compat(reindexStmt, "concurrently") ? "CONCURRENTLY " : "";
if (reindexStmt->kind == REINDEX_OBJECT_INDEX ||
reindexStmt->kind == REINDEX_OBJECT_TABLE)
{
/* extend relation and index name using shard identifier */
AppendShardIdToName(&(reindexStmt->relation->relname), shardid);
relationName = reindexStmt->relation->relname;
}
appendStringInfoString(buffer, "REINDEX ");
AddVacuumParams(reindexStmt, buffer);
switch (reindexStmt->kind)
{
case REINDEX_OBJECT_INDEX:
{
appendStringInfo(buffer, "INDEX %s%s", concurrentlyString,
quote_qualified_identifier(reindexStmt->relation->schemaname,
relationName));
break;
}
case REINDEX_OBJECT_TABLE:
{
appendStringInfo(buffer, "TABLE %s%s", concurrentlyString,
quote_qualified_identifier(reindexStmt->relation->schemaname,
relationName));
break;
}
case REINDEX_OBJECT_SCHEMA:
{
appendStringInfo(buffer, "SCHEMA %s%s", concurrentlyString,
quote_identifier(reindexStmt->name));
break;
}
case REINDEX_OBJECT_SYSTEM:
{
appendStringInfo(buffer, "SYSTEM %s%s", concurrentlyString,
quote_identifier(reindexStmt->name));
break;
}
case REINDEX_OBJECT_DATABASE:
{
appendStringInfo(buffer, "DATABASE %s%s", concurrentlyString,
quote_identifier(reindexStmt->name));
break;
}
}
}
/*
* IsReindexWithParam_compat returns true if the given parameter
* exists for the given reindexStmt.
*/
bool
IsReindexWithParam_compat(ReindexStmt *reindexStmt, char *param)
{
DefElem *opt = NULL;
foreach_ptr(opt, reindexStmt->params)
{
if (strcmp(opt->defname, param) == 0)
{
return defGetBoolean(opt);
}
}
return false;
}
/*
* AddVacuumParams adds vacuum params to the given buffer.
*/
static void
AddVacuumParams(ReindexStmt *reindexStmt, StringInfo buffer)
{
StringInfo temp = makeStringInfo();
if (IsReindexWithParam_compat(reindexStmt, "verbose"))
{
appendStringInfoString(temp, "VERBOSE");
}
char *tableSpaceName = NULL;
DefElem *opt = NULL;
foreach_ptr(opt, reindexStmt->params)
{
if (strcmp(opt->defname, "tablespace") == 0)
{
tableSpaceName = defGetString(opt);
break;
}
}
if (tableSpaceName)
{
if (temp->len > 0)
{
appendStringInfo(temp, ", TABLESPACE %s", tableSpaceName);
}
else
{
appendStringInfo(temp, "TABLESPACE %s", tableSpaceName);
}
}
if (temp->len > 0)
{
appendStringInfo(buffer, "(%s) ", temp->data);
}
}
/* deparse_index_columns appends index or include parameters to the provided buffer */
static void
deparse_index_columns(StringInfo buffer, List *indexParameterList, List *deparseContext)
{
ListCell *indexParameterCell = NULL;
foreach(indexParameterCell, indexParameterList)
{