Debian Codegraph @

src/backend/commands/tablecmds.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * tablecmds.c
4 * Commands for creating and altering table structures and settings
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/commands/tablecmds.c
12 *
13 *-------------------------------------------------------------------------
14 */
15 #include "postgres.h"
16
17 #include "access/attmap.h"
18 #include "access/genam.h"
19 #include "access/gist.h"
20 #include "access/heapam.h"
21 #include "access/heapam_xlog.h"
22 #include "access/multixact.h"
23 #include "access/reloptions.h"
24 #include "access/relscan.h"
25 #include "access/sysattr.h"
26 #include "access/tableam.h"
27 #include "access/toast_compression.h"
28 #include "access/xact.h"
29 #include "access/xlog.h"
30 #include "access/xloginsert.h"
31 #include "catalog/catalog.h"
32 #include "catalog/heap.h"
33 #include "catalog/index.h"
34 #include "catalog/namespace.h"
35 #include "catalog/objectaccess.h"
36 #include "catalog/partition.h"
37 #include "catalog/pg_am.h"
38 #include "catalog/pg_attrdef.h"
39 #include "catalog/pg_collation.h"
40 #include "catalog/pg_constraint.h"
41 #include "catalog/pg_depend.h"
42 #include "catalog/pg_foreign_table.h"
43 #include "catalog/pg_inherits.h"
44 #include "catalog/pg_largeobject.h"
45 #include "catalog/pg_namespace.h"
46 #include "catalog/pg_opclass.h"
47 #include "catalog/pg_policy.h"
48 #include "catalog/pg_proc.h"
49 #include "catalog/pg_publication_rel.h"
50 #include "catalog/pg_rewrite.h"
51 #include "catalog/pg_statistic_ext.h"
52 #include "catalog/pg_tablespace.h"
53 #include "catalog/pg_trigger.h"
54 #include "catalog/pg_type.h"
55 #include "catalog/storage.h"
56 #include "catalog/storage_xlog.h"
57 #include "catalog/toasting.h"
58 #include "commands/cluster.h"
59 #include "commands/comment.h"
60 #include "commands/defrem.h"
61 #include "commands/event_trigger.h"
62 #include "commands/sequence.h"
63 #include "commands/tablecmds.h"
64 #include "commands/tablespace.h"
65 #include "commands/trigger.h"
66 #include "commands/typecmds.h"
67 #include "commands/user.h"
68 #include "commands/vacuum.h"
69 #include "common/int.h"
70 #include "executor/executor.h"
71 #include "foreign/fdwapi.h"
72 #include "foreign/foreign.h"
73 #include "miscadmin.h"
74 #include "nodes/makefuncs.h"
75 #include "nodes/nodeFuncs.h"
76 #include "nodes/parsenodes.h"
77 #include "optimizer/optimizer.h"
78 #include "parser/parse_coerce.h"
79 #include "parser/parse_collate.h"
80 #include "parser/parse_expr.h"
81 #include "parser/parse_relation.h"
82 #include "parser/parse_type.h"
83 #include "parser/parse_utilcmd.h"
84 #include "parser/parser.h"
85 #include "partitioning/partbounds.h"
86 #include "partitioning/partdesc.h"
87 #include "pgstat.h"
88 #include "rewrite/rewriteDefine.h"
89 #include "rewrite/rewriteHandler.h"
90 #include "rewrite/rewriteManip.h"
91 #include "storage/bufmgr.h"
92 #include "storage/lmgr.h"
93 #include "storage/lock.h"
94 #include "storage/predicate.h"
95 #include "storage/smgr.h"
96 #include "tcop/utility.h"
97 #include "utils/acl.h"
98 #include "utils/builtins.h"
99 #include "utils/fmgroids.h"
100 #include "utils/inval.h"
101 #include "utils/lsyscache.h"
102 #include "utils/memutils.h"
103 #include "utils/partcache.h"
104 #include "utils/relcache.h"
105 #include "utils/ruleutils.h"
106 #include "utils/snapmgr.h"
107 #include "utils/syscache.h"
108 #include "utils/timestamp.h"
109 #include "utils/typcache.h"
110 #include "utils/usercontext.h"
111
112 /*
113 * ON COMMIT action list
114 */
115 typedef struct OnCommitItem
116 {
117 Oid relid; /* relid of relation */
118 OnCommitAction oncommit; /* what to do at end of xact */
119
120 /*
121 * If this entry was created during the current transaction,
122 * creating_subid is the ID of the creating subxact; if created in a prior
123 * transaction, creating_subid is zero. If deleted during the current
124 * transaction, deleting_subid is the ID of the deleting subxact; if no
125 * deletion request is pending, deleting_subid is zero.
126 */
127 SubTransactionId creating_subid;
128 SubTransactionId deleting_subid;
129 } OnCommitItem;
130
131 static List *on_commits = NIL;
132
133
134 /*
135 * State information for ALTER TABLE
136 *
137 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
138 * structs, one for each table modified by the operation (the named table
139 * plus any child tables that are affected). We save lists of subcommands
140 * to apply to this table (possibly modified by parse transformation steps);
141 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
142 * necessary information is stored in the constraints and newvals lists.
143 *
144 * Phase 2 is divided into multiple passes; subcommands are executed in
145 * a pass determined by subcommand type.
146 */
147
148 typedef enum AlterTablePass
149 {
150 AT_PASS_UNSET = -1, /* UNSET will cause ERROR */
151 AT_PASS_DROP, /* DROP (all flavors) */
152 AT_PASS_ALTER_TYPE, /* ALTER COLUMN TYPE */
153 AT_PASS_ADD_COL, /* ADD COLUMN */
154 AT_PASS_SET_EXPRESSION, /* ALTER SET EXPRESSION */
155 AT_PASS_OLD_INDEX, /* re-add existing indexes */
156 AT_PASS_OLD_CONSTR, /* re-add existing constraints */
157 /* We could support a RENAME COLUMN pass here, but not currently used */
158 AT_PASS_ADD_CONSTR, /* ADD constraints (initial examination) */
159 AT_PASS_COL_ATTRS, /* set column attributes, eg NOT NULL */
160 AT_PASS_ADD_INDEXCONSTR, /* ADD index-based constraints */
161 AT_PASS_ADD_INDEX, /* ADD indexes */
162 AT_PASS_ADD_OTHERCONSTR, /* ADD other constraints, defaults */
163 AT_PASS_MISC, /* other stuff */
164 } AlterTablePass;
165
166 #define AT_NUM_PASSES (AT_PASS_MISC + 1)
167
168 typedef struct AlteredTableInfo
169 {
170 /* Information saved before any work commences: */
171 Oid relid; /* Relation to work on */
172 char relkind; /* Its relkind */
173 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
174
175 /*
176 * Transiently set during Phase 2, normally set to NULL.
177 *
178 * ATRewriteCatalogs sets this when it starts, and closes when ATExecCmd
179 * returns control. This can be exploited by ATExecCmd subroutines to
180 * close/reopen across transaction boundaries.
181 */
182 Relation rel;
183
184 /* Information saved by Phase 1 for Phase 2: */
185 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
186 /* Information saved by Phases 1/2 for Phase 3: */
187 List *constraints; /* List of NewConstraint */
188 List *newvals; /* List of NewColumnValue */
189 List *afterStmts; /* List of utility command parsetrees */
190 bool verify_new_notnull; /* T if we should recheck NOT NULL */
191 int rewrite; /* Reason for forced rewrite, if any */
192 bool chgAccessMethod; /* T if SET ACCESS METHOD is used */
193 Oid newAccessMethod; /* new access method; 0 means no change,
194 * if above is true */
195 Oid newTableSpace; /* new tablespace; 0 means no change */
196 bool chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
197 char newrelpersistence; /* if above is true */
198 Expr *partition_constraint; /* for attach partition validation */
199 /* true, if validating default due to some other attach/detach */
200 bool validate_default;
201 /* Objects to rebuild after completing ALTER TYPE operations */
202 List *changedConstraintOids; /* OIDs of constraints to rebuild */
203 List *changedConstraintDefs; /* string definitions of same */
204 List *changedIndexOids; /* OIDs of indexes to rebuild */
205 List *changedIndexDefs; /* string definitions of same */
206 char *replicaIdentityIndex; /* index to reset as REPLICA IDENTITY */
207 char *clusterOnIndex; /* index to use for CLUSTER */
208 List *changedStatisticsOids; /* OIDs of statistics to rebuild */
209 List *changedStatisticsDefs; /* string definitions of same */
210 List *changedStatisticsOwners; /* owners of same */
211 } AlteredTableInfo;
212
213 /* Struct describing one new constraint to check in Phase 3 scan */
214 /* Note: new not-null constraints are handled elsewhere */
215 typedef struct NewConstraint
216 {
217 char *name; /* Constraint name, or NULL if none */
218 ConstrType contype; /* CHECK or FOREIGN */
219 Oid refrelid; /* PK rel, if FOREIGN */
220 Oid refindid; /* OID of PK's index, if FOREIGN */
221 bool conwithperiod; /* Whether the new FOREIGN KEY uses PERIOD */
222 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
223 Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
224 ExprState *qualstate; /* Execution state for CHECK expr */
225 } NewConstraint;
226
227 /*
228 * Struct describing one new column value that needs to be computed during
229 * Phase 3 copy (this could be either a new column with a non-null default, or
230 * a column that we're changing the type of). Columns without such an entry
231 * are just copied from the old table during ATRewriteTable. Note that the
232 * expr is an expression over *old* table values, except when is_generated
233 * is true; then it is an expression over columns of the *new* tuple.
234 */
235 typedef struct NewColumnValue
236 {
237 AttrNumber attnum; /* which column */
238 Expr *expr; /* expression to compute */
239 ExprState *exprstate; /* execution state */
240 bool is_generated; /* is it a GENERATED expression? */
241 } NewColumnValue;
242
243 /*
244 * Error-reporting support for RemoveRelations
245 */
246 struct dropmsgstrings
247 {
248 char kind;
249 int nonexistent_code;
250 const char *nonexistent_msg;
251 const char *skipping_msg;
252 const char *nota_msg;
253 const char *drophint_msg;
254 };
255
256 static const struct dropmsgstrings dropmsgstringarray[] = {
257 {RELKIND_RELATION,
258 ERRCODE_UNDEFINED_TABLE,
259 gettext_noop("table \"%s\" does not exist"),
260 gettext_noop("table \"%s\" does not exist, skipping"),
261 gettext_noop("\"%s\" is not a table"),
262 gettext_noop("Use DROP TABLE to remove a table.")},
263 {RELKIND_SEQUENCE,
264 ERRCODE_UNDEFINED_TABLE,
265 gettext_noop("sequence \"%s\" does not exist"),
266 gettext_noop("sequence \"%s\" does not exist, skipping"),
267 gettext_noop("\"%s\" is not a sequence"),
268 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
269 {RELKIND_VIEW,
270 ERRCODE_UNDEFINED_TABLE,
271 gettext_noop("view \"%s\" does not exist"),
272 gettext_noop("view \"%s\" does not exist, skipping"),
273 gettext_noop("\"%s\" is not a view"),
274 gettext_noop("Use DROP VIEW to remove a view.")},
275 {RELKIND_MATVIEW,
276 ERRCODE_UNDEFINED_TABLE,
277 gettext_noop("materialized view \"%s\" does not exist"),
278 gettext_noop("materialized view \"%s\" does not exist, skipping"),
279 gettext_noop("\"%s\" is not a materialized view"),
280 gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
281 {RELKIND_INDEX,
282 ERRCODE_UNDEFINED_OBJECT,
283 gettext_noop("index \"%s\" does not exist"),
284 gettext_noop("index \"%s\" does not exist, skipping"),
285 gettext_noop("\"%s\" is not an index"),
286 gettext_noop("Use DROP INDEX to remove an index.")},
287 {RELKIND_COMPOSITE_TYPE,
288 ERRCODE_UNDEFINED_OBJECT,
289 gettext_noop("type \"%s\" does not exist"),
290 gettext_noop("type \"%s\" does not exist, skipping"),
291 gettext_noop("\"%s\" is not a type"),
292 gettext_noop("Use DROP TYPE to remove a type.")},
293 {RELKIND_FOREIGN_TABLE,
294 ERRCODE_UNDEFINED_OBJECT,
295 gettext_noop("foreign table \"%s\" does not exist"),
296 gettext_noop("foreign table \"%s\" does not exist, skipping"),
297 gettext_noop("\"%s\" is not a foreign table"),
298 gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
299 {RELKIND_PARTITIONED_TABLE,
300 ERRCODE_UNDEFINED_TABLE,
301 gettext_noop("table \"%s\" does not exist"),
302 gettext_noop("table \"%s\" does not exist, skipping"),
303 gettext_noop("\"%s\" is not a table"),
304 gettext_noop("Use DROP TABLE to remove a table.")},
305 {RELKIND_PARTITIONED_INDEX,
306 ERRCODE_UNDEFINED_OBJECT,
307 gettext_noop("index \"%s\" does not exist"),
308 gettext_noop("index \"%s\" does not exist, skipping"),
309 gettext_noop("\"%s\" is not an index"),
310 gettext_noop("Use DROP INDEX to remove an index.")},
311 {'\0', 0, NULL, NULL, NULL, NULL}
312 };
313
314 /* communication between RemoveRelations and RangeVarCallbackForDropRelation */
315 struct DropRelationCallbackState
316 {
317 /* These fields are set by RemoveRelations: */
318 char expected_relkind;
319 LOCKMODE heap_lockmode;
320 /* These fields are state to track which subsidiary locks are held: */
321 Oid heapOid;
322 Oid partParentOid;
323 /* These fields are passed back by RangeVarCallbackForDropRelation: */
324 char actual_relkind;
325 char actual_relpersistence;
326 };
327
328 /* Alter table target-type flags for ATSimplePermissions */
329 #define ATT_TABLE 0x0001
330 #define ATT_VIEW 0x0002
331 #define ATT_MATVIEW 0x0004
332 #define ATT_INDEX 0x0008
333 #define ATT_COMPOSITE_TYPE 0x0010
334 #define ATT_FOREIGN_TABLE 0x0020
335 #define ATT_PARTITIONED_INDEX 0x0040
336 #define ATT_SEQUENCE 0x0080
337 #define ATT_PARTITIONED_TABLE 0x0100
338
339 /*
340 * ForeignTruncateInfo
341 *
342 * Information related to truncation of foreign tables. This is used for
343 * the elements in a hash table. It uses the server OID as lookup key,
344 * and includes a per-server list of all foreign tables involved in the
345 * truncation.
346 */
347 typedef struct ForeignTruncateInfo
348 {
349 Oid serverid;
350 List *rels;
351 } ForeignTruncateInfo;
352
353 /* Partial or complete FK creation in addFkConstraint() */
354 typedef enum addFkConstraintSides
355 {
356 addFkReferencedSide,
357 addFkReferencingSide,
358 addFkBothSides,
359 } addFkConstraintSides;
360
361 /*
362 * Partition tables are expected to be dropped when the parent partitioned
363 * table gets dropped. Hence for partitioning we use AUTO dependency.
364 * Otherwise, for regular inheritance use NORMAL dependency.
365 */
366 #define child_dependency_type(child_is_partition) \
367 ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
368
369 static void truncate_check_rel(Oid relid, Form_pg_class reltuple);
370 static void truncate_check_perms(Oid relid, Form_pg_class reltuple);
371 static void truncate_check_activity(Relation rel);
372 static void RangeVarCallbackForTruncate(const RangeVar *relation,
373 Oid relId, Oid oldRelId, void *arg);
374 static List *MergeAttributes(List *columns, const List *supers, char relpersistence,
375 bool is_partition, List **supconstr,
376 List **supnotnulls);
377 static List *MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced);
378 static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef);
379 static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef);
380 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition);
381 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
382 static void StoreCatalogInheritance(Oid relationId, List *supers,
383 bool child_is_partition);
384 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
385 int32 seqNumber, Relation inhRelation,
386 bool child_is_partition);
387 static int findAttrByName(const char *attributeName, const List *columns);
388 static void AlterIndexNamespaces(Relation classRel, Relation rel,
389 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
390 static void AlterSeqNamespaces(Relation classRel, Relation rel,
391 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
392 LOCKMODE lockmode);
393 static ObjectAddress ATExecAlterConstraint(List **wqueue, Relation rel,
394 ATAlterConstraint *cmdcon,
395 bool recurse, LOCKMODE lockmode);
396 static bool ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel,
397 Relation tgrel, Relation rel, HeapTuple contuple,
398 bool recurse, LOCKMODE lockmode);
399 static bool ATExecAlterConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
400 Relation conrel, Relation tgrel,
401 Oid fkrelid, Oid pkrelid,
402 HeapTuple contuple, LOCKMODE lockmode,
403 Oid ReferencedParentDelTrigger,
404 Oid ReferencedParentUpdTrigger,
405 Oid ReferencingParentInsTrigger,
406 Oid ReferencingParentUpdTrigger);
407 static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
408 Relation conrel, Relation tgrel, Relation rel,
409 HeapTuple contuple, bool recurse,
410 List **otherrelids, LOCKMODE lockmode);
411 static bool ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
412 Relation conrel, Relation rel,
413 HeapTuple contuple, LOCKMODE lockmode);
414 static void AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
415 bool deferrable, bool initdeferred,
416 List **otherrelids);
417 static void AlterConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
418 Relation conrel, Relation tgrel,
419 Oid fkrelid, Oid pkrelid,
420 HeapTuple contuple, LOCKMODE lockmode,
421 Oid ReferencedParentDelTrigger,
422 Oid ReferencedParentUpdTrigger,
423 Oid ReferencingParentInsTrigger,
424 Oid ReferencingParentUpdTrigger);
425 static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
426 Relation conrel, Relation tgrel, Relation rel,
427 HeapTuple contuple, bool recurse,
428 List **otherrelids, LOCKMODE lockmode);
429 static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
430 HeapTuple contuple);
431 static ObjectAddress ATExecValidateConstraint(List **wqueue,
432 Relation rel, char *constrName,
433 bool recurse, bool recursing, LOCKMODE lockmode);
434 static void QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
435 Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode);
436 static void QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
437 char *constrName, HeapTuple contuple,
438 bool recurse, bool recursing, LOCKMODE lockmode);
439 static void QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
440 HeapTuple contuple, bool recurse, bool recursing,
441 LOCKMODE lockmode);
442 static int transformColumnNameList(Oid relId, List *colList,
443 int16 *attnums, Oid *atttypids, Oid *attcollids);
444 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
445 List **attnamelist,
446 int16 *attnums, Oid *atttypids, Oid *attcollids,
447 Oid *opclasses, bool *pk_has_without_overlaps);
448 static Oid transformFkeyCheckAttrs(Relation pkrel,
449 int numattrs, int16 *attnums,
450 bool with_period, Oid *opclasses,
451 bool *pk_has_without_overlaps);
452 static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
453 static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
454 Oid *funcid);
455 static void validateForeignKeyConstraint(char *conname,
456 Relation rel, Relation pkrel,
457 Oid pkindOid, Oid constraintOid, bool hasperiod);
458 static void CheckAlterTableIsSafe(Relation rel);
459 static void ATController(AlterTableStmt *parsetree,
460 Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
461 AlterTableUtilityContext *context);
462 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
463 bool recurse, bool recursing, LOCKMODE lockmode,
464 AlterTableUtilityContext *context);
465 static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
466 AlterTableUtilityContext *context);
467 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab,
468 AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
469 AlterTableUtilityContext *context);
470 static AlterTableCmd *ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab,
471 Relation rel, AlterTableCmd *cmd,
472 bool recurse, LOCKMODE lockmode,
473 AlterTablePass cur_pass,
474 AlterTableUtilityContext *context);
475 static void ATRewriteTables(AlterTableStmt *parsetree,
476 List **wqueue, LOCKMODE lockmode,
477 AlterTableUtilityContext *context);
478 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
479 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
480 static void ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets);
481 static void ATSimpleRecursion(List **wqueue, Relation rel,
482 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
483 AlterTableUtilityContext *context);
484 static void ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode);
485 static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
486 LOCKMODE lockmode,
487 AlterTableUtilityContext *context);
488 static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
489 DropBehavior behavior);
490 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
491 bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
492 AlterTableUtilityContext *context);
493 static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab,
494 Relation rel, AlterTableCmd **cmd,
495 bool recurse, bool recursing,
496 LOCKMODE lockmode, AlterTablePass cur_pass,
497 AlterTableUtilityContext *context);
498 static bool check_for_column_name_collision(Relation rel, const char *colname,
499 bool if_not_exists);
500 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
501 static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
502 static ObjectAddress ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
503 LOCKMODE lockmode);
504 static void set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
505 bool queue_validation);
506 static ObjectAddress ATExecSetNotNull(List **wqueue, Relation rel,
507 char *conName, char *colName,
508 bool recurse, bool recursing,
509 LOCKMODE lockmode);
510 static bool NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr);
511 static bool ConstraintImpliedByRelConstraint(Relation scanrel,
512 List *testConstraint, List *provenConstraint);
513 static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
514 Node *newDefault, LOCKMODE lockmode);
515 static ObjectAddress ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
516 Node *newDefault);
517 static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName,
518 Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
519 static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName,
520 Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
521 static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
522 bool recurse, bool recursing);
523 static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
524 Node *newExpr, LOCKMODE lockmode);
525 static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode);
526 static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
527 static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum,
528 Node *newValue, LOCKMODE lockmode);
529 static ObjectAddress ATExecSetOptions(Relation rel, const char *colName,
530 Node *options, bool isReset, LOCKMODE lockmode);
531 static ObjectAddress ATExecSetStorage(Relation rel, const char *colName,
532 Node *newValue, LOCKMODE lockmode);
533 static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
534 AlterTableCmd *cmd, LOCKMODE lockmode,
535 AlterTableUtilityContext *context);
536 static ObjectAddress ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
537 DropBehavior behavior,
538 bool recurse, bool recursing,
539 bool missing_ok, LOCKMODE lockmode,
540 ObjectAddresses *addrs);
541 static void ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
542 bool recurse, LOCKMODE lockmode,
543 AlterTableUtilityContext *context);
544 static void verifyNotNullPKCompatible(HeapTuple tuple, const char *colname);
545 static ObjectAddress ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
546 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
547 static ObjectAddress ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
548 CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
549 static ObjectAddress ATExecAddConstraint(List **wqueue,
550 AlteredTableInfo *tab, Relation rel,
551 Constraint *newConstraint, bool recurse, bool is_readd,
552 LOCKMODE lockmode);
553 static char *ChooseForeignKeyConstraintNameAddition(List *colnames);
554 static ObjectAddress ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
555 IndexStmt *stmt, LOCKMODE lockmode);
556 static ObjectAddress ATAddCheckNNConstraint(List **wqueue,
557 AlteredTableInfo *tab, Relation rel,
558 Constraint *constr,
559 bool recurse, bool recursing, bool is_readd,
560 LOCKMODE lockmode);
561 static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab,
562 Relation rel, Constraint *fkconstraint,
563 bool recurse, bool recursing,
564 LOCKMODE lockmode);
565 static int validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
566 int numfksetcols, int16 *fksetcolsattnums,
567 List *fksetcols);
568 static ObjectAddress addFkConstraint(addFkConstraintSides fkside,
569 char *constraintname,
570 Constraint *fkconstraint, Relation rel,
571 Relation pkrel, Oid indexOid,
572 Oid parentConstr,
573 int numfks, int16 *pkattnum, int16 *fkattnum,
574 Oid *pfeqoperators, Oid *ppeqoperators,
575 Oid *ffeqoperators, int numfkdelsetcols,
576 int16 *fkdelsetcols, bool is_internal,
577 bool with_period);
578 static void addFkRecurseReferenced(Constraint *fkconstraint,
579 Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
580 int numfks, int16 *pkattnum, int16 *fkattnum,
581 Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
582 int numfkdelsetcols, int16 *fkdelsetcols,
583 bool old_check_ok,
584 Oid parentDelTrigger, Oid parentUpdTrigger,
585 bool with_period);
586 static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
587 Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
588 int numfks, int16 *pkattnum, int16 *fkattnum,
589 Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
590 int numfkdelsetcols, int16 *fkdelsetcols,
591 bool old_check_ok, LOCKMODE lockmode,
592 Oid parentInsTrigger, Oid parentUpdTrigger,
593 bool with_period);
594 static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
595 Relation partitionRel);
596 static void CloneFkReferenced(Relation parentRel, Relation partitionRel);
597 static void CloneFkReferencing(List **wqueue, Relation parentRel,
598 Relation partRel);
599 static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
600 Constraint *fkconstraint, Oid constraintOid,
601 Oid indexOid,
602 Oid parentInsTrigger, Oid parentUpdTrigger,
603 Oid *insertTrigOid, Oid *updateTrigOid);
604 static void createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid,
605 Constraint *fkconstraint, Oid constraintOid,
606 Oid indexOid,
607 Oid parentDelTrigger, Oid parentUpdTrigger,
608 Oid *deleteTrigOid, Oid *updateTrigOid);
609 static bool tryAttachPartitionForeignKey(List **wqueue,
610 ForeignKeyCacheInfo *fk,
611 Relation partition,
612 Oid parentConstrOid, int numfks,
613 AttrNumber *mapped_conkey, AttrNumber *confkey,
614 Oid *conpfeqop,
615 Oid parentInsTrigger,
616 Oid parentUpdTrigger,
617 Relation trigrel);
618 static void AttachPartitionForeignKey(List **wqueue, Relation partition,
619 Oid partConstrOid, Oid parentConstrOid,
620 Oid parentInsTrigger, Oid parentUpdTrigger,
621 Relation trigrel);
622 static void RemoveInheritedConstraint(Relation conrel, Relation trigrel,
623 Oid conoid, Oid conrelid);
624 static void DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid,
625 Oid confrelid, Oid conrelid);
626 static void GetForeignKeyActionTriggers(Relation trigrel,
627 Oid conoid, Oid confrelid, Oid conrelid,
628 Oid *deleteTriggerOid,
629 Oid *updateTriggerOid);
630 static void GetForeignKeyCheckTriggers(Relation trigrel,
631 Oid conoid, Oid confrelid, Oid conrelid,
632 Oid *insertTriggerOid,
633 Oid *updateTriggerOid);
634 static void ATExecDropConstraint(Relation rel, const char *constrName,
635 DropBehavior behavior, bool recurse,
636 bool missing_ok, LOCKMODE lockmode);
637 static ObjectAddress dropconstraint_internal(Relation rel,
638 HeapTuple constraintTup, DropBehavior behavior,
639 bool recurse, bool recursing,
640 bool missing_ok, LOCKMODE lockmode);
641 static void ATPrepAlterColumnType(List **wqueue,
642 AlteredTableInfo *tab, Relation rel,
643 bool recurse, bool recursing,
644 AlterTableCmd *cmd, LOCKMODE lockmode,
645 AlterTableUtilityContext *context);
646 static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
647 static ObjectAddress ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
648 AlterTableCmd *cmd, LOCKMODE lockmode);
649 static void RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
650 Relation rel, AttrNumber attnum, const char *colName);
651 static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
652 static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
653 static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
654 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
655 LOCKMODE lockmode);
656 static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
657 char *cmd, List **wqueue, LOCKMODE lockmode,
658 bool rewrite);
659 static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass,
660 Oid objid, Relation rel, List *domname,
661 const char *conname);
662 static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
663 static void TryReuseForeignKey(Oid oldId, Constraint *con);
664 static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
665 List *options, LOCKMODE lockmode);
666 static void change_owner_fix_column_acls(Oid relationOid,
667 Oid oldOwnerId, Oid newOwnerId);
668 static void change_owner_recurse_to_sequences(Oid relationOid,
669 Oid newOwnerId, LOCKMODE lockmode);
670 static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
671 LOCKMODE lockmode);
672 static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
673 static void ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname);
674 static void ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId);
675 static void ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel,
676 bool toLogged);
677 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
678 const char *tablespacename, LOCKMODE lockmode);
679 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
680 static void ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace);
681 static void ATExecSetRelOptions(Relation rel, List *defList,
682 AlterTableType operation,
683 LOCKMODE lockmode);
684 static void ATExecEnableDisableTrigger(Relation rel, const char *trigname,
685 char fires_when, bool skip_system, bool recurse,
686 LOCKMODE lockmode);
687 static void ATExecEnableDisableRule(Relation rel, const char *rulename,
688 char fires_when, LOCKMODE lockmode);
689 static void ATPrepAddInherit(Relation child_rel);
690 static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
691 static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
692 static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
693 DependencyType deptype);
694 static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
695 static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
696 static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
697 static void ATExecGenericOptions(Relation rel, List *options);
698 static void ATExecSetRowSecurity(Relation rel, bool rls);
699 static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
700 static ObjectAddress ATExecSetCompression(Relation rel,
701 const char *column, Node *newValue, LOCKMODE lockmode);
702
703 static void index_copy_data(Relation rel, RelFileLocator newrlocator);
704 static const char *storage_name(char c);
705
706 static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
707 Oid oldRelOid, void *arg);
708 static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
709 Oid oldrelid, void *arg);
710 static PartitionSpec *transformPartitionSpec(Relation rel, PartitionSpec *partspec);
711 static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
712 List **partexprs, Oid *partopclass, Oid *partcollation,
713 PartitionStrategy strategy);
714 static void CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition);
715 static void RemoveInheritance(Relation child_rel, Relation parent_rel,
716 bool expect_detached);
717 static ObjectAddress ATExecAttachPartition(List **wqueue, Relation rel,
718 PartitionCmd *cmd,
719 AlterTableUtilityContext *context);
720 static void AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel);
721 static void QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
722 List *partConstraint,
723 bool validate_default);
724 static void CloneRowTriggersToPartition(Relation parent, Relation partition);
725 static void DetachAddConstraintIfNeeded(List **wqueue, Relation partRel);
726 static void DropClonedTriggersFromPartition(Oid partitionId);
727 static ObjectAddress ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab,
728 Relation rel, RangeVar *name,
729 bool concurrent);
730 static void DetachPartitionFinalize(Relation rel, Relation partRel,
731 bool concurrent, Oid defaultPartOid);
732 static ObjectAddress ATExecDetachPartitionFinalize(Relation rel, RangeVar *name);
733 static ObjectAddress ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx,
734 RangeVar *name);
735 static void validatePartitionedIndex(Relation partedIdx, Relation partedTbl);
736 static void refuseDupeIndexAttach(Relation parentIdx, Relation partIdx,
737 Relation partitionTbl);
738 static void verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition);
739 static List *GetParentedForeignKeyRefs(Relation partition);
740 static void ATDetachCheckNoForeignKeyRefs(Relation partition);
741 static char GetAttributeCompression(Oid atttypid, const char *compression);
742 static char GetAttributeStorage(Oid atttypid, const char *storagemode);
743
744
745 /* ----------------------------------------------------------------
746 * DefineRelation
747 * Creates a new relation.
748 *
749 * stmt carries parsetree information from an ordinary CREATE TABLE statement.
750 * The other arguments are used to extend the behavior for other cases:
751 * relkind: relkind to assign to the new relation
752 * ownerId: if not InvalidOid, use this as the new relation's owner.
753 * typaddress: if not null, it's set to the pg_type entry's address.
754 * queryString: for error reporting
755 *
756 * Note that permissions checks are done against current user regardless of
757 * ownerId. A nonzero ownerId is used when someone is creating a relation
758 * "on behalf of" someone else, so we still want to see that the current user
759 * has permissions to do it.
760 *
761 * If successful, returns the address of the new relation.
762 * ----------------------------------------------------------------
763 */
764 ObjectAddress
765 DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
766 ObjectAddress *typaddress, const char *queryString)
767 {
768 char relname[NAMEDATALEN];
769 Oid namespaceId;
770 Oid relationId;
771 Oid tablespaceId;
772 Relation rel;
773 TupleDesc descriptor;
774 List *inheritOids;
775 List *old_constraints;
776 List *old_notnulls;
777 List *rawDefaults;
778 List *cookedDefaults;
779 List *nncols;
780 List *connames = NIL;
781 Datum reloptions;
782 ListCell *listptr;
783 AttrNumber attnum;
784 bool partitioned;
785 const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
786 Oid ofTypeId;
787 ObjectAddress address;
788 LOCKMODE parentLockmode;
789 Oid accessMethodId = InvalidOid;
790
791 /*
792 * Truncate relname to appropriate length (probably a waste of time, as
793 * parser should have done this already).
794 */
795 strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
796
797 /*
798 * Check consistency of arguments
799 */
800 if (stmt->oncommit != ONCOMMIT_NOOP
801 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
802 ereport(ERROR,
803 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
804 errmsg("ON COMMIT can only be used on temporary tables")));
805
806 if (stmt->partspec != NULL)
807 {
808 if (relkind != RELKIND_RELATION)
809 elog(ERROR, "unexpected relkind: %d", (int) relkind);
810
811 relkind = RELKIND_PARTITIONED_TABLE;
812 partitioned = true;
813 }
814 else
815 partitioned = false;
816
817 if (relkind == RELKIND_PARTITIONED_TABLE &&
818 stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
819 ereport(ERROR,
820 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
821 errmsg("partitioned tables cannot be unlogged")));
822
823 /*
824 * Look up the namespace in which we are supposed to create the relation,
825 * check we have permission to create there, lock it against concurrent
826 * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
827 * namespace is selected.
828 */
829 namespaceId =
830 RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
831
832 /*
833 * Security check: disallow creating temp tables from security-restricted
834 * code. This is needed because calling code might not expect untrusted
835 * tables to appear in pg_temp at the front of its search path.
836 */
837 if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
838 && InSecurityRestrictedOperation())
839 ereport(ERROR,
840 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
841 errmsg("cannot create temporary table within security-restricted operation")));
842
843 /*
844 * Determine the lockmode to use when scanning parents. A self-exclusive
845 * lock is needed here.
846 *
847 * For regular inheritance, if two backends attempt to add children to the
848 * same parent simultaneously, and that parent has no pre-existing
849 * children, then both will attempt to update the parent's relhassubclass
850 * field, leading to a "tuple concurrently updated" error. Also, this
851 * interlocks against a concurrent ANALYZE on the parent table, which
852 * might otherwise be attempting to clear the parent's relhassubclass
853 * field, if its previous children were recently dropped.
854 *
855 * If the child table is a partition, then we instead grab an exclusive
856 * lock on the parent because its partition descriptor will be changed by
857 * addition of the new partition.
858 */
859 parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
860 ShareUpdateExclusiveLock);
861
862 /* Determine the list of OIDs of the parents. */
863 inheritOids = NIL;
864 foreach(listptr, stmt->inhRelations)
865 {
866 RangeVar *rv = (RangeVar *) lfirst(listptr);
867 Oid parentOid;
868
869 parentOid = RangeVarGetRelid(rv, parentLockmode, false);
870
871 /*
872 * Reject duplications in the list of parents.
873 */
874 if (list_member_oid(inheritOids, parentOid))
875 ereport(ERROR,
876 (errcode(ERRCODE_DUPLICATE_TABLE),
877 errmsg("relation \"%s\" would be inherited from more than once",
878 get_rel_name(parentOid))));
879
880 inheritOids = lappend_oid(inheritOids, parentOid);
881 }
882
883 /*
884 * Select tablespace to use: an explicitly indicated one, or (in the case
885 * of a partitioned table) the parent's, if it has one.
886 */
887 if (stmt->tablespacename)
888 {
889 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
890
891 if (partitioned && tablespaceId == MyDatabaseTableSpace)
892 ereport(ERROR,
893 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
894 errmsg("cannot specify default tablespace for partitioned relations")));
895 }
896 else if (stmt->partbound)
897 {
898 Assert(list_length(inheritOids) == 1);
899 tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
900 }
901 else
902 tablespaceId = InvalidOid;
903
904 /* still nothing? use the default */
905 if (!OidIsValid(tablespaceId))
906 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
907 partitioned);
908
909 /* Check permissions except when using database's default */
910 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
911 {
912 AclResult aclresult;
913
914 aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
915 ACL_CREATE);
916 if (aclresult != ACLCHECK_OK)
917 aclcheck_error(aclresult, OBJECT_TABLESPACE,
918 get_tablespace_name(tablespaceId));
919 }
920
921 /* In all cases disallow placing user relations in pg_global */
922 if (tablespaceId == GLOBALTABLESPACE_OID)
923 ereport(ERROR,
924 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
925 errmsg("only shared relations can be placed in pg_global tablespace")));
926
927 /* Identify user ID that will own the table */
928 if (!OidIsValid(ownerId))
929 ownerId = GetUserId();
930
931 /*
932 * Parse and validate reloptions, if any.
933 */
934 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
935 true, false);
936
937 switch (relkind)
938 {
939 case RELKIND_VIEW:
940 (void) view_reloptions(reloptions, true);
941 break;
942 case RELKIND_PARTITIONED_TABLE:
943 (void) partitioned_table_reloptions(reloptions, true);
944 break;
945 default:
946 (void) heap_reloptions(relkind, reloptions, true);
947 }
948
949 if (stmt->ofTypename)
950 {
951 AclResult aclresult;
952
953 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
954
955 aclresult = object_aclcheck(TypeRelationId, ofTypeId, GetUserId(), ACL_USAGE);
956 if (aclresult != ACLCHECK_OK)
957 aclcheck_error_type(aclresult, ofTypeId);
958 }
959 else
960 ofTypeId = InvalidOid;
961
962 /*
963 * Look up inheritance ancestors and generate relation schema, including
964 * inherited attributes. (Note that stmt->tableElts is destructively
965 * modified by MergeAttributes.)
966 */
967 stmt->tableElts =
968 MergeAttributes(stmt->tableElts, inheritOids,
969 stmt->relation->relpersistence,
970 stmt->partbound != NULL,
971 &old_constraints, &old_notnulls);
972
973 /*
974 * NB: The defaults and constraints we just inherited are already cooked,
975 * so they don't get the USAGE checks that AddRelationNewConstraints()
976 * applies to raw ones. That's intentional: the parent's own catalog
977 * entries already depend on those types, so copying them pins nothing
978 * new, and creating a child requires owning the parent, anyway.
979 */
980
981 /*
982 * Create a tuple descriptor from the relation schema. Note that this
983 * deals with column names, types, and in-descriptor NOT NULL flags, but
984 * not default values, NOT NULL or CHECK constraints; we handle those
985 * below.
986 */
987 descriptor = BuildDescForRelation(stmt->tableElts);
988
989 /*
990 * Find columns with default values and prepare for insertion of the
991 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
992 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
993 * while raw defaults go into a list of RawColumnDefault structs that will
994 * be processed by AddRelationNewConstraints. (We can't deal with raw
995 * expressions until we can do transformExpr.)
996 */
997 rawDefaults = NIL;
998 cookedDefaults = NIL;
999 attnum = 0;
1000
1001 foreach(listptr, stmt->tableElts)
1002 {
1003 ColumnDef *colDef = lfirst(listptr);
1004
1005 attnum++;
1006 if (colDef->raw_default != NULL)
1007 {
1008 RawColumnDefault *rawEnt;
1009
1010 Assert(colDef->cooked_default == NULL);
1011
1012 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
1013 rawEnt->attnum = attnum;
1014 rawEnt->raw_default = colDef->raw_default;
1015 rawEnt->generated = colDef->generated;
1016 rawDefaults = lappend(rawDefaults, rawEnt);
1017 }
1018 else if (colDef->cooked_default != NULL)
1019 {
1020 CookedConstraint *cooked;
1021
1022 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1023 cooked->contype = CONSTR_DEFAULT;
1024 cooked->conoid = InvalidOid; /* until created */
1025 cooked->name = NULL;
1026 cooked->attnum = attnum;
1027 cooked->expr = colDef->cooked_default;
1028 cooked->is_enforced = true;
1029 cooked->skip_validation = false;
1030 cooked->is_local = true; /* not used for defaults */
1031 cooked->inhcount = 0; /* ditto */
1032 cooked->is_no_inherit = false;
1033 cookedDefaults = lappend(cookedDefaults, cooked);
1034 }
1035 }
1036
1037 /*
1038 * For relations with table AM and partitioned tables, select access
1039 * method to use: an explicitly indicated one, or (in the case of a
1040 * partitioned table) the parent's, if it has one.
1041 */
1042 if (stmt->accessMethod != NULL)
1043 {
1044 Assert(RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE);
1045 accessMethodId = get_table_am_oid(stmt->accessMethod, false);
1046 }
1047 else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
1048 {
1049 if (stmt->partbound)
1050 {
1051 Assert(list_length(inheritOids) == 1);
1052 accessMethodId = get_rel_relam(linitial_oid(inheritOids));
1053 }
1054
1055 if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
1056 accessMethodId = get_table_am_oid(default_table_access_method, false);
1057 }
1058
1059 /*
1060 * Create the relation. Inherited defaults and CHECK constraints are
1061 * passed in for immediate handling --- since they don't need parsing,
1062 * they can be stored immediately.
1063 */
1064 relationId = heap_create_with_catalog(relname,
1065 namespaceId,
1066 tablespaceId,
1067 InvalidOid,
1068 InvalidOid,
1069 ofTypeId,
1070 ownerId,
1071 accessMethodId,
1072 descriptor,
1073 list_concat(cookedDefaults,
1074 old_constraints),
1075 relkind,
1076 stmt->relation->relpersistence,
1077 false,
1078 false,
1079 stmt->oncommit,
1080 reloptions,
1081 true,
1082 allowSystemTableMods,
1083 false,
1084 InvalidOid,
1085 typaddress);
1086
1087 /*
1088 * We must bump the command counter to make the newly-created relation
1089 * tuple visible for opening.
1090 */
1091 CommandCounterIncrement();
1092
1093 /*
1094 * Open the new relation and acquire exclusive lock on it. This isn't
1095 * really necessary for locking out other backends (since they can't see
1096 * the new rel anyway until we commit), but it keeps the lock manager from
1097 * complaining about deadlock risks.
1098 */
1099 rel = relation_open(relationId, AccessExclusiveLock);
1100
1101 /*
1102 * Now add any newly specified column default and generation expressions
1103 * to the new relation. These are passed to us in the form of raw
1104 * parsetrees; we need to transform them to executable expression trees
1105 * before they can be added. The most convenient way to do that is to
1106 * apply the parser's transformExpr routine, but transformExpr doesn't
1107 * work unless we have a pre-existing relation. So, the transformation has
1108 * to be postponed to this final step of CREATE TABLE.
1109 *
1110 * This needs to be before processing the partitioning clauses because
1111 * those could refer to generated columns.
1112 */
1113 if (rawDefaults)
1114 AddRelationNewConstraints(rel, rawDefaults, NIL,
1115 true, true, false, queryString);
1116
1117 /*
1118 * Make column generation expressions visible for use by partitioning.
1119 */
1120 CommandCounterIncrement();
1121
1122 /* Process and store partition bound, if any. */
1123 if (stmt->partbound)
1124 {
1125 PartitionBoundSpec *bound;
1126 ParseState *pstate;
1127 Oid parentId = linitial_oid(inheritOids),
1128 defaultPartOid;
1129 Relation parent,
1130 defaultRel = NULL;
1131 ParseNamespaceItem *nsitem;
1132
1133 /* Already have strong enough lock on the parent */
1134 parent = table_open(parentId, NoLock);
1135
1136 /*
1137 * We are going to try to validate the partition bound specification
1138 * against the partition key of parentRel, so it better have one.
1139 */
1140 if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1141 ereport(ERROR,
1142 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1143 errmsg("\"%s\" is not partitioned",
1144 RelationGetRelationName(parent))));
1145
1146 /*
1147 * The partition constraint of the default partition depends on the
1148 * partition bounds of every other partition. It is possible that
1149 * another backend might be about to execute a query on the default
1150 * partition table, and that the query relies on previously cached
1151 * default partition constraints. We must therefore take a table lock
1152 * strong enough to prevent all queries on the default partition from
1153 * proceeding until we commit and send out a shared-cache-inval notice
1154 * that will make them update their index lists.
1155 *
1156 * Order of locking: The relation being added won't be visible to
1157 * other backends until it is committed, hence here in
1158 * DefineRelation() the order of locking the default partition and the
1159 * relation being added does not matter. But at all other places we
1160 * need to lock the default relation before we lock the relation being
1161 * added or removed i.e. we should take the lock in same order at all
1162 * the places such that lock parent, lock default partition and then
1163 * lock the partition so as to avoid a deadlock.
1164 */
1165 defaultPartOid =
1166 get_default_oid_from_partdesc(RelationGetPartitionDesc(parent,
1167 true));
1168 if (OidIsValid(defaultPartOid))
1169 defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
1170
1171 /* Transform the bound values */
1172 pstate = make_parsestate(NULL);
1173 pstate->p_sourcetext = queryString;
1174
1175 /*
1176 * Add an nsitem containing this relation, so that transformExpr
1177 * called on partition bound expressions is able to report errors
1178 * using a proper context.
1179 */
1180 nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1181 NULL, false, false);
1182 addNSItemToQuery(pstate, nsitem, false, true, true);
1183
1184 bound = transformPartitionBound(pstate, parent, stmt->partbound);
1185
1186 /*
1187 * Check first that the new partition's bound is valid and does not
1188 * overlap with any of existing partitions of the parent.
1189 */
1190 check_new_partition_bound(relname, parent, bound, pstate);
1191
1192 /*
1193 * If the default partition exists, its partition constraints will
1194 * change after the addition of this new partition such that it won't
1195 * allow any row that qualifies for this new partition. So, check that
1196 * the existing data in the default partition satisfies the constraint
1197 * as it will exist after adding this partition.
1198 */
1199 if (OidIsValid(defaultPartOid))
1200 {
1201 check_default_partition_contents(parent, defaultRel, bound);
1202 /* Keep the lock until commit. */
1203 table_close(defaultRel, NoLock);
1204 }
1205
1206 /* Update the pg_class entry. */
1207 StorePartitionBound(rel, parent, bound);
1208
1209 table_close(parent, NoLock);
1210 }
1211
1212 /* Store inheritance information for new rel. */
1213 StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
1214
1215 /*
1216 * Process the partitioning specification (if any) and store the partition
1217 * key information into the catalog.
1218 */
1219 if (partitioned)
1220 {
1221 ParseState *pstate;
1222 int partnatts;
1223 AttrNumber partattrs[PARTITION_MAX_KEYS];
1224 Oid partopclass[PARTITION_MAX_KEYS];
1225 Oid partcollation[PARTITION_MAX_KEYS];
1226 List *partexprs = NIL;
1227
1228 pstate = make_parsestate(NULL);
1229 pstate->p_sourcetext = queryString;
1230
1231 partnatts = list_length(stmt->partspec->partParams);
1232
1233 /* Protect fixed-size arrays here and in executor */
1234 if (partnatts > PARTITION_MAX_KEYS)
1235 ereport(ERROR,
1236 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1237 errmsg("cannot partition using more than %d columns",
1238 PARTITION_MAX_KEYS)));
1239
1240 /*
1241 * We need to transform the raw parsetrees corresponding to partition
1242 * expressions into executable expression trees. Like column defaults
1243 * and CHECK constraints, we could not have done the transformation
1244 * earlier.
1245 */
1246 stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1247
1248 ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1249 partattrs, &partexprs, partopclass,
1250 partcollation, stmt->partspec->strategy);
1251
1252 StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1253 partexprs,
1254 partopclass, partcollation);
1255
1256 /* make it all visible */
1257 CommandCounterIncrement();
1258 }
1259
1260 /*
1261 * If we're creating a partition, create now all the indexes, triggers,
1262 * FKs defined in the parent.
1263 *
1264 * We can't do it earlier, because DefineIndex wants to know the partition
1265 * key which we just stored.
1266 */
1267 if (stmt->partbound)
1268 {
1269 Oid parentId = linitial_oid(inheritOids);
1270 Relation parent;
1271 List *idxlist;
1272 ListCell *cell;
1273
1274 /* Already have strong enough lock on the parent */
1275 parent = table_open(parentId, NoLock);
1276 idxlist = RelationGetIndexList(parent);
1277
1278 /*
1279 * For each index in the parent table, create one in the partition
1280 */
1281 foreach(cell, idxlist)
1282 {
1283 Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1284 AttrMap *attmap;
1285 IndexStmt *idxstmt;
1286 Oid constraintOid;
1287
1288 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1289 {
1290 if (idxRel->rd_index->indisunique)
1291 ereport(ERROR,
1292 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1293 errmsg("cannot create foreign partition of partitioned table \"%s\"",
1294 RelationGetRelationName(parent)),
1295 errdetail("Table \"%s\" contains indexes that are unique.",
1296 RelationGetRelationName(parent))));
1297 else
1298 {
1299 index_close(idxRel, AccessShareLock);
1300 continue;
1301 }
1302 }
1303
1304 attmap = build_attrmap_by_name(RelationGetDescr(rel),
1305 RelationGetDescr(parent),
1306 false);
1307 idxstmt =
1308 generateClonedIndexStmt(NULL, idxRel,
1309 attmap, &constraintOid);
1310 DefineIndex(RelationGetRelid(rel),
1311 idxstmt,
1312 InvalidOid,
1313 RelationGetRelid(idxRel),
1314 constraintOid,
1315 -1,
1316 false, false, false, false, false);
1317
1318 index_close(idxRel, AccessShareLock);
1319 }
1320
1321 list_free(idxlist);
1322
1323 /*
1324 * If there are any row-level triggers, clone them to the new
1325 * partition.
1326 */
1327 if (parent->trigdesc != NULL)
1328 CloneRowTriggersToPartition(parent, rel);
1329
1330 /*
1331 * And foreign keys too. Note that because we're freshly creating the
1332 * table, there is no need to verify these new constraints.
1333 */
1334 CloneForeignKeyConstraints(NULL, parent, rel);
1335
1336 table_close(parent, NoLock);
1337 }
1338
1339 /*
1340 * Now add any newly specified CHECK constraints to the new relation. Same
1341 * as for defaults above, but these need to come after partitioning is set
1342 * up. We save the constraint names that were used, to avoid dupes below.
1343 */
1344 if (stmt->constraints)
1345 {
1346 List *conlist;
1347
1348 conlist = AddRelationNewConstraints(rel, NIL, stmt->constraints,
1349 true, true, false, queryString);
1350 foreach_ptr(CookedConstraint, cons, conlist)
1351 {
1352 if (cons->name != NULL)
1353 connames = lappend(connames, cons->name);
1354 }
1355 }
1356
1357 /*
1358 * Finally, merge the not-null constraints that are declared directly with
1359 * those that come from parent relations (making sure to count inheritance
1360 * appropriately for each), create them, and set the attnotnull flag on
1361 * columns that don't yet have it.
1362 */
1363 nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1364 old_notnulls, connames);
1365 foreach_int(attrnum, nncols)
1366 set_attnotnull(NULL, rel, attrnum, false);
1367
1368 ObjectAddressSet(address, RelationRelationId, relationId);
1369
1370 /*
1371 * Clean up. We keep lock on new relation (although it shouldn't be
1372 * visible to anyone else anyway, until commit).
1373 */
1374 relation_close(rel, NoLock);
1375
1376 return address;
1377 }
1378
1379 /*
1380 * BuildDescForRelation
1381 *
1382 * Given a list of ColumnDef nodes, build a TupleDesc.
1383 *
1384 * Note: This is only for the limited purpose of table and view creation. Not
1385 * everything is filled in. A real tuple descriptor should be obtained from
1386 * the relcache.
1387 */
1388 TupleDesc
1389 BuildDescForRelation(const List *columns)
1390 {
1391 int natts;
1392 AttrNumber attnum;
1393 ListCell *l;
1394 TupleDesc desc;
1395 char *attname;
1396 Oid atttypid;
1397 int32 atttypmod;
1398 Oid attcollation;
1399 int attdim;
1400
1401 /*
1402 * allocate a new tuple descriptor
1403 */
1404 natts = list_length(columns);
1405 desc = CreateTemplateTupleDesc(natts);
1406
1407 attnum = 0;
1408
1409 foreach(l, columns)
1410 {
1411 ColumnDef *entry = lfirst(l);
1412 AclResult aclresult;
1413 Form_pg_attribute att;
1414
1415 /*
1416 * for each entry in the list, get the name and type information from
1417 * the list and have TupleDescInitEntry fill in the attribute
1418 * information we need.
1419 */
1420 attnum++;
1421
1422 attname = entry->colname;
1423 typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1424
1425 aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1426 if (aclresult != ACLCHECK_OK)
1427 aclcheck_error_type(aclresult, atttypid);
1428
1429 attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1430 attdim = list_length(entry->typeName->arrayBounds);
1431 if (attdim > PG_INT16_MAX)
1432 ereport(ERROR,
1433 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1434 errmsg("too many array dimensions"));
1435
1436 if (entry->typeName->setof)
1437 ereport(ERROR,
1438 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1439 errmsg("column \"%s\" cannot be declared SETOF",
1440 attname)));
1441
1442 TupleDescInitEntry(desc, attnum, attname,
1443 atttypid, atttypmod, attdim);
1444 att = TupleDescAttr(desc, attnum - 1);
1445
1446 /* Override TupleDescInitEntry's settings as requested */
1447 TupleDescInitEntryCollation(desc, attnum, attcollation);
1448
1449 /* Fill in additional stuff not handled by TupleDescInitEntry */
1450 att->attnotnull = entry->is_not_null;
1451 att->attislocal = entry->is_local;
1452 att->attinhcount = entry->inhcount;
1453 att->attidentity = entry->identity;
1454 att->attgenerated = entry->generated;
1455 att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1456 if (entry->storage)
1457 att->attstorage = entry->storage;
1458 else if (entry->storage_name)
1459 att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1460
1461 populate_compact_attribute(desc, attnum - 1);
1462 }
1463
1464 return desc;
1465 }
1466
1467 /*
1468 * Emit the right error or warning message for a "DROP" command issued on a
1469 * non-existent relation
1470 */
1471 static void
1472 DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
1473 {
1474 const struct dropmsgstrings *rentry;
1475
1476 if (rel->schemaname != NULL &&
1477 !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
1478 {
1479 if (!missing_ok)
1480 {
1481 ereport(ERROR,
1482 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1483 errmsg("schema \"%s\" does not exist", rel->schemaname)));
1484 }
1485 else
1486 {
1487 ereport(NOTICE,
1488 (errmsg("schema \"%s\" does not exist, skipping",
1489 rel->schemaname)));
1490 }
1491 return;
1492 }
1493
1494 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1495 {
1496 if (rentry->kind == rightkind)
1497 {
1498 if (!missing_ok)
1499 {
1500 ereport(ERROR,
1501 (errcode(rentry->nonexistent_code),
1502 errmsg(rentry->nonexistent_msg, rel->relname)));
1503 }
1504 else
1505 {
1506 ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
1507 break;
1508 }
1509 }
1510 }
1511
1512 Assert(rentry->kind != '\0'); /* Should be impossible */
1513 }
1514
1515 /*
1516 * Emit the right error message for a "DROP" command issued on a
1517 * relation of the wrong type
1518 */
1519 static void
1520 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
1521 {
1522 const struct dropmsgstrings *rentry;
1523 const struct dropmsgstrings *wentry;
1524
1525 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1526 if (rentry->kind == rightkind)
1527 break;
1528 Assert(rentry->kind != '\0');
1529
1530 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
1531 if (wentry->kind == wrongkind)
1532 break;
1533 /* wrongkind could be something we don't have in our table... */
1534
1535 ereport(ERROR,
1536 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1537 errmsg(rentry->nota_msg, relname),
1538 (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
1539 }
1540
1541 /*
1542 * RemoveRelations
1543 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
1544 * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
1545 */
1546 void
1547 RemoveRelations(DropStmt *drop)
1548 {
1549 ObjectAddresses *objects;
1550 char relkind;
1551 ListCell *cell;
1552 int flags = 0;
1553 LOCKMODE lockmode = AccessExclusiveLock;
1554
1555 /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1556 if (drop->concurrent)
1557 {
1558 /*
1559 * Note that for temporary relations this lock may get upgraded later
1560 * on, but as no other session can access a temporary relation, this
1561 * is actually fine.
1562 */
1563 lockmode = ShareUpdateExclusiveLock;
1564 Assert(drop->removeType == OBJECT_INDEX);
1565 if (list_length(drop->objects) != 1)
1566 ereport(ERROR,
1567 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1568 errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1569 if (drop->behavior == DROP_CASCADE)
1570 ereport(ERROR,
1571 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1572 errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1573 }
1574
1575 /*
1576 * First we identify all the relations, then we delete them in a single
1577 * performMultipleDeletions() call. This is to avoid unwanted DROP
1578 * RESTRICT errors if one of the relations depends on another.
1579 */
1580
1581 /* Determine required relkind */
1582 switch (drop->removeType)
1583 {
1584 case OBJECT_TABLE:
1585 relkind = RELKIND_RELATION;
1586 break;
1587
1588 case OBJECT_INDEX:
1589 relkind = RELKIND_INDEX;
1590 break;
1591
1592 case OBJECT_SEQUENCE:
1593 relkind = RELKIND_SEQUENCE;
1594 break;
1595
1596 case OBJECT_VIEW:
1597 relkind = RELKIND_VIEW;
1598 break;
1599
1600 case OBJECT_MATVIEW:
1601 relkind = RELKIND_MATVIEW;
1602 break;
1603
1604 case OBJECT_FOREIGN_TABLE:
1605 relkind = RELKIND_FOREIGN_TABLE;
1606 break;
1607
1608 default:
1609 elog(ERROR, "unrecognized drop object type: %d",
1610 (int) drop->removeType);
1611 relkind = 0; /* keep compiler quiet */
1612 break;
1613 }
1614
1615 /* Lock and validate each relation; build a list of object addresses */
1616 objects = new_object_addresses();
1617
1618 foreach(cell, drop->objects)
1619 {
1620 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1621 Oid relOid;
1622 ObjectAddress obj;
1623 struct DropRelationCallbackState state;
1624
1625 /*
1626 * These next few steps are a great deal like relation_openrv, but we
1627 * don't bother building a relcache entry since we don't need it.
1628 *
1629 * Check for shared-cache-inval messages before trying to access the
1630 * relation. This is needed to cover the case where the name
1631 * identifies a rel that has been dropped and recreated since the
1632 * start of our transaction: if we don't flush the old syscache entry,
1633 * then we'll latch onto that entry and suffer an error later.
1634 */
1635 AcceptInvalidationMessages();
1636
1637 /* Look up the appropriate relation using namespace search. */
1638 state.expected_relkind = relkind;
1639 state.heap_lockmode = drop->concurrent ?
1640 ShareUpdateExclusiveLock : AccessExclusiveLock;
1641 /* We must initialize these fields to show that no locks are held: */
1642 state.heapOid = InvalidOid;
1643 state.partParentOid = InvalidOid;
1644
1645 relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1646 RangeVarCallbackForDropRelation,
1647 &state);
1648
1649 /* Not there? */
1650 if (!OidIsValid(relOid))
1651 {
1652 DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1653 continue;
1654 }
1655
1656 /*
1657 * Decide if concurrent mode needs to be used here or not. The
1658 * callback retrieved the rel's persistence for us.
1659 */
1660 if (drop->concurrent &&
1661 state.actual_relpersistence != RELPERSISTENCE_TEMP)
1662 {
1663 Assert(list_length(drop->objects) == 1 &&
1664 drop->removeType == OBJECT_INDEX);
1665 flags |= PERFORM_DELETION_CONCURRENTLY;
1666 }
1667
1668 /*
1669 * Concurrent index drop cannot be used with partitioned indexes,
1670 * either.
1671 */
1672 if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1673 state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1674 ereport(ERROR,
1675 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1676 errmsg("cannot drop partitioned index \"%s\" concurrently",
1677 rel->relname)));
1678
1679 /*
1680 * If we're told to drop a partitioned index, we must acquire lock on
1681 * all the children of its parent partitioned table before proceeding.
1682 * Otherwise we'd try to lock the child index partitions before their
1683 * tables, leading to potential deadlock against other sessions that
1684 * will lock those objects in the other order.
1685 */
1686 if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1687 (void) find_all_inheritors(state.heapOid,
1688 state.heap_lockmode,
1689 NULL);
1690
1691 /* OK, we're ready to delete this one */
1692 obj.classId = RelationRelationId;
1693 obj.objectId = relOid;
1694 obj.objectSubId = 0;
1695
1696 add_exact_object_address(&obj, objects);
1697 }
1698
1699 performMultipleDeletions(objects, drop->behavior, flags);
1700
1701 free_object_addresses(objects);
1702 }
1703
1704 /*
1705 * Before acquiring a table lock, check whether we have sufficient rights.
1706 * In the case of DROP INDEX, also try to lock the table before the index.
1707 * Also, if the table to be dropped is a partition, we try to lock the parent
1708 * first.
1709 */
1710 static void
1711 RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
1712 void *arg)
1713 {
1714 HeapTuple tuple;
1715 struct DropRelationCallbackState *state;
1716 char expected_relkind;
1717 bool is_partition;
1718 Form_pg_class classform;
1719 LOCKMODE heap_lockmode;
1720 bool invalid_system_index = false;
1721
1722 state = (struct DropRelationCallbackState *) arg;
1723 heap_lockmode = state->heap_lockmode;
1724
1725 /*
1726 * If we previously locked some other index's heap, and the name we're
1727 * looking up no longer refers to that relation, release the now-useless
1728 * lock.
1729 */
1730 if (relOid != oldRelOid && OidIsValid(state->heapOid))
1731 {
1732 UnlockRelationOid(state->heapOid, heap_lockmode);
1733 state->heapOid = InvalidOid;
1734 }
1735
1736 /*
1737 * Similarly, if we previously locked some other partition's heap, and the
1738 * name we're looking up no longer refers to that relation, release the
1739 * now-useless lock.
1740 */
1741 if (relOid != oldRelOid && OidIsValid(state->partParentOid))
1742 {
1743 UnlockRelationOid(state->partParentOid, AccessExclusiveLock);
1744 state->partParentOid = InvalidOid;
1745 }
1746
1747 /* Didn't find a relation, so no need for locking or permission checks. */
1748 if (!OidIsValid(relOid))
1749 return;
1750
1751 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1752 if (!HeapTupleIsValid(tuple))
1753 return; /* concurrently dropped, so nothing to do */
1754 classform = (Form_pg_class) GETSTRUCT(tuple);
1755 is_partition = classform->relispartition;
1756
1757 /* Pass back some data to save lookups in RemoveRelations */
1758 state->actual_relkind = classform->relkind;
1759 state->actual_relpersistence = classform->relpersistence;
1760
1761 /*
1762 * Both RELKIND_RELATION and RELKIND_PARTITIONED_TABLE are OBJECT_TABLE,
1763 * but RemoveRelations() can only pass one relkind for a given relation.
1764 * It chooses RELKIND_RELATION for both regular and partitioned tables.
1765 * That means we must be careful before giving the wrong type error when
1766 * the relation is RELKIND_PARTITIONED_TABLE. An equivalent problem
1767 * exists with indexes.
1768 */
1769 if (classform->relkind == RELKIND_PARTITIONED_TABLE)
1770 expected_relkind = RELKIND_RELATION;
1771 else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
1772 expected_relkind = RELKIND_INDEX;
1773 else
1774 expected_relkind = classform->relkind;
1775
1776 if (state->expected_relkind != expected_relkind)
1777 DropErrorMsgWrongType(rel->relname, classform->relkind,
1778 state->expected_relkind);
1779
1780 /* Allow DROP to either table owner or schema owner */
1781 if (!object_ownercheck(RelationRelationId, relOid, GetUserId()) &&
1782 !object_ownercheck(NamespaceRelationId, classform->relnamespace, GetUserId()))
1783 aclcheck_error(ACLCHECK_NOT_OWNER,
1784 get_relkind_objtype(classform->relkind),
1785 rel->relname);
1786
1787 /*
1788 * Check the case of a system index that might have been invalidated by a
1789 * failed concurrent process and allow its drop. For the time being, this
1790 * only concerns indexes of toast relations that became invalid during a
1791 * REINDEX CONCURRENTLY process.
1792 */
1793 if (IsSystemClass(relOid, classform) && classform->relkind == RELKIND_INDEX)
1794 {
1795 HeapTuple locTuple;
1796 Form_pg_index indexform;
1797 bool indisvalid;
1798
1799 locTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
1800 if (!HeapTupleIsValid(locTuple))
1801 {
1802 ReleaseSysCache(tuple);
1803 return;
1804 }
1805
1806 indexform = (Form_pg_index) GETSTRUCT(locTuple);
1807 indisvalid = indexform->indisvalid;
1808 ReleaseSysCache(locTuple);
1809
1810 /* Mark object as being an invalid index of system catalogs */
1811 if (!indisvalid)
1812 invalid_system_index = true;
1813 }
1814
1815 /* In the case of an invalid index, it is fine to bypass this check */
1816 if (!invalid_system_index && !allowSystemTableMods && IsSystemClass(relOid, classform))
1817 ereport(ERROR,
1818 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1819 errmsg("permission denied: \"%s\" is a system catalog",
1820 rel->relname)));
1821
1822 ReleaseSysCache(tuple);
1823
1824 /*
1825 * In DROP INDEX, attempt to acquire lock on the parent table before
1826 * locking the index. index_drop() will need this anyway, and since
1827 * regular queries lock tables before their indexes, we risk deadlock if
1828 * we do it the other way around. No error if we don't find a pg_index
1829 * entry, though --- the relation may have been dropped. Note that this
1830 * code will execute for either plain or partitioned indexes.
1831 */
1832 if (expected_relkind == RELKIND_INDEX &&
1833 relOid != oldRelOid)
1834 {
1835 state->heapOid = IndexGetRelation(relOid, true);
1836 if (OidIsValid(state->heapOid))
1837 LockRelationOid(state->heapOid, heap_lockmode);
1838 }
1839
1840 /*
1841 * Similarly, if the relation is a partition, we must acquire lock on its
1842 * parent before locking the partition. That's because queries lock the
1843 * parent before its partitions, so we risk deadlock if we do it the other
1844 * way around.
1845 */
1846 if (is_partition && relOid != oldRelOid)
1847 {
1848 state->partParentOid = get_partition_parent(relOid, true);
1849 if (OidIsValid(state->partParentOid))
1850 LockRelationOid(state->partParentOid, AccessExclusiveLock);
1851 }
1852 }
1853
1854 /*
1855 * ExecuteTruncate
1856 * Executes a TRUNCATE command.
1857 *
1858 * This is a multi-relation truncate. We first open and grab exclusive
1859 * lock on all relations involved, checking permissions and otherwise
1860 * verifying that the relation is OK for truncation. Note that if relations
1861 * are foreign tables, at this stage, we have not yet checked that their
1862 * foreign data in external data sources are OK for truncation. These are
1863 * checked when foreign data are actually truncated later. In CASCADE mode,
1864 * relations having FK references to the targeted relations are automatically
1865 * added to the group; in RESTRICT mode, we check that all FK references are
1866 * internal to the group that's being truncated. Finally all the relations
1867 * are truncated and reindexed.
1868 */
1869 void
1870 ExecuteTruncate(TruncateStmt *stmt)
1871 {
1872 List *rels = NIL;
1873 List *relids = NIL;
1874 List *relids_logged = NIL;
1875 ListCell *cell;
1876
1877 /*
1878 * Open, exclusive-lock, and check all the explicitly-specified relations
1879 */
1880 foreach(cell, stmt->relations)
1881 {
1882 RangeVar *rv = lfirst(cell);
1883 Relation rel;
1884 bool recurse = rv->inh;
1885 Oid myrelid;
1886 LOCKMODE lockmode = AccessExclusiveLock;
1887
1888 myrelid = RangeVarGetRelidExtended(rv, lockmode,
1889 0, RangeVarCallbackForTruncate,
1890 NULL);
1891
1892 /* don't throw error for "TRUNCATE foo, foo" */
1893 if (list_member_oid(relids, myrelid))
1894 continue;
1895
1896 /* open the relation, we already hold a lock on it */
1897 rel = table_open(myrelid, NoLock);
1898
1899 /*
1900 * RangeVarGetRelidExtended() has done most checks with its callback,
1901 * but other checks with the now-opened Relation remain.
1902 */
1903 truncate_check_activity(rel);
1904
1905 rels = lappend(rels, rel);
1906 relids = lappend_oid(relids, myrelid);
1907
1908 /* Log this relation only if needed for logical decoding */
1909 if (RelationIsLogicallyLogged(rel))
1910 relids_logged = lappend_oid(relids_logged, myrelid);
1911
1912 if (recurse)
1913 {
1914 ListCell *child;
1915 List *children;
1916
1917 children = find_all_inheritors(myrelid, lockmode, NULL);
1918
1919 foreach(child, children)
1920 {
1921 Oid childrelid = lfirst_oid(child);
1922
1923 if (list_member_oid(relids, childrelid))
1924 continue;
1925
1926 /* find_all_inheritors already got lock */
1927 rel = table_open(childrelid, NoLock);
1928
1929 /*
1930 * It is possible that the parent table has children that are
1931 * temp tables of other backends. We cannot safely access
1932 * such tables (because of buffering issues), and the best
1933 * thing to do is to silently ignore them. Note that this
1934 * check is the same as one of the checks done in
1935 * truncate_check_activity() called below, still it is kept
1936 * here for simplicity.
1937 */
1938 if (RELATION_IS_OTHER_TEMP(rel))
1939 {
1940 table_close(rel, lockmode);
1941 continue;
1942 }
1943
1944 /*
1945 * Inherited TRUNCATE commands perform access permission
1946 * checks on the parent table only. So we skip checking the
1947 * children's permissions and don't call
1948 * truncate_check_perms() here.
1949 */
1950 truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
1951 truncate_check_activity(rel);
1952
1953 rels = lappend(rels, rel);
1954 relids = lappend_oid(relids, childrelid);
1955
1956 /* Log this relation only if needed for logical decoding */
1957 if (RelationIsLogicallyLogged(rel))
1958 relids_logged = lappend_oid(relids_logged, childrelid);
1959 }
1960 }
1961 else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1962 ereport(ERROR,
1963 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1964 errmsg("cannot truncate only a partitioned table"),
1965 errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1966 }
1967
1968 ExecuteTruncateGuts(rels, relids, relids_logged,
1969 stmt->behavior, stmt->restart_seqs, false);
1970
1971 /* And close the rels */
1972 foreach(cell, rels)
1973 {
1974 Relation rel = (Relation) lfirst(cell);
1975
1976 table_close(rel, NoLock);
1977 }
1978 }
1979
1980 /*
1981 * ExecuteTruncateGuts
1982 *
1983 * Internal implementation of TRUNCATE. This is called by the actual TRUNCATE
1984 * command (see above) as well as replication subscribers that execute a
1985 * replicated TRUNCATE action.
1986 *
1987 * explicit_rels is the list of Relations to truncate that the command
1988 * specified. relids is the list of Oids corresponding to explicit_rels.
1989 * relids_logged is the list of Oids (a subset of relids) that require
1990 * WAL-logging. This is all a bit redundant, but the existing callers have
1991 * this information handy in this form.
1992 */
1993 void
1994 ExecuteTruncateGuts(List *explicit_rels,
1995 List *relids,
1996 List *relids_logged,
1997 DropBehavior behavior, bool restart_seqs,
1998 bool run_as_table_owner)
1999 {
2000 List *rels;
2001 List *seq_relids = NIL;
2002 HTAB *ft_htab = NULL;
2003 EState *estate;
2004 ResultRelInfo *resultRelInfos;
2005 ResultRelInfo *resultRelInfo;
2006 SubTransactionId mySubid;
2007 ListCell *cell;
2008 Oid *logrelids;
2009
2010 /*
2011 * Check the explicitly-specified relations.
2012 *
2013 * In CASCADE mode, suck in all referencing relations as well. This
2014 * requires multiple iterations to find indirectly-dependent relations. At
2015 * each phase, we need to exclusive-lock new rels before looking for their
2016 * dependencies, else we might miss something. Also, we check each rel as
2017 * soon as we open it, to avoid a faux pas such as holding lock for a long
2018 * time on a rel we have no permissions for.
2019 */
2020 rels = list_copy(explicit_rels);
2021 if (behavior == DROP_CASCADE)
2022 {
2023 for (;;)
2024 {
2025 List *newrelids;
2026
2027 newrelids = heap_truncate_find_FKs(relids);
2028 if (newrelids == NIL)
2029 break; /* nothing else to add */
2030
2031 foreach(cell, newrelids)
2032 {
2033 Oid relid = lfirst_oid(cell);
2034 Relation rel;
2035
2036 rel = table_open(relid, AccessExclusiveLock);
2037 ereport(NOTICE,
2038 (errmsg("truncate cascades to table \"%s\"",
2039 RelationGetRelationName(rel))));
2040 truncate_check_rel(relid, rel->rd_rel);
2041 truncate_check_perms(relid, rel->rd_rel);
2042 truncate_check_activity(rel);
2043 rels = lappend(rels, rel);
2044 relids = lappend_oid(relids, relid);
2045
2046 /* Log this relation only if needed for logical decoding */
2047 if (RelationIsLogicallyLogged(rel))
2048 relids_logged = lappend_oid(relids_logged, relid);
2049 }
2050 }
2051 }
2052
2053 /*
2054 * Check foreign key references. In CASCADE mode, this should be
2055 * unnecessary since we just pulled in all the references; but as a
2056 * cross-check, do it anyway if in an Assert-enabled build.
2057 */
2058 #ifdef USE_ASSERT_CHECKING
2059 heap_truncate_check_FKs(rels, false);
2060 #else
2061 if (behavior == DROP_RESTRICT)
2062 heap_truncate_check_FKs(rels, false);
2063 #endif
2064
2065 /*
2066 * If we are asked to restart sequences, find all the sequences, lock them
2067 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2068 * We want to do this early since it's pointless to do all the truncation
2069 * work only to fail on sequence permissions.
2070 */
2071 if (restart_seqs)
2072 {
2073 foreach(cell, rels)
2074 {
2075 Relation rel = (Relation) lfirst(cell);
2076 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
2077 ListCell *seqcell;
2078
2079 foreach(seqcell, seqlist)
2080 {
2081 Oid seq_relid = lfirst_oid(seqcell);
2082 Relation seq_rel;
2083
2084 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
2085
2086 /* This check must match AlterSequence! */
2087 if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
2088 aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SEQUENCE,
2089 RelationGetRelationName(seq_rel));
2090
2091 seq_relids = lappend_oid(seq_relids, seq_relid);
2092
2093 relation_close(seq_rel, NoLock);
2094 }
2095 }
2096 }
2097
2098 /* Prepare to catch AFTER triggers. */
2099 AfterTriggerBeginQuery();
2100
2101 /*
2102 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2103 * each relation. We don't need to call ExecOpenIndices, though.
2104 *
2105 * We put the ResultRelInfos in the es_opened_result_relations list, even
2106 * though we don't have a range table and don't populate the
2107 * es_result_relations array. That's a bit bogus, but it's enough to make
2108 * ExecGetTriggerResultRel() find them.
2109 */
2110 estate = CreateExecutorState();
2111 resultRelInfos = (ResultRelInfo *)
2112 palloc(list_length(rels) * sizeof(ResultRelInfo));
2113 resultRelInfo = resultRelInfos;
2114 foreach(cell, rels)
2115 {
2116 Relation rel = (Relation) lfirst(cell);
2117
2118 InitResultRelInfo(resultRelInfo,
2119 rel,
2120 0, /* dummy rangetable index */
2121 NULL,
2122 0);
2123 estate->es_opened_result_relations =
2124 lappend(estate->es_opened_result_relations, resultRelInfo);
2125 resultRelInfo++;
2126 }
2127
2128 /*
2129 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2130 * truncating (this is because one of them might throw an error). Also, if
2131 * we were to allow them to prevent statement execution, that would need
2132 * to be handled here.
2133 */
2134 resultRelInfo = resultRelInfos;
2135 foreach(cell, rels)
2136 {
2137 UserContext ucxt;
2138
2139 if (run_as_table_owner)
2140 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2141 &ucxt);
2142 ExecBSTruncateTriggers(estate, resultRelInfo);
2143 if (run_as_table_owner)
2144 RestoreUserContext(&ucxt);
2145 resultRelInfo++;
2146 }
2147
2148 /*
2149 * OK, truncate each table.
2150 */
2151 mySubid = GetCurrentSubTransactionId();
2152
2153 foreach(cell, rels)
2154 {
2155 Relation rel = (Relation) lfirst(cell);
2156
2157 /* Skip partitioned tables as there is nothing to do */
2158 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2159 continue;
2160
2161 /*
2162 * Build the lists of foreign tables belonging to each foreign server
2163 * and pass each list to the foreign data wrapper's callback function,
2164 * so that each server can truncate its all foreign tables in bulk.
2165 * Each list is saved as a single entry in a hash table that uses the
2166 * server OID as lookup key.
2167 */
2168 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2169 {
2170 Oid serverid = GetForeignServerIdByRelId(RelationGetRelid(rel));
2171 bool found;
2172 ForeignTruncateInfo *ft_info;
2173
2174 /* First time through, initialize hashtable for foreign tables */
2175 if (!ft_htab)
2176 {
2177 HASHCTL hctl;
2178
2179 memset(&hctl, 0, sizeof(HASHCTL));
2180 hctl.keysize = sizeof(Oid);
2181 hctl.entrysize = sizeof(ForeignTruncateInfo);
2182 hctl.hcxt = CurrentMemoryContext;
2183
2184 ft_htab = hash_create("TRUNCATE for Foreign Tables",
2185 32, /* start small and extend */
2186 &hctl,
2187 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2188 }
2189
2190 /* Find or create cached entry for the foreign table */
2191 ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2192 if (!found)
2193 ft_info->rels = NIL;
2194
2195 /*
2196 * Save the foreign table in the entry of the server that the
2197 * foreign table belongs to.
2198 */
2199 ft_info->rels = lappend(ft_info->rels, rel);
2200 continue;
2201 }
2202
2203 /*
2204 * Normally, we need a transaction-safe truncation here. However, if
2205 * the table was either created in the current (sub)transaction or has
2206 * a new relfilenumber in the current (sub)transaction, then we can
2207 * just truncate it in-place, because a rollback would cause the whole
2208 * table or the current physical file to be thrown away anyway.
2209 */
2210 if (rel->rd_createSubid == mySubid ||
2211 rel->rd_newRelfilelocatorSubid == mySubid)
2212 {
2213 /* Immediate, non-rollbackable truncation is OK */
2214 heap_truncate_one_rel(rel);
2215 }
2216 else
2217 {
2218 Oid heap_relid;
2219 Oid toast_relid;
2220 ReindexParams reindex_params = {0};
2221
2222 /*
2223 * This effectively deletes all rows in the table, and may be done
2224 * in a serializable transaction. In that case we must record a
2225 * rw-conflict in to this transaction from each transaction
2226 * holding a predicate lock on the table.
2227 */
2228 CheckTableForSerializableConflictIn(rel);
2229
2230 /*
2231 * Need the full transaction-safe pushups.
2232 *
2233 * Create a new empty storage file for the relation, and assign it
2234 * as the relfilenumber value. The old storage file is scheduled
2235 * for deletion at commit.
2236 */
2237 RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2238
2239 heap_relid = RelationGetRelid(rel);
2240
2241 /*
2242 * The same for the toast table, if any.
2243 */
2244 toast_relid = rel->rd_rel->reltoastrelid;
2245 if (OidIsValid(toast_relid))
2246 {
2247 Relation toastrel = relation_open(toast_relid,
2248 AccessExclusiveLock);
2249
2250 RelationSetNewRelfilenumber(toastrel,
2251 toastrel->rd_rel->relpersistence);
2252 table_close(toastrel, NoLock);
2253 }
2254
2255 /*
2256 * Reconstruct the indexes to match, and we're done.
2257 */
2258 reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
2259 &reindex_params);
2260 }
2261
2262 pgstat_count_truncate(rel);
2263 }
2264
2265 /* Now go through the hash table, and truncate foreign tables */
2266 if (ft_htab)
2267 {
2268 ForeignTruncateInfo *ft_info;
2269 HASH_SEQ_STATUS seq;
2270
2271 hash_seq_init(&seq, ft_htab);
2272
2273 PG_TRY();
2274 {
2275 while ((ft_info = hash_seq_search(&seq)) != NULL)
2276 {
2277 FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2278
2279 /* truncate_check_rel() has checked that already */
2280 Assert(routine->ExecForeignTruncate != NULL);
2281
2282 routine->ExecForeignTruncate(ft_info->rels,
2283 behavior,
2284 restart_seqs);
2285 }
2286 }
2287 PG_FINALLY();
2288 {
2289 hash_destroy(ft_htab);
2290 }
2291 PG_END_TRY();
2292 }
2293
2294 /*
2295 * Restart owned sequences if we were asked to.
2296 */
2297 foreach(cell, seq_relids)
2298 {
2299 Oid seq_relid = lfirst_oid(cell);
2300
2301 ResetSequence(seq_relid);
2302 }
2303
2304 /*
2305 * Write a WAL record to allow this set of actions to be logically
2306 * decoded.
2307 *
2308 * Assemble an array of relids so we can write a single WAL record for the
2309 * whole action.
2310 */
2311 if (relids_logged != NIL)
2312 {
2313 xl_heap_truncate xlrec;
2314 int i = 0;
2315
2316 /* should only get here if wal_level >= logical */
2317 Assert(XLogLogicalInfoActive());
2318
2319 logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
2320 foreach(cell, relids_logged)
2321 logrelids[i++] = lfirst_oid(cell);
2322
2323 xlrec.dbId = MyDatabaseId;
2324 xlrec.nrelids = list_length(relids_logged);
2325 xlrec.flags = 0;
2326 if (behavior == DROP_CASCADE)
2327 xlrec.flags |= XLH_TRUNCATE_CASCADE;
2328 if (restart_seqs)
2329 xlrec.flags |= XLH_TRUNCATE_RESTART_SEQS;
2330
2331 XLogBeginInsert();
2332 XLogRegisterData(&xlrec, SizeOfHeapTruncate);
2333 XLogRegisterData(logrelids, list_length(relids_logged) * sizeof(Oid));
2334
2335 XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2336
2337 (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
2338 }
2339
2340 /*
2341 * Process all AFTER STATEMENT TRUNCATE triggers.
2342 */
2343 resultRelInfo = resultRelInfos;
2344 foreach(cell, rels)
2345 {
2346 UserContext ucxt;
2347
2348 if (run_as_table_owner)
2349 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2350 &ucxt);
2351 ExecASTruncateTriggers(estate, resultRelInfo);
2352 if (run_as_table_owner)
2353 RestoreUserContext(&ucxt);
2354 resultRelInfo++;
2355 }
2356
2357 /* Handle queued AFTER triggers */
2358 AfterTriggerEndQuery(estate);
2359
2360 /* We can clean up the EState now */
2361 FreeExecutorState(estate);
2362
2363 /*
2364 * Close any rels opened by CASCADE (can't do this while EState still
2365 * holds refs)
2366 */
2367 rels = list_difference_ptr(rels, explicit_rels);
2368 foreach(cell, rels)
2369 {
2370 Relation rel = (Relation) lfirst(cell);
2371
2372 table_close(rel, NoLock);
2373 }
2374 }
2375
2376 /*
2377 * Check that a given relation is safe to truncate. Subroutine for
2378 * ExecuteTruncate() and RangeVarCallbackForTruncate().
2379 */
2380 static void
2381 truncate_check_rel(Oid relid, Form_pg_class reltuple)
2382 {
2383 char *relname = NameStr(reltuple->relname);
2384
2385 /*
2386 * Only allow truncate on regular tables, foreign tables using foreign
2387 * data wrappers supporting TRUNCATE and partitioned tables (although, the
2388 * latter are only being included here for the following checks; no
2389 * physical truncation will occur in their case.).
2390 */
2391 if (reltuple->relkind == RELKIND_FOREIGN_TABLE)
2392 {
2393 Oid serverid = GetForeignServerIdByRelId(relid);
2394 FdwRoutine *fdwroutine = GetFdwRoutineByServerId(serverid);
2395
2396 if (!fdwroutine->ExecForeignTruncate)
2397 ereport(ERROR,
2398 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2399 errmsg("cannot truncate foreign table \"%s\"",
2400 relname)));
2401 }
2402 else if (reltuple->relkind != RELKIND_RELATION &&
2403 reltuple->relkind != RELKIND_PARTITIONED_TABLE)
2404 ereport(ERROR,
2405 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2406 errmsg("\"%s\" is not a table", relname)));
2407
2408 /*
2409 * Most system catalogs can't be truncated at all, or at least not unless
2410 * allow_system_table_mods=on. As an exception, however, we allow
2411 * pg_largeobject to be truncated as part of pg_upgrade, because we need
2412 * to change its relfilenode to match the old cluster, and allowing a
2413 * TRUNCATE command to be executed is the easiest way of doing that.
2414 */
2415 if (!allowSystemTableMods && IsSystemClass(relid, reltuple)
2416 && (!IsBinaryUpgrade || relid != LargeObjectRelationId))
2417 ereport(ERROR,
2418 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2419 errmsg("permission denied: \"%s\" is a system catalog",
2420 relname)));
2421
2422 InvokeObjectTruncateHook(relid);
2423 }
2424
2425 /*
2426 * Check that current user has the permission to truncate given relation.
2427 */
2428 static void
2429 truncate_check_perms(Oid relid, Form_pg_class reltuple)
2430 {
2431 char *relname = NameStr(reltuple->relname);
2432 AclResult aclresult;
2433
2434 /* Permissions checks */
2435 aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
2436 if (aclresult != ACLCHECK_OK)
2437 aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
2438 relname);
2439 }
2440
2441 /*
2442 * Set of extra sanity checks to check if a given relation is safe to
2443 * truncate. This is split with truncate_check_rel() as
2444 * RangeVarCallbackForTruncate() cannot open a Relation yet.
2445 */
2446 static void
2447 truncate_check_activity(Relation rel)
2448 {
2449 /*
2450 * Don't allow truncate on temp tables of other backends ... their local
2451 * buffer manager is not going to cope.
2452 */
2453 if (RELATION_IS_OTHER_TEMP(rel))
2454 ereport(ERROR,
2455 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2456 errmsg("cannot truncate temporary tables of other sessions")));
2457
2458 /*
2459 * Also check for active uses of the relation in the current transaction,
2460 * including open scans and pending AFTER trigger events.
2461 */
2462 CheckTableNotInUse(rel, "TRUNCATE");
2463 }
2464
2465 /*
2466 * storage_name
2467 * returns the name corresponding to a typstorage/attstorage enum value
2468 */
2469 static const char *
2470 storage_name(char c)
2471 {
2472 switch (c)
2473 {
2474 case TYPSTORAGE_PLAIN:
2475 return "PLAIN";
2476 case TYPSTORAGE_EXTERNAL:
2477 return "EXTERNAL";
2478 case TYPSTORAGE_EXTENDED:
2479 return "EXTENDED";
2480 case TYPSTORAGE_MAIN:
2481 return "MAIN";
2482 default:
2483 return "???";
2484 }
2485 }
2486
2487 /*----------
2488 * MergeAttributes
2489 * Returns new schema given initial schema and superclasses.
2490 *
2491 * Input arguments:
2492 * 'columns' is the column/attribute definition for the table. (It's a list
2493 * of ColumnDef's.) It is destructively changed.
2494 * 'supers' is a list of OIDs of parent relations, already locked by caller.
2495 * 'relpersistence' is the persistence type of the table.
2496 * 'is_partition' tells if the table is a partition.
2497 *
2498 * Output arguments:
2499 * 'supconstr' receives a list of CookedConstraint representing
2500 * CHECK constraints belonging to parent relations, updated as
2501 * necessary to be valid for the child.
2502 * 'supnotnulls' receives a list of CookedConstraint representing
2503 * not-null constraints based on those from parent relations.
2504 *
2505 * Return value:
2506 * Completed schema list.
2507 *
2508 * Notes:
2509 * The order in which the attributes are inherited is very important.
2510 * Intuitively, the inherited attributes should come first. If a table
2511 * inherits from multiple parents, the order of those attributes are
2512 * according to the order of the parents specified in CREATE TABLE.
2513 *
2514 * Here's an example:
2515 *
2516 * create table person (name text, age int4, location point);
2517 * create table emp (salary int4, manager text) inherits(person);
2518 * create table student (gpa float8) inherits (person);
2519 * create table stud_emp (percent int4) inherits (emp, student);
2520 *
2521 * The order of the attributes of stud_emp is:
2522 *
2523 * person {1:name, 2:age, 3:location}
2524 * / \
2525 * {6:gpa} student emp {4:salary, 5:manager}
2526 * \ /
2527 * stud_emp {7:percent}
2528 *
2529 * If the same attribute name appears multiple times, then it appears
2530 * in the result table in the proper location for its first appearance.
2531 *
2532 * Constraints (including not-null constraints) for the child table
2533 * are the union of all relevant constraints, from both the child schema
2534 * and parent tables. In addition, in legacy inheritance, each column that
2535 * appears in a primary key in any of the parents also gets a NOT NULL
2536 * constraint (partitioning doesn't need this, because the PK itself gets
2537 * inherited.)
2538 *
2539 * The default value for a child column is defined as:
2540 * (1) If the child schema specifies a default, that value is used.
2541 * (2) If neither the child nor any parent specifies a default, then
2542 * the column will not have a default.
2543 * (3) If conflicting defaults are inherited from different parents
2544 * (and not overridden by the child), an error is raised.
2545 * (4) Otherwise the inherited default is used.
2546 *
2547 * Note that the default-value infrastructure is used for generated
2548 * columns' expressions too, so most of the preceding paragraph applies
2549 * to generation expressions too. We insist that a child column be
2550 * generated if and only if its parent(s) are, but it need not have
2551 * the same generation expression.
2552 *----------
2553 */
2554 static List *
2555 MergeAttributes(List *columns, const List *supers, char relpersistence,
2556 bool is_partition, List **supconstr, List **supnotnulls)
2557 {
2558 List *inh_columns = NIL;
2559 List *constraints = NIL;
2560 List *nnconstraints = NIL;
2561 bool have_bogus_defaults = false;
2562 int child_attno;
2563 static Node bogus_marker = {0}; /* marks conflicting defaults */
2564 List *saved_columns = NIL;
2565 ListCell *lc;
2566
2567 /*
2568 * Check for and reject tables with too many columns. We perform this
2569 * check relatively early for two reasons: (a) we don't run the risk of
2570 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
2571 * okay if we're processing <= 1600 columns, but could take minutes to
2572 * execute if the user attempts to create a table with hundreds of
2573 * thousands of columns.
2574 *
2575 * Note that we also need to check that we do not exceed this figure after
2576 * including columns from inherited relations.
2577 */
2578 if (list_length(columns) > MaxHeapAttributeNumber)
2579 ereport(ERROR,
2580 (errcode(ERRCODE_TOO_MANY_COLUMNS),
2581 errmsg("tables can have at most %d columns",
2582 MaxHeapAttributeNumber)));
2583
2584 /*
2585 * Check for duplicate names in the explicit list of attributes.
2586 *
2587 * Although we might consider merging such entries in the same way that we
2588 * handle name conflicts for inherited attributes, it seems to make more
2589 * sense to assume such conflicts are errors.
2590 *
2591 * We don't use foreach() here because we have two nested loops over the
2592 * columns list, with possible element deletions in the inner one. If we
2593 * used foreach_delete_current() it could only fix up the state of one of
2594 * the loops, so it seems cleaner to use looping over list indexes for
2595 * both loops. Note that any deletion will happen beyond where the outer
2596 * loop is, so its index never needs adjustment.
2597 */
2598 for (int coldefpos = 0; coldefpos < list_length(columns); coldefpos++)
2599 {
2600 ColumnDef *coldef = list_nth_node(ColumnDef, columns, coldefpos);
2601
2602 if (!is_partition && coldef->typeName == NULL)
2603 {
2604 /*
2605 * Typed table column option that does not belong to a column from
2606 * the type. This works because the columns from the type come
2607 * first in the list. (We omit this check for partition column
2608 * lists; those are processed separately below.)
2609 */
2610 ereport(ERROR,
2611 (errcode(ERRCODE_UNDEFINED_COLUMN),
2612 errmsg("column \"%s\" does not exist",
2613 coldef->colname)));
2614 }
2615
2616 /* restpos scans all entries beyond coldef; incr is in loop body */
2617 for (int restpos = coldefpos + 1; restpos < list_length(columns);)
2618 {
2619 ColumnDef *restdef = list_nth_node(ColumnDef, columns, restpos);
2620
2621 if (strcmp(coldef->colname, restdef->colname) == 0)
2622 {
2623 if (coldef->is_from_type)
2624 {
2625 /*
2626 * merge the column options into the column from the type
2627 */
2628 coldef->is_not_null = restdef->is_not_null;
2629 coldef->raw_default = restdef->raw_default;
2630 coldef->cooked_default = restdef->cooked_default;
2631 coldef->constraints = restdef->constraints;
2632 coldef->is_from_type = false;
2633 columns = list_delete_nth_cell(columns, restpos);
2634 }
2635 else
2636 ereport(ERROR,
2637 (errcode(ERRCODE_DUPLICATE_COLUMN),
2638 errmsg("column \"%s\" specified more than once",
2639 coldef->colname)));
2640 }
2641 else
2642 restpos++;
2643 }
2644 }
2645
2646 /*
2647 * In case of a partition, there are no new column definitions, only dummy
2648 * ColumnDefs created for column constraints. Set them aside for now and
2649 * process them at the end.
2650 */
2651 if (is_partition)
2652 {
2653 saved_columns = columns;
2654 columns = NIL;
2655 }
2656
2657 /*
2658 * Scan the parents left-to-right, and merge their attributes to form a
2659 * list of inherited columns (inh_columns).
2660 */
2661 child_attno = 0;
2662 foreach(lc, supers)
2663 {
2664 Oid parent = lfirst_oid(lc);
2665 Relation relation;
2666 TupleDesc tupleDesc;
2667 TupleConstr *constr;
2668 AttrMap *newattmap;
2669 List *inherited_defaults;
2670 List *cols_with_defaults;
2671 List *nnconstrs;
2672 ListCell *lc1;
2673 ListCell *lc2;
2674 Bitmapset *nncols = NULL;
2675
2676 /* caller already got lock */
2677 relation = table_open(parent, NoLock);
2678
2679 /*
2680 * Check for active uses of the parent partitioned table in the
2681 * current transaction, such as being used in some manner by an
2682 * enclosing command.
2683 */
2684 if (is_partition)
2685 CheckTableNotInUse(relation, "CREATE TABLE .. PARTITION OF");
2686
2687 /*
2688 * We do not allow partitioned tables and partitions to participate in
2689 * regular inheritance.
2690 */
2691 if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !is_partition)
2692 ereport(ERROR,
2693 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2694 errmsg("cannot inherit from partitioned table \"%s\"",
2695 RelationGetRelationName(relation))));
2696 if (relation->rd_rel->relispartition && !is_partition)
2697 ereport(ERROR,
2698 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2699 errmsg("cannot inherit from partition \"%s\"",
2700 RelationGetRelationName(relation))));
2701
2702 if (relation->rd_rel->relkind != RELKIND_RELATION &&
2703 relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2704 relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2705 ereport(ERROR,
2706 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2707 errmsg("inherited relation \"%s\" is not a table or foreign table",
2708 RelationGetRelationName(relation))));
2709
2710 /*
2711 * If the parent is permanent, so must be all of its partitions. Note
2712 * that inheritance allows that case.
2713 */
2714 if (is_partition &&
2715 relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
2716 relpersistence == RELPERSISTENCE_TEMP)
2717 ereport(ERROR,
2718 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2719 errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
2720 RelationGetRelationName(relation))));
2721
2722 /* Permanent rels cannot inherit from temporary ones */
2723 if (relpersistence != RELPERSISTENCE_TEMP &&
2724 relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
2725 ereport(ERROR,
2726 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2727 errmsg(!is_partition
2728 ? "cannot inherit from temporary relation \"%s\""
2729 : "cannot create a permanent relation as partition of temporary relation \"%s\"",
2730 RelationGetRelationName(relation))));
2731
2732 /* If existing rel is temp, it must belong to this session */
2733 if (relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
2734 !relation->rd_islocaltemp)
2735 ereport(ERROR,
2736 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2737 errmsg(!is_partition
2738 ? "cannot inherit from temporary relation of another session"
2739 : "cannot create as partition of temporary relation of another session")));
2740
2741 /*
2742 * We should have an UNDER permission flag for this, but for now,
2743 * demand that creator of a child table own the parent.
2744 */
2745 if (!object_ownercheck(RelationRelationId, RelationGetRelid(relation), GetUserId()))
2746 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(relation->rd_rel->relkind),
2747 RelationGetRelationName(relation));
2748
2749 tupleDesc = RelationGetDescr(relation);
2750 constr = tupleDesc->constr;
2751
2752 /*
2753 * newattmap->attnums[] will contain the child-table attribute numbers
2754 * for the attributes of this parent table. (They are not the same
2755 * for parents after the first one, nor if we have dropped columns.)
2756 */
2757 newattmap = make_attrmap(tupleDesc->natts);
2758
2759 /* We can't process inherited defaults until newattmap is complete. */
2760 inherited_defaults = cols_with_defaults = NIL;
2761
2762 /*
2763 * Request attnotnull on columns that have a not-null constraint
2764 * that's not marked NO INHERIT (even if not valid).
2765 */
2766 nnconstrs = RelationGetNotNullConstraints(RelationGetRelid(relation),
2767 true, false);
2768 foreach_ptr(CookedConstraint, cc, nnconstrs)
2769 nncols = bms_add_member(nncols, cc->attnum);
2770
2771 for (AttrNumber parent_attno = 1; parent_attno <= tupleDesc->natts;
2772 parent_attno++)
2773 {
2774 Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
2775 parent_attno - 1);
2776 char *attributeName = NameStr(attribute->attname);
2777 int exist_attno;
2778 ColumnDef *newdef;
2779 ColumnDef *mergeddef;
2780
2781 /*
2782 * Ignore dropped columns in the parent.
2783 */
2784 if (attribute->attisdropped)
2785 continue; /* leave newattmap->attnums entry as zero */
2786
2787 /*
2788 * Create new column definition
2789 */
2790 newdef = makeColumnDef(attributeName, attribute->atttypid,
2791 attribute->atttypmod, attribute->attcollation);
2792 newdef->storage = attribute->attstorage;
2793 newdef->generated = attribute->attgenerated;
2794 if (CompressionMethodIsValid(attribute->attcompression))
2795 newdef->compression =
2796 pstrdup(GetCompressionMethodName(attribute->attcompression));
2797
2798 /*
2799 * Regular inheritance children are independent enough not to
2800 * inherit identity columns. But partitions are integral part of
2801 * a partitioned table and inherit identity column.
2802 */
2803 if (is_partition)
2804 newdef->identity = attribute->attidentity;
2805
2806 /*
2807 * Does it match some previously considered column from another
2808 * parent?
2809 */
2810 exist_attno = findAttrByName(attributeName, inh_columns);
2811 if (exist_attno > 0)
2812 {
2813 /*
2814 * Yes, try to merge the two column definitions.
2815 */
2816 mergeddef = MergeInheritedAttribute(inh_columns, exist_attno, newdef);
2817
2818 newattmap->attnums[parent_attno - 1] = exist_attno;
2819
2820 /*
2821 * Partitions have only one parent, so conflict should never
2822 * occur.
2823 */
2824 Assert(!is_partition);
2825 }
2826 else
2827 {
2828 /*
2829 * No, create a new inherited column
2830 */
2831 newdef->inhcount = 1;
2832 newdef->is_local = false;
2833 inh_columns = lappend(inh_columns, newdef);
2834
2835 newattmap->attnums[parent_attno - 1] = ++child_attno;
2836 mergeddef = newdef;
2837 }
2838
2839 /*
2840 * mark attnotnull if parent has it
2841 */
2842 if (bms_is_member(parent_attno, nncols))
2843 mergeddef->is_not_null = true;
2844
2845 /*
2846 * Locate default/generation expression if any
2847 */
2848 if (attribute->atthasdef)
2849 {
2850 Node *this_default;
2851
2852 this_default = TupleDescGetDefault(tupleDesc, parent_attno);
2853 if (this_default == NULL)
2854 elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
2855 parent_attno, RelationGetRelationName(relation));
2856
2857 /*
2858 * If it's a GENERATED default, it might contain Vars that
2859 * need to be mapped to the inherited column(s)' new numbers.
2860 * We can't do that till newattmap is ready, so just remember
2861 * all the inherited default expressions for the moment.
2862 */
2863 inherited_defaults = lappend(inherited_defaults, this_default);
2864 cols_with_defaults = lappend(cols_with_defaults, mergeddef);
2865 }
2866 }
2867
2868 /*
2869 * Now process any inherited default expressions, adjusting attnos
2870 * using the completed newattmap map.
2871 */
2872 forboth(lc1, inherited_defaults, lc2, cols_with_defaults)
2873 {
2874 Node *this_default = (Node *) lfirst(lc1);
2875 ColumnDef *def = (ColumnDef *) lfirst(lc2);
2876 bool found_whole_row;
2877
2878 /* Adjust Vars to match new table's column numbering */
2879 this_default = map_variable_attnos(this_default,
2880 1, 0,
2881 newattmap,
2882 InvalidOid, &found_whole_row);
2883
2884 /*
2885 * For the moment we have to reject whole-row variables. We could
2886 * convert them, if we knew the new table's rowtype OID, but that
2887 * hasn't been assigned yet. (A variable could only appear in a
2888 * generation expression, so the error message is correct.)
2889 */
2890 if (found_whole_row)
2891 ereport(ERROR,
2892 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2893 errmsg("cannot convert whole-row table reference"),
2894 errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
2895 def->colname,
2896 RelationGetRelationName(relation))));
2897
2898 /*
2899 * If we already had a default from some prior parent, check to
2900 * see if they are the same. If so, no problem; if not, mark the
2901 * column as having a bogus default. Below, we will complain if
2902 * the bogus default isn't overridden by the child columns.
2903 */
2904 Assert(def->raw_default == NULL);
2905 if (def->cooked_default == NULL)
2906 def->cooked_default = this_default;
2907 else if (!equal(def->cooked_default, this_default))
2908 {
2909 def->cooked_default = &bogus_marker;
2910 have_bogus_defaults = true;
2911 }
2912 }
2913
2914 /*
2915 * Now copy the CHECK constraints of this parent, adjusting attnos
2916 * using the completed newattmap map. Identically named constraints
2917 * are merged if possible, else we throw error.
2918 */
2919 if (constr && constr->num_check > 0)
2920 {
2921 ConstrCheck *check = constr->check;
2922
2923 for (int i = 0; i < constr->num_check; i++)
2924 {
2925 char *name = check[i].ccname;
2926 Node *expr;
2927 bool found_whole_row;
2928
2929 /* ignore if the constraint is non-inheritable */
2930 if (check[i].ccnoinherit)
2931 continue;
2932
2933 /* Adjust Vars to match new table's column numbering */
2934 expr = map_variable_attnos(stringToNode(check[i].ccbin),
2935 1, 0,
2936 newattmap,
2937 InvalidOid, &found_whole_row);
2938
2939 /*
2940 * For the moment we have to reject whole-row variables. We
2941 * could convert them, if we knew the new table's rowtype OID,
2942 * but that hasn't been assigned yet.
2943 */
2944 if (found_whole_row)
2945 ereport(ERROR,
2946 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2947 errmsg("cannot convert whole-row table reference"),
2948 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
2949 name,
2950 RelationGetRelationName(relation))));
2951
2952 constraints = MergeCheckConstraint(constraints, name, expr,
2953 check[i].ccenforced);
2954 }
2955 }
2956
2957 /*
2958 * Also copy the not-null constraints from this parent. The
2959 * attnotnull markings were already installed above.
2960 */
2961 foreach_ptr(CookedConstraint, nn, nnconstrs)
2962 {
2963 Assert(nn->contype == CONSTR_NOTNULL);
2964
2965 nn->attnum = newattmap->attnums[nn->attnum - 1];
2966
2967 nnconstraints = lappend(nnconstraints, nn);
2968 }
2969
2970 free_attrmap(newattmap);
2971
2972 /*
2973 * Close the parent rel, but keep our lock on it until xact commit.
2974 * That will prevent someone else from deleting or ALTERing the parent
2975 * before the child is committed.
2976 */
2977 table_close(relation, NoLock);
2978 }
2979
2980 /*
2981 * If we had no inherited attributes, the result columns are just the
2982 * explicitly declared columns. Otherwise, we need to merge the declared
2983 * columns into the inherited column list. Although, we never have any
2984 * explicitly declared columns if the table is a partition.
2985 */
2986 if (inh_columns != NIL)
2987 {
2988 int newcol_attno = 0;
2989
2990 foreach(lc, columns)
2991 {
2992 ColumnDef *newdef = lfirst_node(ColumnDef, lc);
2993 char *attributeName = newdef->colname;
2994 int exist_attno;
2995
2996 /*
2997 * Partitions have only one parent and have no column definitions
2998 * of their own, so conflict should never occur.
2999 */
3000 Assert(!is_partition);
3001
3002 newcol_attno++;
3003
3004 /*
3005 * Does it match some inherited column?
3006 */
3007 exist_attno = findAttrByName(attributeName, inh_columns);
3008 if (exist_attno > 0)
3009 {
3010 /*
3011 * Yes, try to merge the two column definitions.
3012 */
3013 MergeChildAttribute(inh_columns, exist_attno, newcol_attno, newdef);
3014 }
3015 else
3016 {
3017 /*
3018 * No, attach new column unchanged to result columns.
3019 */
3020 inh_columns = lappend(inh_columns, newdef);
3021 }
3022 }
3023
3024 columns = inh_columns;
3025
3026 /*
3027 * Check that we haven't exceeded the legal # of columns after merging
3028 * in inherited columns.
3029 */
3030 if (list_length(columns) > MaxHeapAttributeNumber)
3031 ereport(ERROR,
3032 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3033 errmsg("tables can have at most %d columns",
3034 MaxHeapAttributeNumber)));
3035 }
3036
3037 /*
3038 * Now that we have the column definition list for a partition, we can
3039 * check whether the columns referenced in the column constraint specs
3040 * actually exist. Also, merge column defaults.
3041 */
3042 if (is_partition)
3043 {
3044 foreach(lc, saved_columns)
3045 {
3046 ColumnDef *restdef = lfirst(lc);
3047 bool found = false;
3048 ListCell *l;
3049
3050 foreach(l, columns)
3051 {
3052 ColumnDef *coldef = lfirst(l);
3053
3054 if (strcmp(coldef->colname, restdef->colname) == 0)
3055 {
3056 found = true;
3057
3058 /*
3059 * Check for conflicts related to generated columns.
3060 *
3061 * Same rules as above: generated-ness has to match the
3062 * parent, but the contents of the generation expression
3063 * can be different.
3064 */
3065 if (coldef->generated)
3066 {
3067 if (restdef->raw_default && !restdef->generated)
3068 ereport(ERROR,
3069 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3070 errmsg("column \"%s\" inherits from generated column but specifies default",
3071 restdef->colname)));
3072 if (restdef->identity)
3073 ereport(ERROR,
3074 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3075 errmsg("column \"%s\" inherits from generated column but specifies identity",
3076 restdef->colname)));
3077 }
3078 else
3079 {
3080 if (restdef->generated)
3081 ereport(ERROR,
3082 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3083 errmsg("child column \"%s\" specifies generation expression",
3084 restdef->colname),
3085 errhint("A child table column cannot be generated unless its parent column is.")));
3086 }
3087
3088 if (coldef->generated && restdef->generated && coldef->generated != restdef->generated)
3089 ereport(ERROR,
3090 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3091 errmsg("column \"%s\" inherits from generated column of different kind",
3092 restdef->colname),
3093 errdetail("Parent column is %s, child column is %s.",
3094 coldef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3095 restdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3096
3097 /*
3098 * Override the parent's default value for this column
3099 * (coldef->cooked_default) with the partition's local
3100 * definition (restdef->raw_default), if there's one. It
3101 * should be physically impossible to get a cooked default
3102 * in the local definition or a raw default in the
3103 * inherited definition, but make sure they're nulls, for
3104 * future-proofing.
3105 */
3106 Assert(restdef->cooked_default == NULL);
3107 Assert(coldef->raw_default == NULL);
3108 if (restdef->raw_default)
3109 {
3110 coldef->raw_default = restdef->raw_default;
3111 coldef->cooked_default = NULL;
3112 }
3113 }
3114 }
3115
3116 /* complain for constraints on columns not in parent */
3117 if (!found)
3118 ereport(ERROR,
3119 (errcode(ERRCODE_UNDEFINED_COLUMN),
3120 errmsg("column \"%s\" does not exist",
3121 restdef->colname)));
3122 }
3123 }
3124
3125 /*
3126 * If we found any conflicting parent default values, check to make sure
3127 * they were overridden by the child.
3128 */
3129 if (have_bogus_defaults)
3130 {
3131 foreach(lc, columns)
3132 {
3133 ColumnDef *def = lfirst(lc);
3134
3135 if (def->cooked_default == &bogus_marker)
3136 {
3137 if (def->generated)
3138 ereport(ERROR,
3139 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3140 errmsg("column \"%s\" inherits conflicting generation expressions",
3141 def->colname),
3142 errhint("To resolve the conflict, specify a generation expression explicitly.")));
3143 else
3144 ereport(ERROR,
3145 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3146 errmsg("column \"%s\" inherits conflicting default values",
3147 def->colname),
3148 errhint("To resolve the conflict, specify a default explicitly.")));
3149 }
3150 }
3151 }
3152
3153 *supconstr = constraints;
3154 *supnotnulls = nnconstraints;
3155
3156 return columns;
3157 }
3158
3159
3160 /*
3161 * MergeCheckConstraint
3162 * Try to merge an inherited CHECK constraint with previous ones
3163 *
3164 * If we inherit identically-named constraints from multiple parents, we must
3165 * merge them, or throw an error if they don't have identical definitions.
3166 *
3167 * constraints is a list of CookedConstraint structs for previous constraints.
3168 *
3169 * If the new constraint matches an existing one, then the existing
3170 * constraint's inheritance count is updated. If there is a conflict (same
3171 * name but different expression), throw an error. If the constraint neither
3172 * matches nor conflicts with an existing one, a new constraint is appended to
3173 * the list.
3174 */
3175 static List *
3176 MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced)
3177 {
3178 ListCell *lc;
3179 CookedConstraint *newcon;
3180
3181 foreach(lc, constraints)
3182 {
3183 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
3184
3185 Assert(ccon->contype == CONSTR_CHECK);
3186
3187 /* Non-matching names never conflict */
3188 if (strcmp(ccon->name, name) != 0)
3189 continue;
3190
3191 if (equal(expr, ccon->expr))
3192 {
3193 /* OK to merge constraint with existing */
3194 if (pg_add_s16_overflow(ccon->inhcount, 1,
3195 &ccon->inhcount))
3196 ereport(ERROR,
3197 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3198 errmsg("too many inheritance parents"));
3199
3200 /*
3201 * When enforceability differs, the merged constraint should be
3202 * marked as ENFORCED because one of the parents is ENFORCED.
3203 */
3204 if (!ccon->is_enforced && is_enforced)
3205 {
3206 ccon->is_enforced = true;
3207 ccon->skip_validation = false;
3208 }
3209
3210 return constraints;
3211 }
3212
3213 ereport(ERROR,
3214 (errcode(ERRCODE_DUPLICATE_OBJECT),
3215 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
3216 name)));
3217 }
3218
3219 /*
3220 * Constraint couldn't be merged with an existing one and also didn't
3221 * conflict with an existing one, so add it as a new one to the list.
3222 */
3223 newcon = palloc0_object(CookedConstraint);
3224 newcon->contype = CONSTR_CHECK;
3225 newcon->name = pstrdup(name);
3226 newcon->expr = expr;
3227 newcon->inhcount = 1;
3228 newcon->is_enforced = is_enforced;
3229 newcon->skip_validation = !is_enforced;
3230 return lappend(constraints, newcon);
3231 }
3232
3233 /*
3234 * MergeChildAttribute
3235 * Merge given child attribute definition into given inherited attribute.
3236 *
3237 * Input arguments:
3238 * 'inh_columns' is the list of inherited ColumnDefs.
3239 * 'exist_attno' is the number of the inherited attribute in inh_columns
3240 * 'newcol_attno' is the attribute number in child table's schema definition
3241 * 'newdef' is the column/attribute definition from the child table.
3242 *
3243 * The ColumnDef in 'inh_columns' list is modified. The child attribute's
3244 * ColumnDef remains unchanged.
3245 *
3246 * Notes:
3247 * - The attribute is merged according to the rules laid out in the prologue
3248 * of MergeAttributes().
3249 * - If matching inherited attribute exists but the child attribute can not be
3250 * merged into it, the function throws respective errors.
3251 * - A partition can not have its own column definitions. Hence this function
3252 * is applicable only to a regular inheritance child.
3253 */
3254 static void
3255 MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef)
3256 {
3257 char *attributeName = newdef->colname;
3258 ColumnDef *inhdef;
3259 Oid inhtypeid,
3260 newtypeid;
3261 int32 inhtypmod,
3262 newtypmod;
3263 Oid inhcollid,
3264 newcollid;
3265
3266 if (exist_attno == newcol_attno)
3267 ereport(NOTICE,
3268 (errmsg("merging column \"%s\" with inherited definition",
3269 attributeName)));
3270 else
3271 ereport(NOTICE,
3272 (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
3273 errdetail("User-specified column moved to the position of the inherited column.")));
3274
3275 inhdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3276
3277 /*
3278 * Must have the same type and typmod
3279 */
3280 typenameTypeIdAndMod(NULL, inhdef->typeName, &inhtypeid, &inhtypmod);
3281 typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3282 if (inhtypeid != newtypeid || inhtypmod != newtypmod)
3283 ereport(ERROR,
3284 (errcode(ERRCODE_DATATYPE_MISMATCH),
3285 errmsg("column \"%s\" has a type conflict",
3286 attributeName),
3287 errdetail("%s versus %s",
3288 format_type_with_typemod(inhtypeid, inhtypmod),
3289 format_type_with_typemod(newtypeid, newtypmod))));
3290
3291 /*
3292 * Must have the same collation
3293 */
3294 inhcollid = GetColumnDefCollation(NULL, inhdef, inhtypeid);
3295 newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3296 if (inhcollid != newcollid)
3297 ereport(ERROR,
3298 (errcode(ERRCODE_COLLATION_MISMATCH),
3299 errmsg("column \"%s\" has a collation conflict",
3300 attributeName),
3301 errdetail("\"%s\" versus \"%s\"",
3302 get_collation_name(inhcollid),
3303 get_collation_name(newcollid))));
3304
3305 /*
3306 * Identity is never inherited by a regular inheritance child. Pick
3307 * child's identity definition if there's one.
3308 */
3309 inhdef->identity = newdef->identity;
3310
3311 /*
3312 * Copy storage parameter
3313 */
3314 if (inhdef->storage == 0)
3315 inhdef->storage = newdef->storage;
3316 else if (newdef->storage != 0 && inhdef->storage != newdef->storage)
3317 ereport(ERROR,
3318 (errcode(ERRCODE_DATATYPE_MISMATCH),
3319 errmsg("column \"%s\" has a storage parameter conflict",
3320 attributeName),
3321 errdetail("%s versus %s",
3322 storage_name(inhdef->storage),
3323 storage_name(newdef->storage))));
3324
3325 /*
3326 * Copy compression parameter
3327 */
3328 if (inhdef->compression == NULL)
3329 inhdef->compression = newdef->compression;
3330 else if (newdef->compression != NULL)
3331 {
3332 if (strcmp(inhdef->compression, newdef->compression) != 0)
3333 ereport(ERROR,
3334 (errcode(ERRCODE_DATATYPE_MISMATCH),
3335 errmsg("column \"%s\" has a compression method conflict",
3336 attributeName),
3337 errdetail("%s versus %s", inhdef->compression, newdef->compression)));
3338 }
3339
3340 /*
3341 * Merge of not-null constraints = OR 'em together
3342 */
3343 inhdef->is_not_null |= newdef->is_not_null;
3344
3345 /*
3346 * Check for conflicts related to generated columns.
3347 *
3348 * If the parent column is generated, the child column will be made a
3349 * generated column if it isn't already. If it is a generated column,
3350 * we'll take its generation expression in preference to the parent's. We
3351 * must check that the child column doesn't specify a default value or
3352 * identity, which matches the rules for a single column in
3353 * parse_utilcmd.c.
3354 *
3355 * Conversely, if the parent column is not generated, the child column
3356 * can't be either. (We used to allow that, but it results in being able
3357 * to override the generation expression via UPDATEs through the parent.)
3358 */
3359 if (inhdef->generated)
3360 {
3361 if (newdef->raw_default && !newdef->generated)
3362 ereport(ERROR,
3363 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3364 errmsg("column \"%s\" inherits from generated column but specifies default",
3365 inhdef->colname)));
3366 if (newdef->identity)
3367 ereport(ERROR,
3368 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3369 errmsg("column \"%s\" inherits from generated column but specifies identity",
3370 inhdef->colname)));
3371 }
3372 else
3373 {
3374 if (newdef->generated)
3375 ereport(ERROR,
3376 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3377 errmsg("child column \"%s\" specifies generation expression",
3378 inhdef->colname),
3379 errhint("A child table column cannot be generated unless its parent column is.")));
3380 }
3381
3382 if (inhdef->generated && newdef->generated && newdef->generated != inhdef->generated)
3383 ereport(ERROR,
3384 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3385 errmsg("column \"%s\" inherits from generated column of different kind",
3386 inhdef->colname),
3387 errdetail("Parent column is %s, child column is %s.",
3388 inhdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3389 newdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3390
3391 /*
3392 * If new def has a default, override previous default
3393 */
3394 if (newdef->raw_default != NULL)
3395 {
3396 inhdef->raw_default = newdef->raw_default;
3397 inhdef->cooked_default = newdef->cooked_default;
3398 }
3399
3400 /* Mark the column as locally defined */
3401 inhdef->is_local = true;
3402 }
3403
3404 /*
3405 * MergeInheritedAttribute
3406 * Merge given parent attribute definition into specified attribute
3407 * inherited from the previous parents.
3408 *
3409 * Input arguments:
3410 * 'inh_columns' is the list of previously inherited ColumnDefs.
3411 * 'exist_attno' is the number the existing matching attribute in inh_columns.
3412 * 'newdef' is the new parent column/attribute definition to be merged.
3413 *
3414 * The matching ColumnDef in 'inh_columns' list is modified and returned.
3415 *
3416 * Notes:
3417 * - The attribute is merged according to the rules laid out in the prologue
3418 * of MergeAttributes().
3419 * - If matching inherited attribute exists but the new attribute can not be
3420 * merged into it, the function throws respective errors.
3421 * - A partition inherits from only a single parent. Hence this function is
3422 * applicable only to a regular inheritance.
3423 */
3424 static ColumnDef *
3425 MergeInheritedAttribute(List *inh_columns,
3426 int exist_attno,
3427 const ColumnDef *newdef)
3428 {
3429 char *attributeName = newdef->colname;
3430 ColumnDef *prevdef;
3431 Oid prevtypeid,
3432 newtypeid;
3433 int32 prevtypmod,
3434 newtypmod;
3435 Oid prevcollid,
3436 newcollid;
3437
3438 ereport(NOTICE,
3439 (errmsg("merging multiple inherited definitions of column \"%s\"",
3440 attributeName)));
3441 prevdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3442
3443 /*
3444 * Must have the same type and typmod
3445 */
3446 typenameTypeIdAndMod(NULL, prevdef->typeName, &prevtypeid, &prevtypmod);
3447 typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3448 if (prevtypeid != newtypeid || prevtypmod != newtypmod)
3449 ereport(ERROR,
3450 (errcode(ERRCODE_DATATYPE_MISMATCH),
3451 errmsg("inherited column \"%s\" has a type conflict",
3452 attributeName),
3453 errdetail("%s versus %s",
3454 format_type_with_typemod(prevtypeid, prevtypmod),
3455 format_type_with_typemod(newtypeid, newtypmod))));
3456
3457 /*
3458 * Must have the same collation
3459 */
3460 prevcollid = GetColumnDefCollation(NULL, prevdef, prevtypeid);
3461 newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3462 if (prevcollid != newcollid)
3463 ereport(ERROR,
3464 (errcode(ERRCODE_COLLATION_MISMATCH),
3465 errmsg("inherited column \"%s\" has a collation conflict",
3466 attributeName),
3467 errdetail("\"%s\" versus \"%s\"",
3468 get_collation_name(prevcollid),
3469 get_collation_name(newcollid))));
3470
3471 /*
3472 * Copy/check storage parameter
3473 */
3474 if (prevdef->storage == 0)
3475 prevdef->storage = newdef->storage;
3476 else if (prevdef->storage != newdef->storage)
3477 ereport(ERROR,
3478 (errcode(ERRCODE_DATATYPE_MISMATCH),
3479 errmsg("inherited column \"%s\" has a storage parameter conflict",
3480 attributeName),
3481 errdetail("%s versus %s",
3482 storage_name(prevdef->storage),
3483 storage_name(newdef->storage))));
3484
3485 /*
3486 * Copy/check compression parameter
3487 */
3488 if (prevdef->compression == NULL)
3489 prevdef->compression = newdef->compression;
3490 else if (newdef->compression != NULL)
3491 {
3492 if (strcmp(prevdef->compression, newdef->compression) != 0)
3493 ereport(ERROR,
3494 (errcode(ERRCODE_DATATYPE_MISMATCH),
3495 errmsg("column \"%s\" has a compression method conflict",
3496 attributeName),
3497 errdetail("%s versus %s",
3498 prevdef->compression, newdef->compression)));
3499 }
3500
3501 /*
3502 * Check for GENERATED conflicts
3503 */
3504 if (prevdef->generated != newdef->generated)
3505 ereport(ERROR,
3506 (errcode(ERRCODE_DATATYPE_MISMATCH),
3507 errmsg("inherited column \"%s\" has a generation conflict",
3508 attributeName)));
3509
3510 /*
3511 * Default and other constraints are handled by the caller.
3512 */
3513
3514 if (pg_add_s16_overflow(prevdef->inhcount, 1,
3515 &prevdef->inhcount))
3516 ereport(ERROR,
3517 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3518 errmsg("too many inheritance parents"));
3519
3520 return prevdef;
3521 }
3522
3523 /*
3524 * StoreCatalogInheritance
3525 * Updates the system catalogs with proper inheritance information.
3526 *
3527 * supers is a list of the OIDs of the new relation's direct ancestors.
3528 */
3529 static void
3530 StoreCatalogInheritance(Oid relationId, List *supers,
3531 bool child_is_partition)
3532 {
3533 Relation relation;
3534 int32 seqNumber;
3535 ListCell *entry;
3536
3537 /*
3538 * sanity checks
3539 */
3540 Assert(OidIsValid(relationId));
3541
3542 if (supers == NIL)
3543 return;
3544
3545 /*
3546 * Store INHERITS information in pg_inherits using direct ancestors only.
3547 * Also enter dependencies on the direct ancestors, and make sure they are
3548 * marked with relhassubclass = true.
3549 *
3550 * (Once upon a time, both direct and indirect ancestors were found here
3551 * and then entered into pg_ipl. Since that catalog doesn't exist
3552 * anymore, there's no need to look for indirect ancestors.)
3553 */
3554 relation = table_open(InheritsRelationId, RowExclusiveLock);
3555
3556 seqNumber = 1;
3557 foreach(entry, supers)
3558 {
3559 Oid parentOid = lfirst_oid(entry);
3560
3561 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
3562 child_is_partition);
3563 seqNumber++;
3564 }
3565
3566 table_close(relation, RowExclusiveLock);
3567 }
3568
3569 /*
3570 * Make catalog entries showing relationId as being an inheritance child
3571 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
3572 */
3573 static void
3574 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
3575 int32 seqNumber, Relation inhRelation,
3576 bool child_is_partition)
3577 {
3578 ObjectAddress childobject,
3579 parentobject;
3580
3581 /* store the pg_inherits row */
3582 StoreSingleInheritance(relationId, parentOid, seqNumber);
3583
3584 /*
3585 * Store a dependency too
3586 */
3587 parentobject.classId = RelationRelationId;
3588 parentobject.objectId = parentOid;
3589 parentobject.objectSubId = 0;
3590 childobject.classId = RelationRelationId;
3591 childobject.objectId = relationId;
3592 childobject.objectSubId = 0;
3593
3594 recordDependencyOn(&childobject, &parentobject,
3595 child_dependency_type(child_is_partition));
3596
3597 /*
3598 * Post creation hook of this inheritance. Since object_access_hook
3599 * doesn't take multiple object identifiers, we relay oid of parent
3600 * relation using auxiliary_id argument.
3601 */
3602 InvokeObjectPostAlterHookArg(InheritsRelationId,
3603 relationId, 0,
3604 parentOid, false);
3605
3606 /*
3607 * Mark the parent as having subclasses.
3608 */
3609 SetRelationHasSubclass(parentOid, true);
3610 }
3611
3612 /*
3613 * Look for an existing column entry with the given name.
3614 *
3615 * Returns the index (starting with 1) if attribute already exists in columns,
3616 * 0 if it doesn't.
3617 */
3618 static int
3619 findAttrByName(const char *attributeName, const List *columns)
3620 {
3621 ListCell *lc;
3622 int i = 1;
3623
3624 foreach(lc, columns)
3625 {
3626 if (strcmp(attributeName, lfirst_node(ColumnDef, lc)->colname) == 0)
3627 return i;
3628
3629 i++;
3630 }
3631 return 0;
3632 }
3633
3634
3635 /*
3636 * SetRelationHasSubclass
3637 * Set the value of the relation's relhassubclass field in pg_class.
3638 *
3639 * It's always safe to set this field to true, because all SQL commands are
3640 * ready to see true and then find no children. On the other hand, commands
3641 * generally assume zero children if this is false.
3642 *
3643 * Caller must hold any self-exclusive lock until end of transaction. If the
3644 * new value is false, caller must have acquired that lock before reading the
3645 * evidence that justified the false value. That way, it properly waits if
3646 * another backend is simultaneously concluding no need to change the tuple
3647 * (new and old values are true).
3648 *
3649 * NOTE: an important side-effect of this operation is that an SI invalidation
3650 * message is sent out to all backends --- including me --- causing plans
3651 * referencing the relation to be rebuilt with the new list of children.
3652 * This must happen even if we find that no change is needed in the pg_class
3653 * row.
3654 */
3655 void
3656 SetRelationHasSubclass(Oid relationId, bool relhassubclass)
3657 {
3658 Relation relationRelation;
3659 HeapTuple tuple;
3660 Form_pg_class classtuple;
3661
3662 Assert(CheckRelationOidLockedByMe(relationId,
3663 ShareUpdateExclusiveLock, false) ||
3664 CheckRelationOidLockedByMe(relationId,
3665 ShareRowExclusiveLock, true));
3666
3667 /*
3668 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3669 */
3670 relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3671 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3672 if (!HeapTupleIsValid(tuple))
3673 elog(ERROR, "cache lookup failed for relation %u", relationId);
3674 classtuple = (Form_pg_class) GETSTRUCT(tuple);
3675
3676 if (classtuple->relhassubclass != relhassubclass)
3677 {
3678 classtuple->relhassubclass = relhassubclass;
3679 CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3680 }
3681 else
3682 {
3683 /* no need to change tuple, but force relcache rebuild anyway */
3684 CacheInvalidateRelcacheByTuple(tuple);
3685 }
3686
3687 heap_freetuple(tuple);
3688 table_close(relationRelation, RowExclusiveLock);
3689 }
3690
3691 /*
3692 * CheckRelationTableSpaceMove
3693 * Check if relation can be moved to new tablespace.
3694 *
3695 * NOTE: The caller must hold AccessExclusiveLock on the relation.
3696 *
3697 * Returns true if the relation can be moved to the new tablespace; raises
3698 * an error if it is not possible to do the move; returns false if the move
3699 * would have no effect.
3700 */
3701 bool
3702 CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
3703 {
3704 Oid oldTableSpaceId;
3705
3706 /*
3707 * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3708 * stored as 0.
3709 */
3710 oldTableSpaceId = rel->rd_rel->reltablespace;
3711 if (newTableSpaceId == oldTableSpaceId ||
3712 (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3713 return false;
3714
3715 /*
3716 * We cannot support moving mapped relations into different tablespaces.
3717 * (In particular this eliminates all shared catalogs.)
3718 */
3719 if (RelationIsMapped(rel))
3720 ereport(ERROR,
3721 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3722 errmsg("cannot move system relation \"%s\"",
3723 RelationGetRelationName(rel))));
3724
3725 /* Cannot move a non-shared relation into pg_global */
3726 if (newTableSpaceId == GLOBALTABLESPACE_OID)
3727 ereport(ERROR,
3728 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3729 errmsg("only shared relations can be placed in pg_global tablespace")));
3730
3731 /*
3732 * Do not allow moving temp tables of other backends ... their local
3733 * buffer manager is not going to cope.
3734 */
3735 if (RELATION_IS_OTHER_TEMP(rel))
3736 ereport(ERROR,
3737 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3738 errmsg("cannot move temporary tables of other sessions")));
3739
3740 return true;
3741 }
3742
3743 /*
3744 * SetRelationTableSpace
3745 * Set new reltablespace and relfilenumber in pg_class entry.
3746 *
3747 * newTableSpaceId is the new tablespace for the relation, and
3748 * newRelFilenumber its new filenumber. If newRelFilenumber is
3749 * InvalidRelFileNumber, this field is not updated.
3750 *
3751 * NOTE: The caller must hold AccessExclusiveLock on the relation.
3752 *
3753 * The caller of this routine had better check if a relation can be
3754 * moved to this new tablespace by calling CheckRelationTableSpaceMove()
3755 * first, and is responsible for making the change visible with
3756 * CommandCounterIncrement().
3757 */
3758 void
3759 SetRelationTableSpace(Relation rel,
3760 Oid newTableSpaceId,
3761 RelFileNumber newRelFilenumber)
3762 {
3763 Relation pg_class;
3764 HeapTuple tuple;
3765 ItemPointerData otid;
3766 Form_pg_class rd_rel;
3767 Oid reloid = RelationGetRelid(rel);
3768
3769 Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3770
3771 /* Get a modifiable copy of the relation's pg_class row. */
3772 pg_class = table_open(RelationRelationId, RowExclusiveLock);
3773
3774 tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
3775 if (!HeapTupleIsValid(tuple))
3776 elog(ERROR, "cache lookup failed for relation %u", reloid);
3777 otid = tuple->t_self;
3778 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3779
3780 /* Update the pg_class row. */
3781 rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3782 InvalidOid : newTableSpaceId;
3783 if (RelFileNumberIsValid(newRelFilenumber))
3784 rd_rel->relfilenode = newRelFilenumber;
3785 CatalogTupleUpdate(pg_class, &otid, tuple);
3786 UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3787
3788 /*
3789 * Record dependency on tablespace. This is only required for relations
3790 * that have no physical storage.
3791 */
3792 if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3793 changeDependencyOnTablespace(RelationRelationId, reloid,
3794 rd_rel->reltablespace);
3795
3796 heap_freetuple(tuple);
3797 table_close(pg_class, RowExclusiveLock);
3798 }
3799
3800 /*
3801 * renameatt_check - basic sanity checks before attribute rename
3802 */
3803 static void
3804 renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
3805 {
3806 char relkind = classform->relkind;
3807
3808 if (classform->reloftype && !recursing)
3809 ereport(ERROR,
3810 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3811 errmsg("cannot rename column of typed table")));
3812
3813 /*
3814 * Renaming the columns of sequences or toast tables doesn't actually
3815 * break anything from the system's point of view, since internal
3816 * references are by attnum. But it doesn't seem right to allow users to
3817 * change names that are hardcoded into the system, hence the following
3818 * restriction.
3819 */
3820 if (relkind != RELKIND_RELATION &&
3821 relkind != RELKIND_VIEW &&
3822 relkind != RELKIND_MATVIEW &&
3823 relkind != RELKIND_COMPOSITE_TYPE &&
3824 relkind != RELKIND_INDEX &&
3825 relkind != RELKIND_PARTITIONED_INDEX &&
3826 relkind != RELKIND_FOREIGN_TABLE &&
3827 relkind != RELKIND_PARTITIONED_TABLE)
3828 ereport(ERROR,
3829 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3830 errmsg("cannot rename columns of relation \"%s\"",
3831 NameStr(classform->relname)),
3832 errdetail_relkind_not_supported(relkind)));
3833
3834 /*
3835 * permissions checking. only the owner of a class can change its schema.
3836 */
3837 if (!object_ownercheck(RelationRelationId, myrelid, GetUserId()))
3838 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(myrelid)),
3839 NameStr(classform->relname));
3840 if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
3841 ereport(ERROR,
3842 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3843 errmsg("permission denied: \"%s\" is a system catalog",
3844 NameStr(classform->relname))));
3845 }
3846
3847 /*
3848 * renameatt_internal - workhorse for renameatt
3849 *
3850 * Return value is the attribute number in the 'myrelid' relation.
3851 */
3852 static AttrNumber
3853 renameatt_internal(Oid myrelid,
3854 const char *oldattname,
3855 const char *newattname,
3856 bool recurse,
3857 bool recursing,
3858 int expected_parents,
3859 DropBehavior behavior)
3860 {
3861 Relation targetrelation;
3862 Relation attrelation;
3863 HeapTuple atttup;
3864 Form_pg_attribute attform;
3865 AttrNumber attnum;
3866
3867 /*
3868 * Grab an exclusive lock on the target table, which we will NOT release
3869 * until end of transaction.
3870 */
3871 targetrelation = relation_open(myrelid, AccessExclusiveLock);
3872 renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
3873
3874 /*
3875 * if the 'recurse' flag is set then we are supposed to rename this
3876 * attribute in all classes that inherit from 'relname' (as well as in
3877 * 'relname').
3878 *
3879 * any permissions or problems with duplicate attributes will cause the
3880 * whole transaction to abort, which is what we want -- all or nothing.
3881 */
3882 if (recurse)
3883 {
3884 List *child_oids,
3885 *child_numparents;
3886 ListCell *lo,
3887 *li;
3888
3889 /*
3890 * we need the number of parents for each child so that the recursive
3891 * calls to renameatt() can determine whether there are any parents
3892 * outside the inheritance hierarchy being processed.
3893 */
3894 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
3895 &child_numparents);
3896
3897 /*
3898 * find_all_inheritors does the recursive search of the inheritance
3899 * hierarchy, so all we have to do is process all of the relids in the
3900 * list that it returns.
3901 */
3902 forboth(lo, child_oids, li, child_numparents)
3903 {
3904 Oid childrelid = lfirst_oid(lo);
3905 int numparents = lfirst_int(li);
3906
3907 if (childrelid == myrelid)
3908 continue;
3909 /* note we need not recurse again */
3910 renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
3911 }
3912 }
3913 else
3914 {
3915 /*
3916 * If we are told not to recurse, there had better not be any child
3917 * tables; else the rename would put them out of step.
3918 *
3919 * expected_parents will only be 0 if we are not already recursing.
3920 */
3921 if (expected_parents == 0 &&
3922 find_inheritance_children(myrelid, NoLock) != NIL)
3923 ereport(ERROR,
3924 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3925 errmsg("inherited column \"%s\" must be renamed in child tables too",
3926 oldattname)));
3927 }
3928
3929 /* rename attributes in typed tables of composite type */
3930 if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
3931 {
3932 List *child_oids;
3933 ListCell *lo;
3934
3935 child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
3936 RelationGetRelationName(targetrelation),
3937 behavior);
3938
3939 foreach(lo, child_oids)
3940 renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
3941 }
3942
3943 attrelation = table_open(AttributeRelationId, RowExclusiveLock);
3944
3945 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
3946 if (!HeapTupleIsValid(atttup))
3947 ereport(ERROR,
3948 (errcode(ERRCODE_UNDEFINED_COLUMN),
3949 errmsg("column \"%s\" does not exist",
3950 oldattname)));
3951 attform = (Form_pg_attribute) GETSTRUCT(atttup);
3952
3953 attnum = attform->attnum;
3954 if (attnum <= 0)
3955 ereport(ERROR,
3956 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3957 errmsg("cannot rename system column \"%s\"",
3958 oldattname)));
3959
3960 /*
3961 * if the attribute is inherited, forbid the renaming. if this is a
3962 * top-level call to renameatt(), then expected_parents will be 0, so the
3963 * effect of this code will be to prohibit the renaming if the attribute
3964 * is inherited at all. if this is a recursive call to renameatt(),
3965 * expected_parents will be the number of parents the current relation has
3966 * within the inheritance hierarchy being processed, so we'll prohibit the
3967 * renaming only if there are additional parents from elsewhere.
3968 */
3969 if (attform->attinhcount > expected_parents)
3970 ereport(ERROR,
3971 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3972 errmsg("cannot rename inherited column \"%s\"",
3973 oldattname)));
3974
3975 /* new name should not already exist */
3976 (void) check_for_column_name_collision(targetrelation, newattname, false);
3977
3978 /* apply the update */
3979 namestrcpy(&(attform->attname), newattname);
3980
3981 CatalogTupleUpdate(attrelation, &atttup->t_self, atttup);
3982
3983 InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
3984
3985 heap_freetuple(atttup);
3986
3987 table_close(attrelation, RowExclusiveLock);
3988
3989 relation_close(targetrelation, NoLock); /* close rel but keep lock */
3990
3991 return attnum;
3992 }
3993
3994 /*
3995 * Perform permissions and integrity checks before acquiring a relation lock.
3996 */
3997 static void
3998 RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
3999 void *arg)
4000 {
4001 HeapTuple tuple;
4002 Form_pg_class form;
4003
4004 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
4005 if (!HeapTupleIsValid(tuple))
4006 return; /* concurrently dropped */
4007 form = (Form_pg_class) GETSTRUCT(tuple);
4008 renameatt_check(relid, form, false);
4009 ReleaseSysCache(tuple);
4010 }
4011
4012 /*
4013 * renameatt - changes the name of an attribute in a relation
4014 *
4015 * The returned ObjectAddress is that of the renamed column.
4016 */
4017 ObjectAddress
4018 renameatt(RenameStmt *stmt)
4019 {
4020 Oid relid;
4021 AttrNumber attnum;
4022 ObjectAddress address;
4023
4024 /* lock level taken here should match renameatt_internal */
4025 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4026 stmt->missing_ok ? RVR_MISSING_OK : 0,
4027 RangeVarCallbackForRenameAttribute,
4028 NULL);
4029
4030 if (!OidIsValid(relid))
4031 {
4032 ereport(NOTICE,
4033 (errmsg("relation \"%s\" does not exist, skipping",
4034 stmt->relation->relname)));
4035 return InvalidObjectAddress;
4036 }
4037
4038 attnum =
4039 renameatt_internal(relid,
4040 stmt->subname, /* old att name */
4041 stmt->newname, /* new att name */
4042 stmt->relation->inh, /* recursive? */
4043 false, /* recursing? */
4044 0, /* expected inhcount */
4045 stmt->behavior);
4046
4047 ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
4048
4049 return address;
4050 }
4051
4052 /*
4053 * same logic as renameatt_internal
4054 */
4055 static ObjectAddress
4056 rename_constraint_internal(Oid myrelid,
4057 Oid mytypid,
4058 const char *oldconname,
4059 const char *newconname,
4060 bool recurse,
4061 bool recursing,
4062 int expected_parents)
4063 {
4064 Relation targetrelation = NULL;
4065 Oid constraintOid;
4066 HeapTuple tuple;
4067 Form_pg_constraint con;
4068 ObjectAddress address;
4069
4070 Assert(!myrelid || !mytypid);
4071
4072 if (mytypid)
4073 {
4074 constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
4075 }
4076 else
4077 {
4078 targetrelation = relation_open(myrelid, AccessExclusiveLock);
4079
4080 /*
4081 * don't tell it whether we're recursing; we allow changing typed
4082 * tables here
4083 */
4084 renameatt_check(myrelid, RelationGetForm(targetrelation), false);
4085
4086 constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
4087 }
4088
4089 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
4090 if (!HeapTupleIsValid(tuple))
4091 elog(ERROR, "cache lookup failed for constraint %u",
4092 constraintOid);
4093 con = (Form_pg_constraint) GETSTRUCT(tuple);
4094
4095 if (myrelid &&
4096 (con->contype == CONSTRAINT_CHECK ||
4097 con->contype == CONSTRAINT_NOTNULL) &&
4098 !con->connoinherit)
4099 {
4100 if (recurse)
4101 {
4102 List *child_oids,
4103 *child_numparents;
4104 ListCell *lo,
4105 *li;
4106
4107 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
4108 &child_numparents);
4109
4110 forboth(lo, child_oids, li, child_numparents)
4111 {
4112 Oid childrelid = lfirst_oid(lo);
4113 int numparents = lfirst_int(li);
4114
4115 if (childrelid == myrelid)
4116 continue;
4117
4118 rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
4119 }
4120 }
4121 else
4122 {
4123 if (expected_parents == 0 &&
4124 find_inheritance_children(myrelid, NoLock) != NIL)
4125 ereport(ERROR,
4126 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4127 errmsg("inherited constraint \"%s\" must be renamed in child tables too",
4128 oldconname)));
4129 }
4130
4131 if (con->coninhcount > expected_parents)
4132 ereport(ERROR,
4133 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4134 errmsg("cannot rename inherited constraint \"%s\"",
4135 oldconname)));
4136 }
4137
4138 if (con->conindid
4139 && (con->contype == CONSTRAINT_PRIMARY
4140 || con->contype == CONSTRAINT_UNIQUE
4141 || con->contype == CONSTRAINT_EXCLUSION))
4142 /* rename the index; this renames the constraint as well */
4143 RenameRelationInternal(con->conindid, newconname, false, true);
4144 else
4145 RenameConstraintById(constraintOid, newconname);
4146
4147 ObjectAddressSet(address, ConstraintRelationId, constraintOid);
4148
4149 ReleaseSysCache(tuple);
4150
4151 if (targetrelation)
4152 {
4153 /*
4154 * Invalidate relcache so as others can see the new constraint name.
4155 */
4156 CacheInvalidateRelcache(targetrelation);
4157
4158 relation_close(targetrelation, NoLock); /* close rel but keep lock */
4159 }
4160
4161 return address;
4162 }
4163
4164 ObjectAddress
4165 RenameConstraint(RenameStmt *stmt)
4166 {
4167 Oid relid = InvalidOid;
4168 Oid typid = InvalidOid;
4169
4170 if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4171 {
4172 Relation rel;
4173 HeapTuple tup;
4174
4175 typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4176 rel = table_open(TypeRelationId, RowExclusiveLock);
4177 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4178 if (!HeapTupleIsValid(tup))
4179 elog(ERROR, "cache lookup failed for type %u", typid);
4180 checkDomainOwner(tup);
4181 ReleaseSysCache(tup);
4182 table_close(rel, NoLock);
4183 }
4184 else
4185 {
4186 /* lock level taken here should match rename_constraint_internal */
4187 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4188 stmt->missing_ok ? RVR_MISSING_OK : 0,
4189 RangeVarCallbackForRenameAttribute,
4190 NULL);
4191 if (!OidIsValid(relid))
4192 {
4193 ereport(NOTICE,
4194 (errmsg("relation \"%s\" does not exist, skipping",
4195 stmt->relation->relname)));
4196 return InvalidObjectAddress;
4197 }
4198 }
4199
4200 return
4201 rename_constraint_internal(relid, typid,
4202 stmt->subname,
4203 stmt->newname,
4204 (stmt->relation &&
4205 stmt->relation->inh), /* recursive? */
4206 false, /* recursing? */
4207 0 /* expected inhcount */ );
4208 }
4209
4210 /*
4211 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
4212 * RENAME
4213 */
4214 ObjectAddress
4215 RenameRelation(RenameStmt *stmt)
4216 {
4217 bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4218 Oid relid;
4219 ObjectAddress address;
4220
4221 /*
4222 * Grab an exclusive lock on the target table, index, sequence, view,
4223 * materialized view, or foreign table, which we will NOT release until
4224 * end of transaction.
4225 *
4226 * Lock level used here should match RenameRelationInternal, to avoid lock
4227 * escalation. However, because ALTER INDEX can be used with any relation
4228 * type, we mustn't believe without verification.
4229 */
4230 for (;;)
4231 {
4232 LOCKMODE lockmode;
4233 char relkind;
4234 bool obj_is_index;
4235
4236 lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
4237
4238 relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4239 stmt->missing_ok ? RVR_MISSING_OK : 0,
4240 RangeVarCallbackForAlterRelation,
4241 stmt);
4242
4243 if (!OidIsValid(relid))
4244 {
4245 ereport(NOTICE,
4246 (errmsg("relation \"%s\" does not exist, skipping",
4247 stmt->relation->relname)));
4248 return InvalidObjectAddress;
4249 }
4250
4251 /*
4252 * We allow mismatched statement and object types (e.g., ALTER INDEX
4253 * to rename a table), but we might've used the wrong lock level. If
4254 * that happens, retry with the correct lock level. We don't bother
4255 * if we already acquired AccessExclusiveLock with an index, however.
4256 */
4257 relkind = get_rel_relkind(relid);
4258 obj_is_index = (relkind == RELKIND_INDEX ||
4259 relkind == RELKIND_PARTITIONED_INDEX);
4260 if (obj_is_index || is_index_stmt == obj_is_index)
4261 break;
4262
4263 UnlockRelationOid(relid, lockmode);
4264 is_index_stmt = obj_is_index;
4265 }
4266
4267 /* Do the work */
4268 RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4269
4270 ObjectAddressSet(address, RelationRelationId, relid);
4271
4272 return address;
4273 }
4274
4275 /*
4276 * RenameRelationInternal - change the name of a relation
4277 */
4278 void
4279 RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
4280 {
4281 Relation targetrelation;
4282 Relation relrelation; /* for RELATION relation */
4283 ItemPointerData otid;
4284 HeapTuple reltup;
4285 Form_pg_class relform;
4286 Oid namespaceId;
4287
4288 /*
4289 * Grab a lock on the target relation, which we will NOT release until end
4290 * of transaction. We need at least a self-exclusive lock so that
4291 * concurrent DDL doesn't overwrite the rename if they start updating
4292 * while still seeing the old version. The lock also guards against
4293 * triggering relcache reloads in concurrent sessions, which might not
4294 * handle this information changing under them. For indexes, we can use a
4295 * reduced lock level because RelationReloadIndexInfo() handles indexes
4296 * specially.
4297 */
4298 targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
4299 namespaceId = RelationGetNamespace(targetrelation);
4300
4301 /*
4302 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4303 */
4304 relrelation = table_open(RelationRelationId, RowExclusiveLock);
4305
4306 reltup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(myrelid));
4307 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4308 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4309 otid = reltup->t_self;
4310 relform = (Form_pg_class) GETSTRUCT(reltup);
4311
4312 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
4313 ereport(ERROR,
4314 (errcode(ERRCODE_DUPLICATE_TABLE),
4315 errmsg("relation \"%s\" already exists",
4316 newrelname)));
4317
4318 /*
4319 * RenameRelation is careful not to believe the caller's idea of the
4320 * relation kind being handled. We don't have to worry about this, but
4321 * let's not be totally oblivious to it. We can process an index as
4322 * not-an-index, but not the other way around.
4323 */
4324 Assert(!is_index ||
4325 is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4326 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4327
4328 /*
4329 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4330 * because it's a copy...)
4331 */
4332 namestrcpy(&(relform->relname), newrelname);
4333
4334 CatalogTupleUpdate(relrelation, &otid, reltup);
4335 UnlockTuple(relrelation, &otid, InplaceUpdateTupleLock);
4336
4337 InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
4338 InvalidOid, is_internal);
4339
4340 heap_freetuple(reltup);
4341 table_close(relrelation, RowExclusiveLock);
4342
4343 /*
4344 * Also rename the associated type, if any.
4345 */
4346 if (OidIsValid(targetrelation->rd_rel->reltype))
4347 RenameTypeInternal(targetrelation->rd_rel->reltype,
4348 newrelname, namespaceId);
4349
4350 /*
4351 * Also rename the associated constraint, if any.
4352 */
4353 if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4354 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4355 {
4356 Oid constraintId = get_index_constraint(myrelid);
4357
4358 if (OidIsValid(constraintId))
4359 RenameConstraintById(constraintId, newrelname);
4360 }
4361
4362 /*
4363 * Close rel, but keep lock!
4364 */
4365 relation_close(targetrelation, NoLock);
4366 }
4367
4368 /*
4369 * ResetRelRewrite - reset relrewrite
4370 */
4371 void
4372 ResetRelRewrite(Oid myrelid)
4373 {
4374 Relation relrelation; /* for RELATION relation */
4375 HeapTuple reltup;
4376 Form_pg_class relform;
4377
4378 /*
4379 * Find relation's pg_class tuple.
4380 */
4381 relrelation = table_open(RelationRelationId, RowExclusiveLock);
4382
4383 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4384 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4385 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4386 relform = (Form_pg_class) GETSTRUCT(reltup);
4387
4388 /*
4389 * Update pg_class tuple.
4390 */
4391 relform->relrewrite = InvalidOid;
4392
4393 CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4394
4395 heap_freetuple(reltup);
4396 table_close(relrelation, RowExclusiveLock);
4397 }
4398
4399 /*
4400 * Disallow ALTER TABLE (and similar commands) when the current backend has
4401 * any open reference to the target table besides the one just acquired by
4402 * the calling command; this implies there's an open cursor or active plan.
4403 * We need this check because our lock doesn't protect us against stomping
4404 * on our own foot, only other people's feet!
4405 *
4406 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
4407 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
4408 * possibly be relaxed to only error out for certain types of alterations.
4409 * But the use-case for allowing any of these things is not obvious, so we
4410 * won't work hard at it for now.
4411 *
4412 * We also reject these commands if there are any pending AFTER trigger events
4413 * for the rel. This is certainly necessary for the rewriting variants of
4414 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
4415 * events would try to fetch the wrong tuples. It might be overly cautious
4416 * in other cases, but again it seems better to err on the side of paranoia.
4417 *
4418 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
4419 * we are worried about active indexscans on the index. The trigger-event
4420 * check can be skipped, since we are doing no damage to the parent table.
4421 *
4422 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
4423 */
4424 void
4425 CheckTableNotInUse(Relation rel, const char *stmt)
4426 {
4427 int expected_refcnt;
4428
4429 expected_refcnt = rel->rd_isnailed ? 2 : 1;
4430 if (rel->rd_refcnt != expected_refcnt)
4431 ereport(ERROR,
4432 (errcode(ERRCODE_OBJECT_IN_USE),
4433 /* translator: first %s is a SQL command, eg ALTER TABLE */
4434 errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4435 stmt, RelationGetRelationName(rel))));
4436
4437 if (rel->rd_rel->relkind != RELKIND_INDEX &&
4438 rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4439 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
4440 ereport(ERROR,
4441 (errcode(ERRCODE_OBJECT_IN_USE),
4442 /* translator: first %s is a SQL command, eg ALTER TABLE */
4443 errmsg("cannot %s \"%s\" because it has pending trigger events",
4444 stmt, RelationGetRelationName(rel))));
4445 }
4446
4447 /*
4448 * CheckAlterTableIsSafe
4449 * Verify that it's safe to allow ALTER TABLE on this relation.
4450 *
4451 * This consists of CheckTableNotInUse() plus a check that the relation
4452 * isn't another session's temp table. We must split out the temp-table
4453 * check because there are callers of CheckTableNotInUse() that don't want
4454 * that, notably DROP TABLE. (We must allow DROP or we couldn't clean out
4455 * an orphaned temp schema.) Compare truncate_check_activity().
4456 */
4457 static void
4458 CheckAlterTableIsSafe(Relation rel)
4459 {
4460 /*
4461 * Don't allow ALTER on temp tables of other backends. Their local buffer
4462 * manager is not going to cope if we need to change the table's contents.
4463 * Even if we don't, there may be optimizations that assume temp tables
4464 * aren't subject to such interference.
4465 */
4466 if (RELATION_IS_OTHER_TEMP(rel))
4467 ereport(ERROR,
4468 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4469 errmsg("cannot alter temporary tables of other sessions")));
4470
4471 /*
4472 * Also check for active uses of the relation in the current transaction,
4473 * including open scans and pending AFTER trigger events.
4474 */
4475 CheckTableNotInUse(rel, "ALTER TABLE");
4476 }
4477
4478 /*
4479 * AlterTableLookupRelation
4480 * Look up, and lock, the OID for the relation named by an alter table
4481 * statement.
4482 */
4483 Oid
4484 AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
4485 {
4486 return RangeVarGetRelidExtended(stmt->relation, lockmode,
4487 stmt->missing_ok ? RVR_MISSING_OK : 0,
4488 RangeVarCallbackForAlterRelation,
4489 stmt);
4490 }
4491
4492 /*
4493 * AlterTable
4494 * Execute ALTER TABLE, which can be a list of subcommands
4495 *
4496 * ALTER TABLE is performed in three phases:
4497 * 1. Examine subcommands and perform pre-transformation checking.
4498 * 2. Validate and transform subcommands, and update system catalogs.
4499 * 3. Scan table(s) to check new constraints, and optionally recopy
4500 * the data into new table(s).
4501 * Phase 3 is not performed unless one or more of the subcommands requires
4502 * it. The intention of this design is to allow multiple independent
4503 * updates of the table schema to be performed with only one pass over the
4504 * data.
4505 *
4506 * ATPrepCmd performs phase 1. A "work queue" entry is created for
4507 * each table to be affected (there may be multiple affected tables if the
4508 * commands traverse a table inheritance hierarchy). Also we do preliminary
4509 * validation of the subcommands. Because earlier subcommands may change
4510 * the catalog state seen by later commands, there are limits to what can
4511 * be done in this phase. Generally, this phase acquires table locks,
4512 * checks permissions and relkind, and recurses to find child tables.
4513 *
4514 * ATRewriteCatalogs performs phase 2 for each affected table.
4515 * Certain subcommands need to be performed before others to avoid
4516 * unnecessary conflicts; for example, DROP COLUMN should come before
4517 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
4518 * lists, one for each logical "pass" of phase 2.
4519 *
4520 * ATRewriteTables performs phase 3 for those tables that need it.
4521 *
4522 * For most subcommand types, phases 2 and 3 do no explicit recursion,
4523 * since phase 1 already does it. However, for certain subcommand types
4524 * it is only possible to determine how to recurse at phase 2 time; for
4525 * those cases, phase 1 sets the cmd->recurse flag.
4526 *
4527 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
4528 * the whole operation; we don't have to do anything special to clean up.
4529 *
4530 * The caller must lock the relation, with an appropriate lock level
4531 * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
4532 * or higher. We pass the lock level down
4533 * so that we can apply it recursively to inherited tables. Note that the
4534 * lock level we want as we recurse might well be higher than required for
4535 * that specific subcommand. So we pass down the overall lock requirement,
4536 * rather than reassess it at lower levels.
4537 *
4538 * The caller also provides a "context" which is to be passed back to
4539 * utility.c when we need to execute a subcommand such as CREATE INDEX.
4540 * Some of the fields therein, such as the relid, are used here as well.
4541 */
4542 void
4543 AlterTable(AlterTableStmt *stmt, LOCKMODE lockmode,
4544 AlterTableUtilityContext *context)
4545 {
4546 Relation rel;
4547
4548 /* Caller is required to provide an adequate lock. */
4549 rel = relation_open(context->relid, NoLock);
4550
4551 CheckAlterTableIsSafe(rel);
4552
4553 ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4554 }
4555
4556 /*
4557 * AlterTableInternal
4558 *
4559 * ALTER TABLE with target specified by OID
4560 *
4561 * We do not reject if the relation is already open, because it's quite
4562 * likely that one or more layers of caller have it open. That means it
4563 * is unsafe to use this entry point for alterations that could break
4564 * existing query plans. On the assumption it's not used for such, we
4565 * don't have to reject pending AFTER triggers, either.
4566 *
4567 * Also, since we don't have an AlterTableUtilityContext, this cannot be
4568 * used for any subcommand types that require parse transformation or
4569 * could generate subcommands that have to be passed to ProcessUtility.
4570 */
4571 void
4572 AlterTableInternal(Oid relid, List *cmds, bool recurse)
4573 {
4574 Relation rel;
4575 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4576
4577 rel = relation_open(relid, lockmode);
4578
4579 EventTriggerAlterTableRelid(relid);
4580
4581 ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4582 }
4583
4584 /*
4585 * AlterTableGetLockLevel
4586 *
4587 * Sets the overall lock level required for the supplied list of subcommands.
4588 * Policy for doing this set according to needs of AlterTable(), see
4589 * comments there for overall explanation.
4590 *
4591 * Function is called before and after parsing, so it must give same
4592 * answer each time it is called. Some subcommands are transformed
4593 * into other subcommand types, so the transform must never be made to a
4594 * lower lock level than previously assigned. All transforms are noted below.
4595 *
4596 * Since this is called before we lock the table we cannot use table metadata
4597 * to influence the type of lock we acquire.
4598 *
4599 * There should be no lockmodes hardcoded into the subcommand functions. All
4600 * lockmode decisions for ALTER TABLE are made here only. The one exception is
4601 * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
4602 * and does not travel through this section of code and cannot be combined with
4603 * any of the subcommands given here.
4604 *
4605 * Note that Hot Standby only knows about AccessExclusiveLocks on the primary
4606 * so any changes that might affect SELECTs running on standbys need to use
4607 * AccessExclusiveLocks even if you think a lesser lock would do, unless you
4608 * have a solution for that also.
4609 *
4610 * Also note that pg_dump uses only an AccessShareLock, meaning that anything
4611 * that takes a lock less than AccessExclusiveLock can change object definitions
4612 * while pg_dump is running. Be careful to check that the appropriate data is
4613 * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
4614 * otherwise we might end up with an inconsistent dump that can't restore.
4615 */
4616 LOCKMODE
4617 AlterTableGetLockLevel(List *cmds)
4618 {
4619 /*
4620 * This only works if we read catalog tables using MVCC snapshots.
4621 */
4622 ListCell *lcmd;
4623 LOCKMODE lockmode = ShareUpdateExclusiveLock;
4624
4625 foreach(lcmd, cmds)
4626 {
4627 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4628 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4629
4630 switch (cmd->subtype)
4631 {
4632 /*
4633 * These subcommands rewrite the heap, so require full locks.
4634 */
4635 case AT_AddColumn: /* may rewrite heap, in some cases and visible
4636 * to SELECT */
4637 case AT_SetAccessMethod: /* must rewrite heap */
4638 case AT_SetTableSpace: /* must rewrite heap */
4639 case AT_AlterColumnType: /* must rewrite heap */
4640 cmd_lockmode = AccessExclusiveLock;
4641 break;
4642
4643 /*
4644 * These subcommands may require addition of toast tables. If
4645 * we add a toast table to a table currently being scanned, we
4646 * might miss data added to the new toast table by concurrent
4647 * insert transactions.
4648 */
4649 case AT_SetStorage: /* may add toast tables, see
4650 * ATRewriteCatalogs() */
4651 cmd_lockmode = AccessExclusiveLock;
4652 break;
4653
4654 /*
4655 * Removing constraints can affect SELECTs that have been
4656 * optimized assuming the constraint holds true. See also
4657 * CloneFkReferenced.
4658 */
4659 case AT_DropConstraint: /* as DROP INDEX */
4660 case AT_DropNotNull: /* may change some SQL plans */
4661 cmd_lockmode = AccessExclusiveLock;
4662 break;
4663
4664 /*
4665 * Subcommands that may be visible to concurrent SELECTs
4666 */
4667 case AT_DropColumn: /* change visible to SELECT */
4668 case AT_AddColumnToView: /* CREATE VIEW */
4669 case AT_DropOids: /* used to equiv to DropColumn */
4670 case AT_EnableAlwaysRule: /* may change SELECT rules */
4671 case AT_EnableReplicaRule: /* may change SELECT rules */
4672 case AT_EnableRule: /* may change SELECT rules */
4673 case AT_DisableRule: /* may change SELECT rules */
4674 cmd_lockmode = AccessExclusiveLock;
4675 break;
4676
4677 /*
4678 * Changing owner may remove implicit SELECT privileges
4679 */
4680 case AT_ChangeOwner: /* change visible to SELECT */
4681 cmd_lockmode = AccessExclusiveLock;
4682 break;
4683
4684 /*
4685 * Changing foreign table options may affect optimization.
4686 */
4687 case AT_GenericOptions:
4688 case AT_AlterColumnGenericOptions:
4689 cmd_lockmode = AccessExclusiveLock;
4690 break;
4691
4692 /*
4693 * These subcommands affect write operations only.
4694 */
4695 case AT_EnableTrig:
4696 case AT_EnableAlwaysTrig:
4697 case AT_EnableReplicaTrig:
4698 case AT_EnableTrigAll:
4699 case AT_EnableTrigUser:
4700 case AT_DisableTrig:
4701 case AT_DisableTrigAll:
4702 case AT_DisableTrigUser:
4703 cmd_lockmode = ShareRowExclusiveLock;
4704 break;
4705
4706 /*
4707 * These subcommands affect write operations only. XXX
4708 * Theoretically, these could be ShareRowExclusiveLock.
4709 */
4710 case AT_ColumnDefault:
4711 case AT_CookedColumnDefault:
4712 case AT_AlterConstraint:
4713 case AT_AddIndex: /* from ADD CONSTRAINT */
4714 case AT_AddIndexConstraint:
4715 case AT_ReplicaIdentity:
4716 case AT_SetNotNull:
4717 case AT_EnableRowSecurity:
4718 case AT_DisableRowSecurity:
4719 case AT_ForceRowSecurity:
4720 case AT_NoForceRowSecurity:
4721 case AT_AddIdentity:
4722 case AT_DropIdentity:
4723 case AT_SetIdentity:
4724 case AT_SetExpression:
4725 case AT_DropExpression:
4726 case AT_SetCompression:
4727 cmd_lockmode = AccessExclusiveLock;
4728 break;
4729
4730 case AT_AddConstraint:
4731 case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4732 case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4733 if (IsA(cmd->def, Constraint))
4734 {
4735 Constraint *con = (Constraint *) cmd->def;
4736
4737 switch (con->contype)
4738 {
4739 case CONSTR_EXCLUSION:
4740 case CONSTR_PRIMARY:
4741 case CONSTR_UNIQUE:
4742
4743 /*
4744 * Cases essentially the same as CREATE INDEX. We
4745 * could reduce the lock strength to ShareLock if
4746 * we can work out how to allow concurrent catalog
4747 * updates. XXX Might be set down to
4748 * ShareRowExclusiveLock but requires further
4749 * analysis.
4750 */
4751 cmd_lockmode = AccessExclusiveLock;
4752 break;
4753 case CONSTR_FOREIGN:
4754
4755 /*
4756 * We add triggers to both tables when we add a
4757 * Foreign Key, so the lock level must be at least
4758 * as strong as CREATE TRIGGER.
4759 */
4760 cmd_lockmode = ShareRowExclusiveLock;
4761 break;
4762
4763 default:
4764 cmd_lockmode = AccessExclusiveLock;
4765 }
4766 }
4767 break;
4768
4769 /*
4770 * These subcommands affect inheritance behaviour. Queries
4771 * started before us will continue to see the old inheritance
4772 * behaviour, while queries started after we commit will see
4773 * new behaviour. No need to prevent reads or writes to the
4774 * subtable while we hook it up though. Changing the TupDesc
4775 * may be a problem, so keep highest lock.
4776 */
4777 case AT_AddInherit:
4778 case AT_DropInherit:
4779 cmd_lockmode = AccessExclusiveLock;
4780 break;
4781
4782 /*
4783 * These subcommands affect implicit row type conversion. They
4784 * have affects similar to CREATE/DROP CAST on queries. don't
4785 * provide for invalidating parse trees as a result of such
4786 * changes, so we keep these at AccessExclusiveLock.
4787 */
4788 case AT_AddOf:
4789 case AT_DropOf:
4790 cmd_lockmode = AccessExclusiveLock;
4791 break;
4792
4793 /*
4794 * Only used by CREATE OR REPLACE VIEW which must conflict
4795 * with an SELECTs currently using the view.
4796 */
4797 case AT_ReplaceRelOptions:
4798 cmd_lockmode = AccessExclusiveLock;
4799 break;
4800
4801 /*
4802 * These subcommands affect general strategies for performance
4803 * and maintenance, though don't change the semantic results
4804 * from normal data reads and writes. Delaying an ALTER TABLE
4805 * behind currently active writes only delays the point where
4806 * the new strategy begins to take effect, so there is no
4807 * benefit in waiting. In this case the minimum restriction
4808 * applies: we don't currently allow concurrent catalog
4809 * updates.
4810 */
4811 case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4812 case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4813 case AT_DropCluster: /* Uses MVCC in getIndexes() */
4814 case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4815 case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4816 cmd_lockmode = ShareUpdateExclusiveLock;
4817 break;
4818
4819 case AT_SetLogged:
4820 case AT_SetUnLogged:
4821 cmd_lockmode = AccessExclusiveLock;
4822 break;
4823
4824 case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4825 cmd_lockmode = ShareUpdateExclusiveLock;
4826 break;
4827
4828 /*
4829 * Rel options are more complex than first appears. Options
4830 * are set here for tables, views and indexes; for historical
4831 * reasons these can all be used with ALTER TABLE, so we can't
4832 * decide between them using the basic grammar.
4833 */
4834 case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4835 * getTables() */
4836 case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4837 * getTables() */
4838 cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4839 break;
4840
4841 case AT_AttachPartition:
4842 cmd_lockmode = ShareUpdateExclusiveLock;
4843 break;
4844
4845 case AT_DetachPartition:
4846 if (((PartitionCmd *) cmd->def)->concurrent)
4847 cmd_lockmode = ShareUpdateExclusiveLock;
4848 else
4849 cmd_lockmode = AccessExclusiveLock;
4850 break;
4851
4852 case AT_DetachPartitionFinalize:
4853 cmd_lockmode = ShareUpdateExclusiveLock;
4854 break;
4855
4856 default: /* oops */
4857 elog(ERROR, "unrecognized alter table type: %d",
4858 (int) cmd->subtype);
4859 break;
4860 }
4861
4862 /*
4863 * Take the greatest lockmode from any subcommand
4864 */
4865 if (cmd_lockmode > lockmode)
4866 lockmode = cmd_lockmode;
4867 }
4868
4869 return lockmode;
4870 }
4871
4872 /*
4873 * ATController provides top level control over the phases.
4874 *
4875 * parsetree is passed in to allow it to be passed to event triggers
4876 * when requested.
4877 */
4878 static void
4879 ATController(AlterTableStmt *parsetree,
4880 Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
4881 AlterTableUtilityContext *context)
4882 {
4883 List *wqueue = NIL;
4884 ListCell *lcmd;
4885
4886 /* Phase 1: preliminary examination of commands, create work queue */
4887 foreach(lcmd, cmds)
4888 {
4889 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4890
4891 ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
4892 }
4893
4894 /* Close the relation, but keep lock until commit */
4895 relation_close(rel, NoLock);
4896
4897 /* Phase 2: update system catalogs */
4898 ATRewriteCatalogs(&wqueue, lockmode, context);
4899
4900 /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
4901 ATRewriteTables(parsetree, &wqueue, lockmode, context);
4902 }
4903
4904 /*
4905 * ATPrepCmd
4906 *
4907 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
4908 * recursion and permission checks.
4909 *
4910 * Caller must have acquired appropriate lock type on relation already.
4911 * This lock should be held until commit.
4912 */
4913 static void
4914 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
4915 bool recurse, bool recursing, LOCKMODE lockmode,
4916 AlterTableUtilityContext *context)
4917 {
4918 AlteredTableInfo *tab;
4919 AlterTablePass pass = AT_PASS_UNSET;
4920
4921 /* Find or create work queue entry for this table */
4922 tab = ATGetQueueEntry(wqueue, rel);
4923
4924 /*
4925 * Disallow any ALTER TABLE other than ALTER TABLE DETACH FINALIZE on
4926 * partitions that are pending detach.
4927 */
4928 if (rel->rd_rel->relispartition &&
4929 cmd->subtype != AT_DetachPartitionFinalize &&
4930 PartitionHasPendingDetach(RelationGetRelid(rel)))
4931 ereport(ERROR,
4932 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4933 errmsg("cannot alter partition \"%s\" with an incomplete detach",
4934 RelationGetRelationName(rel)),
4935 errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
4936
4937 /*
4938 * Copy the original subcommand for each table, so we can scribble on it.
4939 * This avoids conflicts when different child tables need to make
4940 * different parse transformations (for example, the same column may have
4941 * different column numbers in different children).
4942 */
4943 cmd = copyObject(cmd);
4944
4945 /*
4946 * Do permissions and relkind checking, recursion to child tables if
4947 * needed, and any additional phase-1 processing needed. (But beware of
4948 * adding any processing that looks at table details that another
4949 * subcommand could change. In some cases we reject multiple subcommands
4950 * that could try to change the same state in contrary ways.)
4951 */
4952 switch (cmd->subtype)
4953 {
4954 case AT_AddColumn: /* ADD COLUMN */
4955 ATSimplePermissions(cmd->subtype, rel,
4956 ATT_TABLE | ATT_PARTITIONED_TABLE |
4957 ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
4958 ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
4959 lockmode, context);
4960 /* Recursion occurs during execution phase */
4961 pass = AT_PASS_ADD_COL;
4962 break;
4963 case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
4964 ATSimplePermissions(cmd->subtype, rel, ATT_VIEW);
4965 ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
4966 lockmode, context);
4967 /* Recursion occurs during execution phase */
4968 pass = AT_PASS_ADD_COL;
4969 break;
4970 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
4971
4972 /*
4973 * We allow defaults on views so that INSERT into a view can have
4974 * default-ish behavior. This works because the rewriter
4975 * substitutes default values into INSERTs before it expands
4976 * rules.
4977 */
4978 ATSimplePermissions(cmd->subtype, rel,
4979 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
4980 ATT_FOREIGN_TABLE);
4981 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
4982 /* No command-specific prep needed */
4983 pass = cmd->def ? AT_PASS_ADD_OTHERCONSTR : AT_PASS_DROP;
4984 break;
4985 case AT_CookedColumnDefault: /* add a pre-cooked default */
4986 /* This is currently used only in CREATE TABLE */
4987 /* (so the permission check really isn't necessary) */
4988 ATSimplePermissions(cmd->subtype, rel,
4989 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
4990 /* This command never recurses */
4991 pass = AT_PASS_ADD_OTHERCONSTR;
4992 break;
4993 case AT_AddIdentity:
4994 ATSimplePermissions(cmd->subtype, rel,
4995 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
4996 ATT_FOREIGN_TABLE);
4997 /* Set up recursion for phase 2; no other prep needed */
4998 if (recurse)
4999 cmd->recurse = true;
5000 pass = AT_PASS_ADD_OTHERCONSTR;
5001 break;
5002 case AT_SetIdentity:
5003 ATSimplePermissions(cmd->subtype, rel,
5004 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5005 ATT_FOREIGN_TABLE);
5006 /* Set up recursion for phase 2; no other prep needed */
5007 if (recurse)
5008 cmd->recurse = true;
5009 /* This should run after AddIdentity, so do it in MISC pass */
5010 pass = AT_PASS_MISC;
5011 break;
5012 case AT_DropIdentity:
5013 ATSimplePermissions(cmd->subtype, rel,
5014 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5015 ATT_FOREIGN_TABLE);
5016 /* Set up recursion for phase 2; no other prep needed */
5017 if (recurse)
5018 cmd->recurse = true;
5019 pass = AT_PASS_DROP;
5020 break;
5021 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5022 ATSimplePermissions(cmd->subtype, rel,
5023 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5024 /* Set up recursion for phase 2; no other prep needed */
5025 if (recurse)
5026 cmd->recurse = true;
5027 pass = AT_PASS_DROP;
5028 break;
5029 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5030 ATSimplePermissions(cmd->subtype, rel,
5031 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5032 /* Set up recursion for phase 2; no other prep needed */
5033 if (recurse)
5034 cmd->recurse = true;
5035 pass = AT_PASS_COL_ATTRS;
5036 break;
5037 case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */
5038 ATSimplePermissions(cmd->subtype, rel,
5039 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5040 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5041 pass = AT_PASS_SET_EXPRESSION;
5042 break;
5043 case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */
5044 ATSimplePermissions(cmd->subtype, rel,
5045 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5046 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5047 ATPrepDropExpression(rel, cmd, recurse, recursing, lockmode);
5048 pass = AT_PASS_DROP;
5049 break;
5050 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5051 ATSimplePermissions(cmd->subtype, rel,
5052 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW |
5053 ATT_INDEX | ATT_PARTITIONED_INDEX | ATT_FOREIGN_TABLE);
5054 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5055 /* No command-specific prep needed */
5056 pass = AT_PASS_MISC;
5057 break;
5058 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5059 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5060 ATSimplePermissions(cmd->subtype, rel,
5061 ATT_TABLE | ATT_PARTITIONED_TABLE |
5062 ATT_MATVIEW | ATT_FOREIGN_TABLE);
5063 /* This command never recurses */
5064 pass = AT_PASS_MISC;
5065 break;
5066 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5067 ATSimplePermissions(cmd->subtype, rel,
5068 ATT_TABLE | ATT_PARTITIONED_TABLE |
5069 ATT_MATVIEW | ATT_FOREIGN_TABLE);
5070 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5071 /* No command-specific prep needed */
5072 pass = AT_PASS_MISC;
5073 break;
5074 case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5075 ATSimplePermissions(cmd->subtype, rel,
5076 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5077 /* This command never recurses */
5078 /* No command-specific prep needed */
5079 pass = AT_PASS_MISC;
5080 break;
5081 case AT_DropColumn: /* DROP COLUMN */
5082 ATSimplePermissions(cmd->subtype, rel,
5083 ATT_TABLE | ATT_PARTITIONED_TABLE |
5084 ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5085 ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd,
5086 lockmode, context);
5087 /* Recursion occurs during execution phase */
5088 pass = AT_PASS_DROP;
5089 break;
5090 case AT_AddIndex: /* ADD INDEX */
5091 ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5092 /* This command never recurses */
5093 /* No command-specific prep needed */
5094 pass = AT_PASS_ADD_INDEX;
5095 break;
5096 case AT_AddConstraint: /* ADD CONSTRAINT */
5097 ATSimplePermissions(cmd->subtype, rel,
5098 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5099 ATPrepAddPrimaryKey(wqueue, rel, cmd, recurse, lockmode, context);
5100 if (recurse)
5101 {
5102 /* recurses at exec time; lock descendants and set flag */
5103 (void) find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5104 cmd->recurse = true;
5105 }
5106 pass = AT_PASS_ADD_CONSTR;
5107 break;
5108 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5109 ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5110 /* This command never recurses */
5111 /* No command-specific prep needed */
5112 pass = AT_PASS_ADD_INDEXCONSTR;
5113 break;
5114 case AT_DropConstraint: /* DROP CONSTRAINT */
5115 ATSimplePermissions(cmd->subtype, rel,
5116 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5117 ATCheckPartitionsNotInUse(rel, lockmode);
5118 /* Other recursion occurs during execution phase */
5119 /* No command-specific prep needed except saving recurse flag */
5120 if (recurse)
5121 cmd->recurse = true;
5122 pass = AT_PASS_DROP;
5123 break;
5124 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5125 ATSimplePermissions(cmd->subtype, rel,
5126 ATT_TABLE | ATT_PARTITIONED_TABLE |
5127 ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5128 /* See comments for ATPrepAlterColumnType */
5129 cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
5130 AT_PASS_UNSET, context);
5131 Assert(cmd != NULL);
5132 /* Performs own recursion */
5133 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
5134 lockmode, context);
5135 pass = AT_PASS_ALTER_TYPE;
5136 break;
5137 case AT_AlterColumnGenericOptions:
5138 ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5139 /* This command never recurses */
5140 /* No command-specific prep needed */
5141 pass = AT_PASS_MISC;
5142 break;
5143 case AT_ChangeOwner: /* ALTER OWNER */
5144 /* This command never recurses */
5145 /* No command-specific prep needed */
5146 pass = AT_PASS_MISC;
5147 break;
5148 case AT_ClusterOn: /* CLUSTER ON */
5149 case AT_DropCluster: /* SET WITHOUT CLUSTER */
5150 ATSimplePermissions(cmd->subtype, rel,
5151 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5152 /* These commands never recurse */
5153 /* No command-specific prep needed */
5154 pass = AT_PASS_MISC;
5155 break;
5156 case AT_SetLogged: /* SET LOGGED */
5157 case AT_SetUnLogged: /* SET UNLOGGED */
5158 ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_SEQUENCE);
5159 if (tab->chgPersistence)
5160 ereport(ERROR,
5161 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5162 errmsg("cannot change persistence setting twice")));
5163 ATPrepChangePersistence(tab, rel, cmd->subtype == AT_SetLogged);
5164 pass = AT_PASS_MISC;
5165 break;
5166 case AT_DropOids: /* SET WITHOUT OIDS */
5167 ATSimplePermissions(cmd->subtype, rel,
5168 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5169 pass = AT_PASS_DROP;
5170 break;
5171 case AT_SetAccessMethod: /* SET ACCESS METHOD */
5172 ATSimplePermissions(cmd->subtype, rel,
5173 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5174
5175 /* check if another access method change was already requested */
5176 if (tab->chgAccessMethod)
5177 ereport(ERROR,
5178 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5179 errmsg("cannot have multiple SET ACCESS METHOD subcommands")));
5180
5181 ATPrepSetAccessMethod(tab, rel, cmd->name);
5182 pass = AT_PASS_MISC; /* does not matter; no work in Phase 2 */
5183 break;
5184 case AT_SetTableSpace: /* SET TABLESPACE */
5185 ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE |
5186 ATT_MATVIEW | ATT_INDEX | ATT_PARTITIONED_INDEX);
5187 /* This command never recurses */
5188 ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
5189 pass = AT_PASS_MISC; /* doesn't actually matter */
5190 break;
5191 case AT_SetRelOptions: /* SET (...) */
5192 case AT_ResetRelOptions: /* RESET (...) */
5193 case AT_ReplaceRelOptions: /* reset them all, then set just these */
5194 ATSimplePermissions(cmd->subtype, rel,
5195 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5196 ATT_MATVIEW | ATT_INDEX);
5197 /* This command never recurses */
5198 /* No command-specific prep needed */
5199 pass = AT_PASS_MISC;
5200 break;
5201 case AT_AddInherit: /* INHERIT */
5202 ATSimplePermissions(cmd->subtype, rel,
5203 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5204 /* This command never recurses */
5205 ATPrepAddInherit(rel);
5206 pass = AT_PASS_MISC;
5207 break;
5208 case AT_DropInherit: /* NO INHERIT */
5209 ATSimplePermissions(cmd->subtype, rel,
5210 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5211 /* This command never recurses */
5212 /* No command-specific prep needed */
5213 pass = AT_PASS_MISC;
5214 break;
5215 case AT_AlterConstraint: /* ALTER CONSTRAINT */
5216 ATSimplePermissions(cmd->subtype, rel,
5217 ATT_TABLE | ATT_PARTITIONED_TABLE);
5218 /* Recursion occurs during execution phase */
5219 if (recurse)
5220 cmd->recurse = true;
5221 pass = AT_PASS_MISC;
5222 break;
5223 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5224 ATSimplePermissions(cmd->subtype, rel,
5225 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5226 /* Recursion occurs during execution phase */
5227 /* No command-specific prep needed except saving recurse flag */
5228 if (recurse)
5229 cmd->recurse = true;
5230 pass = AT_PASS_MISC;
5231 break;
5232 case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
5233 ATSimplePermissions(cmd->subtype, rel,
5234 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5235 pass = AT_PASS_MISC;
5236 /* This command never recurses */
5237 /* No command-specific prep needed */
5238 break;
5239 case AT_EnableTrig: /* ENABLE TRIGGER variants */
5240 case AT_EnableAlwaysTrig:
5241 case AT_EnableReplicaTrig:
5242 case AT_EnableTrigAll:
5243 case AT_EnableTrigUser:
5244 case AT_DisableTrig: /* DISABLE TRIGGER variants */
5245 case AT_DisableTrigAll:
5246 case AT_DisableTrigUser:
5247 ATSimplePermissions(cmd->subtype, rel,
5248 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5249 /* Set up recursion for phase 2; no other prep needed */
5250 if (recurse)
5251 cmd->recurse = true;
5252 pass = AT_PASS_MISC;
5253 break;
5254 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
5255 case AT_EnableAlwaysRule:
5256 case AT_EnableReplicaRule:
5257 case AT_DisableRule:
5258 case AT_AddOf: /* OF */
5259 case AT_DropOf: /* NOT OF */
5260 case AT_EnableRowSecurity:
5261 case AT_DisableRowSecurity:
5262 case AT_ForceRowSecurity:
5263 case AT_NoForceRowSecurity:
5264 ATSimplePermissions(cmd->subtype, rel,
5265 ATT_TABLE | ATT_PARTITIONED_TABLE);
5266 /* These commands never recurse */
5267 /* No command-specific prep needed */
5268 pass = AT_PASS_MISC;
5269 break;
5270 case AT_GenericOptions:
5271 ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5272 /* No command-specific prep needed */
5273 pass = AT_PASS_MISC;
5274 break;
5275 case AT_AttachPartition:
5276 ATSimplePermissions(cmd->subtype, rel,
5277 ATT_PARTITIONED_TABLE | ATT_PARTITIONED_INDEX);
5278 /* No command-specific prep needed */
5279 pass = AT_PASS_MISC;
5280 break;
5281 case AT_DetachPartition:
5282 ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5283 /* No command-specific prep needed */
5284 pass = AT_PASS_MISC;
5285 break;
5286 case AT_DetachPartitionFinalize:
5287 ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5288 /* No command-specific prep needed */
5289 pass = AT_PASS_MISC;
5290 break;
5291 default: /* oops */
5292 elog(ERROR, "unrecognized alter table type: %d",
5293 (int) cmd->subtype);
5294 pass = AT_PASS_UNSET; /* keep compiler quiet */
5295 break;
5296 }
5297 Assert(pass > AT_PASS_UNSET);
5298
5299 /* Add the subcommand to the appropriate list for phase 2 */
5300 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
5301 }
5302
5303 /*
5304 * ATRewriteCatalogs
5305 *
5306 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
5307 * dispatched in a "safe" execution order (designed to avoid unnecessary
5308 * conflicts).
5309 */
5310 static void
5311 ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
5312 AlterTableUtilityContext *context)
5313 {
5314 ListCell *ltab;
5315
5316 /*
5317 * We process all the tables "in parallel", one pass at a time. This is
5318 * needed because we may have to propagate work from one table to another
5319 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
5320 * re-adding of the foreign key constraint to the other table). Work can
5321 * only be propagated into later passes, however.
5322 */
5323 for (AlterTablePass pass = 0; pass < AT_NUM_PASSES; pass++)
5324 {
5325 /* Go through each table that needs to be processed */
5326 foreach(ltab, *wqueue)
5327 {
5328 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5329 List *subcmds = tab->subcmds[pass];
5330 ListCell *lcmd;
5331
5332 if (subcmds == NIL)
5333 continue;
5334
5335 /*
5336 * Open the relation and store it in tab. This allows subroutines
5337 * close and reopen, if necessary. Appropriate lock was obtained
5338 * by phase 1, needn't get it again.
5339 */
5340 tab->rel = relation_open(tab->relid, NoLock);
5341
5342 foreach(lcmd, subcmds)
5343 ATExecCmd(wqueue, tab,
5344 lfirst_node(AlterTableCmd, lcmd),
5345 lockmode, pass, context);
5346
5347 /*
5348 * After the ALTER TYPE or SET EXPRESSION pass, do cleanup work
5349 * (this is not done in ATExecAlterColumnType since it should be
5350 * done only once if multiple columns of a table are altered).
5351 */
5352 if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
5353 ATPostAlterTypeCleanup(wqueue, tab, lockmode);
5354
5355 if (tab->rel)
5356 {
5357 relation_close(tab->rel, NoLock);
5358 tab->rel = NULL;
5359 }
5360 }
5361 }
5362
5363 /* Check to see if a toast table must be added. */
5364 foreach(ltab, *wqueue)
5365 {
5366 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5367
5368 /*
5369 * If the table is source table of ATTACH PARTITION command, we did
5370 * not modify anything about it that will change its toasting
5371 * requirement, so no need to check.
5372 */
5373 if (((tab->relkind == RELKIND_RELATION ||
5374 tab->relkind == RELKIND_PARTITIONED_TABLE) &&
5375 tab->partition_constraint == NULL) ||
5376 tab->relkind == RELKIND_MATVIEW)
5377 AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
5378 }
5379 }
5380
5381 /*
5382 * ATExecCmd: dispatch a subcommand to appropriate execution routine
5383 */
5384 static void
5385 ATExecCmd(List **wqueue, AlteredTableInfo *tab,
5386 AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
5387 AlterTableUtilityContext *context)
5388 {
5389 ObjectAddress address = InvalidObjectAddress;
5390 Relation rel = tab->rel;
5391
5392 switch (cmd->subtype)
5393 {
5394 case AT_AddColumn: /* ADD COLUMN */
5395 case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5396 address = ATExecAddColumn(wqueue, tab, rel, &cmd,
5397 cmd->recurse, false,
5398 lockmode, cur_pass, context);
5399 break;
5400 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5401 address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
5402 break;
5403 case AT_CookedColumnDefault: /* add a pre-cooked default */
5404 address = ATExecCookedColumnDefault(rel, cmd->num, cmd->def);
5405 break;
5406 case AT_AddIdentity:
5407 cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5408 cur_pass, context);
5409 Assert(cmd != NULL);
5410 address = ATExecAddIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5411 break;
5412 case AT_SetIdentity:
5413 cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5414 cur_pass, context);
5415 Assert(cmd != NULL);
5416 address = ATExecSetIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5417 break;
5418 case AT_DropIdentity:
5419 address = ATExecDropIdentity(rel, cmd->name, cmd->missing_ok, lockmode, cmd->recurse, false);
5420 break;
5421 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5422 address = ATExecDropNotNull(rel, cmd->name, cmd->recurse, lockmode);
5423 break;
5424 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5425 address = ATExecSetNotNull(wqueue, rel, NULL, cmd->name,
5426 cmd->recurse, false, lockmode);
5427 break;
5428 case AT_SetExpression:
5429 address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode);
5430 break;
5431 case AT_DropExpression:
5432 address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode);
5433 break;
5434 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5435 address = ATExecSetStatistics(rel, cmd->name, cmd->num, cmd->def, lockmode);
5436 break;
5437 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5438 address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
5439 break;
5440 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5441 address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
5442 break;
5443 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5444 address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
5445 break;
5446 case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5447 address = ATExecSetCompression(rel, cmd->name, cmd->def,
5448 lockmode);
5449 break;
5450 case AT_DropColumn: /* DROP COLUMN */
5451 address = ATExecDropColumn(wqueue, rel, cmd->name,
5452 cmd->behavior, cmd->recurse, false,
5453 cmd->missing_ok, lockmode,
5454 NULL);
5455 break;
5456 case AT_AddIndex: /* ADD INDEX */
5457 address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
5458 lockmode);
5459 break;
5460 case AT_ReAddIndex: /* ADD INDEX */
5461 address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
5462 lockmode);
5463 break;
5464 case AT_ReAddStatistics: /* ADD STATISTICS */
5465 address = ATExecAddStatistics(tab, rel, (CreateStatsStmt *) cmd->def,
5466 true, lockmode);
5467 break;
5468 case AT_AddConstraint: /* ADD CONSTRAINT */
5469 /* Transform the command only during initial examination */
5470 if (cur_pass == AT_PASS_ADD_CONSTR)
5471 cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
5472 cmd->recurse, lockmode,
5473 cur_pass, context);
5474 /* Depending on constraint type, might be no more work to do now */
5475 if (cmd != NULL)
5476 address =
5477 ATExecAddConstraint(wqueue, tab, rel,
5478 (Constraint *) cmd->def,
5479 cmd->recurse, false, lockmode);
5480 break;
5481 case AT_ReAddConstraint: /* Re-add pre-existing check constraint */
5482 address =
5483 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
5484 true, true, lockmode);
5485 break;
5486 case AT_ReAddDomainConstraint: /* Re-add pre-existing domain check
5487 * constraint */
5488 address =
5489 AlterDomainAddConstraint(((AlterDomainStmt *) cmd->def)->typeName,
5490 ((AlterDomainStmt *) cmd->def)->def,
5491 NULL, true);
5492 break;
5493 case AT_ReAddComment: /* Re-add existing comment */
5494 address = CommentObject((CommentStmt *) cmd->def);
5495 break;
5496 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5497 address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
5498 lockmode);
5499 break;
5500 case AT_AlterConstraint: /* ALTER CONSTRAINT */
5501 address = ATExecAlterConstraint(wqueue, rel,
5502 castNode(ATAlterConstraint, cmd->def),
5503 cmd->recurse, lockmode);
5504 break;
5505 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5506 address = ATExecValidateConstraint(wqueue, rel, cmd->name, cmd->recurse,
5507 false, lockmode);
5508 break;
5509 case AT_DropConstraint: /* DROP CONSTRAINT */
5510 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
5511 cmd->recurse,
5512 cmd->missing_ok, lockmode);
5513 break;
5514 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5515 /* parse transformation was done earlier */
5516 address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
5517 break;
5518 case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
5519 address =
5520 ATExecAlterColumnGenericOptions(rel, cmd->name,
5521 (List *) cmd->def, lockmode);
5522 break;
5523 case AT_ChangeOwner: /* ALTER OWNER */
5524 ATExecChangeOwner(RelationGetRelid(rel),
5525 get_rolespec_oid(cmd->newowner, false),
5526 false, lockmode);
5527 break;
5528 case AT_ClusterOn: /* CLUSTER ON */
5529 address = ATExecClusterOn(rel, cmd->name, lockmode);
5530 break;
5531 case AT_DropCluster: /* SET WITHOUT CLUSTER */
5532 ATExecDropCluster(rel, lockmode);
5533 break;
5534 case AT_SetLogged: /* SET LOGGED */
5535 case AT_SetUnLogged: /* SET UNLOGGED */
5536 break;
5537 case AT_DropOids: /* SET WITHOUT OIDS */
5538 /* nothing to do here, oid columns don't exist anymore */
5539 break;
5540 case AT_SetAccessMethod: /* SET ACCESS METHOD */
5541
5542 /*
5543 * Only do this for partitioned tables, for which this is just a
5544 * catalog change. Tables with storage are handled by Phase 3.
5545 */
5546 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
5547 tab->chgAccessMethod)
5548 ATExecSetAccessMethodNoStorage(rel, tab->newAccessMethod);
5549 break;
5550 case AT_SetTableSpace: /* SET TABLESPACE */
5551
5552 /*
5553 * Only do this for partitioned tables and indexes, for which this
5554 * is just a catalog change. Other relation types which have
5555 * storage are handled by Phase 3.
5556 */
5557 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
5558 rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
5559 ATExecSetTableSpaceNoStorage(rel, tab->newTableSpace);
5560
5561 break;
5562 case AT_SetRelOptions: /* SET (...) */
5563 case AT_ResetRelOptions: /* RESET (...) */
5564 case AT_ReplaceRelOptions: /* replace entire option list */
5565 ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
5566 break;
5567 case AT_EnableTrig: /* ENABLE TRIGGER name */
5568 ATExecEnableDisableTrigger(rel, cmd->name,
5569 TRIGGER_FIRES_ON_ORIGIN, false,
5570 cmd->recurse,
5571 lockmode);
5572 break;
5573 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
5574 ATExecEnableDisableTrigger(rel, cmd->name,
5575 TRIGGER_FIRES_ALWAYS, false,
5576 cmd->recurse,
5577 lockmode);
5578 break;
5579 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
5580 ATExecEnableDisableTrigger(rel, cmd->name,
5581 TRIGGER_FIRES_ON_REPLICA, false,
5582 cmd->recurse,
5583 lockmode);
5584 break;
5585 case AT_DisableTrig: /* DISABLE TRIGGER name */
5586 ATExecEnableDisableTrigger(rel, cmd->name,
5587 TRIGGER_DISABLED, false,
5588 cmd->recurse,
5589 lockmode);
5590 break;
5591 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
5592 ATExecEnableDisableTrigger(rel, NULL,
5593 TRIGGER_FIRES_ON_ORIGIN, false,
5594 cmd->recurse,
5595 lockmode);
5596 break;
5597 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
5598 ATExecEnableDisableTrigger(rel, NULL,
5599 TRIGGER_DISABLED, false,
5600 cmd->recurse,
5601 lockmode);
5602 break;
5603 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
5604 ATExecEnableDisableTrigger(rel, NULL,
5605 TRIGGER_FIRES_ON_ORIGIN, true,
5606 cmd->recurse,
5607 lockmode);
5608 break;
5609 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
5610 ATExecEnableDisableTrigger(rel, NULL,
5611 TRIGGER_DISABLED, true,
5612 cmd->recurse,
5613 lockmode);
5614 break;
5615
5616 case AT_EnableRule: /* ENABLE RULE name */
5617 ATExecEnableDisableRule(rel, cmd->name,
5618 RULE_FIRES_ON_ORIGIN, lockmode);
5619 break;
5620 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
5621 ATExecEnableDisableRule(rel, cmd->name,
5622 RULE_FIRES_ALWAYS, lockmode);
5623 break;
5624 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
5625 ATExecEnableDisableRule(rel, cmd->name,
5626 RULE_FIRES_ON_REPLICA, lockmode);
5627 break;
5628 case AT_DisableRule: /* DISABLE RULE name */
5629 ATExecEnableDisableRule(rel, cmd->name,
5630 RULE_DISABLED, lockmode);
5631 break;
5632
5633 case AT_AddInherit:
5634 address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
5635 break;
5636 case AT_DropInherit:
5637 address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
5638 break;
5639 case AT_AddOf:
5640 address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
5641 break;
5642 case AT_DropOf:
5643 ATExecDropOf(rel, lockmode);
5644 break;
5645 case AT_ReplicaIdentity:
5646 ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
5647 break;
5648 case AT_EnableRowSecurity:
5649 ATExecSetRowSecurity(rel, true);
5650 break;
5651 case AT_DisableRowSecurity:
5652 ATExecSetRowSecurity(rel, false);
5653 break;
5654 case AT_ForceRowSecurity:
5655 ATExecForceNoForceRowSecurity(rel, true);
5656 break;
5657 case AT_NoForceRowSecurity:
5658 ATExecForceNoForceRowSecurity(rel, false);
5659 break;
5660 case AT_GenericOptions:
5661 ATExecGenericOptions(rel, (List *) cmd->def);
5662 break;
5663 case AT_AttachPartition:
5664 cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5665 cur_pass, context);
5666 Assert(cmd != NULL);
5667 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5668 address = ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
5669 context);
5670 else
5671 address = ATExecAttachPartitionIdx(wqueue, rel,
5672 ((PartitionCmd *) cmd->def)->name);
5673 break;
5674 case AT_DetachPartition:
5675 cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5676 cur_pass, context);
5677 Assert(cmd != NULL);
5678 /* ATPrepCmd ensures it must be a table */
5679 Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
5680 address = ATExecDetachPartition(wqueue, tab, rel,
5681 ((PartitionCmd *) cmd->def)->name,
5682 ((PartitionCmd *) cmd->def)->concurrent);
5683 break;
5684 case AT_DetachPartitionFinalize:
5685 address = ATExecDetachPartitionFinalize(rel, ((PartitionCmd *) cmd->def)->name);
5686 break;
5687 default: /* oops */
5688 elog(ERROR, "unrecognized alter table type: %d",
5689 (int) cmd->subtype);
5690 break;
5691 }
5692
5693 /*
5694 * Report the subcommand to interested event triggers.
5695 */
5696 if (cmd)
5697 EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
5698
5699 /*
5700 * Bump the command counter to ensure the next subcommand in the sequence
5701 * can see the changes so far
5702 */
5703 CommandCounterIncrement();
5704 }
5705
5706 /*
5707 * ATParseTransformCmd: perform parse transformation for one subcommand
5708 *
5709 * Returns the transformed subcommand tree, if there is one, else NULL.
5710 *
5711 * The parser may hand back additional AlterTableCmd(s) and/or other
5712 * utility statements, either before or after the original subcommand.
5713 * Other AlterTableCmds are scheduled into the appropriate slot of the
5714 * AlteredTableInfo (they had better be for later passes than the current one).
5715 * Utility statements that are supposed to happen before the AlterTableCmd
5716 * are executed immediately. Those that are supposed to happen afterwards
5717 * are added to the tab->afterStmts list to be done at the very end.
5718 */
5719 static AlterTableCmd *
5720 ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
5721 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
5722 AlterTablePass cur_pass, AlterTableUtilityContext *context)
5723 {
5724 AlterTableCmd *newcmd = NULL;
5725 AlterTableStmt *atstmt = makeNode(AlterTableStmt);
5726 List *beforeStmts;
5727 List *afterStmts;
5728 ListCell *lc;
5729
5730 /* Gin up an AlterTableStmt with just this subcommand and this table */
5731 atstmt->relation =
5732 makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5733 pstrdup(RelationGetRelationName(rel)),
5734 -1);
5735 atstmt->relation->inh = recurse;
5736 atstmt->cmds = list_make1(cmd);
5737 atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
5738 atstmt->missing_ok = false;
5739
5740 /* Transform the AlterTableStmt */
5741 atstmt = transformAlterTableStmt(RelationGetRelid(rel),
5742 atstmt,
5743 context->queryString,
5744 &beforeStmts,
5745 &afterStmts);
5746
5747 /* Execute any statements that should happen before these subcommand(s) */
5748 foreach(lc, beforeStmts)
5749 {
5750 Node *stmt = (Node *) lfirst(lc);
5751
5752 ProcessUtilityForAlterTable(stmt, context);
5753 CommandCounterIncrement();
5754 }
5755
5756 /* Examine the transformed subcommands and schedule them appropriately */
5757 foreach(lc, atstmt->cmds)
5758 {
5759 AlterTableCmd *cmd2 = lfirst_node(AlterTableCmd, lc);
5760 AlterTablePass pass;
5761
5762 /*
5763 * This switch need only cover the subcommand types that can be added
5764 * by parse_utilcmd.c; otherwise, we'll use the default strategy of
5765 * executing the subcommand immediately, as a substitute for the
5766 * original subcommand. (Note, however, that this does cause
5767 * AT_AddConstraint subcommands to be rescheduled into later passes,
5768 * which is important for index and foreign key constraints.)
5769 *
5770 * We assume we needn't do any phase-1 checks for added subcommands.
5771 */
5772 switch (cmd2->subtype)
5773 {
5774 case AT_AddIndex:
5775 pass = AT_PASS_ADD_INDEX;
5776 break;
5777 case AT_AddIndexConstraint:
5778 pass = AT_PASS_ADD_INDEXCONSTR;
5779 break;
5780 case AT_AddConstraint:
5781 /* Recursion occurs during execution phase */
5782 if (recurse)
5783 cmd2->recurse = true;
5784 switch (castNode(Constraint, cmd2->def)->contype)
5785 {
5786 case CONSTR_NOTNULL:
5787 pass = AT_PASS_COL_ATTRS;
5788 break;
5789 case CONSTR_PRIMARY:
5790 case CONSTR_UNIQUE:
5791 case CONSTR_EXCLUSION:
5792 pass = AT_PASS_ADD_INDEXCONSTR;
5793 break;
5794 default:
5795 pass = AT_PASS_ADD_OTHERCONSTR;
5796 break;
5797 }
5798 break;
5799 case AT_AlterColumnGenericOptions:
5800 /* This command never recurses */
5801 /* No command-specific prep needed */
5802 pass = AT_PASS_MISC;
5803 break;
5804 default:
5805 pass = cur_pass;
5806 break;
5807 }
5808
5809 if (pass < cur_pass)
5810 {
5811 /* Cannot schedule into a pass we already finished */
5812 elog(ERROR, "ALTER TABLE scheduling failure: too late for pass %d",
5813 pass);
5814 }
5815 else if (pass > cur_pass)
5816 {
5817 /* OK, queue it up for later */
5818 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd2);
5819 }
5820 else
5821 {
5822 /*
5823 * We should see at most one subcommand for the current pass,
5824 * which is the transformed version of the original subcommand.
5825 */
5826 if (newcmd == NULL && cmd->subtype == cmd2->subtype)
5827 {
5828 /* Found the transformed version of our subcommand */
5829 newcmd = cmd2;
5830 }
5831 else
5832 elog(ERROR, "ALTER TABLE scheduling failure: bogus item for pass %d",
5833 pass);
5834 }
5835 }
5836
5837 /* Queue up any after-statements to happen at the end */
5838 tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
5839
5840 return newcmd;
5841 }
5842
5843 /*
5844 * ATRewriteTables: ALTER TABLE phase 3
5845 */
5846 static void
5847 ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
5848 AlterTableUtilityContext *context)
5849 {
5850 ListCell *ltab;
5851
5852 /* Go through each table that needs to be checked or rewritten */
5853 foreach(ltab, *wqueue)
5854 {
5855 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5856
5857 /* Relations without storage may be ignored here */
5858 if (!RELKIND_HAS_STORAGE(tab->relkind))
5859 continue;
5860
5861 /*
5862 * If we change column data types, the operation has to be propagated
5863 * to tables that use this table's rowtype as a column type.
5864 * tab->newvals will also be non-NULL in the case where we're adding a
5865 * column with a default. We choose to forbid that case as well,
5866 * since composite types might eventually support defaults.
5867 *
5868 * (Eventually we'll probably need to check for composite type
5869 * dependencies even when we're just scanning the table without a
5870 * rewrite, but at the moment a composite type does not enforce any
5871 * constraints, so it's not necessary/appropriate to enforce them just
5872 * during ALTER.)
5873 */
5874 if (tab->newvals != NIL || tab->rewrite > 0)
5875 {
5876 Relation rel;
5877
5878 rel = table_open(tab->relid, NoLock);
5879 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
5880 table_close(rel, NoLock);
5881 }
5882
5883 /*
5884 * We only need to rewrite the table if at least one column needs to
5885 * be recomputed, or we are changing its persistence or access method.
5886 *
5887 * There are two reasons for requiring a rewrite when changing
5888 * persistence: on one hand, we need to ensure that the buffers
5889 * belonging to each of the two relations are marked with or without
5890 * BM_PERMANENT properly. On the other hand, since rewriting creates
5891 * and assigns a new relfilenumber, we automatically create or drop an
5892 * init fork for the relation as appropriate.
5893 */
5894 if (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE)
5895 {
5896 /* Build a temporary relation and copy data */
5897 Relation OldHeap;
5898 Oid OIDNewHeap;
5899 Oid NewAccessMethod;
5900 Oid NewTableSpace;
5901 char persistence;
5902
5903 OldHeap = table_open(tab->relid, NoLock);
5904
5905 /*
5906 * We don't support rewriting of system catalogs; there are too
5907 * many corner cases and too little benefit. In particular this
5908 * is certainly not going to work for mapped catalogs.
5909 */
5910 if (IsSystemRelation(OldHeap))
5911 ereport(ERROR,
5912 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5913 errmsg("cannot rewrite system relation \"%s\"",
5914 RelationGetRelationName(OldHeap))));
5915
5916 if (RelationIsUsedAsCatalogTable(OldHeap))
5917 ereport(ERROR,
5918 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5919 errmsg("cannot rewrite table \"%s\" used as a catalog table",
5920 RelationGetRelationName(OldHeap))));
5921
5922 /*
5923 * Don't allow rewrite on temp tables of other backends ... their
5924 * local buffer manager is not going to cope. (This is redundant
5925 * with the check in CheckAlterTableIsSafe, but for safety we'll
5926 * check here too.)
5927 */
5928 if (RELATION_IS_OTHER_TEMP(OldHeap))
5929 ereport(ERROR,
5930 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5931 errmsg("cannot rewrite temporary tables of other sessions")));
5932
5933 /*
5934 * Select destination tablespace (same as original unless user
5935 * requested a change)
5936 */
5937 if (tab->newTableSpace)
5938 NewTableSpace = tab->newTableSpace;
5939 else
5940 NewTableSpace = OldHeap->rd_rel->reltablespace;
5941
5942 /*
5943 * Select destination access method (same as original unless user
5944 * requested a change)
5945 */
5946 if (tab->chgAccessMethod)
5947 NewAccessMethod = tab->newAccessMethod;
5948 else
5949 NewAccessMethod = OldHeap->rd_rel->relam;
5950
5951 /*
5952 * Select persistence of transient table (same as original unless
5953 * user requested a change)
5954 */
5955 persistence = tab->chgPersistence ?
5956 tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
5957
5958 table_close(OldHeap, NoLock);
5959
5960 /*
5961 * Fire off an Event Trigger now, before actually rewriting the
5962 * table.
5963 *
5964 * We don't support Event Trigger for nested commands anywhere,
5965 * here included, and parsetree is given NULL when coming from
5966 * AlterTableInternal.
5967 *
5968 * And fire it only once.
5969 */
5970 if (parsetree)
5971 EventTriggerTableRewrite((Node *) parsetree,
5972 tab->relid,
5973 tab->rewrite);
5974
5975 /*
5976 * Create transient table that will receive the modified data.
5977 *
5978 * Ensure it is marked correctly as logged or unlogged. We have
5979 * to do this here so that buffers for the new relfilenumber will
5980 * have the right persistence set, and at the same time ensure
5981 * that the original filenumbers's buffers will get read in with
5982 * the correct setting (i.e. the original one). Otherwise a
5983 * rollback after the rewrite would possibly result with buffers
5984 * for the original filenumbers having the wrong persistence
5985 * setting.
5986 *
5987 * NB: This relies on swap_relation_files() also swapping the
5988 * persistence. That wouldn't work for pg_class, but that can't be
5989 * unlogged anyway.
5990 */
5991 OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, NewAccessMethod,
5992 persistence, lockmode);
5993
5994 /*
5995 * Copy the heap data into the new table with the desired
5996 * modifications, and test the current data within the table
5997 * against new constraints generated by ALTER TABLE commands.
5998 */
5999 ATRewriteTable(tab, OIDNewHeap);
6000
6001 /*
6002 * Swap the physical files of the old and new heaps, then rebuild
6003 * indexes and discard the old heap. We can use RecentXmin for
6004 * the table's new relfrozenxid because we rewrote all the tuples
6005 * in ATRewriteTable, so no older Xid remains in the table. Also,
6006 * we never try to swap toast tables by content, since we have no
6007 * interest in letting this code work on system catalogs.
6008 */
6009 finish_heap_swap(tab->relid, OIDNewHeap,
6010 false, false, true,
6011 !OidIsValid(tab->newTableSpace),
6012 RecentXmin,
6013 ReadNextMultiXactId(),
6014 persistence);
6015
6016 InvokeObjectPostAlterHook(RelationRelationId, tab->relid, 0);
6017 }
6018 else if (tab->rewrite > 0 && tab->relkind == RELKIND_SEQUENCE)
6019 {
6020 if (tab->chgPersistence)
6021 SequenceChangePersistence(tab->relid, tab->newrelpersistence);
6022 }
6023 else
6024 {
6025 /*
6026 * If required, test the current data within the table against new
6027 * constraints generated by ALTER TABLE commands, but don't
6028 * rebuild data.
6029 */
6030 if (tab->constraints != NIL || tab->verify_new_notnull ||
6031 tab->partition_constraint != NULL)
6032 ATRewriteTable(tab, InvalidOid);
6033
6034 /*
6035 * If we had SET TABLESPACE but no reason to reconstruct tuples,
6036 * just do a block-by-block copy.
6037 */
6038 if (tab->newTableSpace)
6039 ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
6040 }
6041
6042 /*
6043 * Also change persistence of owned sequences, so that it matches the
6044 * table persistence.
6045 */
6046 if (tab->chgPersistence)
6047 {
6048 List *seqlist = getOwnedSequences(tab->relid);
6049 ListCell *lc;
6050
6051 foreach(lc, seqlist)
6052 {
6053 Oid seq_relid = lfirst_oid(lc);
6054
6055 SequenceChangePersistence(seq_relid, tab->newrelpersistence);
6056 }
6057 }
6058 }
6059
6060 /*
6061 * Foreign key constraints are checked in a final pass, since (a) it's
6062 * generally best to examine each one separately, and (b) it's at least
6063 * theoretically possible that we have changed both relations of the
6064 * foreign key, and we'd better have finished both rewrites before we try
6065 * to read the tables.
6066 */
6067 foreach(ltab, *wqueue)
6068 {
6069 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6070 Relation rel = NULL;
6071 ListCell *lcon;
6072
6073 /* Relations without storage may be ignored here too */
6074 if (!RELKIND_HAS_STORAGE(tab->relkind))
6075 continue;
6076
6077 foreach(lcon, tab->constraints)
6078 {
6079 NewConstraint *con = lfirst(lcon);
6080
6081 if (con->contype == CONSTR_FOREIGN)
6082 {
6083 Constraint *fkconstraint = (Constraint *) con->qual;
6084 Relation refrel;
6085
6086 if (rel == NULL)
6087 {
6088 /* Long since locked, no need for another */
6089 rel = table_open(tab->relid, NoLock);
6090 }
6091
6092 refrel = table_open(con->refrelid, RowShareLock);
6093
6094 validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
6095 con->refindid,
6096 con->conid,
6097 con->conwithperiod);
6098
6099 /*
6100 * No need to mark the constraint row as validated, we did
6101 * that when we inserted the row earlier.
6102 */
6103
6104 table_close(refrel, NoLock);
6105 }
6106 }
6107
6108 if (rel)
6109 table_close(rel, NoLock);
6110 }
6111
6112 /* Finally, run any afterStmts that were queued up */
6113 foreach(ltab, *wqueue)
6114 {
6115 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6116 ListCell *lc;
6117
6118 foreach(lc, tab->afterStmts)
6119 {
6120 Node *stmt = (Node *) lfirst(lc);
6121
6122 ProcessUtilityForAlterTable(stmt, context);
6123 CommandCounterIncrement();
6124 }
6125 }
6126 }
6127
6128 /*
6129 * ATRewriteTable: scan or rewrite one table
6130 *
6131 * A rewrite is requested by passing a valid OIDNewHeap; in that case, caller
6132 * must already hold AccessExclusiveLock on it.
6133 */
6134 static void
6135 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
6136 {
6137 Relation oldrel;
6138 Relation newrel;
6139 TupleDesc oldTupDesc;
6140 TupleDesc newTupDesc;
6141 bool needscan = false;
6142 List *notnull_attrs;
6143 List *notnull_virtual_attrs;
6144 int i;
6145 ListCell *l;
6146 EState *estate;
6147 CommandId mycid;
6148 BulkInsertState bistate;
6149 int ti_options;
6150 ExprState *partqualstate = NULL;
6151
6152 /*
6153 * Open the relation(s). We have surely already locked the existing
6154 * table.
6155 */
6156 oldrel = table_open(tab->relid, NoLock);
6157 oldTupDesc = tab->oldDesc;
6158 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
6159
6160 if (OidIsValid(OIDNewHeap))
6161 {
6162 Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock,
6163 false));
6164 newrel = table_open(OIDNewHeap, NoLock);
6165 }
6166 else
6167 newrel = NULL;
6168
6169 /*
6170 * Prepare a BulkInsertState and options for table_tuple_insert. The FSM
6171 * is empty, so don't bother using it.
6172 */
6173 if (newrel)
6174 {
6175 mycid = GetCurrentCommandId(true);
6176 bistate = GetBulkInsertState();
6177 ti_options = TABLE_INSERT_SKIP_FSM;
6178 }
6179 else
6180 {
6181 /* keep compiler quiet about using these uninitialized */
6182 mycid = 0;
6183 bistate = NULL;
6184 ti_options = 0;
6185 }
6186
6187 /*
6188 * Generate the constraint and default execution states
6189 */
6190
6191 estate = CreateExecutorState();
6192
6193 /* Build the needed expression execution states */
6194 foreach(l, tab->constraints)
6195 {
6196 NewConstraint *con = lfirst(l);
6197
6198 switch (con->contype)
6199 {
6200 case CONSTR_CHECK:
6201 needscan = true;
6202 con->qualstate = ExecPrepareExpr((Expr *) expand_generated_columns_in_expr(con->qual, oldrel, 1), estate);
6203 break;
6204 case CONSTR_FOREIGN:
6205 /* Nothing to do here */
6206 break;
6207 default:
6208 elog(ERROR, "unrecognized constraint type: %d",
6209 (int) con->contype);
6210 }
6211 }
6212
6213 /* Build expression execution states for partition check quals */
6214 if (tab->partition_constraint)
6215 {
6216 needscan = true;
6217 partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
6218 }
6219
6220 foreach(l, tab->newvals)
6221 {
6222 NewColumnValue *ex = lfirst(l);
6223
6224 /* expr already planned */
6225 ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
6226 }
6227
6228 notnull_attrs = notnull_virtual_attrs = NIL;
6229 if (newrel || tab->verify_new_notnull)
6230 {
6231 /*
6232 * If we are rebuilding the tuples OR if we added any new but not
6233 * verified not-null constraints, check all *valid* not-null
6234 * constraints. This is a bit of overkill but it minimizes risk of
6235 * bugs.
6236 *
6237 * notnull_attrs does *not* collect attribute numbers for valid
6238 * not-null constraints over virtual generated columns; instead, they
6239 * are collected in notnull_virtual_attrs for verification elsewhere.
6240 */
6241 for (i = 0; i < newTupDesc->natts; i++)
6242 {
6243 CompactAttribute *attr = TupleDescCompactAttr(newTupDesc, i);
6244
6245 if (attr->attnullability == ATTNULLABLE_VALID &&
6246 !attr->attisdropped)
6247 {
6248 Form_pg_attribute wholeatt = TupleDescAttr(newTupDesc, i);
6249
6250 if (wholeatt->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL)
6251 notnull_attrs = lappend_int(notnull_attrs, wholeatt->attnum);
6252 else
6253 notnull_virtual_attrs = lappend_int(notnull_virtual_attrs,
6254 wholeatt->attnum);
6255 }
6256 }
6257 if (notnull_attrs || notnull_virtual_attrs)
6258 needscan = true;
6259 }
6260
6261 if (newrel || needscan)
6262 {
6263 ExprContext *econtext;
6264 TupleTableSlot *oldslot;
6265 TupleTableSlot *newslot;
6266 TableScanDesc scan;
6267 MemoryContext oldCxt;
6268 List *dropped_attrs = NIL;
6269 ListCell *lc;
6270 Snapshot snapshot;
6271 ResultRelInfo *rInfo = NULL;
6272
6273 /*
6274 * When adding or changing a virtual generated column with a not-null
6275 * constraint, we need to evaluate whether the generation expression
6276 * is null. For that, we borrow ExecRelGenVirtualNotNull(). Here, we
6277 * prepare a dummy ResultRelInfo.
6278 */
6279 if (notnull_virtual_attrs != NIL)
6280 {
6281 MemoryContext oldcontext;
6282
6283 Assert(newTupDesc->constr->has_generated_virtual);
6284 Assert(newTupDesc->constr->has_not_null);
6285 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
6286 rInfo = makeNode(ResultRelInfo);
6287 InitResultRelInfo(rInfo,
6288 oldrel,
6289 0, /* dummy rangetable index */
6290 NULL,
6291 estate->es_instrument);
6292 MemoryContextSwitchTo(oldcontext);
6293 }
6294
6295 if (newrel)
6296 ereport(DEBUG1,
6297 (errmsg_internal("rewriting table \"%s\"",
6298 RelationGetRelationName(oldrel))));
6299 else
6300 ereport(DEBUG1,
6301 (errmsg_internal("verifying table \"%s\"",
6302 RelationGetRelationName(oldrel))));
6303
6304 if (newrel)
6305 {
6306 /*
6307 * All predicate locks on the tuples or pages are about to be made
6308 * invalid, because we move tuples around. Promote them to
6309 * relation locks.
6310 */
6311 TransferPredicateLocksToHeapRelation(oldrel);
6312 }
6313
6314 econtext = GetPerTupleExprContext(estate);
6315
6316 /*
6317 * Create necessary tuple slots. When rewriting, two slots are needed,
6318 * otherwise one suffices. In the case where one slot suffices, we
6319 * need to use the new tuple descriptor, otherwise some constraints
6320 * can't be evaluated. Note that even when the tuple layout is the
6321 * same and no rewrite is required, the tupDescs might not be
6322 * (consider ADD COLUMN without a default).
6323 */
6324 if (tab->rewrite)
6325 {
6326 Assert(newrel != NULL);
6327 oldslot = MakeSingleTupleTableSlot(oldTupDesc,
6328 table_slot_callbacks(oldrel));
6329 newslot = MakeSingleTupleTableSlot(newTupDesc,
6330 table_slot_callbacks(newrel));
6331
6332 /*
6333 * Set all columns in the new slot to NULL initially, to ensure
6334 * columns added as part of the rewrite are initialized to NULL.
6335 * That is necessary as tab->newvals will not contain an
6336 * expression for columns with a NULL default, e.g. when adding a
6337 * column without a default together with a column with a default
6338 * requiring an actual rewrite.
6339 */
6340 ExecStoreAllNullTuple(newslot);
6341 }
6342 else
6343 {
6344 oldslot = MakeSingleTupleTableSlot(newTupDesc,
6345 table_slot_callbacks(oldrel));
6346 newslot = NULL;
6347 }
6348
6349 /*
6350 * Any attributes that are dropped according to the new tuple
6351 * descriptor can be set to NULL. We precompute the list of dropped
6352 * attributes to avoid needing to do so in the per-tuple loop.
6353 */
6354 for (i = 0; i < newTupDesc->natts; i++)
6355 {
6356 if (TupleDescAttr(newTupDesc, i)->attisdropped)
6357 dropped_attrs = lappend_int(dropped_attrs, i);
6358 }
6359
6360 /*
6361 * Scan through the rows, generating a new row if needed and then
6362 * checking all the constraints.
6363 */
6364 snapshot = RegisterSnapshot(GetLatestSnapshot());
6365 scan = table_beginscan(oldrel, snapshot, 0, NULL);
6366
6367 /*
6368 * Switch to per-tuple memory context and reset it for each tuple
6369 * produced, so we don't leak memory.
6370 */
6371 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
6372
6373 while (table_scan_getnextslot(scan, ForwardScanDirection, oldslot))
6374 {
6375 TupleTableSlot *insertslot;
6376
6377 if (tab->rewrite > 0)
6378 {
6379 /* Extract data from old tuple */
6380 slot_getallattrs(oldslot);
6381 ExecClearTuple(newslot);
6382
6383 /* copy attributes */
6384 memcpy(newslot->tts_values, oldslot->tts_values,
6385 sizeof(Datum) * oldslot->tts_nvalid);
6386 memcpy(newslot->tts_isnull, oldslot->tts_isnull,
6387 sizeof(bool) * oldslot->tts_nvalid);
6388
6389 /* Set dropped attributes to null in new tuple */
6390 foreach(lc, dropped_attrs)
6391 newslot->tts_isnull[lfirst_int(lc)] = true;
6392
6393 /*
6394 * Constraints and GENERATED expressions might reference the
6395 * tableoid column, so fill tts_tableOid with the desired
6396 * value. (We must do this each time, because it gets
6397 * overwritten with newrel's OID during storing.)
6398 */
6399 newslot->tts_tableOid = RelationGetRelid(oldrel);
6400
6401 /*
6402 * Process supplied expressions to replace selected columns.
6403 *
6404 * First, evaluate expressions whose inputs come from the old
6405 * tuple.
6406 */
6407 econtext->ecxt_scantuple = oldslot;
6408
6409 foreach(l, tab->newvals)
6410 {
6411 NewColumnValue *ex = lfirst(l);
6412
6413 if (ex->is_generated)
6414 continue;
6415
6416 newslot->tts_values[ex->attnum - 1]
6417 = ExecEvalExpr(ex->exprstate,
6418 econtext,
6419 &newslot->tts_isnull[ex->attnum - 1]);
6420 }
6421
6422 ExecStoreVirtualTuple(newslot);
6423
6424 /*
6425 * Now, evaluate any expressions whose inputs come from the
6426 * new tuple. We assume these columns won't reference each
6427 * other, so that there's no ordering dependency.
6428 */
6429 econtext->ecxt_scantuple = newslot;
6430
6431 foreach(l, tab->newvals)
6432 {
6433 NewColumnValue *ex = lfirst(l);
6434
6435 if (!ex->is_generated)
6436 continue;
6437
6438 newslot->tts_values[ex->attnum - 1]
6439 = ExecEvalExpr(ex->exprstate,
6440 econtext,
6441 &newslot->tts_isnull[ex->attnum - 1]);
6442 }
6443
6444 insertslot = newslot;
6445 }
6446 else
6447 {
6448 /*
6449 * If there's no rewrite, old and new table are guaranteed to
6450 * have the same AM, so we can just use the old slot to verify
6451 * new constraints etc.
6452 */
6453 insertslot = oldslot;
6454 }
6455
6456 /* Now check any constraints on the possibly-changed tuple */
6457 econtext->ecxt_scantuple = insertslot;
6458
6459 foreach_int(attn, notnull_attrs)
6460 {
6461 if (slot_attisnull(insertslot, attn))
6462 {
6463 Form_pg_attribute attr = TupleDescAttr(newTupDesc, attn - 1);
6464
6465 ereport(ERROR,
6466 (errcode(ERRCODE_NOT_NULL_VIOLATION),
6467 errmsg("column \"%s\" of relation \"%s\" contains null values",
6468 NameStr(attr->attname),
6469 RelationGetRelationName(oldrel)),
6470 errtablecol(oldrel, attn)));
6471 }
6472 }
6473
6474 if (notnull_virtual_attrs != NIL)
6475 {
6476 AttrNumber attnum;
6477
6478 attnum = ExecRelGenVirtualNotNull(rInfo, insertslot,
6479 estate,
6480 notnull_virtual_attrs);
6481 if (attnum != InvalidAttrNumber)
6482 {
6483 Form_pg_attribute attr = TupleDescAttr(newTupDesc, attnum - 1);
6484
6485 ereport(ERROR,
6486 errcode(ERRCODE_NOT_NULL_VIOLATION),
6487 errmsg("column \"%s\" of relation \"%s\" contains null values",
6488 NameStr(attr->attname),
6489 RelationGetRelationName(oldrel)),
6490 errtablecol(oldrel, attnum));
6491 }
6492 }
6493
6494 foreach(l, tab->constraints)
6495 {
6496 NewConstraint *con = lfirst(l);
6497
6498 switch (con->contype)
6499 {
6500 case CONSTR_CHECK:
6501 if (!ExecCheck(con->qualstate, econtext))
6502 ereport(ERROR,
6503 (errcode(ERRCODE_CHECK_VIOLATION),
6504 errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
6505 con->name,
6506 RelationGetRelationName(oldrel)),
6507 errtableconstraint(oldrel, con->name)));
6508 break;
6509 case CONSTR_NOTNULL:
6510 case CONSTR_FOREIGN:
6511 /* Nothing to do here */
6512 break;
6513 default:
6514 elog(ERROR, "unrecognized constraint type: %d",
6515 (int) con->contype);
6516 }
6517 }
6518
6519 if (partqualstate && !ExecCheck(partqualstate, econtext))
6520 {
6521 if (tab->validate_default)
6522 ereport(ERROR,
6523 (errcode(ERRCODE_CHECK_VIOLATION),
6524 errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
6525 RelationGetRelationName(oldrel)),
6526 errtable(oldrel)));
6527 else
6528 ereport(ERROR,
6529 (errcode(ERRCODE_CHECK_VIOLATION),
6530 errmsg("partition constraint of relation \"%s\" is violated by some row",
6531 RelationGetRelationName(oldrel)),
6532 errtable(oldrel)));
6533 }
6534
6535 /* Write the tuple out to the new relation */
6536 if (newrel)
6537 table_tuple_insert(newrel, insertslot, mycid,
6538 ti_options, bistate);
6539
6540 ResetExprContext(econtext);
6541
6542 CHECK_FOR_INTERRUPTS();
6543 }
6544
6545 MemoryContextSwitchTo(oldCxt);
6546 table_endscan(scan);
6547 UnregisterSnapshot(snapshot);
6548
6549 ExecDropSingleTupleTableSlot(oldslot);
6550 if (newslot)
6551 ExecDropSingleTupleTableSlot(newslot);
6552 }
6553
6554 FreeExecutorState(estate);
6555
6556 table_close(oldrel, NoLock);
6557 if (newrel)
6558 {
6559 FreeBulkInsertState(bistate);
6560
6561 table_finish_bulk_insert(newrel, ti_options);
6562
6563 table_close(newrel, NoLock);
6564 }
6565 }
6566
6567 /*
6568 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
6569 */
6570 static AlteredTableInfo *
6571 ATGetQueueEntry(List **wqueue, Relation rel)
6572 {
6573 Oid relid = RelationGetRelid(rel);
6574 AlteredTableInfo *tab;
6575 ListCell *ltab;
6576
6577 foreach(ltab, *wqueue)
6578 {
6579 tab = (AlteredTableInfo *) lfirst(ltab);
6580 if (tab->relid == relid)
6581 return tab;
6582 }
6583
6584 /*
6585 * Not there, so add it. Note that we make a copy of the relation's
6586 * existing descriptor before anything interesting can happen to it.
6587 */
6588 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
6589 tab->relid = relid;
6590 tab->rel = NULL; /* set later */
6591 tab->relkind = rel->rd_rel->relkind;
6592 tab->oldDesc = CreateTupleDescCopyConstr(RelationGetDescr(rel));
6593 tab->newAccessMethod = InvalidOid;
6594 tab->chgAccessMethod = false;
6595 tab->newTableSpace = InvalidOid;
6596 tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
6597 tab->chgPersistence = false;
6598
6599 *wqueue = lappend(*wqueue, tab);
6600
6601 return tab;
6602 }
6603
6604 static const char *
6605 alter_table_type_to_string(AlterTableType cmdtype)
6606 {
6607 switch (cmdtype)
6608 {
6609 case AT_AddColumn:
6610 case AT_AddColumnToView:
6611 return "ADD COLUMN";
6612 case AT_ColumnDefault:
6613 case AT_CookedColumnDefault:
6614 return "ALTER COLUMN ... SET DEFAULT";
6615 case AT_DropNotNull:
6616 return "ALTER COLUMN ... DROP NOT NULL";
6617 case AT_SetNotNull:
6618 return "ALTER COLUMN ... SET NOT NULL";
6619 case AT_SetExpression:
6620 return "ALTER COLUMN ... SET EXPRESSION";
6621 case AT_DropExpression:
6622 return "ALTER COLUMN ... DROP EXPRESSION";
6623 case AT_SetStatistics:
6624 return "ALTER COLUMN ... SET STATISTICS";
6625 case AT_SetOptions:
6626 return "ALTER COLUMN ... SET";
6627 case AT_ResetOptions:
6628 return "ALTER COLUMN ... RESET";
6629 case AT_SetStorage:
6630 return "ALTER COLUMN ... SET STORAGE";
6631 case AT_SetCompression:
6632 return "ALTER COLUMN ... SET COMPRESSION";
6633 case AT_DropColumn:
6634 return "DROP COLUMN";
6635 case AT_AddIndex:
6636 case AT_ReAddIndex:
6637 return NULL; /* not real grammar */
6638 case AT_AddConstraint:
6639 case AT_ReAddConstraint:
6640 case AT_ReAddDomainConstraint:
6641 case AT_AddIndexConstraint:
6642 return "ADD CONSTRAINT";
6643 case AT_AlterConstraint:
6644 return "ALTER CONSTRAINT";
6645 case AT_ValidateConstraint:
6646 return "VALIDATE CONSTRAINT";
6647 case AT_DropConstraint:
6648 return "DROP CONSTRAINT";
6649 case AT_ReAddComment:
6650 return NULL; /* not real grammar */
6651 case AT_AlterColumnType:
6652 return "ALTER COLUMN ... SET DATA TYPE";
6653 case AT_AlterColumnGenericOptions:
6654 return "ALTER COLUMN ... OPTIONS";
6655 case AT_ChangeOwner:
6656 return "OWNER TO";
6657 case AT_ClusterOn:
6658 return "CLUSTER ON";
6659 case AT_DropCluster:
6660 return "SET WITHOUT CLUSTER";
6661 case AT_SetAccessMethod:
6662 return "SET ACCESS METHOD";
6663 case AT_SetLogged:
6664 return "SET LOGGED";
6665 case AT_SetUnLogged:
6666 return "SET UNLOGGED";
6667 case AT_DropOids:
6668 return "SET WITHOUT OIDS";
6669 case AT_SetTableSpace:
6670 return "SET TABLESPACE";
6671 case AT_SetRelOptions:
6672 return "SET";
6673 case AT_ResetRelOptions:
6674 return "RESET";
6675 case AT_ReplaceRelOptions:
6676 return NULL; /* not real grammar */
6677 case AT_EnableTrig:
6678 return "ENABLE TRIGGER";
6679 case AT_EnableAlwaysTrig:
6680 return "ENABLE ALWAYS TRIGGER";
6681 case AT_EnableReplicaTrig:
6682 return "ENABLE REPLICA TRIGGER";
6683 case AT_DisableTrig:
6684 return "DISABLE TRIGGER";
6685 case AT_EnableTrigAll:
6686 return "ENABLE TRIGGER ALL";
6687 case AT_DisableTrigAll:
6688 return "DISABLE TRIGGER ALL";
6689 case AT_EnableTrigUser:
6690 return "ENABLE TRIGGER USER";
6691 case AT_DisableTrigUser:
6692 return "DISABLE TRIGGER USER";
6693 case AT_EnableRule:
6694 return "ENABLE RULE";
6695 case AT_EnableAlwaysRule:
6696 return "ENABLE ALWAYS RULE";
6697 case AT_EnableReplicaRule:
6698 return "ENABLE REPLICA RULE";
6699 case AT_DisableRule:
6700 return "DISABLE RULE";
6701 case AT_AddInherit:
6702 return "INHERIT";
6703 case AT_DropInherit:
6704 return "NO INHERIT";
6705 case AT_AddOf:
6706 return "OF";
6707 case AT_DropOf:
6708 return "NOT OF";
6709 case AT_ReplicaIdentity:
6710 return "REPLICA IDENTITY";
6711 case AT_EnableRowSecurity:
6712 return "ENABLE ROW SECURITY";
6713 case AT_DisableRowSecurity:
6714 return "DISABLE ROW SECURITY";
6715 case AT_ForceRowSecurity:
6716 return "FORCE ROW SECURITY";
6717 case AT_NoForceRowSecurity:
6718 return "NO FORCE ROW SECURITY";
6719 case AT_GenericOptions:
6720 return "OPTIONS";
6721 case AT_AttachPartition:
6722 return "ATTACH PARTITION";
6723 case AT_DetachPartition:
6724 return "DETACH PARTITION";
6725 case AT_DetachPartitionFinalize:
6726 return "DETACH PARTITION ... FINALIZE";
6727 case AT_AddIdentity:
6728 return "ALTER COLUMN ... ADD IDENTITY";
6729 case AT_SetIdentity:
6730 return "ALTER COLUMN ... SET";
6731 case AT_DropIdentity:
6732 return "ALTER COLUMN ... DROP IDENTITY";
6733 case AT_ReAddStatistics:
6734 return NULL; /* not real grammar */
6735 }
6736
6737 return NULL;
6738 }
6739
6740 /*
6741 * ATSimplePermissions
6742 *
6743 * - Ensure that it is a relation (or possibly a view)
6744 * - Ensure this user is the owner
6745 * - Ensure that it is not a system table
6746 */
6747 static void
6748 ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
6749 {
6750 int actual_target;
6751
6752 switch (rel->rd_rel->relkind)
6753 {
6754 case RELKIND_RELATION:
6755 actual_target = ATT_TABLE;
6756 break;
6757 case RELKIND_PARTITIONED_TABLE:
6758 actual_target = ATT_PARTITIONED_TABLE;
6759 break;
6760 case RELKIND_VIEW:
6761 actual_target = ATT_VIEW;
6762 break;
6763 case RELKIND_MATVIEW:
6764 actual_target = ATT_MATVIEW;
6765 break;
6766 case RELKIND_INDEX:
6767 actual_target = ATT_INDEX;
6768 break;
6769 case RELKIND_PARTITIONED_INDEX:
6770 actual_target = ATT_PARTITIONED_INDEX;
6771 break;
6772 case RELKIND_COMPOSITE_TYPE:
6773 actual_target = ATT_COMPOSITE_TYPE;
6774 break;
6775 case RELKIND_FOREIGN_TABLE:
6776 actual_target = ATT_FOREIGN_TABLE;
6777 break;
6778 case RELKIND_SEQUENCE:
6779 actual_target = ATT_SEQUENCE;
6780 break;
6781 default:
6782 actual_target = 0;
6783 break;
6784 }
6785
6786 /* Wrong target type? */
6787 if ((actual_target & allowed_targets) == 0)
6788 {
6789 const char *action_str = alter_table_type_to_string(cmdtype);
6790
6791 if (action_str)
6792 ereport(ERROR,
6793 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6794 /* translator: %s is a group of some SQL keywords */
6795 errmsg("ALTER action %s cannot be performed on relation \"%s\"",
6796 action_str, RelationGetRelationName(rel)),
6797 errdetail_relkind_not_supported(rel->rd_rel->relkind)));
6798 else
6799 /* internal error? */
6800 elog(ERROR, "invalid ALTER action attempted on relation \"%s\"",
6801 RelationGetRelationName(rel));
6802 }
6803
6804 /* Permissions checks */
6805 if (!object_ownercheck(RelationRelationId, RelationGetRelid(rel), GetUserId()))
6806 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
6807 RelationGetRelationName(rel));
6808
6809 if (!allowSystemTableMods && IsSystemRelation(rel))
6810 ereport(ERROR,
6811 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6812 errmsg("permission denied: \"%s\" is a system catalog",
6813 RelationGetRelationName(rel))));
6814 }
6815
6816 /*
6817 * ATSimpleRecursion
6818 *
6819 * Simple table recursion sufficient for most ALTER TABLE operations.
6820 * All direct and indirect children are processed in an unspecified order.
6821 * Note that if a child inherits from the original table via multiple
6822 * inheritance paths, it will be visited just once.
6823 */
6824 static void
6825 ATSimpleRecursion(List **wqueue, Relation rel,
6826 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
6827 AlterTableUtilityContext *context)
6828 {
6829 /*
6830 * Propagate to children, if desired and if there are (or might be) any
6831 * children.
6832 */
6833 if (recurse && rel->rd_rel->relhassubclass)
6834 {
6835 Oid relid = RelationGetRelid(rel);
6836 ListCell *child;
6837 List *children;
6838
6839 children = find_all_inheritors(relid, lockmode, NULL);
6840
6841 /*
6842 * find_all_inheritors does the recursive search of the inheritance
6843 * hierarchy, so all we have to do is process all of the relids in the
6844 * list that it returns.
6845 */
6846 foreach(child, children)
6847 {
6848 Oid childrelid = lfirst_oid(child);
6849 Relation childrel;
6850
6851 if (childrelid == relid)
6852 continue;
6853 /* find_all_inheritors already got lock */
6854 childrel = relation_open(childrelid, NoLock);
6855 CheckAlterTableIsSafe(childrel);
6856 ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
6857 relation_close(childrel, NoLock);
6858 }
6859 }
6860 }
6861
6862 /*
6863 * Obtain list of partitions of the given table, locking them all at the given
6864 * lockmode and ensuring that they all pass CheckAlterTableIsSafe.
6865 *
6866 * This function is a no-op if the given relation is not a partitioned table;
6867 * in particular, nothing is done if it's a legacy inheritance parent.
6868 */
6869 static void
6870 ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode)
6871 {
6872 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6873 {
6874 List *inh;
6875 ListCell *cell;
6876
6877 inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
6878 /* first element is the parent rel; must ignore it */
6879 for_each_from(cell, inh, 1)
6880 {
6881 Relation childrel;
6882
6883 /* find_all_inheritors already got lock */
6884 childrel = table_open(lfirst_oid(cell), NoLock);
6885 CheckAlterTableIsSafe(childrel);
6886 table_close(childrel, NoLock);
6887 }
6888 list_free(inh);
6889 }
6890 }
6891
6892 /*
6893 * ATTypedTableRecursion
6894 *
6895 * Propagate ALTER TYPE operations to the typed tables of that type.
6896 * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
6897 * recursion to inheritance children of the typed tables.
6898 */
6899 static void
6900 ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
6901 LOCKMODE lockmode, AlterTableUtilityContext *context)
6902 {
6903 ListCell *child;
6904 List *children;
6905
6906 Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6907
6908 children = find_typed_table_dependencies(rel->rd_rel->reltype,
6909 RelationGetRelationName(rel),
6910 cmd->behavior);
6911
6912 foreach(child, children)
6913 {
6914 Oid childrelid = lfirst_oid(child);
6915 Relation childrel;
6916
6917 childrel = relation_open(childrelid, lockmode);
6918 CheckAlterTableIsSafe(childrel);
6919 ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode, context);
6920 relation_close(childrel, NoLock);
6921 }
6922 }
6923
6924
6925 /*
6926 * find_composite_type_dependencies
6927 *
6928 * Check to see if the type "typeOid" is being used as a column in some table
6929 * (possibly nested several levels deep in composite types, arrays, etc!).
6930 * Eventually, we'd like to propagate the check or rewrite operation
6931 * into such tables, but for now, just error out if we find any.
6932 *
6933 * Caller should provide either the associated relation of a rowtype,
6934 * or a type name (not both) for use in the error message, if any.
6935 *
6936 * Note that "typeOid" is not necessarily a composite type; it could also be
6937 * another container type such as an array or range, or a domain over one of
6938 * these things. The name of this function is therefore somewhat historical,
6939 * but it's not worth changing.
6940 *
6941 * We assume that functions and views depending on the type are not reasons
6942 * to reject the ALTER. (How safe is this really?)
6943 */
6944 void
6945 find_composite_type_dependencies(Oid typeOid, Relation origRelation,
6946 const char *origTypeName)
6947 {
6948 Relation depRel;
6949 ScanKeyData key[2];
6950 SysScanDesc depScan;
6951 HeapTuple depTup;
6952
6953 /* since this function recurses, it could be driven to stack overflow */
6954 check_stack_depth();
6955
6956 /*
6957 * We scan pg_depend to find those things that depend on the given type.
6958 * (We assume we can ignore refobjsubid for a type.)
6959 */
6960 depRel = table_open(DependRelationId, AccessShareLock);
6961
6962 ScanKeyInit(&key[0],
6963 Anum_pg_depend_refclassid,
6964 BTEqualStrategyNumber, F_OIDEQ,
6965 ObjectIdGetDatum(TypeRelationId));
6966 ScanKeyInit(&key[1],
6967 Anum_pg_depend_refobjid,
6968 BTEqualStrategyNumber, F_OIDEQ,
6969 ObjectIdGetDatum(typeOid));
6970
6971 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
6972 NULL, 2, key);
6973
6974 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
6975 {
6976 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
6977 Relation rel;
6978 TupleDesc tupleDesc;
6979 Form_pg_attribute att;
6980
6981 /* Check for directly dependent types */
6982 if (pg_depend->classid == TypeRelationId)
6983 {
6984 /*
6985 * This must be an array, domain, or range containing the given
6986 * type, so recursively check for uses of this type. Note that
6987 * any error message will mention the original type not the
6988 * container; this is intentional.
6989 */
6990 find_composite_type_dependencies(pg_depend->objid,
6991 origRelation, origTypeName);
6992 continue;
6993 }
6994
6995 /* Else, ignore dependees that aren't relations */
6996 if (pg_depend->classid != RelationRelationId)
6997 continue;
6998
6999 rel = relation_open(pg_depend->objid, AccessShareLock);
7000 tupleDesc = RelationGetDescr(rel);
7001
7002 /*
7003 * If objsubid identifies a specific column, refer to that in error
7004 * messages. Otherwise, search to see if there's a user column of the
7005 * type. (We assume system columns are never of interesting types.)
7006 * The search is needed because an index containing an expression
7007 * column of the target type will just be recorded as a whole-relation
7008 * dependency. If we do not find a column of the type, the dependency
7009 * must indicate that the type is transiently referenced in an index
7010 * expression but not stored on disk, which we assume is OK, just as
7011 * we do for references in views. (It could also be that the target
7012 * type is embedded in some container type that is stored in an index
7013 * column, but the previous recursion should catch such cases.)
7014 */
7015 if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
7016 att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
7017 else
7018 {
7019 att = NULL;
7020 for (int attno = 1; attno <= tupleDesc->natts; attno++)
7021 {
7022 att = TupleDescAttr(tupleDesc, attno - 1);
7023 if (att->atttypid == typeOid && !att->attisdropped)
7024 break;
7025 att = NULL;
7026 }
7027 if (att == NULL)
7028 {
7029 /* No such column, so assume OK */
7030 relation_close(rel, AccessShareLock);
7031 continue;
7032 }
7033 }
7034
7035 /*
7036 * We definitely should reject if the relation has storage. If it's
7037 * partitioned, then perhaps we don't have to reject: if there are
7038 * partitions then we'll fail when we find one, else there is no
7039 * stored data to worry about. However, it's possible that the type
7040 * change would affect conclusions about whether the type is sortable
7041 * or hashable and thus (if it's a partitioning column) break the
7042 * partitioning rule. For now, reject for partitioned rels too.
7043 */
7044 if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
7045 RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
7046 {
7047 if (origTypeName)
7048 ereport(ERROR,
7049 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7050 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7051 origTypeName,
7052 RelationGetRelationName(rel),
7053 NameStr(att->attname))));
7054 else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7055 ereport(ERROR,
7056 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7057 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7058 RelationGetRelationName(origRelation),
7059 RelationGetRelationName(rel),
7060 NameStr(att->attname))));
7061 else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7062 ereport(ERROR,
7063 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7064 errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
7065 RelationGetRelationName(origRelation),
7066 RelationGetRelationName(rel),
7067 NameStr(att->attname))));
7068 else
7069 ereport(ERROR,
7070 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7071 errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
7072 RelationGetRelationName(origRelation),
7073 RelationGetRelationName(rel),
7074 NameStr(att->attname))));
7075 }
7076 else if (OidIsValid(rel->rd_rel->reltype))
7077 {
7078 /*
7079 * A view or composite type itself isn't a problem, but we must
7080 * recursively check for indirect dependencies via its rowtype.
7081 */
7082 find_composite_type_dependencies(rel->rd_rel->reltype,
7083 origRelation, origTypeName);
7084 }
7085
7086 relation_close(rel, AccessShareLock);
7087 }
7088
7089 systable_endscan(depScan);
7090
7091 relation_close(depRel, AccessShareLock);
7092 }
7093
7094
7095 /*
7096 * find_typed_table_dependencies
7097 *
7098 * Check to see if a composite type is being used as the type of a
7099 * typed table. Abort if any are found and behavior is RESTRICT.
7100 * Else return the list of tables.
7101 */
7102 static List *
7103 find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
7104 {
7105 Relation classRel;
7106 ScanKeyData key[1];
7107 TableScanDesc scan;
7108 HeapTuple tuple;
7109 List *result = NIL;
7110
7111 classRel = table_open(RelationRelationId, AccessShareLock);
7112
7113 ScanKeyInit(&key[0],
7114 Anum_pg_class_reloftype,
7115 BTEqualStrategyNumber, F_OIDEQ,
7116 ObjectIdGetDatum(typeOid));
7117
7118 scan = table_beginscan_catalog(classRel, 1, key);
7119
7120 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7121 {
7122 Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
7123
7124 if (behavior == DROP_RESTRICT)
7125 ereport(ERROR,
7126 (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
7127 errmsg("cannot alter type \"%s\" because it is the type of a typed table",
7128 typeName),
7129 errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
7130 else
7131 result = lappend_oid(result, classform->oid);
7132 }
7133
7134 table_endscan(scan);
7135 table_close(classRel, AccessShareLock);
7136
7137 return result;
7138 }
7139
7140
7141 /*
7142 * check_of_type
7143 *
7144 * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
7145 * isn't suitable, throw an error. Currently, we require that the type
7146 * originated with CREATE TYPE AS. We could support any row type, but doing so
7147 * would require handling a number of extra corner cases in the DDL commands.
7148 * (Also, allowing domain-over-composite would open up a can of worms about
7149 * whether and how the domain's constraints should apply to derived tables.)
7150 */
7151 void
7152 check_of_type(HeapTuple typetuple)
7153 {
7154 Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
7155 bool typeOk = false;
7156
7157 if (typ->typtype == TYPTYPE_COMPOSITE)
7158 {
7159 Relation typeRelation;
7160
7161 Assert(OidIsValid(typ->typrelid));
7162 typeRelation = relation_open(typ->typrelid, AccessShareLock);
7163 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7164
7165 /*
7166 * Close the parent rel, but keep our AccessShareLock on it until xact
7167 * commit. That will prevent someone else from deleting or ALTERing
7168 * the type before the typed table creation/conversion commits.
7169 */
7170 relation_close(typeRelation, NoLock);
7171
7172 if (!typeOk)
7173 ereport(ERROR,
7174 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7175 errmsg("type %s is the row type of another table",
7176 format_type_be(typ->oid)),
7177 errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
7178 }
7179 else
7180 ereport(ERROR,
7181 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7182 errmsg("type %s is not a composite type",
7183 format_type_be(typ->oid))));
7184 }
7185
7186
7187 /*
7188 * ALTER TABLE ADD COLUMN
7189 *
7190 * Adds an additional attribute to a relation making the assumption that
7191 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
7192 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
7193 * AlterTableCmd's.
7194 *
7195 * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
7196 * have to decide at runtime whether to recurse or not depending on whether we
7197 * actually add a column or merely merge with an existing column. (We can't
7198 * check this in a static pre-pass because it won't handle multiple inheritance
7199 * situations correctly.)
7200 */
7201 static void
7202 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
7203 bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
7204 AlterTableUtilityContext *context)
7205 {
7206 if (rel->rd_rel->reloftype && !recursing)
7207 ereport(ERROR,
7208 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7209 errmsg("cannot add column to typed table")));
7210
7211 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7212 ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
7213
7214 if (recurse && !is_view)
7215 cmd->recurse = true;
7216 }
7217
7218 /*
7219 * Add a column to a table. The return value is the address of the
7220 * new column in the parent relation.
7221 *
7222 * cmd is pass-by-ref so that we can replace it with the parse-transformed
7223 * copy (but that happens only after we check for IF NOT EXISTS).
7224 */
7225 static ObjectAddress
7226 ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
7227 AlterTableCmd **cmd, bool recurse, bool recursing,
7228 LOCKMODE lockmode, AlterTablePass cur_pass,
7229 AlterTableUtilityContext *context)
7230 {
7231 Oid myrelid = RelationGetRelid(rel);
7232 ColumnDef *colDef = castNode(ColumnDef, (*cmd)->def);
7233 bool if_not_exists = (*cmd)->missing_ok;
7234 Relation pgclass,
7235 attrdesc;
7236 HeapTuple reltup;
7237 Form_pg_class relform;
7238 Form_pg_attribute attribute;
7239 int newattnum;
7240 char relkind;
7241 Expr *defval;
7242 List *children;
7243 ListCell *child;
7244 AlterTableCmd *childcmd;
7245 ObjectAddress address;
7246 TupleDesc tupdesc;
7247
7248 /* since this function recurses, it could be driven to stack overflow */
7249 check_stack_depth();
7250
7251 /* At top level, permission check was done in ATPrepCmd, else do it */
7252 if (recursing)
7253 ATSimplePermissions((*cmd)->subtype, rel,
7254 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
7255
7256 if (rel->rd_rel->relispartition && !recursing)
7257 ereport(ERROR,
7258 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7259 errmsg("cannot add column to a partition")));
7260
7261 attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
7262
7263 /*
7264 * Are we adding the column to a recursion child? If so, check whether to
7265 * merge with an existing definition for the column. If we do merge, we
7266 * must not recurse. Children will already have the column, and recursing
7267 * into them would mess up attinhcount.
7268 */
7269 if (colDef->inhcount > 0)
7270 {
7271 HeapTuple tuple;
7272
7273 /* Does child already have a column by this name? */
7274 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
7275 if (HeapTupleIsValid(tuple))
7276 {
7277 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
7278 Oid ctypeId;
7279 int32 ctypmod;
7280 Oid ccollid;
7281
7282 /* Child column must match on type, typmod, and collation */
7283 typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
7284 if (ctypeId != childatt->atttypid ||
7285 ctypmod != childatt->atttypmod)
7286 ereport(ERROR,
7287 (errcode(ERRCODE_DATATYPE_MISMATCH),
7288 errmsg("child table \"%s\" has different type for column \"%s\"",
7289 RelationGetRelationName(rel), colDef->colname)));
7290 ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
7291 if (ccollid != childatt->attcollation)
7292 ereport(ERROR,
7293 (errcode(ERRCODE_COLLATION_MISMATCH),
7294 errmsg("child table \"%s\" has different collation for column \"%s\"",
7295 RelationGetRelationName(rel), colDef->colname),
7296 errdetail("\"%s\" versus \"%s\"",
7297 get_collation_name(ccollid),
7298 get_collation_name(childatt->attcollation))));
7299
7300 /* Bump the existing child att's inhcount */
7301 if (pg_add_s16_overflow(childatt->attinhcount, 1,
7302 &childatt->attinhcount))
7303 ereport(ERROR,
7304 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
7305 errmsg("too many inheritance parents"));
7306 CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
7307
7308 heap_freetuple(tuple);
7309
7310 /* Inform the user about the merge */
7311 ereport(NOTICE,
7312 (errmsg("merging definition of column \"%s\" for child \"%s\"",
7313 colDef->colname, RelationGetRelationName(rel))));
7314
7315 table_close(attrdesc, RowExclusiveLock);
7316
7317 /* Make the child column change visible */
7318 CommandCounterIncrement();
7319
7320 return InvalidObjectAddress;
7321 }
7322 }
7323
7324 /* skip if the name already exists and if_not_exists is true */
7325 if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
7326 {
7327 table_close(attrdesc, RowExclusiveLock);
7328 return InvalidObjectAddress;
7329 }
7330
7331 /*
7332 * Okay, we need to add the column, so go ahead and do parse
7333 * transformation. This can result in queueing up, or even immediately
7334 * executing, subsidiary operations (such as creation of unique indexes);
7335 * so we mustn't do it until we have made the if_not_exists check.
7336 *
7337 * When recursing, the command was already transformed and we needn't do
7338 * so again. Also, if context isn't given we can't transform. (That
7339 * currently happens only for AT_AddColumnToView; we expect that view.c
7340 * passed us a ColumnDef that doesn't need work.)
7341 */
7342 if (context != NULL && !recursing)
7343 {
7344 *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
7345 cur_pass, context);
7346 Assert(*cmd != NULL);
7347 colDef = castNode(ColumnDef, (*cmd)->def);
7348 }
7349
7350 /*
7351 * Regular inheritance children are independent enough not to inherit the
7352 * identity column from parent hence cannot recursively add identity
7353 * column if the table has inheritance children.
7354 *
7355 * Partitions, on the other hand, are integral part of a partitioned table
7356 * and inherit identity column. Hence propagate identity column down the
7357 * partition hierarchy.
7358 */
7359 if (colDef->identity &&
7360 recurse &&
7361 rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
7362 find_inheritance_children(myrelid, NoLock) != NIL)
7363 ereport(ERROR,
7364 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7365 errmsg("cannot recursively add identity column to table that has child tables")));
7366
7367 pgclass = table_open(RelationRelationId, RowExclusiveLock);
7368
7369 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
7370 if (!HeapTupleIsValid(reltup))
7371 elog(ERROR, "cache lookup failed for relation %u", myrelid);
7372 relform = (Form_pg_class) GETSTRUCT(reltup);
7373 relkind = relform->relkind;
7374
7375 /* Determine the new attribute's number */
7376 newattnum = relform->relnatts + 1;
7377 if (newattnum > MaxHeapAttributeNumber)
7378 ereport(ERROR,
7379 (errcode(ERRCODE_TOO_MANY_COLUMNS),
7380 errmsg("tables can have at most %d columns",
7381 MaxHeapAttributeNumber)));
7382
7383 /*
7384 * Construct new attribute's pg_attribute entry.
7385 */
7386 tupdesc = BuildDescForRelation(list_make1(colDef));
7387
7388 attribute = TupleDescAttr(tupdesc, 0);
7389
7390 /* Fix up attribute number */
7391 attribute->attnum = newattnum;
7392
7393 /* make sure datatype is legal for a column */
7394 CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
7395 list_make1_oid(rel->rd_rel->reltype),
7396 (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
7397
7398 InsertPgAttributeTuples(attrdesc, tupdesc, myrelid, NULL, NULL);
7399
7400 table_close(attrdesc, RowExclusiveLock);
7401
7402 /*
7403 * Update pg_class tuple as appropriate
7404 */
7405 relform->relnatts = newattnum;
7406
7407 CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
7408
7409 heap_freetuple(reltup);
7410
7411 /* Post creation hook for new attribute */
7412 InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
7413
7414 table_close(pgclass, RowExclusiveLock);
7415
7416 /* Make the attribute's catalog entry visible */
7417 CommandCounterIncrement();
7418
7419 /*
7420 * Store the DEFAULT, if any, in the catalogs
7421 */
7422 if (colDef->raw_default)
7423 {
7424 RawColumnDefault *rawEnt;
7425
7426 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
7427 rawEnt->attnum = attribute->attnum;
7428 rawEnt->raw_default = copyObject(colDef->raw_default);
7429 rawEnt->generated = colDef->generated;
7430
7431 /*
7432 * This function is intended for CREATE TABLE, so it processes a
7433 * _list_ of defaults, but we just do one.
7434 */
7435 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
7436 false, true, false, NULL);
7437
7438 /* Make the additional catalog changes visible */
7439 CommandCounterIncrement();
7440 }
7441
7442 /*
7443 * Tell Phase 3 to fill in the default expression, if there is one.
7444 *
7445 * If there is no default, Phase 3 doesn't have to do anything, because
7446 * that effectively means that the default is NULL. The heap tuple access
7447 * routines always check for attnum > # of attributes in tuple, and return
7448 * NULL if so, so without any modification of the tuple data we will get
7449 * the effect of NULL values in the new column.
7450 *
7451 * An exception occurs when the new column is of a domain type: the domain
7452 * might have a not-null constraint, or a check constraint that indirectly
7453 * rejects nulls. If there are any domain constraints then we construct
7454 * an explicit NULL default value that will be passed through
7455 * CoerceToDomain processing. (This is a tad inefficient, since it causes
7456 * rewriting the table which we really wouldn't have to do; but we do it
7457 * to preserve the historical behavior that such a failure will be raised
7458 * only if the table currently contains some rows.)
7459 *
7460 * Note: we use build_column_default, and not just the cooked default
7461 * returned by AddRelationNewConstraints, so that the right thing happens
7462 * when a datatype's default applies.
7463 *
7464 * Note: it might seem that this should happen at the end of Phase 2, so
7465 * that the effects of subsequent subcommands can be taken into account.
7466 * It's intentional that we do it now, though. The new column should be
7467 * filled according to what is said in the ADD COLUMN subcommand, so that
7468 * the effects are the same as if this subcommand had been run by itself
7469 * and the later subcommands had been issued in new ALTER TABLE commands.
7470 *
7471 * We can skip this entirely for relations without storage, since Phase 3
7472 * is certainly not going to touch them.
7473 */
7474 if (RELKIND_HAS_STORAGE(relkind))
7475 {
7476 bool has_domain_constraints;
7477 bool has_missing = false;
7478
7479 /*
7480 * For an identity column, we can't use build_column_default(),
7481 * because the sequence ownership isn't set yet. So do it manually.
7482 */
7483 if (colDef->identity)
7484 {
7485 NextValueExpr *nve = makeNode(NextValueExpr);
7486
7487 nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
7488 nve->typeId = attribute->atttypid;
7489
7490 defval = (Expr *) nve;
7491 }
7492 else
7493 defval = (Expr *) build_column_default(rel, attribute->attnum);
7494
7495 /* Build CoerceToDomain(NULL) expression if needed */
7496 has_domain_constraints = DomainHasConstraints(attribute->atttypid);
7497 if (!defval && has_domain_constraints)
7498 {
7499 Oid baseTypeId;
7500 int32 baseTypeMod;
7501 Oid baseTypeColl;
7502
7503 baseTypeMod = attribute->atttypmod;
7504 baseTypeId = getBaseTypeAndTypmod(attribute->atttypid, &baseTypeMod);
7505 baseTypeColl = get_typcollation(baseTypeId);
7506 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
7507 defval = (Expr *) coerce_to_target_type(NULL,
7508 (Node *) defval,
7509 baseTypeId,
7510 attribute->atttypid,
7511 attribute->atttypmod,
7512 COERCION_ASSIGNMENT,
7513 COERCE_IMPLICIT_CAST,
7514 -1);
7515 if (defval == NULL) /* should not happen */
7516 elog(ERROR, "failed to coerce base type to domain");
7517 }
7518
7519 if (defval)
7520 {
7521 NewColumnValue *newval;
7522
7523 /* Prepare defval for execution, either here or in Phase 3 */
7524 defval = expression_planner(defval);
7525
7526 /* Add the new default to the newvals list */
7527 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
7528 newval->attnum = attribute->attnum;
7529 newval->expr = defval;
7530 newval->is_generated = (colDef->generated != '\0');
7531
7532 tab->newvals = lappend(tab->newvals, newval);
7533
7534 /*
7535 * Attempt to skip a complete table rewrite by storing the
7536 * specified DEFAULT value outside of the heap. This is only
7537 * allowed for plain relations and non-generated columns, and the
7538 * default expression can't be volatile (stable is OK). Note that
7539 * contain_volatile_functions deems CoerceToDomain immutable, but
7540 * here we consider that coercion to a domain with constraints is
7541 * volatile; else it might fail even when the table is empty.
7542 */
7543 if (rel->rd_rel->relkind == RELKIND_RELATION &&
7544 !colDef->generated &&
7545 !has_domain_constraints &&
7546 !contain_volatile_functions((Node *) defval))
7547 {
7548 EState *estate;
7549 ExprState *exprState;
7550 Datum missingval;
7551 bool missingIsNull;
7552
7553 /* Evaluate the default expression */
7554 estate = CreateExecutorState();
7555 exprState = ExecPrepareExpr(defval, estate);
7556 missingval = ExecEvalExpr(exprState,
7557 GetPerTupleExprContext(estate),
7558 &missingIsNull);
7559 /* If it turns out NULL, nothing to do; else store it */
7560 if (!missingIsNull)
7561 {
7562 StoreAttrMissingVal(rel, attribute->attnum, missingval);
7563 /* Make the additional catalog change visible */
7564 CommandCounterIncrement();
7565 has_missing = true;
7566 }
7567 FreeExecutorState(estate);
7568 }
7569 else
7570 {
7571 /*
7572 * Failed to use missing mode. We have to do a table rewrite
7573 * to install the value --- unless it's a virtual generated
7574 * column.
7575 */
7576 if (colDef->generated != ATTRIBUTE_GENERATED_VIRTUAL)
7577 tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
7578 }
7579 }
7580
7581 if (!has_missing)
7582 {
7583 /*
7584 * If the new column is NOT NULL, and there is no missing value,
7585 * tell Phase 3 it needs to check for NULLs.
7586 */
7587 tab->verify_new_notnull |= colDef->is_not_null;
7588 }
7589 }
7590
7591 /*
7592 * Add needed dependency entries for the new column.
7593 */
7594 add_column_datatype_dependency(myrelid, newattnum, attribute->atttypid);
7595 add_column_collation_dependency(myrelid, newattnum, attribute->attcollation);
7596
7597 /*
7598 * Propagate to children as appropriate. Unlike most other ALTER
7599 * routines, we have to do this one level of recursion at a time; we can't
7600 * use find_all_inheritors to do it in one pass.
7601 */
7602 children =
7603 find_inheritance_children(RelationGetRelid(rel), lockmode);
7604
7605 /*
7606 * If we are told not to recurse, there had better not be any child
7607 * tables; else the addition would put them out of step.
7608 */
7609 if (children && !recurse)
7610 ereport(ERROR,
7611 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7612 errmsg("column must be added to child tables too")));
7613
7614 /* Children should see column as singly inherited */
7615 if (!recursing)
7616 {
7617 childcmd = copyObject(*cmd);
7618 colDef = castNode(ColumnDef, childcmd->def);
7619 colDef->inhcount = 1;
7620 colDef->is_local = false;
7621 }
7622 else
7623 childcmd = *cmd; /* no need to copy again */
7624
7625 foreach(child, children)
7626 {
7627 Oid childrelid = lfirst_oid(child);
7628 Relation childrel;
7629 AlteredTableInfo *childtab;
7630
7631 /* find_inheritance_children already got lock */
7632 childrel = table_open(childrelid, NoLock);
7633 CheckAlterTableIsSafe(childrel);
7634
7635 /* Find or create work queue entry for this table */
7636 childtab = ATGetQueueEntry(wqueue, childrel);
7637
7638 /* Recurse to child; return value is ignored */
7639 ATExecAddColumn(wqueue, childtab, childrel,
7640 &childcmd, recurse, true,
7641 lockmode, cur_pass, context);
7642
7643 table_close(childrel, NoLock);
7644 }
7645
7646 ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
7647 return address;
7648 }
7649
7650 /*
7651 * If a new or renamed column will collide with the name of an existing
7652 * column and if_not_exists is false then error out, else do nothing.
7653 */
7654 static bool
7655 check_for_column_name_collision(Relation rel, const char *colname,
7656 bool if_not_exists)
7657 {
7658 HeapTuple attTuple;
7659 int attnum;
7660
7661 /*
7662 * this test is deliberately not attisdropped-aware, since if one tries to
7663 * add a column matching a dropped column name, it's gonna fail anyway.
7664 */
7665 attTuple = SearchSysCache2(ATTNAME,
7666 ObjectIdGetDatum(RelationGetRelid(rel)),
7667 PointerGetDatum(colname));
7668 if (!HeapTupleIsValid(attTuple))
7669 return true;
7670
7671 attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
7672 ReleaseSysCache(attTuple);
7673
7674 /*
7675 * We throw a different error message for conflicts with system column
7676 * names, since they are normally not shown and the user might otherwise
7677 * be confused about the reason for the conflict.
7678 */
7679 if (attnum <= 0)
7680 ereport(ERROR,
7681 (errcode(ERRCODE_DUPLICATE_COLUMN),
7682 errmsg("column name \"%s\" conflicts with a system column name",
7683 colname)));
7684 else
7685 {
7686 if (if_not_exists)
7687 {
7688 ereport(NOTICE,
7689 (errcode(ERRCODE_DUPLICATE_COLUMN),
7690 errmsg("column \"%s\" of relation \"%s\" already exists, skipping",
7691 colname, RelationGetRelationName(rel))));
7692 return false;
7693 }
7694
7695 ereport(ERROR,
7696 (errcode(ERRCODE_DUPLICATE_COLUMN),
7697 errmsg("column \"%s\" of relation \"%s\" already exists",
7698 colname, RelationGetRelationName(rel))));
7699 }
7700
7701 return true;
7702 }
7703
7704 /*
7705 * Install a column's dependency on its datatype.
7706 */
7707 static void
7708 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
7709 {
7710 ObjectAddress myself,
7711 referenced;
7712
7713 myself.classId = RelationRelationId;
7714 myself.objectId = relid;
7715 myself.objectSubId = attnum;
7716 referenced.classId = TypeRelationId;
7717 referenced.objectId = typid;
7718 referenced.objectSubId = 0;
7719 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7720 }
7721
7722 /*
7723 * Install a column's dependency on its collation.
7724 */
7725 static void
7726 add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
7727 {
7728 ObjectAddress myself,
7729 referenced;
7730
7731 /* We know the default collation is pinned, so don't bother recording it */
7732 if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
7733 {
7734 myself.classId = RelationRelationId;
7735 myself.objectId = relid;
7736 myself.objectSubId = attnum;
7737 referenced.classId = CollationRelationId;
7738 referenced.objectId = collid;
7739 referenced.objectSubId = 0;
7740 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7741 }
7742 }
7743
7744 /*
7745 * ALTER TABLE ALTER COLUMN DROP NOT NULL
7746 *
7747 * Return the address of the modified column. If the column was already
7748 * nullable, InvalidObjectAddress is returned.
7749 */
7750 static ObjectAddress
7751 ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
7752 LOCKMODE lockmode)
7753 {
7754 HeapTuple tuple;
7755 HeapTuple conTup;
7756 Form_pg_attribute attTup;
7757 AttrNumber attnum;
7758 Relation attr_rel;
7759 ObjectAddress address;
7760
7761 /*
7762 * lookup the attribute
7763 */
7764 attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7765
7766 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7767 if (!HeapTupleIsValid(tuple))
7768 ereport(ERROR,
7769 (errcode(ERRCODE_UNDEFINED_COLUMN),
7770 errmsg("column \"%s\" of relation \"%s\" does not exist",
7771 colName, RelationGetRelationName(rel))));
7772 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7773 attnum = attTup->attnum;
7774 ObjectAddressSubSet(address, RelationRelationId,
7775 RelationGetRelid(rel), attnum);
7776
7777 /* If the column is already nullable there's nothing to do. */
7778 if (!attTup->attnotnull)
7779 {
7780 table_close(attr_rel, RowExclusiveLock);
7781 return InvalidObjectAddress;
7782 }
7783
7784 /* Prevent them from altering a system attribute */
7785 if (attnum <= 0)
7786 ereport(ERROR,
7787 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7788 errmsg("cannot alter system column \"%s\"",
7789 colName)));
7790
7791 if (attTup->attidentity)
7792 ereport(ERROR,
7793 (errcode(ERRCODE_SYNTAX_ERROR),
7794 errmsg("column \"%s\" of relation \"%s\" is an identity column",
7795 colName, RelationGetRelationName(rel))));
7796
7797 /*
7798 * If rel is partition, shouldn't drop NOT NULL if parent has the same.
7799 */
7800 if (rel->rd_rel->relispartition)
7801 {
7802 Oid parentId = get_partition_parent(RelationGetRelid(rel), false);
7803 Relation parent = table_open(parentId, AccessShareLock);
7804 TupleDesc tupDesc = RelationGetDescr(parent);
7805 AttrNumber parent_attnum;
7806
7807 parent_attnum = get_attnum(parentId, colName);
7808 if (TupleDescAttr(tupDesc, parent_attnum - 1)->attnotnull)
7809 ereport(ERROR,
7810 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7811 errmsg("column \"%s\" is marked NOT NULL in parent table",
7812 colName)));
7813 table_close(parent, AccessShareLock);
7814 }
7815
7816 /*
7817 * Find the constraint that makes this column NOT NULL, and drop it.
7818 * dropconstraint_internal() resets attnotnull.
7819 */
7820 conTup = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
7821 if (conTup == NULL)
7822 elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
7823 colName, RelationGetRelationName(rel));
7824
7825 /* The normal case: we have a pg_constraint row, remove it */
7826 dropconstraint_internal(rel, conTup, DROP_RESTRICT, recurse, false,
7827 false, lockmode);
7828 heap_freetuple(conTup);
7829
7830 InvokeObjectPostAlterHook(RelationRelationId,
7831 RelationGetRelid(rel), attnum);
7832
7833 table_close(attr_rel, RowExclusiveLock);
7834
7835 return address;
7836 }
7837
7838 /*
7839 * set_attnotnull
7840 * Helper to update/validate the pg_attribute status of a not-null
7841 * constraint
7842 *
7843 * pg_attribute.attnotnull is set true, if it isn't already.
7844 * If queue_validation is true, also set up wqueue to validate the constraint.
7845 * wqueue may be given as NULL when validation is not needed (e.g., on table
7846 * creation).
7847 */
7848 static void
7849 set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
7850 bool queue_validation)
7851 {
7852 Form_pg_attribute attr;
7853
7854 Assert(!queue_validation || wqueue);
7855
7856 CheckAlterTableIsSafe(rel);
7857
7858 /*
7859 * Exit quickly by testing attnotnull from the tupledesc's copy of the
7860 * attribute.
7861 */
7862 attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
7863 if (attr->attisdropped)
7864 return;
7865
7866 if (!attr->attnotnull)
7867 {
7868 Relation attr_rel;
7869 HeapTuple tuple;
7870
7871 attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7872
7873 tuple = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
7874 if (!HeapTupleIsValid(tuple))
7875 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
7876 attnum, RelationGetRelid(rel));
7877
7878 attr = (Form_pg_attribute) GETSTRUCT(tuple);
7879
7880 attr->attnotnull = true;
7881 CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
7882
7883 /*
7884 * If the nullness isn't already proven by validated constraints, have
7885 * ALTER TABLE phase 3 test for it.
7886 */
7887 if (queue_validation && wqueue &&
7888 !NotNullImpliedByRelConstraints(rel, attr))
7889 {
7890 AlteredTableInfo *tab;
7891
7892 tab = ATGetQueueEntry(wqueue, rel);
7893 tab->verify_new_notnull = true;
7894 }
7895
7896 CommandCounterIncrement();
7897
7898 table_close(attr_rel, RowExclusiveLock);
7899 heap_freetuple(tuple);
7900 }
7901 else
7902 {
7903 CacheInvalidateRelcache(rel);
7904 }
7905 }
7906
7907 /*
7908 * ALTER TABLE ALTER COLUMN SET NOT NULL
7909 *
7910 * Add a not-null constraint to a single table and its children. Returns
7911 * the address of the constraint added to the parent relation, if one gets
7912 * added, or InvalidObjectAddress otherwise.
7913 *
7914 * We must recurse to child tables during execution, rather than using
7915 * ALTER TABLE's normal prep-time recursion.
7916 */
7917 static ObjectAddress
7918 ATExecSetNotNull(List **wqueue, Relation rel, char *conName, char *colName,
7919 bool recurse, bool recursing, LOCKMODE lockmode)
7920 {
7921 HeapTuple tuple;
7922 AttrNumber attnum;
7923 ObjectAddress address;
7924 Constraint *constraint;
7925 CookedConstraint *ccon;
7926 List *cooked;
7927 bool is_no_inherit = false;
7928
7929 /* Guard against stack overflow due to overly deep inheritance tree. */
7930 check_stack_depth();
7931
7932 /* At top level, permission check was done in ATPrepCmd, else do it */
7933 if (recursing)
7934 {
7935 ATSimplePermissions(AT_AddConstraint, rel,
7936 ATT_PARTITIONED_TABLE | ATT_TABLE | ATT_FOREIGN_TABLE);
7937 Assert(conName != NULL);
7938 }
7939
7940 attnum = get_attnum(RelationGetRelid(rel), colName);
7941 if (attnum == InvalidAttrNumber)
7942 ereport(ERROR,
7943 (errcode(ERRCODE_UNDEFINED_COLUMN),
7944 errmsg("column \"%s\" of relation \"%s\" does not exist",
7945 colName, RelationGetRelationName(rel))));
7946
7947 /* Prevent them from altering a system attribute */
7948 if (attnum <= 0)
7949 ereport(ERROR,
7950 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7951 errmsg("cannot alter system column \"%s\"",
7952 colName)));
7953
7954 /* See if there's already a constraint */
7955 tuple = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
7956 if (HeapTupleIsValid(tuple))
7957 {
7958 Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
7959 bool changed = false;
7960
7961 /*
7962 * Don't let a NO INHERIT constraint be changed into inherit.
7963 */
7964 if (conForm->connoinherit && recurse)
7965 ereport(ERROR,
7966 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7967 errmsg("cannot change NO INHERIT status of NOT NULL constraint \"%s\" on relation \"%s\"",
7968 NameStr(conForm->conname),
7969 RelationGetRelationName(rel)));
7970
7971 /*
7972 * If we find an appropriate constraint, we're almost done, but just
7973 * need to change some properties on it: if we're recursing, increment
7974 * coninhcount; if not, set conislocal if not already set.
7975 */
7976 if (recursing)
7977 {
7978 if (pg_add_s16_overflow(conForm->coninhcount, 1,
7979 &conForm->coninhcount))
7980 ereport(ERROR,
7981 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
7982 errmsg("too many inheritance parents"));
7983 changed = true;
7984 }
7985 else if (!conForm->conislocal)
7986 {
7987 conForm->conislocal = true;
7988 changed = true;
7989 }
7990 else if (!conForm->convalidated)
7991 {
7992 /*
7993 * Flip attnotnull and convalidated, and also validate the
7994 * constraint.
7995 */
7996 return ATExecValidateConstraint(wqueue, rel, NameStr(conForm->conname),
7997 recurse, recursing, lockmode);
7998 }
7999
8000 if (changed)
8001 {
8002 Relation constr_rel;
8003
8004 constr_rel = table_open(ConstraintRelationId, RowExclusiveLock);
8005
8006 CatalogTupleUpdate(constr_rel, &tuple->t_self, tuple);
8007 ObjectAddressSet(address, ConstraintRelationId, conForm->oid);
8008 table_close(constr_rel, RowExclusiveLock);
8009 }
8010
8011 if (changed)
8012 return address;
8013 else
8014 return InvalidObjectAddress;
8015 }
8016
8017 /*
8018 * If we're asked not to recurse, and children exist, raise an error for
8019 * partitioned tables. For inheritance, we act as if NO INHERIT had been
8020 * specified.
8021 */
8022 if (!recurse &&
8023 find_inheritance_children(RelationGetRelid(rel),
8024 NoLock) != NIL)
8025 {
8026 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8027 ereport(ERROR,
8028 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8029 errmsg("constraint must be added to child tables too"),
8030 errhint("Do not specify the ONLY keyword."));
8031 else
8032 is_no_inherit = true;
8033 }
8034
8035 /*
8036 * No constraint exists; we must add one. First determine a name to use,
8037 * if we haven't already.
8038 */
8039 if (!recursing)
8040 {
8041 Assert(conName == NULL);
8042 conName = ChooseConstraintName(RelationGetRelationName(rel),
8043 colName, "not_null",
8044 RelationGetNamespace(rel),
8045 NIL);
8046 }
8047
8048 constraint = makeNotNullConstraint(makeString(colName));
8049 constraint->is_no_inherit = is_no_inherit;
8050 constraint->conname = conName;
8051
8052 /* and do it */
8053 cooked = AddRelationNewConstraints(rel, NIL, list_make1(constraint),
8054 false, !recursing, false, NULL);
8055 ccon = linitial(cooked);
8056 ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
8057
8058 /* Mark pg_attribute.attnotnull for the column and queue validation */
8059 set_attnotnull(wqueue, rel, attnum, true);
8060
8061 InvokeObjectPostAlterHook(RelationRelationId,
8062 RelationGetRelid(rel), attnum);
8063
8064 /*
8065 * Recurse to propagate the constraint to children that don't have one.
8066 */
8067 if (recurse)
8068 {
8069 List *children;
8070
8071 children = find_inheritance_children(RelationGetRelid(rel),
8072 lockmode);
8073
8074 foreach_oid(childoid, children)
8075 {
8076 Relation childrel = table_open(childoid, NoLock);
8077
8078 CommandCounterIncrement();
8079
8080 ATExecSetNotNull(wqueue, childrel, conName, colName,
8081 recurse, true, lockmode);
8082 table_close(childrel, NoLock);
8083 }
8084 }
8085
8086 return address;
8087 }
8088
8089 /*
8090 * NotNullImpliedByRelConstraints
8091 * Does rel's existing constraints imply NOT NULL for the given attribute?
8092 */
8093 static bool
8094 NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr)
8095 {
8096 NullTest *nnulltest = makeNode(NullTest);
8097
8098 nnulltest->arg = (Expr *) makeVar(1,
8099 attr->attnum,
8100 attr->atttypid,
8101 attr->atttypmod,
8102 attr->attcollation,
8103 0);
8104 nnulltest->nulltesttype = IS_NOT_NULL;
8105
8106 /*
8107 * argisrow = false is correct even for a composite column, because
8108 * attnotnull does not represent a SQL-spec IS NOT NULL test in such a
8109 * case, just IS DISTINCT FROM NULL.
8110 */
8111 nnulltest->argisrow = false;
8112 nnulltest->location = -1;
8113
8114 if (ConstraintImpliedByRelConstraint(rel, list_make1(nnulltest), NIL))
8115 {
8116 ereport(DEBUG1,
8117 (errmsg_internal("existing constraints on column \"%s.%s\" are sufficient to prove that it does not contain nulls",
8118 RelationGetRelationName(rel), NameStr(attr->attname))));
8119 return true;
8120 }
8121
8122 return false;
8123 }
8124
8125 /*
8126 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
8127 *
8128 * Return the address of the affected column.
8129 */
8130 static ObjectAddress
8131 ATExecColumnDefault(Relation rel, const char *colName,
8132 Node *newDefault, LOCKMODE lockmode)
8133 {
8134 TupleDesc tupdesc = RelationGetDescr(rel);
8135 AttrNumber attnum;
8136 ObjectAddress address;
8137
8138 /*
8139 * get the number of the attribute
8140 */
8141 attnum = get_attnum(RelationGetRelid(rel), colName);
8142 if (attnum == InvalidAttrNumber)
8143 ereport(ERROR,
8144 (errcode(ERRCODE_UNDEFINED_COLUMN),
8145 errmsg("column \"%s\" of relation \"%s\" does not exist",
8146 colName, RelationGetRelationName(rel))));
8147
8148 /* Prevent them from altering a system attribute */
8149 if (attnum <= 0)
8150 ereport(ERROR,
8151 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8152 errmsg("cannot alter system column \"%s\"",
8153 colName)));
8154
8155 if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
8156 ereport(ERROR,
8157 (errcode(ERRCODE_SYNTAX_ERROR),
8158 errmsg("column \"%s\" of relation \"%s\" is an identity column",
8159 colName, RelationGetRelationName(rel)),
8160 /* translator: %s is an SQL ALTER command */
8161 newDefault ? 0 : errhint("Use %s instead.",
8162 "ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY")));
8163
8164 if (TupleDescAttr(tupdesc, attnum - 1)->attgenerated)
8165 ereport(ERROR,
8166 (errcode(ERRCODE_SYNTAX_ERROR),
8167 errmsg("column \"%s\" of relation \"%s\" is a generated column",
8168 colName, RelationGetRelationName(rel)),
8169 newDefault ?
8170 /* translator: %s is an SQL ALTER command */
8171 errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... SET EXPRESSION") :
8172 (TupleDescAttr(tupdesc, attnum - 1)->attgenerated == ATTRIBUTE_GENERATED_STORED ?
8173 errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION") : 0)));
8174
8175 /*
8176 * Remove any old default for the column. We use RESTRICT here for
8177 * safety, but at present we do not expect anything to depend on the
8178 * default.
8179 *
8180 * We treat removing the existing default as an internal operation when it
8181 * is preparatory to adding a new default, but as a user-initiated
8182 * operation when the user asked for a drop.
8183 */
8184 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8185 newDefault != NULL);
8186
8187 if (newDefault)
8188 {
8189 /* SET DEFAULT */
8190 RawColumnDefault *rawEnt;
8191
8192 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
8193 rawEnt->attnum = attnum;
8194 rawEnt->raw_default = newDefault;
8195 rawEnt->generated = '\0';
8196
8197 /*
8198 * This function is intended for CREATE TABLE, so it processes a
8199 * _list_ of defaults, but we just do one.
8200 */
8201 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8202 false, true, false, NULL);
8203 }
8204
8205 ObjectAddressSubSet(address, RelationRelationId,
8206 RelationGetRelid(rel), attnum);
8207 return address;
8208 }
8209
8210 /*
8211 * Add a pre-cooked default expression.
8212 *
8213 * Return the address of the affected column.
8214 */
8215 static ObjectAddress
8216 ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
8217 Node *newDefault)
8218 {
8219 ObjectAddress address;
8220
8221 /*
8222 * This is used for a cooked default copied by CREATE TABLE ... LIKE,
8223 * which adds new type dependencies. Such a default doesn't go through
8224 * AddRelationNewConstraints(), and StoreAttrDefault() leaves the
8225 * privilege checks to its caller, so we must check for USAGE on the types
8226 * here.
8227 */
8228 CheckUsageOnTypesInSingleRelExpr(newDefault, RelationGetRelid(rel), GetUserId());
8229
8230 /*
8231 * Remove any old default for the column. We use RESTRICT here for
8232 * safety, but at present we do not expect anything to depend on the
8233 * default. (In ordinary cases, there could not be a default in place
8234 * anyway, but it's possible when combining LIKE with inheritance.)
8235 */
8236 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8237 true);
8238
8239 (void) StoreAttrDefault(rel, attnum, newDefault, true);
8240
8241 ObjectAddressSubSet(address, RelationRelationId,
8242 RelationGetRelid(rel), attnum);
8243 return address;
8244 }
8245
8246 /*
8247 * ALTER TABLE ALTER COLUMN ADD IDENTITY
8248 *
8249 * Return the address of the affected column.
8250 */
8251 static ObjectAddress
8252 ATExecAddIdentity(Relation rel, const char *colName,
8253 Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
8254 {
8255 Relation attrelation;
8256 HeapTuple tuple;
8257 Form_pg_attribute attTup;
8258 AttrNumber attnum;
8259 ObjectAddress address;
8260 ColumnDef *cdef = castNode(ColumnDef, def);
8261 bool ispartitioned;
8262
8263 ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8264 if (ispartitioned && !recurse)
8265 ereport(ERROR,
8266 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8267 errmsg("cannot add identity to a column of only the partitioned table"),
8268 errhint("Do not specify the ONLY keyword.")));
8269
8270 if (rel->rd_rel->relispartition && !recursing)
8271 ereport(ERROR,
8272 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8273 errmsg("cannot add identity to a column of a partition"));
8274
8275 attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8276
8277 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8278 if (!HeapTupleIsValid(tuple))
8279 ereport(ERROR,
8280 (errcode(ERRCODE_UNDEFINED_COLUMN),
8281 errmsg("column \"%s\" of relation \"%s\" does not exist",
8282 colName, RelationGetRelationName(rel))));
8283 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8284 attnum = attTup->attnum;
8285
8286 /* Can't alter a system attribute */
8287 if (attnum <= 0)
8288 ereport(ERROR,
8289 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8290 errmsg("cannot alter system column \"%s\"",
8291 colName)));
8292
8293 /*
8294 * Creating a column as identity implies NOT NULL, so adding the identity
8295 * to an existing column that is not NOT NULL would create a state that
8296 * cannot be reproduced without contortions.
8297 */
8298 if (!attTup->attnotnull)
8299 ereport(ERROR,
8300 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8301 errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
8302 colName, RelationGetRelationName(rel))));
8303
8304 /*
8305 * On the other hand, if a not-null constraint exists, then verify that
8306 * it's compatible.
8307 */
8308 if (attTup->attnotnull)
8309 {
8310 HeapTuple contup;
8311 Form_pg_constraint conForm;
8312
8313 contup = findNotNullConstraintAttnum(RelationGetRelid(rel),
8314 attnum);
8315 if (!HeapTupleIsValid(contup))
8316 elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
8317 colName, RelationGetRelationName(rel));
8318
8319 conForm = (Form_pg_constraint) GETSTRUCT(contup);
8320 if (!conForm->convalidated)
8321 ereport(ERROR,
8322 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8323 errmsg("incompatible NOT VALID constraint \"%s\" on relation \"%s\"",
8324 NameStr(conForm->conname), RelationGetRelationName(rel)),
8325 errhint("You might need to validate it using %s.",
8326 "ALTER TABLE ... VALIDATE CONSTRAINT"));
8327 }
8328
8329 if (attTup->attidentity)
8330 ereport(ERROR,
8331 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8332 errmsg("column \"%s\" of relation \"%s\" is already an identity column",
8333 colName, RelationGetRelationName(rel))));
8334
8335 if (attTup->atthasdef)
8336 ereport(ERROR,
8337 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8338 errmsg("column \"%s\" of relation \"%s\" already has a default value",
8339 colName, RelationGetRelationName(rel))));
8340
8341 attTup->attidentity = cdef->identity;
8342 CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8343
8344 InvokeObjectPostAlterHook(RelationRelationId,
8345 RelationGetRelid(rel),
8346 attTup->attnum);
8347 ObjectAddressSubSet(address, RelationRelationId,
8348 RelationGetRelid(rel), attnum);
8349 heap_freetuple(tuple);
8350
8351 table_close(attrelation, RowExclusiveLock);
8352
8353 /*
8354 * Recurse to propagate the identity column to partitions. Identity is
8355 * not inherited in regular inheritance children.
8356 */
8357 if (recurse && ispartitioned)
8358 {
8359 List *children;
8360 ListCell *lc;
8361
8362 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8363
8364 foreach(lc, children)
8365 {
8366 Relation childrel;
8367
8368 childrel = table_open(lfirst_oid(lc), NoLock);
8369 ATExecAddIdentity(childrel, colName, def, lockmode, recurse, true);
8370 table_close(childrel, NoLock);
8371 }
8372 }
8373
8374 return address;
8375 }
8376
8377 /*
8378 * ALTER TABLE ALTER COLUMN SET { GENERATED or sequence options }
8379 *
8380 * Return the address of the affected column.
8381 */
8382 static ObjectAddress
8383 ATExecSetIdentity(Relation rel, const char *colName, Node *def,
8384 LOCKMODE lockmode, bool recurse, bool recursing)
8385 {
8386 ListCell *option;
8387 DefElem *generatedEl = NULL;
8388 HeapTuple tuple;
8389 Form_pg_attribute attTup;
8390 AttrNumber attnum;
8391 Relation attrelation;
8392 ObjectAddress address;
8393 bool ispartitioned;
8394
8395 ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8396 if (ispartitioned && !recurse)
8397 ereport(ERROR,
8398 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8399 errmsg("cannot change identity column of only the partitioned table"),
8400 errhint("Do not specify the ONLY keyword.")));
8401
8402 if (rel->rd_rel->relispartition && !recursing)
8403 ereport(ERROR,
8404 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8405 errmsg("cannot change identity column of a partition"));
8406
8407 foreach(option, castNode(List, def))
8408 {
8409 DefElem *defel = lfirst_node(DefElem, option);
8410
8411 if (strcmp(defel->defname, "generated") == 0)
8412 {
8413 if (generatedEl)
8414 ereport(ERROR,
8415 (errcode(ERRCODE_SYNTAX_ERROR),
8416 errmsg("conflicting or redundant options")));
8417 generatedEl = defel;
8418 }
8419 else
8420 elog(ERROR, "option \"%s\" not recognized",
8421 defel->defname);
8422 }
8423
8424 /*
8425 * Even if there is nothing to change here, we run all the checks. There
8426 * will be a subsequent ALTER SEQUENCE that relies on everything being
8427 * there.
8428 */
8429
8430 attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8431 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8432 if (!HeapTupleIsValid(tuple))
8433 ereport(ERROR,
8434 (errcode(ERRCODE_UNDEFINED_COLUMN),
8435 errmsg("column \"%s\" of relation \"%s\" does not exist",
8436 colName, RelationGetRelationName(rel))));
8437
8438 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8439 attnum = attTup->attnum;
8440
8441 if (attnum <= 0)
8442 ereport(ERROR,
8443 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8444 errmsg("cannot alter system column \"%s\"",
8445 colName)));
8446
8447 if (!attTup->attidentity)
8448 ereport(ERROR,
8449 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8450 errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8451 colName, RelationGetRelationName(rel))));
8452
8453 if (generatedEl)
8454 {
8455 attTup->attidentity = defGetInt32(generatedEl);
8456 CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8457
8458 InvokeObjectPostAlterHook(RelationRelationId,
8459 RelationGetRelid(rel),
8460 attTup->attnum);
8461 ObjectAddressSubSet(address, RelationRelationId,
8462 RelationGetRelid(rel), attnum);
8463 }
8464 else
8465 address = InvalidObjectAddress;
8466
8467 heap_freetuple(tuple);
8468 table_close(attrelation, RowExclusiveLock);
8469
8470 /*
8471 * Recurse to propagate the identity change to partitions. Identity is not
8472 * inherited in regular inheritance children.
8473 */
8474 if (generatedEl && recurse && ispartitioned)
8475 {
8476 List *children;
8477 ListCell *lc;
8478
8479 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8480
8481 foreach(lc, children)
8482 {
8483 Relation childrel;
8484
8485 childrel = table_open(lfirst_oid(lc), NoLock);
8486 ATExecSetIdentity(childrel, colName, def, lockmode, recurse, true);
8487 table_close(childrel, NoLock);
8488 }
8489 }
8490
8491 return address;
8492 }
8493
8494 /*
8495 * ALTER TABLE ALTER COLUMN DROP IDENTITY
8496 *
8497 * Return the address of the affected column.
8498 */
8499 static ObjectAddress
8500 ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
8501 bool recurse, bool recursing)
8502 {
8503 HeapTuple tuple;
8504 Form_pg_attribute attTup;
8505 AttrNumber attnum;
8506 Relation attrelation;
8507 ObjectAddress address;
8508 Oid seqid;
8509 ObjectAddress seqaddress;
8510 bool ispartitioned;
8511
8512 ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8513 if (ispartitioned && !recurse)
8514 ereport(ERROR,
8515 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8516 errmsg("cannot drop identity from a column of only the partitioned table"),
8517 errhint("Do not specify the ONLY keyword.")));
8518
8519 if (rel->rd_rel->relispartition && !recursing)
8520 ereport(ERROR,
8521 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8522 errmsg("cannot drop identity from a column of a partition"));
8523
8524 attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8525 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8526 if (!HeapTupleIsValid(tuple))
8527 ereport(ERROR,
8528 (errcode(ERRCODE_UNDEFINED_COLUMN),
8529 errmsg("column \"%s\" of relation \"%s\" does not exist",
8530 colName, RelationGetRelationName(rel))));
8531
8532 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8533 attnum = attTup->attnum;
8534
8535 if (attnum <= 0)
8536 ereport(ERROR,
8537 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8538 errmsg("cannot alter system column \"%s\"",
8539 colName)));
8540
8541 if (!attTup->attidentity)
8542 {
8543 if (!missing_ok)
8544 ereport(ERROR,
8545 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8546 errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8547 colName, RelationGetRelationName(rel))));
8548 else
8549 {
8550 ereport(NOTICE,
8551 (errmsg("column \"%s\" of relation \"%s\" is not an identity column, skipping",
8552 colName, RelationGetRelationName(rel))));
8553 heap_freetuple(tuple);
8554 table_close(attrelation, RowExclusiveLock);
8555 return InvalidObjectAddress;
8556 }
8557 }
8558
8559 attTup->attidentity = '\0';
8560 CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8561
8562 InvokeObjectPostAlterHook(RelationRelationId,
8563 RelationGetRelid(rel),
8564 attTup->attnum);
8565 ObjectAddressSubSet(address, RelationRelationId,
8566 RelationGetRelid(rel), attnum);
8567 heap_freetuple(tuple);
8568
8569 table_close(attrelation, RowExclusiveLock);
8570
8571 /*
8572 * Recurse to drop the identity from column in partitions. Identity is
8573 * not inherited in regular inheritance children so ignore them.
8574 */
8575 if (recurse && ispartitioned)
8576 {
8577 List *children;
8578 ListCell *lc;
8579
8580 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8581
8582 foreach(lc, children)
8583 {
8584 Relation childrel;
8585
8586 childrel = table_open(lfirst_oid(lc), NoLock);
8587 ATExecDropIdentity(childrel, colName, false, lockmode, recurse, true);
8588 table_close(childrel, NoLock);
8589 }
8590 }
8591
8592 if (!recursing)
8593 {
8594 /* drop the internal sequence */
8595 seqid = getIdentitySequence(rel, attnum, false);
8596 deleteDependencyRecordsForClass(RelationRelationId, seqid,
8597 RelationRelationId, DEPENDENCY_INTERNAL);
8598 CommandCounterIncrement();
8599 seqaddress.classId = RelationRelationId;
8600 seqaddress.objectId = seqid;
8601 seqaddress.objectSubId = 0;
8602 performDeletion(&seqaddress, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8603 }
8604
8605 return address;
8606 }
8607
8608 /*
8609 * ALTER TABLE ALTER COLUMN SET EXPRESSION
8610 *
8611 * Return the address of the affected column.
8612 */
8613 static ObjectAddress
8614 ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
8615 Node *newExpr, LOCKMODE lockmode)
8616 {
8617 HeapTuple tuple;
8618 Form_pg_attribute attTup;
8619 AttrNumber attnum;
8620 char attgenerated;
8621 bool rewrite;
8622 Oid attrdefoid;
8623 ObjectAddress address;
8624 Expr *defval;
8625 NewColumnValue *newval;
8626 RawColumnDefault *rawEnt;
8627
8628 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8629 if (!HeapTupleIsValid(tuple))
8630 ereport(ERROR,
8631 (errcode(ERRCODE_UNDEFINED_COLUMN),
8632 errmsg("column \"%s\" of relation \"%s\" does not exist",
8633 colName, RelationGetRelationName(rel))));
8634
8635 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8636
8637 attnum = attTup->attnum;
8638 if (attnum <= 0)
8639 ereport(ERROR,
8640 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8641 errmsg("cannot alter system column \"%s\"",
8642 colName)));
8643
8644 attgenerated = attTup->attgenerated;
8645 if (!attgenerated)
8646 ereport(ERROR,
8647 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8648 errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8649 colName, RelationGetRelationName(rel))));
8650
8651 /*
8652 * TODO: This could be done, just need to recheck any constraints
8653 * afterwards.
8654 */
8655 if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
8656 rel->rd_att->constr && rel->rd_att->constr->num_check > 0)
8657 ereport(ERROR,
8658 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8659 errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables with check constraints"),
8660 errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8661 colName, RelationGetRelationName(rel))));
8662
8663 if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull)
8664 tab->verify_new_notnull = true;
8665
8666 /*
8667 * We need to prevent this because a change of expression could affect a
8668 * row filter and inject expressions that are not permitted in a row
8669 * filter. XXX We could try to have a more precise check to catch only
8670 * publications with row filters, or even re-verify the row filter
8671 * expressions.
8672 */
8673 if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
8674 GetRelationPublications(RelationGetRelid(rel)) != NIL)
8675 ereport(ERROR,
8676 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8677 errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables that are part of a publication"),
8678 errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8679 colName, RelationGetRelationName(rel))));
8680
8681 rewrite = (attgenerated == ATTRIBUTE_GENERATED_STORED);
8682
8683 ReleaseSysCache(tuple);
8684
8685 if (rewrite)
8686 {
8687 /*
8688 * Clear all the missing values if we're rewriting the table, since
8689 * this renders them pointless.
8690 */
8691 RelationClearMissing(rel);
8692
8693 /* make sure we don't conflict with later attribute modifications */
8694 CommandCounterIncrement();
8695
8696 /*
8697 * Find everything that depends on the column (constraints, indexes,
8698 * etc), and record enough information to let us recreate the objects
8699 * after rewrite.
8700 */
8701 RememberAllDependentForRebuilding(tab, AT_SetExpression, rel, attnum, colName);
8702 }
8703
8704 /*
8705 * Drop the dependency records of the GENERATED expression, in particular
8706 * its INTERNAL dependency on the column, which would otherwise cause
8707 * dependency.c to refuse to perform the deletion.
8708 */
8709 attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8710 if (!OidIsValid(attrdefoid))
8711 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8712 RelationGetRelid(rel), attnum);
8713 (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8714
8715 /* Make above changes visible */
8716 CommandCounterIncrement();
8717
8718 /*
8719 * Get rid of the GENERATED expression itself. We use RESTRICT here for
8720 * safety, but at present we do not expect anything to depend on the
8721 * expression.
8722 */
8723 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8724 false, false);
8725
8726 /* Prepare to store the new expression, in the catalogs */
8727 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
8728 rawEnt->attnum = attnum;
8729 rawEnt->raw_default = newExpr;
8730 rawEnt->generated = attgenerated;
8731
8732 /* Store the generated expression */
8733 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8734 false, true, false, NULL);
8735
8736 /* Make above new expression visible */
8737 CommandCounterIncrement();
8738
8739 if (rewrite)
8740 {
8741 /* Prepare for table rewrite */
8742 defval = (Expr *) build_column_default(rel, attnum);
8743
8744 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
8745 newval->attnum = attnum;
8746 newval->expr = expression_planner(defval);
8747 newval->is_generated = true;
8748
8749 tab->newvals = lappend(tab->newvals, newval);
8750 tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
8751 }
8752
8753 /* Drop any pg_statistic entry for the column */
8754 RemoveStatistics(RelationGetRelid(rel), attnum);
8755
8756 InvokeObjectPostAlterHook(RelationRelationId,
8757 RelationGetRelid(rel), attnum);
8758
8759 ObjectAddressSubSet(address, RelationRelationId,
8760 RelationGetRelid(rel), attnum);
8761 return address;
8762 }
8763
8764 /*
8765 * ALTER TABLE ALTER COLUMN DROP EXPRESSION
8766 */
8767 static void
8768 ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
8769 {
8770 /*
8771 * Reject ONLY if there are child tables -- but only, of course, at the
8772 * top of the tree, otherwise it'd be impossible to run this command with
8773 * trees deeper than two levels. Caller already got lock.
8774 */
8775 if (!recurse && !recursing &&
8776 find_inheritance_children(RelationGetRelid(rel), NoLock))
8777 ereport(ERROR,
8778 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8779 errmsg("ALTER TABLE / DROP EXPRESSION must be applied to child tables too")));
8780
8781 /*
8782 * Cannot drop generation expression from inherited columns.
8783 */
8784 if (!recursing)
8785 {
8786 HeapTuple tuple;
8787 Form_pg_attribute attTup;
8788
8789 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), cmd->name);
8790 if (!HeapTupleIsValid(tuple))
8791 ereport(ERROR,
8792 (errcode(ERRCODE_UNDEFINED_COLUMN),
8793 errmsg("column \"%s\" of relation \"%s\" does not exist",
8794 cmd->name, RelationGetRelationName(rel))));
8795
8796 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8797
8798 if (attTup->attinhcount > 0)
8799 ereport(ERROR,
8800 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8801 errmsg("cannot drop generation expression from inherited column")));
8802 }
8803 }
8804
8805 /*
8806 * Return the address of the affected column.
8807 */
8808 static ObjectAddress
8809 ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
8810 {
8811 HeapTuple tuple;
8812 Form_pg_attribute attTup;
8813 AttrNumber attnum;
8814 Relation attrelation;
8815 Oid attrdefoid;
8816 ObjectAddress address;
8817
8818 attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8819 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8820 if (!HeapTupleIsValid(tuple))
8821 ereport(ERROR,
8822 (errcode(ERRCODE_UNDEFINED_COLUMN),
8823 errmsg("column \"%s\" of relation \"%s\" does not exist",
8824 colName, RelationGetRelationName(rel))));
8825
8826 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8827 attnum = attTup->attnum;
8828
8829 if (attnum <= 0)
8830 ereport(ERROR,
8831 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8832 errmsg("cannot alter system column \"%s\"",
8833 colName)));
8834
8835 /*
8836 * TODO: This could be done, but it would need a table rewrite to
8837 * materialize the generated values. Note that for the time being, we
8838 * still error with missing_ok, so that we don't silently leave the column
8839 * as generated.
8840 */
8841 if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
8842 ereport(ERROR,
8843 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8844 errmsg("ALTER TABLE / DROP EXPRESSION is not supported for virtual generated columns"),
8845 errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8846 colName, RelationGetRelationName(rel))));
8847
8848 if (!attTup->attgenerated)
8849 {
8850 if (!missing_ok)
8851 ereport(ERROR,
8852 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8853 errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8854 colName, RelationGetRelationName(rel))));
8855 else
8856 {
8857 ereport(NOTICE,
8858 (errmsg("column \"%s\" of relation \"%s\" is not a generated column, skipping",
8859 colName, RelationGetRelationName(rel))));
8860 heap_freetuple(tuple);
8861 table_close(attrelation, RowExclusiveLock);
8862 return InvalidObjectAddress;
8863 }
8864 }
8865
8866 /*
8867 * Mark the column as no longer generated. (The atthasdef flag needs to
8868 * get cleared too, but RemoveAttrDefault will handle that.)
8869 */
8870 attTup->attgenerated = '\0';
8871 CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8872
8873 InvokeObjectPostAlterHook(RelationRelationId,
8874 RelationGetRelid(rel),
8875 attnum);
8876 heap_freetuple(tuple);
8877
8878 table_close(attrelation, RowExclusiveLock);
8879
8880 /*
8881 * Drop the dependency records of the GENERATED expression, in particular
8882 * its INTERNAL dependency on the column, which would otherwise cause
8883 * dependency.c to refuse to perform the deletion.
8884 */
8885 attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8886 if (!OidIsValid(attrdefoid))
8887 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8888 RelationGetRelid(rel), attnum);
8889 (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8890
8891 /* Make above changes visible */
8892 CommandCounterIncrement();
8893
8894 /*
8895 * Get rid of the GENERATED expression itself. We use RESTRICT here for
8896 * safety, but at present we do not expect anything to depend on the
8897 * default.
8898 */
8899 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8900 false, false);
8901
8902 ObjectAddressSubSet(address, RelationRelationId,
8903 RelationGetRelid(rel), attnum);
8904 return address;
8905 }
8906
8907 /*
8908 * ALTER TABLE ALTER COLUMN SET STATISTICS
8909 *
8910 * Return value is the address of the modified column
8911 */
8912 static ObjectAddress
8913 ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
8914 {
8915 int newtarget = 0;
8916 bool newtarget_default;
8917 Relation attrelation;
8918 HeapTuple tuple,
8919 newtuple;
8920 Form_pg_attribute attrtuple;
8921 AttrNumber attnum;
8922 ObjectAddress address;
8923 Datum repl_val[Natts_pg_attribute];
8924 bool repl_null[Natts_pg_attribute];
8925 bool repl_repl[Natts_pg_attribute];
8926
8927 /*
8928 * We allow referencing columns by numbers only for indexes, since table
8929 * column numbers could contain gaps if columns are later dropped.
8930 */
8931 if (rel->rd_rel->relkind != RELKIND_INDEX &&
8932 rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
8933 !colName)
8934 ereport(ERROR,
8935 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8936 errmsg("cannot refer to non-index column by number")));
8937
8938 /* -1 was used in previous versions for the default setting */
8939 if (newValue && intVal(newValue) != -1)
8940 {
8941 newtarget = intVal(newValue);
8942 newtarget_default = false;
8943 }
8944 else
8945 newtarget_default = true;
8946
8947 if (!newtarget_default)
8948 {
8949 /*
8950 * Limit target to a sane range
8951 */
8952 if (newtarget < 0)
8953 {
8954 ereport(ERROR,
8955 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8956 errmsg("statistics target %d is too low",
8957 newtarget)));
8958 }
8959 else if (newtarget > MAX_STATISTICS_TARGET)
8960 {
8961 newtarget = MAX_STATISTICS_TARGET;
8962 ereport(WARNING,
8963 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8964 errmsg("lowering statistics target to %d",
8965 newtarget)));
8966 }
8967 }
8968
8969 attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8970
8971 if (colName)
8972 {
8973 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8974
8975 if (!HeapTupleIsValid(tuple))
8976 ereport(ERROR,
8977 (errcode(ERRCODE_UNDEFINED_COLUMN),
8978 errmsg("column \"%s\" of relation \"%s\" does not exist",
8979 colName, RelationGetRelationName(rel))));
8980 }
8981 else
8982 {
8983 tuple = SearchSysCacheAttNum(RelationGetRelid(rel), colNum);
8984
8985 if (!HeapTupleIsValid(tuple))
8986 ereport(ERROR,
8987 (errcode(ERRCODE_UNDEFINED_COLUMN),
8988 errmsg("column number %d of relation \"%s\" does not exist",
8989 colNum, RelationGetRelationName(rel))));
8990 }
8991
8992 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
8993
8994 attnum = attrtuple->attnum;
8995 if (attnum <= 0)
8996 ereport(ERROR,
8997 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8998 errmsg("cannot alter system column \"%s\"",
8999 colName)));
9000
9001 /*
9002 * Prevent this as long as the ANALYZE code skips virtual generated
9003 * columns.
9004 */
9005 if (attrtuple->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
9006 ereport(ERROR,
9007 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9008 errmsg("cannot alter statistics on virtual generated column \"%s\"",
9009 colName)));
9010
9011 if (rel->rd_rel->relkind == RELKIND_INDEX ||
9012 rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
9013 {
9014 if (attnum > rel->rd_index->indnkeyatts)
9015 ereport(ERROR,
9016 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9017 errmsg("cannot alter statistics on included column \"%s\" of index \"%s\"",
9018 NameStr(attrtuple->attname), RelationGetRelationName(rel))));
9019 else if (rel->rd_index->indkey.values[attnum - 1] != 0)
9020 ereport(ERROR,
9021 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9022 errmsg("cannot alter statistics on non-expression column \"%s\" of index \"%s\"",
9023 NameStr(attrtuple->attname), RelationGetRelationName(rel)),
9024 errhint("Alter statistics on table column instead.")));
9025 }
9026
9027 /* Build new tuple. */
9028 memset(repl_null, false, sizeof(repl_null));
9029 memset(repl_repl, false, sizeof(repl_repl));
9030 if (!newtarget_default)
9031 repl_val[Anum_pg_attribute_attstattarget - 1] = newtarget;
9032 else
9033 repl_null[Anum_pg_attribute_attstattarget - 1] = true;
9034 repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
9035 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9036 repl_val, repl_null, repl_repl);
9037 CatalogTupleUpdate(attrelation, &tuple->t_self, newtuple);
9038
9039 InvokeObjectPostAlterHook(RelationRelationId,
9040 RelationGetRelid(rel),
9041 attrtuple->attnum);
9042 ObjectAddressSubSet(address, RelationRelationId,
9043 RelationGetRelid(rel), attnum);
9044
9045 heap_freetuple(newtuple);
9046
9047 ReleaseSysCache(tuple);
9048
9049 table_close(attrelation, RowExclusiveLock);
9050
9051 return address;
9052 }
9053
9054 /*
9055 * Return value is the address of the modified column
9056 */
9057 static ObjectAddress
9058 ATExecSetOptions(Relation rel, const char *colName, Node *options,
9059 bool isReset, LOCKMODE lockmode)
9060 {
9061 Relation attrelation;
9062 HeapTuple tuple,
9063 newtuple;
9064 Form_pg_attribute attrtuple;
9065 AttrNumber attnum;
9066 Datum datum,
9067 newOptions;
9068 bool isnull;
9069 ObjectAddress address;
9070 Datum repl_val[Natts_pg_attribute];
9071 bool repl_null[Natts_pg_attribute];
9072 bool repl_repl[Natts_pg_attribute];
9073
9074 attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9075
9076 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9077
9078 if (!HeapTupleIsValid(tuple))
9079 ereport(ERROR,
9080 (errcode(ERRCODE_UNDEFINED_COLUMN),
9081 errmsg("column \"%s\" of relation \"%s\" does not exist",
9082 colName, RelationGetRelationName(rel))));
9083 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9084
9085 attnum = attrtuple->attnum;
9086 if (attnum <= 0)
9087 ereport(ERROR,
9088 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9089 errmsg("cannot alter system column \"%s\"",
9090 colName)));
9091
9092 /* Generate new proposed attoptions (text array) */
9093 datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
9094 &isnull);
9095 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9096 castNode(List, options), NULL, NULL,
9097 false, isReset);
9098 /* Validate new options */
9099 (void) attribute_reloptions(newOptions, true);
9100
9101 /* Build new tuple. */
9102 memset(repl_null, false, sizeof(repl_null));
9103 memset(repl_repl, false, sizeof(repl_repl));
9104 if (newOptions != (Datum) 0)
9105 repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
9106 else
9107 repl_null[Anum_pg_attribute_attoptions - 1] = true;
9108 repl_repl[Anum_pg_attribute_attoptions - 1] = true;
9109 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9110 repl_val, repl_null, repl_repl);
9111
9112 /* Update system catalog. */
9113 CatalogTupleUpdate(attrelation, &newtuple->t_self, newtuple);
9114
9115 InvokeObjectPostAlterHook(RelationRelationId,
9116 RelationGetRelid(rel),
9117 attrtuple->attnum);
9118 ObjectAddressSubSet(address, RelationRelationId,
9119 RelationGetRelid(rel), attnum);
9120
9121 heap_freetuple(newtuple);
9122
9123 ReleaseSysCache(tuple);
9124
9125 table_close(attrelation, RowExclusiveLock);
9126
9127 return address;
9128 }
9129
9130 /*
9131 * Helper function for ATExecSetStorage and ATExecSetCompression
9132 *
9133 * Set the attstorage and/or attcompression fields for index columns
9134 * associated with the specified table column.
9135 */
9136 static void
9137 SetIndexStorageProperties(Relation rel, Relation attrelation,
9138 AttrNumber attnum,
9139 bool setstorage, char newstorage,
9140 bool setcompression, char newcompression,
9141 LOCKMODE lockmode)
9142 {
9143 ListCell *lc;
9144
9145 foreach(lc, RelationGetIndexList(rel))
9146 {
9147 Oid indexoid = lfirst_oid(lc);
9148 Relation indrel;
9149 AttrNumber indattnum = 0;
9150 HeapTuple tuple;
9151
9152 indrel = index_open(indexoid, lockmode);
9153
9154 for (int i = 0; i < indrel->rd_index->indnatts; i++)
9155 {
9156 if (indrel->rd_index->indkey.values[i] == attnum)
9157 {
9158 indattnum = i + 1;
9159 break;
9160 }
9161 }
9162
9163 if (indattnum == 0)
9164 {
9165 index_close(indrel, lockmode);
9166 continue;
9167 }
9168
9169 tuple = SearchSysCacheCopyAttNum(RelationGetRelid(indrel), indattnum);
9170
9171 if (HeapTupleIsValid(tuple))
9172 {
9173 Form_pg_attribute attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9174
9175 if (setstorage)
9176 attrtuple->attstorage = newstorage;
9177
9178 if (setcompression)
9179 attrtuple->attcompression = newcompression;
9180
9181 CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9182
9183 InvokeObjectPostAlterHook(RelationRelationId,
9184 RelationGetRelid(rel),
9185 attrtuple->attnum);
9186
9187 heap_freetuple(tuple);
9188 }
9189
9190 index_close(indrel, lockmode);
9191 }
9192 }
9193
9194 /*
9195 * ALTER TABLE ALTER COLUMN SET STORAGE
9196 *
9197 * Return value is the address of the modified column
9198 */
9199 static ObjectAddress
9200 ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
9201 {
9202 Relation attrelation;
9203 HeapTuple tuple;
9204 Form_pg_attribute attrtuple;
9205 AttrNumber attnum;
9206 ObjectAddress address;
9207
9208 attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9209
9210 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9211
9212 if (!HeapTupleIsValid(tuple))
9213 ereport(ERROR,
9214 (errcode(ERRCODE_UNDEFINED_COLUMN),
9215 errmsg("column \"%s\" of relation \"%s\" does not exist",
9216 colName, RelationGetRelationName(rel))));
9217 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9218
9219 attnum = attrtuple->attnum;
9220 if (attnum <= 0)
9221 ereport(ERROR,
9222 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9223 errmsg("cannot alter system column \"%s\"",
9224 colName)));
9225
9226 attrtuple->attstorage = GetAttributeStorage(attrtuple->atttypid, strVal(newValue));
9227
9228 CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9229
9230 InvokeObjectPostAlterHook(RelationRelationId,
9231 RelationGetRelid(rel),
9232 attrtuple->attnum);
9233
9234 /*
9235 * Apply the change to indexes as well (only for simple index columns,
9236 * matching behavior of index.c ConstructTupleDescriptor()).
9237 */
9238 SetIndexStorageProperties(rel, attrelation, attnum,
9239 true, attrtuple->attstorage,
9240 false, 0,
9241 lockmode);
9242
9243 heap_freetuple(tuple);
9244
9245 table_close(attrelation, RowExclusiveLock);
9246
9247 ObjectAddressSubSet(address, RelationRelationId,
9248 RelationGetRelid(rel), attnum);
9249 return address;
9250 }
9251
9252
9253 /*
9254 * ALTER TABLE DROP COLUMN
9255 *
9256 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
9257 * because we have to decide at runtime whether to recurse or not depending
9258 * on whether attinhcount goes to zero or not. (We can't check this in a
9259 * static pre-pass because it won't handle multiple inheritance situations
9260 * correctly.)
9261 */
9262 static void
9263 ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
9264 AlterTableCmd *cmd, LOCKMODE lockmode,
9265 AlterTableUtilityContext *context)
9266 {
9267 if (rel->rd_rel->reloftype && !recursing)
9268 ereport(ERROR,
9269 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9270 errmsg("cannot drop column from typed table")));
9271
9272 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
9273 ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
9274
9275 if (recurse)
9276 cmd->recurse = true;
9277 }
9278
9279 /*
9280 * Drops column 'colName' from relation 'rel' and returns the address of the
9281 * dropped column. The column is also dropped (or marked as no longer
9282 * inherited from relation) from the relation's inheritance children, if any.
9283 *
9284 * In the recursive invocations for inheritance child relations, instead of
9285 * dropping the column directly (if to be dropped at all), its object address
9286 * is added to 'addrs', which must be non-NULL in such invocations. All
9287 * columns are dropped at the same time after all the children have been
9288 * checked recursively.
9289 */
9290 static ObjectAddress
9291 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
9292 DropBehavior behavior,
9293 bool recurse, bool recursing,
9294 bool missing_ok, LOCKMODE lockmode,
9295 ObjectAddresses *addrs)
9296 {
9297 HeapTuple tuple;
9298 Form_pg_attribute targetatt;
9299 AttrNumber attnum;
9300 List *children;
9301 ObjectAddress object;
9302 bool is_expr;
9303
9304 /* At top level, permission check was done in ATPrepCmd, else do it */
9305 if (recursing)
9306 ATSimplePermissions(AT_DropColumn, rel,
9307 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
9308
9309 /* Initialize addrs on the first invocation */
9310 Assert(!recursing || addrs != NULL);
9311
9312 /* since this function recurses, it could be driven to stack overflow */
9313 check_stack_depth();
9314
9315 if (!recursing)
9316 addrs = new_object_addresses();
9317
9318 /*
9319 * get the number of the attribute
9320 */
9321 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9322 if (!HeapTupleIsValid(tuple))
9323 {
9324 if (!missing_ok)
9325 {
9326 ereport(ERROR,
9327 (errcode(ERRCODE_UNDEFINED_COLUMN),
9328 errmsg("column \"%s\" of relation \"%s\" does not exist",
9329 colName, RelationGetRelationName(rel))));
9330 }
9331 else
9332 {
9333 ereport(NOTICE,
9334 (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
9335 colName, RelationGetRelationName(rel))));
9336 return InvalidObjectAddress;
9337 }
9338 }
9339 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
9340
9341 attnum = targetatt->attnum;
9342
9343 /* Can't drop a system attribute */
9344 if (attnum <= 0)
9345 ereport(ERROR,
9346 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9347 errmsg("cannot drop system column \"%s\"",
9348 colName)));
9349
9350 /*
9351 * Don't drop inherited columns, unless recursing (presumably from a drop
9352 * of the parent column)
9353 */
9354 if (targetatt->attinhcount > 0 && !recursing)
9355 ereport(ERROR,
9356 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9357 errmsg("cannot drop inherited column \"%s\"",
9358 colName)));
9359
9360 /*
9361 * Don't drop columns used in the partition key, either. (If we let this
9362 * go through, the key column's dependencies would cause a cascaded drop
9363 * of the whole table, which is surely not what the user expected.)
9364 */
9365 if (has_partition_attrs(rel,
9366 bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
9367 &is_expr))
9368 ereport(ERROR,
9369 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9370 errmsg("cannot drop column \"%s\" because it is part of the partition key of relation \"%s\"",
9371 colName, RelationGetRelationName(rel))));
9372
9373 ReleaseSysCache(tuple);
9374
9375 /*
9376 * Propagate to children as appropriate. Unlike most other ALTER
9377 * routines, we have to do this one level of recursion at a time; we can't
9378 * use find_all_inheritors to do it in one pass.
9379 */
9380 children =
9381 find_inheritance_children(RelationGetRelid(rel), lockmode);
9382
9383 if (children)
9384 {
9385 Relation attr_rel;
9386 ListCell *child;
9387
9388 /*
9389 * In case of a partitioned table, the column must be dropped from the
9390 * partitions as well.
9391 */
9392 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
9393 ereport(ERROR,
9394 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9395 errmsg("cannot drop column from only the partitioned table when partitions exist"),
9396 errhint("Do not specify the ONLY keyword.")));
9397
9398 attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
9399 foreach(child, children)
9400 {
9401 Oid childrelid = lfirst_oid(child);
9402 Relation childrel;
9403 Form_pg_attribute childatt;
9404
9405 /* find_inheritance_children already got lock */
9406 childrel = table_open(childrelid, NoLock);
9407 CheckAlterTableIsSafe(childrel);
9408
9409 tuple = SearchSysCacheCopyAttName(childrelid, colName);
9410 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
9411 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
9412 colName, childrelid);
9413 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
9414
9415 if (childatt->attinhcount <= 0) /* shouldn't happen */
9416 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
9417 childrelid, colName);
9418
9419 if (recurse)
9420 {
9421 /*
9422 * If the child column has other definition sources, just
9423 * decrement its inheritance count; if not, recurse to delete
9424 * it.
9425 */
9426 if (childatt->attinhcount == 1 && !childatt->attislocal)
9427 {
9428 /* Time to delete this child column, too */
9429 ATExecDropColumn(wqueue, childrel, colName,
9430 behavior, true, true,
9431 false, lockmode, addrs);
9432 }
9433 else
9434 {
9435 /* Child column must survive my deletion */
9436 childatt->attinhcount--;
9437
9438 CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9439
9440 /* Make update visible */
9441 CommandCounterIncrement();
9442 }
9443 }
9444 else
9445 {
9446 /*
9447 * If we were told to drop ONLY in this table (no recursion),
9448 * we need to mark the inheritors' attributes as locally
9449 * defined rather than inherited.
9450 */
9451 childatt->attinhcount--;
9452 childatt->attislocal = true;
9453
9454 CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9455
9456 /* Make update visible */
9457 CommandCounterIncrement();
9458 }
9459
9460 heap_freetuple(tuple);
9461
9462 table_close(childrel, NoLock);
9463 }
9464 table_close(attr_rel, RowExclusiveLock);
9465 }
9466
9467 /* Add object to delete */
9468 object.classId = RelationRelationId;
9469 object.objectId = RelationGetRelid(rel);
9470 object.objectSubId = attnum;
9471 add_exact_object_address(&object, addrs);
9472
9473 if (!recursing)
9474 {
9475 /* Recursion has ended, drop everything that was collected */
9476 performMultipleDeletions(addrs, behavior, 0);
9477 free_object_addresses(addrs);
9478 }
9479
9480 return object;
9481 }
9482
9483 /*
9484 * Prepare to add a primary key on a table, by adding not-null constraints
9485 * on all columns.
9486 *
9487 * The not-null constraints for a primary key must cover the whole inheritance
9488 * hierarchy (failing to ensure that leads to funny corner cases). For the
9489 * normal case where we're asked to recurse, this routine checks if the
9490 * not-null constraints exist already, and if not queues a requirement for
9491 * them to be created by phase 2.
9492 *
9493 * For the case where we're asked not to recurse, we verify that a not-null
9494 * constraint exists on each column of each (direct) child table, throwing an
9495 * error if not. Not throwing an error would also work, because a not-null
9496 * constraint would be created anyway, but it'd cause a silent scan of the
9497 * child table to verify absence of nulls. We prefer to let the user know so
9498 * that they can add the constraint manually without having to hold
9499 * AccessExclusiveLock while at it.
9500 *
9501 * However, it's also important that we do not acquire locks on children if
9502 * the not-null constraints already exist on the parent, to avoid risking
9503 * deadlocks during parallel pg_restore of PKs on partitioned tables.
9504 */
9505 static void
9506 ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
9507 bool recurse, LOCKMODE lockmode,
9508 AlterTableUtilityContext *context)
9509 {
9510 Constraint *pkconstr;
9511 List *children = NIL;
9512 bool got_children = false;
9513
9514 pkconstr = castNode(Constraint, cmd->def);
9515 if (pkconstr->contype != CONSTR_PRIMARY)
9516 return;
9517
9518 /* Verify that columns are not-null, or request that they be made so */
9519 foreach_node(String, column, pkconstr->keys)
9520 {
9521 AlterTableCmd *newcmd;
9522 Constraint *nnconstr;
9523 HeapTuple tuple;
9524
9525 /*
9526 * First check if a suitable constraint exists. If it does, we don't
9527 * need to request another one. We do need to bail out if it's not
9528 * valid, though.
9529 */
9530 tuple = findNotNullConstraint(RelationGetRelid(rel), strVal(column));
9531 if (tuple != NULL)
9532 {
9533 verifyNotNullPKCompatible(tuple, strVal(column));
9534
9535 /* All good with this one; don't request another */
9536 heap_freetuple(tuple);
9537 continue;
9538 }
9539 else if (!recurse)
9540 {
9541 /*
9542 * No constraint on this column. Asked not to recurse, we won't
9543 * create one here, but verify that all children have one.
9544 */
9545 if (!got_children)
9546 {
9547 children = find_inheritance_children(RelationGetRelid(rel),
9548 lockmode);
9549 /* only search for children on the first time through */
9550 got_children = true;
9551 }
9552
9553 foreach_oid(childrelid, children)
9554 {
9555 HeapTuple tup;
9556
9557 tup = findNotNullConstraint(childrelid, strVal(column));
9558 if (!tup)
9559 ereport(ERROR,
9560 errmsg("column \"%s\" of table \"%s\" is not marked NOT NULL",
9561 strVal(column), get_rel_name(childrelid)));
9562 /* verify it's good enough */
9563 verifyNotNullPKCompatible(tup, strVal(column));
9564 }
9565 }
9566
9567 /* This column is not already not-null, so add it to the queue */
9568 nnconstr = makeNotNullConstraint(column);
9569
9570 newcmd = makeNode(AlterTableCmd);
9571 newcmd->subtype = AT_AddConstraint;
9572 /* note we force recurse=true here; see above */
9573 newcmd->recurse = true;
9574 newcmd->def = (Node *) nnconstr;
9575
9576 ATPrepCmd(wqueue, rel, newcmd, true, false, lockmode, context);
9577 }
9578 }
9579
9580 /*
9581 * Verify whether the given not-null constraint is compatible with a
9582 * primary key. If not, an error is thrown.
9583 */
9584 static void
9585 verifyNotNullPKCompatible(HeapTuple tuple, const char *colname)
9586 {
9587 Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
9588
9589 if (conForm->contype != CONSTRAINT_NOTNULL)
9590 elog(ERROR, "constraint %u is not a not-null constraint", conForm->oid);
9591
9592 /* a NO INHERIT constraint is no good */
9593 if (conForm->connoinherit)
9594 ereport(ERROR,
9595 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9596 errmsg("cannot create primary key on column \"%s\"", colname),
9597 /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9598 errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9599 NameStr(conForm->conname), colname,
9600 get_rel_name(conForm->conrelid), "NO INHERIT"),
9601 errhint("You might need to make the existing constraint inheritable using %s.",
9602 "ALTER TABLE ... ALTER CONSTRAINT ... INHERIT"));
9603
9604 /* an unvalidated constraint is no good */
9605 if (!conForm->convalidated)
9606 ereport(ERROR,
9607 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9608 errmsg("cannot create primary key on column \"%s\"", colname),
9609 /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9610 errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9611 NameStr(conForm->conname), colname,
9612 get_rel_name(conForm->conrelid), "NOT VALID"),
9613 errhint("You might need to validate it using %s.",
9614 "ALTER TABLE ... VALIDATE CONSTRAINT"));
9615 }
9616
9617 /*
9618 * ALTER TABLE ADD INDEX
9619 *
9620 * There is no such command in the grammar, but parse_utilcmd.c converts
9621 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
9622 * us schedule creation of the index at the appropriate time during ALTER.
9623 *
9624 * Return value is the address of the new index.
9625 */
9626 static ObjectAddress
9627 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
9628 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9629 {
9630 bool check_rights;
9631 bool skip_build;
9632 bool quiet;
9633 ObjectAddress address;
9634
9635 Assert(IsA(stmt, IndexStmt));
9636 Assert(!stmt->concurrent);
9637
9638 /* The IndexStmt has already been through transformIndexStmt */
9639 Assert(stmt->transformed);
9640
9641 /* suppress schema rights check when rebuilding existing index */
9642 check_rights = !is_rebuild;
9643 /* skip index build if phase 3 will do it or we're reusing an old one */
9644 skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
9645 /* suppress notices when rebuilding existing index */
9646 quiet = is_rebuild;
9647
9648 address = DefineIndex(RelationGetRelid(rel),
9649 stmt,
9650 InvalidOid, /* no predefined OID */
9651 InvalidOid, /* no parent index */
9652 InvalidOid, /* no parent constraint */
9653 -1, /* total_parts unknown */
9654 true, /* is_alter_table */
9655 check_rights,
9656 false, /* check_not_in_use - we did it already */
9657 skip_build,
9658 quiet);
9659
9660 /*
9661 * If TryReuseIndex() stashed a relfilenumber for us, we used it for the
9662 * new index instead of building from scratch. Restore associated fields.
9663 * This may store InvalidSubTransactionId in both fields, in which case
9664 * relcache.c will assume it can rebuild the relcache entry. Hence, do
9665 * this after the CCI that made catalog rows visible to any rebuild. The
9666 * DROP of the old edition of this index will have scheduled the storage
9667 * for deletion at commit, so cancel that pending deletion.
9668 */
9669 if (RelFileNumberIsValid(stmt->oldNumber))
9670 {
9671 Relation irel = index_open(address.objectId, NoLock);
9672
9673 irel->rd_createSubid = stmt->oldCreateSubid;
9674 irel->rd_firstRelfilelocatorSubid = stmt->oldFirstRelfilelocatorSubid;
9675 RelationPreserveStorage(irel->rd_locator, true);
9676 index_close(irel, NoLock);
9677 }
9678
9679 return address;
9680 }
9681
9682 /*
9683 * ALTER TABLE ADD STATISTICS
9684 *
9685 * This is no such command in the grammar, but we use this internally to add
9686 * AT_ReAddStatistics subcommands to rebuild extended statistics after a table
9687 * column type change.
9688 */
9689 static ObjectAddress
9690 ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
9691 CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9692 {
9693 ObjectAddress address;
9694
9695 Assert(IsA(stmt, CreateStatsStmt));
9696
9697 /* The CreateStatsStmt has already been through transformStatsStmt */
9698 Assert(stmt->transformed);
9699
9700 /* The owner must be set to the original statistics owner */
9701 Assert(OidIsValid(stmt->owner));
9702
9703 address = CreateStatistics(list_make1_oid(RelationGetRelid(rel)),
9704 stmt, !is_rebuild);
9705
9706 return address;
9707 }
9708
9709 /*
9710 * ALTER TABLE ADD CONSTRAINT USING INDEX
9711 *
9712 * Returns the address of the new constraint.
9713 */
9714 static ObjectAddress
9715 ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
9716 IndexStmt *stmt, LOCKMODE lockmode)
9717 {
9718 Oid index_oid = stmt->indexOid;
9719 Relation indexRel;
9720 char *indexName;
9721 IndexInfo *indexInfo;
9722 char *constraintName;
9723 char constraintType;
9724 ObjectAddress address;
9725 bits16 flags;
9726
9727 Assert(IsA(stmt, IndexStmt));
9728 Assert(OidIsValid(index_oid));
9729 Assert(stmt->isconstraint);
9730
9731 /*
9732 * Doing this on partitioned tables is not a simple feature to implement,
9733 * so let's punt for now.
9734 */
9735 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
9736 ereport(ERROR,
9737 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9738 errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
9739
9740 indexRel = index_open(index_oid, AccessShareLock);
9741
9742 indexName = pstrdup(RelationGetRelationName(indexRel));
9743
9744 indexInfo = BuildIndexInfo(indexRel);
9745
9746 /* this should have been checked at parse time */
9747 if (!indexInfo->ii_Unique)
9748 elog(ERROR, "index \"%s\" is not unique", indexName);
9749
9750 /*
9751 * Determine name to assign to constraint. We require a constraint to
9752 * have the same name as the underlying index; therefore, use the index's
9753 * existing name as the default constraint name, and if the user
9754 * explicitly gives some other name for the constraint, rename the index
9755 * to match.
9756 */
9757 constraintName = stmt->idxname;
9758 if (constraintName == NULL)
9759 constraintName = indexName;
9760 else if (strcmp(constraintName, indexName) != 0)
9761 {
9762 ereport(NOTICE,
9763 (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
9764 indexName, constraintName)));
9765 RenameRelationInternal(index_oid, constraintName, false, true);
9766 }
9767
9768 /* Extra checks needed if making primary key */
9769 if (stmt->primary)
9770 index_check_primary_key(rel, indexInfo, true, stmt);
9771
9772 /* Note we currently don't support EXCLUSION constraints here */
9773 if (stmt->primary)
9774 constraintType = CONSTRAINT_PRIMARY;
9775 else
9776 constraintType = CONSTRAINT_UNIQUE;
9777
9778 /* Create the catalog entries for the constraint */
9779 flags = INDEX_CONSTR_CREATE_UPDATE_INDEX |
9780 INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS |
9781 (stmt->initdeferred ? INDEX_CONSTR_CREATE_INIT_DEFERRED : 0) |
9782 (stmt->deferrable ? INDEX_CONSTR_CREATE_DEFERRABLE : 0) |
9783 (stmt->primary ? INDEX_CONSTR_CREATE_MARK_AS_PRIMARY : 0);
9784
9785 address = index_constraint_create(rel,
9786 index_oid,
9787 InvalidOid,
9788 indexInfo,
9789 constraintName,
9790 constraintType,
9791 flags,
9792 allowSystemTableMods,
9793 false); /* is_internal */
9794
9795 index_close(indexRel, NoLock);
9796
9797 return address;
9798 }
9799
9800 /*
9801 * ALTER TABLE ADD CONSTRAINT
9802 *
9803 * Return value is the address of the new constraint; if no constraint was
9804 * added, InvalidObjectAddress is returned.
9805 */
9806 static ObjectAddress
9807 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
9808 Constraint *newConstraint, bool recurse, bool is_readd,
9809 LOCKMODE lockmode)
9810 {
9811 ObjectAddress address = InvalidObjectAddress;
9812
9813 Assert(IsA(newConstraint, Constraint));
9814
9815 /*
9816 * Currently, we only expect to see CONSTR_CHECK, CONSTR_NOTNULL and
9817 * CONSTR_FOREIGN nodes arriving here (see the preprocessing done in
9818 * parse_utilcmd.c).
9819 */
9820 switch (newConstraint->contype)
9821 {
9822 case CONSTR_CHECK:
9823 case CONSTR_NOTNULL:
9824 address =
9825 ATAddCheckNNConstraint(wqueue, tab, rel,
9826 newConstraint, recurse, false, is_readd,
9827 lockmode);
9828 break;
9829
9830 case CONSTR_FOREIGN:
9831
9832 /*
9833 * Assign or validate constraint name
9834 */
9835 if (newConstraint->conname)
9836 {
9837 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
9838 RelationGetRelid(rel),
9839 newConstraint->conname))
9840 ereport(ERROR,
9841 (errcode(ERRCODE_DUPLICATE_OBJECT),
9842 errmsg("constraint \"%s\" for relation \"%s\" already exists",
9843 newConstraint->conname,
9844 RelationGetRelationName(rel))));
9845 }
9846 else
9847 newConstraint->conname =
9848 ChooseConstraintName(RelationGetRelationName(rel),
9849 ChooseForeignKeyConstraintNameAddition(newConstraint->fk_attrs),
9850 "fkey",
9851 RelationGetNamespace(rel),
9852 NIL);
9853
9854 address = ATAddForeignKeyConstraint(wqueue, tab, rel,
9855 newConstraint,
9856 recurse, false,
9857 lockmode);
9858 break;
9859
9860 default:
9861 elog(ERROR, "unrecognized constraint type: %d",
9862 (int) newConstraint->contype);
9863 }
9864
9865 return address;
9866 }
9867
9868 /*
9869 * Generate the column-name portion of the constraint name for a new foreign
9870 * key given the list of column names that reference the referenced
9871 * table. This will be passed to ChooseConstraintName along with the parent
9872 * table name and the "fkey" suffix.
9873 *
9874 * We know that less than NAMEDATALEN characters will actually be used, so we
9875 * can truncate the result once we've generated that many.
9876 *
9877 * XXX see also ChooseExtendedStatisticNameAddition and
9878 * ChooseIndexNameAddition.
9879 */
9880 static char *
9881 ChooseForeignKeyConstraintNameAddition(List *colnames)
9882 {
9883 char buf[NAMEDATALEN * 2];
9884 int buflen = 0;
9885 ListCell *lc;
9886
9887 buf[0] = '\0';
9888 foreach(lc, colnames)
9889 {
9890 const char *name = strVal(lfirst(lc));
9891
9892 if (buflen > 0)
9893 buf[buflen++] = '_'; /* insert _ between names */
9894
9895 /*
9896 * At this point we have buflen <= NAMEDATALEN. name should be less
9897 * than NAMEDATALEN already, but use strlcpy for paranoia.
9898 */
9899 strlcpy(buf + buflen, name, NAMEDATALEN);
9900 buflen += strlen(buf + buflen);
9901 if (buflen >= NAMEDATALEN)
9902 break;
9903 }
9904 return pstrdup(buf);
9905 }
9906
9907 /*
9908 * Add a check or not-null constraint to a single table and its children.
9909 * Returns the address of the constraint added to the parent relation,
9910 * if one gets added, or InvalidObjectAddress otherwise.
9911 *
9912 * Subroutine for ATExecAddConstraint.
9913 *
9914 * We must recurse to child tables during execution, rather than using
9915 * ALTER TABLE's normal prep-time recursion. The reason is that all the
9916 * constraints *must* be given the same name, else they won't be seen as
9917 * related later. If the user didn't explicitly specify a name, then
9918 * AddRelationNewConstraints would normally assign different names to the
9919 * child constraints. To fix that, we must capture the name assigned at
9920 * the parent table and pass that down.
9921 */
9922 static ObjectAddress
9923 ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
9924 Constraint *constr, bool recurse, bool recursing,
9925 bool is_readd, LOCKMODE lockmode)
9926 {
9927 List *newcons;
9928 ListCell *lcon;
9929 List *children;
9930 ListCell *child;
9931 ObjectAddress address = InvalidObjectAddress;
9932
9933 /* Guard against stack overflow due to overly deep inheritance tree. */
9934 check_stack_depth();
9935
9936 /* At top level, permission check was done in ATPrepCmd, else do it */
9937 if (recursing)
9938 ATSimplePermissions(AT_AddConstraint, rel,
9939 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
9940
9941 /*
9942 * Call AddRelationNewConstraints to do the work, making sure it works on
9943 * a copy of the Constraint so transformExpr can't modify the original. It
9944 * returns a list of cooked constraints.
9945 *
9946 * If the constraint ends up getting merged with a pre-existing one, it's
9947 * omitted from the returned list, which is what we want: we do not need
9948 * to do any validation work. That can only happen at child tables,
9949 * though, since we disallow merging at the top level.
9950 */
9951 newcons = AddRelationNewConstraints(rel, NIL,
9952 list_make1(copyObject(constr)),
9953 recursing || is_readd, /* allow_merge */
9954 !recursing, /* is_local */
9955 is_readd, /* is_internal */
9956 NULL); /* queryString not available
9957 * here */
9958
9959 /* we don't expect more than one constraint here */
9960 Assert(list_length(newcons) <= 1);
9961
9962 /* Add each to-be-validated constraint to Phase 3's queue */
9963 foreach(lcon, newcons)
9964 {
9965 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
9966
9967 if (!ccon->skip_validation && ccon->contype != CONSTR_NOTNULL)
9968 {
9969 NewConstraint *newcon;
9970
9971 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
9972 newcon->name = ccon->name;
9973 newcon->contype = ccon->contype;
9974 newcon->qual = ccon->expr;
9975
9976 tab->constraints = lappend(tab->constraints, newcon);
9977 }
9978
9979 /* Save the actually assigned name if it was defaulted */
9980 if (constr->conname == NULL)
9981 constr->conname = ccon->name;
9982
9983 /*
9984 * If adding a valid not-null constraint, set the pg_attribute flag
9985 * and tell phase 3 to verify existing rows, if needed. For an
9986 * invalid constraint, just set attnotnull, without queueing
9987 * verification.
9988 */
9989 if (constr->contype == CONSTR_NOTNULL)
9990 set_attnotnull(wqueue, rel, ccon->attnum,
9991 !constr->skip_validation);
9992
9993 ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
9994 }
9995
9996 /* At this point we must have a locked-down name to use */
9997 Assert(newcons == NIL || constr->conname != NULL);
9998
9999 /* Advance command counter in case same table is visited multiple times */
10000 CommandCounterIncrement();
10001
10002 /*
10003 * If the constraint got merged with an existing constraint, we're done.
10004 * We mustn't recurse to child tables in this case, because they've
10005 * already got the constraint, and visiting them again would lead to an
10006 * incorrect value for coninhcount.
10007 */
10008 if (newcons == NIL)
10009 return address;
10010
10011 /*
10012 * If adding a NO INHERIT constraint, no need to find our children.
10013 */
10014 if (constr->is_no_inherit)
10015 return address;
10016
10017 /*
10018 * Propagate to children as appropriate. Unlike most other ALTER
10019 * routines, we have to do this one level of recursion at a time; we can't
10020 * use find_all_inheritors to do it in one pass.
10021 */
10022 children =
10023 find_inheritance_children(RelationGetRelid(rel), lockmode);
10024
10025 /*
10026 * Check if ONLY was specified with ALTER TABLE. If so, allow the
10027 * constraint creation only if there are no children currently. Error out
10028 * otherwise.
10029 */
10030 if (!recurse && children != NIL)
10031 ereport(ERROR,
10032 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10033 errmsg("constraint must be added to child tables too")));
10034
10035 /*
10036 * Recurse to create the constraint on each child.
10037 */
10038 foreach(child, children)
10039 {
10040 Oid childrelid = lfirst_oid(child);
10041 Relation childrel;
10042 AlteredTableInfo *childtab;
10043
10044 /* find_inheritance_children already got lock */
10045 childrel = table_open(childrelid, NoLock);
10046 CheckAlterTableIsSafe(childrel);
10047
10048 /* Find or create work queue entry for this table */
10049 childtab = ATGetQueueEntry(wqueue, childrel);
10050
10051 /* Recurse to this child */
10052 ATAddCheckNNConstraint(wqueue, childtab, childrel,
10053 constr, recurse, true, is_readd, lockmode);
10054
10055 table_close(childrel, NoLock);
10056 }
10057
10058 return address;
10059 }
10060
10061 /*
10062 * Add a foreign-key constraint to a single table; return the new constraint's
10063 * address.
10064 *
10065 * Subroutine for ATExecAddConstraint. Must already hold exclusive
10066 * lock on the rel, and have done appropriate validity checks for it.
10067 * We do permissions checks here, however.
10068 *
10069 * When the referenced or referencing tables (or both) are partitioned,
10070 * multiple pg_constraint rows are required -- one for each partitioned table
10071 * and each partition on each side (fortunately, not one for every combination
10072 * thereof). We also need action triggers on each leaf partition on the
10073 * referenced side, and check triggers on each leaf partition on the
10074 * referencing side.
10075 */
10076 static ObjectAddress
10077 ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10078 Constraint *fkconstraint,
10079 bool recurse, bool recursing, LOCKMODE lockmode)
10080 {
10081 Relation pkrel;
10082 int16 pkattnum[INDEX_MAX_KEYS] = {0};
10083 int16 fkattnum[INDEX_MAX_KEYS] = {0};
10084 Oid pktypoid[INDEX_MAX_KEYS] = {0};
10085 Oid fktypoid[INDEX_MAX_KEYS] = {0};
10086 Oid pkcolloid[INDEX_MAX_KEYS] = {0};
10087 Oid fkcolloid[INDEX_MAX_KEYS] = {0};
10088 Oid opclasses[INDEX_MAX_KEYS] = {0};
10089 Oid pfeqoperators[INDEX_MAX_KEYS] = {0};
10090 Oid ppeqoperators[INDEX_MAX_KEYS] = {0};
10091 Oid ffeqoperators[INDEX_MAX_KEYS] = {0};
10092 int16 fkdelsetcols[INDEX_MAX_KEYS] = {0};
10093 bool with_period;
10094 bool pk_has_without_overlaps;
10095 int i;
10096 int numfks,
10097 numpks,
10098 numfkdelsetcols;
10099 Oid indexOid;
10100 bool old_check_ok;
10101 ObjectAddress address;
10102 ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
10103
10104 /*
10105 * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
10106 * delete rows out from under us.
10107 */
10108 if (OidIsValid(fkconstraint->old_pktable_oid))
10109 pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
10110 else
10111 pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
10112
10113 /*
10114 * Validity checks (permission checks wait till we have the column
10115 * numbers)
10116 */
10117 if (!recurse && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10118 ereport(ERROR,
10119 errcode(ERRCODE_WRONG_OBJECT_TYPE),
10120 errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
10121 RelationGetRelationName(rel),
10122 RelationGetRelationName(pkrel)));
10123
10124 if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10125 pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10126 ereport(ERROR,
10127 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10128 errmsg("referenced relation \"%s\" is not a table",
10129 RelationGetRelationName(pkrel))));
10130
10131 if (!allowSystemTableMods && IsSystemRelation(pkrel))
10132 ereport(ERROR,
10133 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
10134 errmsg("permission denied: \"%s\" is a system catalog",
10135 RelationGetRelationName(pkrel))));
10136
10137 /*
10138 * References from permanent or unlogged tables to temp tables, and from
10139 * permanent tables to unlogged tables, are disallowed because the
10140 * referenced data can vanish out from under us. References from temp
10141 * tables to any other table type are also disallowed, because other
10142 * backends might need to run the RI triggers on the perm table, but they
10143 * can't reliably see tuples in the local buffers of other backends.
10144 */
10145 switch (rel->rd_rel->relpersistence)
10146 {
10147 case RELPERSISTENCE_PERMANENT:
10148 if (!RelationIsPermanent(pkrel))
10149 ereport(ERROR,
10150 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10151 errmsg("constraints on permanent tables may reference only permanent tables")));
10152 break;
10153 case RELPERSISTENCE_UNLOGGED:
10154 if (!RelationIsPermanent(pkrel)
10155 && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
10156 ereport(ERROR,
10157 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10158 errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
10159 break;
10160 case RELPERSISTENCE_TEMP:
10161 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
10162 ereport(ERROR,
10163 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10164 errmsg("constraints on temporary tables may reference only temporary tables")));
10165 if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
10166 ereport(ERROR,
10167 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10168 errmsg("constraints on temporary tables must involve temporary tables of this session")));
10169 break;
10170 }
10171
10172 /*
10173 * Look up the referencing attributes to make sure they exist, and record
10174 * their attnums and type and collation OIDs.
10175 */
10176 numfks = transformColumnNameList(RelationGetRelid(rel),
10177 fkconstraint->fk_attrs,
10178 fkattnum, fktypoid, fkcolloid);
10179 with_period = fkconstraint->fk_with_period || fkconstraint->pk_with_period;
10180 if (with_period && !fkconstraint->fk_with_period)
10181 ereport(ERROR,
10182 errcode(ERRCODE_INVALID_FOREIGN_KEY),
10183 errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10184
10185 numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
10186 fkconstraint->fk_del_set_cols,
10187 fkdelsetcols, NULL, NULL);
10188 numfkdelsetcols = validateFkOnDeleteSetColumns(numfks, fkattnum,
10189 numfkdelsetcols,
10190 fkdelsetcols,
10191 fkconstraint->fk_del_set_cols);
10192
10193 /*
10194 * If the attribute list for the referenced table was omitted, lookup the
10195 * definition of the primary key and use it. Otherwise, validate the
10196 * supplied attribute list. In either case, discover the index OID and
10197 * index opclasses, and the attnums and type and collation OIDs of the
10198 * attributes.
10199 */
10200 if (fkconstraint->pk_attrs == NIL)
10201 {
10202 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
10203 &fkconstraint->pk_attrs,
10204 pkattnum, pktypoid, pkcolloid,
10205 opclasses, &pk_has_without_overlaps);
10206
10207 /* If the primary key uses WITHOUT OVERLAPS, the fk must use PERIOD */
10208 if (pk_has_without_overlaps && !fkconstraint->fk_with_period)
10209 ereport(ERROR,
10210 errcode(ERRCODE_INVALID_FOREIGN_KEY),
10211 errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10212 }
10213 else
10214 {
10215 numpks = transformColumnNameList(RelationGetRelid(pkrel),
10216 fkconstraint->pk_attrs,
10217 pkattnum, pktypoid, pkcolloid);
10218
10219 /* Since we got pk_attrs, one should be a period. */
10220 if (with_period && !fkconstraint->pk_with_period)
10221 ereport(ERROR,
10222 errcode(ERRCODE_INVALID_FOREIGN_KEY),
10223 errmsg("foreign key uses PERIOD on the referencing table but not the referenced table"));
10224
10225 /* Look for an index matching the column list */
10226 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
10227 with_period, opclasses, &pk_has_without_overlaps);
10228 }
10229
10230 /*
10231 * If the referenced primary key has WITHOUT OVERLAPS, the foreign key
10232 * must use PERIOD.
10233 */
10234 if (pk_has_without_overlaps && !with_period)
10235 ereport(ERROR,
10236 errcode(ERRCODE_INVALID_FOREIGN_KEY),
10237 errmsg("foreign key must use PERIOD when referencing a primary key using WITHOUT OVERLAPS"));
10238
10239 /*
10240 * Now we can check permissions.
10241 */
10242 checkFkeyPermissions(pkrel, pkattnum, numpks);
10243
10244 /*
10245 * Check some things for generated columns.
10246 */
10247 for (i = 0; i < numfks; i++)
10248 {
10249 char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
10250
10251 if (attgenerated)
10252 {
10253 /*
10254 * Check restrictions on UPDATE/DELETE actions, per SQL standard
10255 */
10256 if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10257 fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
10258 fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
10259 ereport(ERROR,
10260 (errcode(ERRCODE_SYNTAX_ERROR),
10261 errmsg("invalid %s action for foreign key constraint containing generated column",
10262 "ON UPDATE")));
10263 if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10264 fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10265 ereport(ERROR,
10266 (errcode(ERRCODE_SYNTAX_ERROR),
10267 errmsg("invalid %s action for foreign key constraint containing generated column",
10268 "ON DELETE")));
10269 }
10270
10271 /*
10272 * FKs on virtual columns are not supported. This would require
10273 * various additional support in ri_triggers.c, including special
10274 * handling in ri_NullCheck(), ri_KeysEqual(),
10275 * RI_FKey_fk_upd_check_required() (since all virtual columns appear
10276 * as NULL there). Also not really practical as long as you can't
10277 * index virtual columns.
10278 */
10279 if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
10280 ereport(ERROR,
10281 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10282 errmsg("foreign key constraints on virtual generated columns are not supported")));
10283 }
10284
10285 /*
10286 * Some actions are currently unsupported for foreign keys using PERIOD.
10287 */
10288 if (fkconstraint->fk_with_period)
10289 {
10290 if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_RESTRICT ||
10291 fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE ||
10292 fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10293 fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT)
10294 ereport(ERROR,
10295 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10296 errmsg("unsupported %s action for foreign key constraint using PERIOD",
10297 "ON UPDATE"));
10298
10299 if (fkconstraint->fk_del_action == FKCONSTR_ACTION_RESTRICT ||
10300 fkconstraint->fk_del_action == FKCONSTR_ACTION_CASCADE ||
10301 fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10302 fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10303 ereport(ERROR,
10304 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10305 errmsg("unsupported %s action for foreign key constraint using PERIOD",
10306 "ON DELETE"));
10307 }
10308
10309 /*
10310 * Look up the equality operators to use in the constraint.
10311 *
10312 * Note that we have to be careful about the difference between the actual
10313 * PK column type and the opclass' declared input type, which might be
10314 * only binary-compatible with it. The declared opcintype is the right
10315 * thing to probe pg_amop with.
10316 */
10317 if (numfks != numpks)
10318 ereport(ERROR,
10319 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
10320 errmsg("number of referencing and referenced columns for foreign key disagree")));
10321
10322 /*
10323 * On the strength of a previous constraint, we might avoid scanning
10324 * tables to validate this one. See below.
10325 */
10326 old_check_ok = (fkconstraint->old_conpfeqop != NIL);
10327 Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
10328
10329 for (i = 0; i < numpks; i++)
10330 {
10331 Oid pktype = pktypoid[i];
10332 Oid fktype = fktypoid[i];
10333 Oid fktyped;
10334 Oid pkcoll = pkcolloid[i];
10335 Oid fkcoll = fkcolloid[i];
10336 HeapTuple cla_ht;
10337 Form_pg_opclass cla_tup;
10338 Oid amid;
10339 Oid opfamily;
10340 Oid opcintype;
10341 bool for_overlaps;
10342 CompareType cmptype;
10343 Oid pfeqop;
10344 Oid ppeqop;
10345 Oid ffeqop;
10346 int16 eqstrategy;
10347 Oid pfeqop_right;
10348
10349 /* We need several fields out of the pg_opclass entry */
10350 cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
10351 if (!HeapTupleIsValid(cla_ht))
10352 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
10353 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
10354 amid = cla_tup->opcmethod;
10355 opfamily = cla_tup->opcfamily;
10356 opcintype = cla_tup->opcintype;
10357 ReleaseSysCache(cla_ht);
10358
10359 /*
10360 * Get strategy number from index AM.
10361 *
10362 * For a normal foreign-key constraint, this should not fail, since we
10363 * already checked that the index is unique and should therefore have
10364 * appropriate equal operators. For a period foreign key, this could
10365 * fail if we selected a non-matching exclusion constraint earlier.
10366 * (XXX Maybe we should do these lookups earlier so we don't end up
10367 * doing that.)
10368 */
10369 for_overlaps = with_period && i == numpks - 1;
10370 cmptype = for_overlaps ? COMPARE_OVERLAP : COMPARE_EQ;
10371 eqstrategy = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
10372 if (eqstrategy == InvalidStrategy)
10373 ereport(ERROR,
10374 errcode(ERRCODE_UNDEFINED_OBJECT),
10375 for_overlaps
10376 ? errmsg("could not identify an overlaps operator for foreign key")
10377 : errmsg("could not identify an equality operator for foreign key"),
10378 errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
10379 cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
10380
10381 /*
10382 * There had better be a primary equality operator for the index.
10383 * We'll use it for PK = PK comparisons.
10384 */
10385 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
10386 eqstrategy);
10387
10388 if (!OidIsValid(ppeqop))
10389 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
10390 eqstrategy, opcintype, opcintype, opfamily);
10391
10392 /*
10393 * Are there equality operators that take exactly the FK type? Assume
10394 * we should look through any domain here.
10395 */
10396 fktyped = getBaseType(fktype);
10397
10398 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
10399 eqstrategy);
10400 if (OidIsValid(pfeqop))
10401 {
10402 pfeqop_right = fktyped;
10403 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
10404 eqstrategy);
10405 }
10406 else
10407 {
10408 /* keep compiler quiet */
10409 pfeqop_right = InvalidOid;
10410 ffeqop = InvalidOid;
10411 }
10412
10413 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10414 {
10415 /*
10416 * Otherwise, look for an implicit cast from the FK type to the
10417 * opcintype, and if found, use the primary equality operator.
10418 * This is a bit tricky because opcintype might be a polymorphic
10419 * type such as ANYARRAY or ANYENUM; so what we have to test is
10420 * whether the two actual column types can be concurrently cast to
10421 * that type. (Otherwise, we'd fail to reject combinations such
10422 * as int[] and point[].)
10423 */
10424 Oid input_typeids[2];
10425 Oid target_typeids[2];
10426
10427 input_typeids[0] = pktype;
10428 input_typeids[1] = fktype;
10429 target_typeids[0] = opcintype;
10430 target_typeids[1] = opcintype;
10431 if (can_coerce_type(2, input_typeids, target_typeids,
10432 COERCION_IMPLICIT))
10433 {
10434 pfeqop = ffeqop = ppeqop;
10435 pfeqop_right = opcintype;
10436 }
10437 }
10438
10439 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10440 ereport(ERROR,
10441 (errcode(ERRCODE_DATATYPE_MISMATCH),
10442 errmsg("foreign key constraint \"%s\" cannot be implemented",
10443 fkconstraint->conname),
10444 errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10445 "are of incompatible types: %s and %s.",
10446 strVal(list_nth(fkconstraint->fk_attrs, i)),
10447 strVal(list_nth(fkconstraint->pk_attrs, i)),
10448 format_type_be(fktype),
10449 format_type_be(pktype))));
10450
10451 /*
10452 * This shouldn't be possible, but better check to make sure we have a
10453 * consistent state for the check below.
10454 */
10455 if ((OidIsValid(pkcoll) && !OidIsValid(fkcoll)) || (!OidIsValid(pkcoll) && OidIsValid(fkcoll)))
10456 elog(ERROR, "key columns are not both collatable");
10457
10458 if (OidIsValid(pkcoll) && OidIsValid(fkcoll))
10459 {
10460 bool pkcolldet;
10461 bool fkcolldet;
10462
10463 pkcolldet = get_collation_isdeterministic(pkcoll);
10464 fkcolldet = get_collation_isdeterministic(fkcoll);
10465
10466 /*
10467 * SQL requires that both collations are the same. This is
10468 * because we need a consistent notion of equality on both
10469 * columns. We relax this by allowing different collations if
10470 * they are both deterministic. (This is also for backward
10471 * compatibility, because PostgreSQL has always allowed this.)
10472 */
10473 if ((!pkcolldet || !fkcolldet) && pkcoll != fkcoll)
10474 ereport(ERROR,
10475 (errcode(ERRCODE_COLLATION_MISMATCH),
10476 errmsg("foreign key constraint \"%s\" cannot be implemented", fkconstraint->conname),
10477 errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10478 "have incompatible collations: \"%s\" and \"%s\". "
10479 "If either collation is nondeterministic, then both collations have to be the same.",
10480 strVal(list_nth(fkconstraint->fk_attrs, i)),
10481 strVal(list_nth(fkconstraint->pk_attrs, i)),
10482 get_collation_name(fkcoll),
10483 get_collation_name(pkcoll))));
10484 }
10485
10486 if (old_check_ok)
10487 {
10488 /*
10489 * When a pfeqop changes, revalidate the constraint. We could
10490 * permit intra-opfamily changes, but that adds subtle complexity
10491 * without any concrete benefit for core types. We need not
10492 * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
10493 */
10494 old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
10495 old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
10496 old_pfeqop_item);
10497 }
10498 if (old_check_ok)
10499 {
10500 Oid old_fktype;
10501 Oid new_fktype;
10502 CoercionPathType old_pathtype;
10503 CoercionPathType new_pathtype;
10504 Oid old_castfunc;
10505 Oid new_castfunc;
10506 Oid old_fkcoll;
10507 Oid new_fkcoll;
10508 Form_pg_attribute attr = TupleDescAttr(tab->oldDesc,
10509 fkattnum[i] - 1);
10510
10511 /*
10512 * Identify coercion pathways from each of the old and new FK-side
10513 * column types to the right (foreign) operand type of the pfeqop.
10514 * We may assume that pg_constraint.conkey is not changing.
10515 */
10516 old_fktype = attr->atttypid;
10517 new_fktype = fktype;
10518 old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
10519 &old_castfunc);
10520 new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
10521 &new_castfunc);
10522
10523 old_fkcoll = attr->attcollation;
10524 new_fkcoll = fkcoll;
10525
10526 /*
10527 * Upon a change to the cast from the FK column to its pfeqop
10528 * operand, revalidate the constraint. For this evaluation, a
10529 * binary coercion cast is equivalent to no cast at all. While
10530 * type implementors should design implicit casts with an eye
10531 * toward consistency of operations like equality, we cannot
10532 * assume here that they have done so.
10533 *
10534 * A function with a polymorphic argument could change behavior
10535 * arbitrarily in response to get_fn_expr_argtype(). Therefore,
10536 * when the cast destination is polymorphic, we only avoid
10537 * revalidation if the input type has not changed at all. Given
10538 * just the core data types and operator classes, this requirement
10539 * prevents no would-be optimizations.
10540 *
10541 * If the cast converts from a base type to a domain thereon, then
10542 * that domain type must be the opcintype of the unique index.
10543 * Necessarily, the primary key column must then be of the domain
10544 * type. Since the constraint was previously valid, all values on
10545 * the foreign side necessarily exist on the primary side and in
10546 * turn conform to the domain. Consequently, we need not treat
10547 * domains specially here.
10548 *
10549 * If the collation changes, revalidation is required, unless both
10550 * collations are deterministic, because those share the same
10551 * notion of equality (because texteq reduces to bitwise
10552 * equality).
10553 *
10554 * We need not directly consider the PK type. It's necessarily
10555 * binary coercible to the opcintype of the unique index column,
10556 * and ri_triggers.c will only deal with PK datums in terms of
10557 * that opcintype. Changing the opcintype also changes pfeqop.
10558 */
10559 old_check_ok = (new_pathtype == old_pathtype &&
10560 new_castfunc == old_castfunc &&
10561 (!IsPolymorphicType(pfeqop_right) ||
10562 new_fktype == old_fktype) &&
10563 (new_fkcoll == old_fkcoll ||
10564 (get_collation_isdeterministic(old_fkcoll) && get_collation_isdeterministic(new_fkcoll))));
10565 }
10566
10567 pfeqoperators[i] = pfeqop;
10568 ppeqoperators[i] = ppeqop;
10569 ffeqoperators[i] = ffeqop;
10570 }
10571
10572 /*
10573 * For FKs with PERIOD we need additional operators to check whether the
10574 * referencing row's range is contained by the aggregated ranges of the
10575 * referenced row(s). For rangetypes and multirangetypes this is
10576 * fk.periodatt <@ range_agg(pk.periodatt). Those are the only types we
10577 * support for now. FKs will look these up at "runtime", but we should
10578 * make sure the lookup works here, even if we don't use the values.
10579 */
10580 if (with_period)
10581 {
10582 Oid periodoperoid;
10583 Oid aggedperiodoperoid;
10584 Oid intersectoperoid;
10585
10586 FindFKPeriodOpers(opclasses[numpks - 1], &periodoperoid, &aggedperiodoperoid,
10587 &intersectoperoid);
10588 }
10589
10590 /* First, create the constraint catalog entry itself. */
10591 address = addFkConstraint(addFkBothSides,
10592 fkconstraint->conname, fkconstraint, rel, pkrel,
10593 indexOid,
10594 InvalidOid, /* no parent constraint */
10595 numfks,
10596 pkattnum,
10597 fkattnum,
10598 pfeqoperators,
10599 ppeqoperators,
10600 ffeqoperators,
10601 numfkdelsetcols,
10602 fkdelsetcols,
10603 false,
10604 with_period);
10605
10606 /* Next process the action triggers at the referenced side and recurse */
10607 addFkRecurseReferenced(fkconstraint, rel, pkrel,
10608 indexOid,
10609 address.objectId,
10610 numfks,
10611 pkattnum,
10612 fkattnum,
10613 pfeqoperators,
10614 ppeqoperators,
10615 ffeqoperators,
10616 numfkdelsetcols,
10617 fkdelsetcols,
10618 old_check_ok,
10619 InvalidOid, InvalidOid,
10620 with_period);
10621
10622 /* Lastly create the check triggers at the referencing side and recurse */
10623 addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
10624 indexOid,
10625 address.objectId,
10626 numfks,
10627 pkattnum,
10628 fkattnum,
10629 pfeqoperators,
10630 ppeqoperators,
10631 ffeqoperators,
10632 numfkdelsetcols,
10633 fkdelsetcols,
10634 old_check_ok,
10635 lockmode,
10636 InvalidOid, InvalidOid,
10637 with_period);
10638
10639 /*
10640 * Done. Close pk table, but keep lock until we've committed.
10641 */
10642 table_close(pkrel, NoLock);
10643
10644 return address;
10645 }
10646
10647 /*
10648 * validateFkOnDeleteSetColumns
10649 * Verifies that columns used in ON DELETE SET NULL/DEFAULT (...)
10650 * column lists are valid.
10651 *
10652 * If there are duplicates in the fksetcolsattnums[] array, this silently
10653 * removes the dups. The new count of numfksetcols is returned.
10654 */
10655 static int
10656 validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
10657 int numfksetcols, int16 *fksetcolsattnums,
10658 List *fksetcols)
10659 {
10660 int numcolsout = 0;
10661
10662 for (int i = 0; i < numfksetcols; i++)
10663 {
10664 int16 setcol_attnum = fksetcolsattnums[i];
10665 bool seen = false;
10666
10667 /* Make sure it's in fkattnums[] */
10668 for (int j = 0; j < numfks; j++)
10669 {
10670 if (fkattnums[j] == setcol_attnum)
10671 {
10672 seen = true;
10673 break;
10674 }
10675 }
10676
10677 if (!seen)
10678 {
10679 char *col = strVal(list_nth(fksetcols, i));
10680
10681 ereport(ERROR,
10682 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
10683 errmsg("column \"%s\" referenced in ON DELETE SET action must be part of foreign key", col)));
10684 }
10685
10686 /* Now check for dups */
10687 seen = false;
10688 for (int j = 0; j < numcolsout; j++)
10689 {
10690 if (fksetcolsattnums[j] == setcol_attnum)
10691 {
10692 seen = true;
10693 break;
10694 }
10695 }
10696 if (!seen)
10697 fksetcolsattnums[numcolsout++] = setcol_attnum;
10698 }
10699 return numcolsout;
10700 }
10701
10702 /*
10703 * addFkConstraint
10704 * Install pg_constraint entries to implement a foreign key constraint.
10705 * Caller must separately invoke addFkRecurseReferenced and
10706 * addFkRecurseReferencing, as appropriate, to install pg_trigger entries
10707 * and (for partitioned tables) recurse to partitions.
10708 *
10709 * fkside: the side of the FK (or both) to create. Caller should
10710 * call addFkRecurseReferenced if this is addFkReferencedSide,
10711 * addFkRecurseReferencing if it's addFkReferencingSide, or both if it's
10712 * addFkBothSides.
10713 * constraintname: the base name for the constraint being added,
10714 * copied to fkconstraint->conname if the latter is not set
10715 * fkconstraint: the constraint being added
10716 * rel: the root referencing relation
10717 * pkrel: the referenced relation; might be a partition, if recursing
10718 * indexOid: the OID of the index (on pkrel) implementing this constraint
10719 * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10720 * top-level constraint
10721 * numfks: the number of columns in the foreign key
10722 * pkattnum: the attnum array of referenced attributes
10723 * fkattnum: the attnum array of referencing attributes
10724 * pf/pp/ffeqoperators: OID array of operators between columns
10725 * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
10726 * (...) clause
10727 * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10728 * NULL/DEFAULT clause
10729 * with_period: true if this is a temporal FK
10730 */
10731 static ObjectAddress
10732 addFkConstraint(addFkConstraintSides fkside,
10733 char *constraintname, Constraint *fkconstraint,
10734 Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
10735 int numfks, int16 *pkattnum,
10736 int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators,
10737 Oid *ffeqoperators, int numfkdelsetcols, int16 *fkdelsetcols,
10738 bool is_internal, bool with_period)
10739 {
10740 ObjectAddress address;
10741 Oid constrOid;
10742 char *conname;
10743 bool conislocal;
10744 int16 coninhcount;
10745 bool connoinherit;
10746
10747 /*
10748 * Verify relkind for each referenced partition. At the top level, this
10749 * is redundant with a previous check, but we need it when recursing.
10750 */
10751 if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10752 pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10753 ereport(ERROR,
10754 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10755 errmsg("referenced relation \"%s\" is not a table",
10756 RelationGetRelationName(pkrel))));
10757
10758 /*
10759 * Caller supplies us with a constraint name; however, it may be used in
10760 * this partition, so come up with a different one in that case. Unless
10761 * truncation to NAMEDATALEN dictates otherwise, the new name will be the
10762 * supplied name with an underscore and digit(s) appended.
10763 */
10764 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
10765 RelationGetRelid(rel),
10766 constraintname))
10767 conname = ChooseConstraintName(constraintname,
10768 NULL,
10769 "",
10770 RelationGetNamespace(rel), NIL);
10771 else
10772 conname = constraintname;
10773
10774 if (fkconstraint->conname == NULL)
10775 fkconstraint->conname = pstrdup(conname);
10776
10777 if (OidIsValid(parentConstr))
10778 {
10779 conislocal = false;
10780 coninhcount = 1;
10781 connoinherit = false;
10782 }
10783 else
10784 {
10785 conislocal = true;
10786 coninhcount = 0;
10787
10788 /*
10789 * always inherit for partitioned tables, never for legacy inheritance
10790 */
10791 connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
10792 }
10793
10794 /*
10795 * Record the FK constraint in pg_constraint.
10796 */
10797 constrOid = CreateConstraintEntry(conname,
10798 RelationGetNamespace(rel),
10799 CONSTRAINT_FOREIGN,
10800 fkconstraint->deferrable,
10801 fkconstraint->initdeferred,
10802 fkconstraint->is_enforced,
10803 fkconstraint->initially_valid,
10804 parentConstr,
10805 RelationGetRelid(rel),
10806 fkattnum,
10807 numfks,
10808 numfks,
10809 InvalidOid, /* not a domain constraint */
10810 indexOid,
10811 RelationGetRelid(pkrel),
10812 pkattnum,
10813 pfeqoperators,
10814 ppeqoperators,
10815 ffeqoperators,
10816 numfks,
10817 fkconstraint->fk_upd_action,
10818 fkconstraint->fk_del_action,
10819 fkdelsetcols,
10820 numfkdelsetcols,
10821 fkconstraint->fk_matchtype,
10822 NULL, /* no exclusion constraint */
10823 NULL, /* no check constraint */
10824 NULL,
10825 conislocal, /* islocal */
10826 coninhcount, /* inhcount */
10827 connoinherit, /* conNoInherit */
10828 with_period, /* conPeriod */
10829 is_internal); /* is_internal */
10830
10831 ObjectAddressSet(address, ConstraintRelationId, constrOid);
10832
10833 /*
10834 * In partitioning cases, create the dependency entries for this
10835 * constraint. (For non-partitioned cases, relevant entries were created
10836 * by CreateConstraintEntry.)
10837 *
10838 * On the referenced side, we need the constraint to have an internal
10839 * dependency on its parent constraint; this means that this constraint
10840 * cannot be dropped on its own -- only through the parent constraint. It
10841 * also means the containing partition cannot be dropped on its own, but
10842 * it can be detached, at which point this dependency is removed (after
10843 * verifying that no rows are referenced via this FK.)
10844 *
10845 * When processing the referencing side, we link the constraint via the
10846 * special partitioning dependencies: the parent constraint is the primary
10847 * dependent, and the partition on which the foreign key exists is the
10848 * secondary dependency. That way, this constraint is dropped if either
10849 * of these objects is.
10850 *
10851 * Note that this is only necessary for the subsidiary pg_constraint rows
10852 * in partitions; the topmost row doesn't need any of this.
10853 */
10854 if (OidIsValid(parentConstr))
10855 {
10856 ObjectAddress referenced;
10857
10858 ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
10859
10860 Assert(fkside != addFkBothSides);
10861 if (fkside == addFkReferencedSide)
10862 recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
10863 else
10864 {
10865 recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
10866 ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
10867 recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
10868 }
10869 }
10870
10871 /* make new constraint visible, in case we add more */
10872 CommandCounterIncrement();
10873
10874 return address;
10875 }
10876
10877 /*
10878 * addFkRecurseReferenced
10879 * Recursive helper for the referenced side of foreign key creation,
10880 * which creates the action triggers and recurses
10881 *
10882 * If the referenced relation is a plain relation, create the necessary action
10883 * triggers that implement the constraint. If the referenced relation is a
10884 * partitioned table, then we create a pg_constraint row referencing the parent
10885 * of the referencing side for it and recurse on this routine for each
10886 * partition.
10887 *
10888 * fkconstraint: the constraint being added
10889 * rel: the root referencing relation
10890 * pkrel: the referenced relation; might be a partition, if recursing
10891 * indexOid: the OID of the index (on pkrel) implementing this constraint
10892 * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10893 * top-level constraint
10894 * numfks: the number of columns in the foreign key
10895 * pkattnum: the attnum array of referenced attributes
10896 * fkattnum: the attnum array of referencing attributes
10897 * numfkdelsetcols: the number of columns in the ON DELETE SET
10898 * NULL/DEFAULT (...) clause
10899 * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10900 * NULL/DEFAULT clause
10901 * pf/pp/ffeqoperators: OID array of operators between columns
10902 * old_check_ok: true if this constraint replaces an existing one that
10903 * was already validated (thus this one doesn't need validation)
10904 * parentDelTrigger and parentUpdTrigger: when recursively called on a
10905 * partition, the OIDs of the parent action triggers for DELETE and
10906 * UPDATE respectively.
10907 * with_period: true if this is a temporal FK
10908 */
10909 static void
10910 addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
10911 Relation pkrel, Oid indexOid, Oid parentConstr,
10912 int numfks,
10913 int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators,
10914 Oid *ppeqoperators, Oid *ffeqoperators,
10915 int numfkdelsetcols, int16 *fkdelsetcols,
10916 bool old_check_ok,
10917 Oid parentDelTrigger, Oid parentUpdTrigger,
10918 bool with_period)
10919 {
10920 Oid deleteTriggerOid = InvalidOid,
10921 updateTriggerOid = InvalidOid;
10922
10923 Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
10924 Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
10925
10926 /*
10927 * Create action triggers to enforce the constraint, or skip them if the
10928 * constraint is NOT ENFORCED.
10929 */
10930 if (fkconstraint->is_enforced)
10931 createForeignKeyActionTriggers(RelationGetRelid(rel),
10932 RelationGetRelid(pkrel),
10933 fkconstraint,
10934 parentConstr, indexOid,
10935 parentDelTrigger, parentUpdTrigger,
10936 &deleteTriggerOid, &updateTriggerOid);
10937
10938 /*
10939 * If the referenced table is partitioned, recurse on ourselves to handle
10940 * each partition. We need one pg_constraint row created for each
10941 * partition in addition to the pg_constraint row for the parent table.
10942 */
10943 if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10944 {
10945 PartitionDesc pd = RelationGetPartitionDesc(pkrel, true);
10946
10947 for (int i = 0; i < pd->nparts; i++)
10948 {
10949 Relation partRel;
10950 AttrMap *map;
10951 AttrNumber *mapped_pkattnum;
10952 Oid partIndexId;
10953 ObjectAddress address;
10954
10955 /* XXX would it be better to acquire these locks beforehand? */
10956 partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
10957
10958 /*
10959 * Map the attribute numbers in the referenced side of the FK
10960 * definition to match the partition's column layout.
10961 */
10962 map = build_attrmap_by_name_if_req(RelationGetDescr(partRel),
10963 RelationGetDescr(pkrel),
10964 false);
10965 if (map)
10966 {
10967 mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
10968 for (int j = 0; j < numfks; j++)
10969 mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
10970 }
10971 else
10972 mapped_pkattnum = pkattnum;
10973
10974 /* Determine the index to use at this level */
10975 partIndexId = index_get_partition(partRel, indexOid);
10976 if (!OidIsValid(partIndexId))
10977 elog(ERROR, "index for %u not found in partition %s",
10978 indexOid, RelationGetRelationName(partRel));
10979
10980 /* Create entry at this level ... */
10981 address = addFkConstraint(addFkReferencedSide,
10982 fkconstraint->conname, fkconstraint, rel,
10983 partRel, partIndexId, parentConstr,
10984 numfks, mapped_pkattnum,
10985 fkattnum, pfeqoperators, ppeqoperators,
10986 ffeqoperators, numfkdelsetcols,
10987 fkdelsetcols, true, with_period);
10988 /* ... and recurse to our children */
10989 addFkRecurseReferenced(fkconstraint, rel, partRel,
10990 partIndexId, address.objectId, numfks,
10991 mapped_pkattnum, fkattnum,
10992 pfeqoperators, ppeqoperators, ffeqoperators,
10993 numfkdelsetcols, fkdelsetcols,
10994 old_check_ok,
10995 deleteTriggerOid, updateTriggerOid,
10996 with_period);
10997
10998 /* Done -- clean up (but keep the lock) */
10999 table_close(partRel, NoLock);
11000 if (map)
11001 {
11002 pfree(mapped_pkattnum);
11003 free_attrmap(map);
11004 }
11005 }
11006 }
11007 }
11008
11009 /*
11010 * addFkRecurseReferencing
11011 * Recursive helper for the referencing side of foreign key creation,
11012 * which creates the check triggers and recurses
11013 *
11014 * If the referencing relation is a plain relation, create the necessary check
11015 * triggers that implement the constraint, and set up for Phase 3 constraint
11016 * verification. If the referencing relation is a partitioned table, then
11017 * we create a pg_constraint row for it and recurse on this routine for each
11018 * partition.
11019 *
11020 * We assume that the referenced relation is locked against concurrent
11021 * deletions. If it's a partitioned relation, every partition must be so
11022 * locked.
11023 *
11024 * wqueue: the ALTER TABLE work queue; NULL when not running as part
11025 * of an ALTER TABLE sequence.
11026 * fkconstraint: the constraint being added
11027 * rel: the referencing relation; might be a partition, if recursing
11028 * pkrel: the root referenced relation
11029 * indexOid: the OID of the index (on pkrel) implementing this constraint
11030 * parentConstr: the OID of the parent constraint (there is always one)
11031 * numfks: the number of columns in the foreign key
11032 * pkattnum: the attnum array of referenced attributes
11033 * fkattnum: the attnum array of referencing attributes
11034 * pf/pp/ffeqoperators: OID array of operators between columns
11035 * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
11036 * (...) clause
11037 * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
11038 * NULL/DEFAULT clause
11039 * old_check_ok: true if this constraint replaces an existing one that
11040 * was already validated (thus this one doesn't need validation)
11041 * lockmode: the lockmode to acquire on partitions when recursing
11042 * parentInsTrigger and parentUpdTrigger: when being recursively called on
11043 * a partition, the OIDs of the parent check triggers for INSERT and
11044 * UPDATE respectively.
11045 * with_period: true if this is a temporal FK
11046 */
11047 static void
11048 addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
11049 Relation pkrel, Oid indexOid, Oid parentConstr,
11050 int numfks, int16 *pkattnum, int16 *fkattnum,
11051 Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
11052 int numfkdelsetcols, int16 *fkdelsetcols,
11053 bool old_check_ok, LOCKMODE lockmode,
11054 Oid parentInsTrigger, Oid parentUpdTrigger,
11055 bool with_period)
11056 {
11057 Oid insertTriggerOid = InvalidOid,
11058 updateTriggerOid = InvalidOid;
11059
11060 Assert(OidIsValid(parentConstr));
11061 Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11062 Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11063
11064 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11065 ereport(ERROR,
11066 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11067 errmsg("foreign key constraints are not supported on foreign tables")));
11068
11069 /*
11070 * Add check triggers if the constraint is ENFORCED, and if needed,
11071 * schedule them to be checked in Phase 3.
11072 *
11073 * If the relation is partitioned, drill down to do it to its partitions.
11074 */
11075 if (fkconstraint->is_enforced)
11076 createForeignKeyCheckTriggers(RelationGetRelid(rel),
11077 RelationGetRelid(pkrel),
11078 fkconstraint,
11079 parentConstr,
11080 indexOid,
11081 parentInsTrigger, parentUpdTrigger,
11082 &insertTriggerOid, &updateTriggerOid);
11083
11084 if (rel->rd_rel->relkind == RELKIND_RELATION)
11085 {
11086 /*
11087 * Tell Phase 3 to check that the constraint is satisfied by existing
11088 * rows. We can skip this during table creation, when constraint is
11089 * specified as NOT ENFORCED, or when requested explicitly by
11090 * specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
11091 * recreating a constraint following a SET DATA TYPE operation that
11092 * did not impugn its validity.
11093 */
11094 if (wqueue && !old_check_ok && !fkconstraint->skip_validation &&
11095 fkconstraint->is_enforced)
11096 {
11097 NewConstraint *newcon;
11098 AlteredTableInfo *tab;
11099
11100 tab = ATGetQueueEntry(wqueue, rel);
11101
11102 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
11103 newcon->name = get_constraint_name(parentConstr);
11104 newcon->contype = CONSTR_FOREIGN;
11105 newcon->refrelid = RelationGetRelid(pkrel);
11106 newcon->refindid = indexOid;
11107 newcon->conid = parentConstr;
11108 newcon->conwithperiod = fkconstraint->fk_with_period;
11109 newcon->qual = (Node *) fkconstraint;
11110
11111 tab->constraints = lappend(tab->constraints, newcon);
11112 }
11113 }
11114 else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11115 {
11116 PartitionDesc pd = RelationGetPartitionDesc(rel, true);
11117 Relation trigrel;
11118
11119 /*
11120 * Triggers of the foreign keys will be manipulated a bunch of times
11121 * in the loop below. To avoid repeatedly opening/closing the trigger
11122 * catalog relation, we open it here and pass it to the subroutines
11123 * called below.
11124 */
11125 trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11126
11127 /*
11128 * Recurse to take appropriate action on each partition; either we
11129 * find an existing constraint to reparent to ours, or we create a new
11130 * one.
11131 */
11132 for (int i = 0; i < pd->nparts; i++)
11133 {
11134 Relation partition = table_open(pd->oids[i], lockmode);
11135 List *partFKs;
11136 AttrMap *attmap;
11137 AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
11138 bool attached;
11139 ObjectAddress address;
11140
11141 CheckAlterTableIsSafe(partition);
11142
11143 attmap = build_attrmap_by_name(RelationGetDescr(partition),
11144 RelationGetDescr(rel),
11145 false);
11146 for (int j = 0; j < numfks; j++)
11147 mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
11148
11149 /* Check whether an existing constraint can be repurposed */
11150 partFKs = copyObject(RelationGetFKeyList(partition));
11151 attached = false;
11152 foreach_node(ForeignKeyCacheInfo, fk, partFKs)
11153 {
11154 if (tryAttachPartitionForeignKey(wqueue,
11155 fk,
11156 partition,
11157 parentConstr,
11158 numfks,
11159 mapped_fkattnum,
11160 pkattnum,
11161 pfeqoperators,
11162 insertTriggerOid,
11163 updateTriggerOid,
11164 trigrel))
11165 {
11166 attached = true;
11167 break;
11168 }
11169 }
11170 if (attached)
11171 {
11172 table_close(partition, NoLock);
11173 continue;
11174 }
11175
11176 /*
11177 * No luck finding a good constraint to reuse; create our own.
11178 */
11179 address = addFkConstraint(addFkReferencingSide,
11180 fkconstraint->conname, fkconstraint,
11181 partition, pkrel, indexOid, parentConstr,
11182 numfks, pkattnum,
11183 mapped_fkattnum, pfeqoperators,
11184 ppeqoperators, ffeqoperators,
11185 numfkdelsetcols, fkdelsetcols, true,
11186 with_period);
11187
11188 /* call ourselves to finalize the creation and we're done */
11189 addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
11190 indexOid,
11191 address.objectId,
11192 numfks,
11193 pkattnum,
11194 mapped_fkattnum,
11195 pfeqoperators,
11196 ppeqoperators,
11197 ffeqoperators,
11198 numfkdelsetcols,
11199 fkdelsetcols,
11200 old_check_ok,
11201 lockmode,
11202 insertTriggerOid,
11203 updateTriggerOid,
11204 with_period);
11205
11206 table_close(partition, NoLock);
11207 }
11208
11209 table_close(trigrel, RowExclusiveLock);
11210 }
11211 }
11212
11213 /*
11214 * CloneForeignKeyConstraints
11215 * Clone foreign keys from a partitioned table to a newly acquired
11216 * partition.
11217 *
11218 * partitionRel is a partition of parentRel, so we can be certain that it has
11219 * the same columns with the same datatypes. The columns may be in different
11220 * order, though.
11221 *
11222 * wqueue must be passed to set up phase 3 constraint checking, unless the
11223 * referencing-side partition is known to be empty (such as in CREATE TABLE /
11224 * PARTITION OF).
11225 */
11226 static void
11227 CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
11228 Relation partitionRel)
11229 {
11230 /* This only works for declarative partitioning */
11231 Assert(parentRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
11232
11233 /*
11234 * First, clone constraints where the parent is on the referencing side.
11235 */
11236 CloneFkReferencing(wqueue, parentRel, partitionRel);
11237
11238 /*
11239 * Clone constraints for which the parent is on the referenced side.
11240 */
11241 CloneFkReferenced(parentRel, partitionRel);
11242 }
11243
11244 /*
11245 * CloneFkReferenced
11246 * Subroutine for CloneForeignKeyConstraints
11247 *
11248 * Find all the FKs that have the parent relation on the referenced side;
11249 * clone those constraints to the given partition. This is to be called
11250 * when the partition is being created or attached.
11251 *
11252 * This recurses to partitions, if the relation being attached is partitioned.
11253 * Recursion is done by calling addFkRecurseReferenced.
11254 */
11255 static void
11256 CloneFkReferenced(Relation parentRel, Relation partitionRel)
11257 {
11258 Relation pg_constraint;
11259 AttrMap *attmap;
11260 ListCell *cell;
11261 SysScanDesc scan;
11262 ScanKeyData key[2];
11263 HeapTuple tuple;
11264 List *clone = NIL;
11265 Relation trigrel;
11266
11267 /*
11268 * Search for any constraints where this partition's parent is in the
11269 * referenced side. However, we must not clone any constraint whose
11270 * parent constraint is also going to be cloned, to avoid duplicates. So
11271 * do it in two steps: first construct the list of constraints to clone,
11272 * then go over that list cloning those whose parents are not in the list.
11273 * (We must not rely on the parent being seen first, since the catalog
11274 * scan could return children first.)
11275 */
11276 pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11277 ScanKeyInit(&key[0],
11278 Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
11279 F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parentRel)));
11280 ScanKeyInit(&key[1],
11281 Anum_pg_constraint_contype, BTEqualStrategyNumber,
11282 F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
11283 /* This is a seqscan, as we don't have a usable index ... */
11284 scan = systable_beginscan(pg_constraint, InvalidOid, true,
11285 NULL, 2, key);
11286 while ((tuple = systable_getnext(scan)) != NULL)
11287 {
11288 Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11289
11290 clone = lappend_oid(clone, constrForm->oid);
11291 }
11292 systable_endscan(scan);
11293 table_close(pg_constraint, RowShareLock);
11294
11295 /*
11296 * Triggers of the foreign keys will be manipulated a bunch of times in
11297 * the loop below. To avoid repeatedly opening/closing the trigger
11298 * catalog relation, we open it here and pass it to the subroutines called
11299 * below.
11300 */
11301 trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11302
11303 attmap = build_attrmap_by_name(RelationGetDescr(partitionRel),
11304 RelationGetDescr(parentRel),
11305 false);
11306 foreach(cell, clone)
11307 {
11308 Oid constrOid = lfirst_oid(cell);
11309 Form_pg_constraint constrForm;
11310 Relation fkRel;
11311 Oid indexOid;
11312 Oid partIndexId;
11313 int numfks;
11314 AttrNumber conkey[INDEX_MAX_KEYS];
11315 AttrNumber mapped_confkey[INDEX_MAX_KEYS];
11316 AttrNumber confkey[INDEX_MAX_KEYS];
11317 Oid conpfeqop[INDEX_MAX_KEYS];
11318 Oid conppeqop[INDEX_MAX_KEYS];
11319 Oid conffeqop[INDEX_MAX_KEYS];
11320 int numfkdelsetcols;
11321 AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11322 Constraint *fkconstraint;
11323 ObjectAddress address;
11324 Oid deleteTriggerOid = InvalidOid,
11325 updateTriggerOid = InvalidOid;
11326
11327 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
11328 if (!HeapTupleIsValid(tuple))
11329 elog(ERROR, "cache lookup failed for constraint %u", constrOid);
11330 constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11331
11332 /*
11333 * As explained above: don't try to clone a constraint for which we're
11334 * going to clone the parent.
11335 */
11336 if (list_member_oid(clone, constrForm->conparentid))
11337 {
11338 ReleaseSysCache(tuple);
11339 continue;
11340 }
11341
11342 /* We need the same lock level that CreateTrigger will acquire */
11343 fkRel = table_open(constrForm->conrelid, ShareRowExclusiveLock);
11344
11345 indexOid = constrForm->conindid;
11346 DeconstructFkConstraintRow(tuple,
11347 &numfks,
11348 conkey,
11349 confkey,
11350 conpfeqop,
11351 conppeqop,
11352 conffeqop,
11353 &numfkdelsetcols,
11354 confdelsetcols);
11355
11356 for (int i = 0; i < numfks; i++)
11357 mapped_confkey[i] = attmap->attnums[confkey[i] - 1];
11358
11359 fkconstraint = makeNode(Constraint);
11360 fkconstraint->contype = CONSTRAINT_FOREIGN;
11361 fkconstraint->conname = NameStr(constrForm->conname);
11362 fkconstraint->deferrable = constrForm->condeferrable;
11363 fkconstraint->initdeferred = constrForm->condeferred;
11364 fkconstraint->location = -1;
11365 fkconstraint->pktable = NULL;
11366 /* ->fk_attrs determined below */
11367 fkconstraint->pk_attrs = NIL;
11368 fkconstraint->fk_matchtype = constrForm->confmatchtype;
11369 fkconstraint->fk_upd_action = constrForm->confupdtype;
11370 fkconstraint->fk_del_action = constrForm->confdeltype;
11371 fkconstraint->fk_del_set_cols = NIL;
11372 fkconstraint->old_conpfeqop = NIL;
11373 fkconstraint->old_pktable_oid = InvalidOid;
11374 fkconstraint->is_enforced = constrForm->conenforced;
11375 fkconstraint->skip_validation = false;
11376 fkconstraint->initially_valid = constrForm->convalidated;
11377
11378 /* set up colnames that are used to generate the constraint name */
11379 for (int i = 0; i < numfks; i++)
11380 {
11381 Form_pg_attribute att;
11382
11383 att = TupleDescAttr(RelationGetDescr(fkRel),
11384 conkey[i] - 1);
11385 fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11386 makeString(NameStr(att->attname)));
11387 }
11388
11389 /*
11390 * Add the new foreign key constraint pointing to the new partition.
11391 * Because this new partition appears in the referenced side of the
11392 * constraint, we don't need to set up for Phase 3 check.
11393 */
11394 partIndexId = index_get_partition(partitionRel, indexOid);
11395 if (!OidIsValid(partIndexId))
11396 elog(ERROR, "index for %u not found in partition %s",
11397 indexOid, RelationGetRelationName(partitionRel));
11398
11399 /*
11400 * Get the "action" triggers belonging to the constraint to pass as
11401 * parent OIDs for similar triggers that will be created on the
11402 * partition in addFkRecurseReferenced().
11403 */
11404 if (constrForm->conenforced)
11405 GetForeignKeyActionTriggers(trigrel, constrOid,
11406 constrForm->confrelid, constrForm->conrelid,
11407 &deleteTriggerOid, &updateTriggerOid);
11408
11409 /* Add this constraint ... */
11410 address = addFkConstraint(addFkReferencedSide,
11411 fkconstraint->conname, fkconstraint, fkRel,
11412 partitionRel, partIndexId, constrOid,
11413 numfks, mapped_confkey,
11414 conkey, conpfeqop, conppeqop, conffeqop,
11415 numfkdelsetcols, confdelsetcols, false,
11416 constrForm->conperiod);
11417 /* ... and recurse */
11418 addFkRecurseReferenced(fkconstraint,
11419 fkRel,
11420 partitionRel,
11421 partIndexId,
11422 address.objectId,
11423 numfks,
11424 mapped_confkey,
11425 conkey,
11426 conpfeqop,
11427 conppeqop,
11428 conffeqop,
11429 numfkdelsetcols,
11430 confdelsetcols,
11431 true,
11432 deleteTriggerOid,
11433 updateTriggerOid,
11434 constrForm->conperiod);
11435
11436 table_close(fkRel, NoLock);
11437 ReleaseSysCache(tuple);
11438 }
11439
11440 table_close(trigrel, RowExclusiveLock);
11441 }
11442
11443 /*
11444 * CloneFkReferencing
11445 * Subroutine for CloneForeignKeyConstraints
11446 *
11447 * For each FK constraint of the parent relation in the given list, find an
11448 * equivalent constraint in its partition relation that can be reparented;
11449 * if one cannot be found, create a new constraint in the partition as its
11450 * child.
11451 *
11452 * If wqueue is given, it is used to set up phase-3 verification for each
11453 * cloned constraint; omit it if such verification is not needed
11454 * (example: the partition is being created anew).
11455 */
11456 static void
11457 CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
11458 {
11459 AttrMap *attmap;
11460 List *partFKs;
11461 List *clone = NIL;
11462 ListCell *cell;
11463 Relation trigrel;
11464
11465 /* obtain a list of constraints that we need to clone */
11466 foreach(cell, RelationGetFKeyList(parentRel))
11467 {
11468 ForeignKeyCacheInfo *fk = lfirst(cell);
11469
11470 /*
11471 * Refuse to attach a table as partition that this partitioned table
11472 * already has a foreign key to. This isn't useful schema, which is
11473 * proven by the fact that there have been no user complaints that
11474 * it's already impossible to achieve this in the opposite direction,
11475 * i.e., creating a foreign key that references a partition. This
11476 * restriction allows us to dodge some complexities around
11477 * pg_constraint and pg_trigger row creations that would be needed
11478 * during ATTACH/DETACH for this kind of relationship.
11479 */
11480 if (fk->confrelid == RelationGetRelid(partRel))
11481 ereport(ERROR,
11482 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11483 errmsg("cannot attach table \"%s\" as a partition because it is referenced by foreign key \"%s\"",
11484 RelationGetRelationName(partRel),
11485 get_constraint_name(fk->conoid))));
11486
11487 clone = lappend_oid(clone, fk->conoid);
11488 }
11489
11490 /*
11491 * Silently do nothing if there's nothing to do. In particular, this
11492 * avoids throwing a spurious error for foreign tables.
11493 */
11494 if (clone == NIL)
11495 return;
11496
11497 if (partRel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11498 ereport(ERROR,
11499 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11500 errmsg("foreign key constraints are not supported on foreign tables")));
11501
11502 /*
11503 * Triggers of the foreign keys will be manipulated a bunch of times in
11504 * the loop below. To avoid repeatedly opening/closing the trigger
11505 * catalog relation, we open it here and pass it to the subroutines called
11506 * below.
11507 */
11508 trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11509
11510 /*
11511 * The constraint key may differ, if the columns in the partition are
11512 * different. This map is used to convert them.
11513 */
11514 attmap = build_attrmap_by_name(RelationGetDescr(partRel),
11515 RelationGetDescr(parentRel),
11516 false);
11517
11518 partFKs = copyObject(RelationGetFKeyList(partRel));
11519
11520 foreach(cell, clone)
11521 {
11522 Oid parentConstrOid = lfirst_oid(cell);
11523 Form_pg_constraint constrForm;
11524 Relation pkrel;
11525 HeapTuple tuple;
11526 int numfks;
11527 AttrNumber conkey[INDEX_MAX_KEYS];
11528 AttrNumber mapped_conkey[INDEX_MAX_KEYS];
11529 AttrNumber confkey[INDEX_MAX_KEYS];
11530 Oid conpfeqop[INDEX_MAX_KEYS];
11531 Oid conppeqop[INDEX_MAX_KEYS];
11532 Oid conffeqop[INDEX_MAX_KEYS];
11533 int numfkdelsetcols;
11534 AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11535 Constraint *fkconstraint;
11536 bool attached;
11537 Oid indexOid;
11538 ObjectAddress address;
11539 ListCell *lc;
11540 Oid insertTriggerOid = InvalidOid,
11541 updateTriggerOid = InvalidOid;
11542 bool with_period;
11543
11544 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parentConstrOid));
11545 if (!HeapTupleIsValid(tuple))
11546 elog(ERROR, "cache lookup failed for constraint %u",
11547 parentConstrOid);
11548 constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11549
11550 /* Don't clone constraints whose parents are being cloned */
11551 if (list_member_oid(clone, constrForm->conparentid))
11552 {
11553 ReleaseSysCache(tuple);
11554 continue;
11555 }
11556
11557 /*
11558 * Need to prevent concurrent deletions. If pkrel is a partitioned
11559 * relation, that means to lock all partitions.
11560 */
11561 pkrel = table_open(constrForm->confrelid, ShareRowExclusiveLock);
11562 if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11563 (void) find_all_inheritors(RelationGetRelid(pkrel),
11564 ShareRowExclusiveLock, NULL);
11565
11566 DeconstructFkConstraintRow(tuple, &numfks, conkey, confkey,
11567 conpfeqop, conppeqop, conffeqop,
11568 &numfkdelsetcols, confdelsetcols);
11569 for (int i = 0; i < numfks; i++)
11570 mapped_conkey[i] = attmap->attnums[conkey[i] - 1];
11571
11572 /*
11573 * Get the "check" triggers belonging to the constraint, if it is
11574 * ENFORCED, to pass as parent OIDs for similar triggers that will be
11575 * created on the partition in addFkRecurseReferencing(). They are
11576 * also passed to tryAttachPartitionForeignKey() below to simply
11577 * assign as parents to the partition's existing "check" triggers,
11578 * that is, if the corresponding constraints is deemed attachable to
11579 * the parent constraint.
11580 */
11581 if (constrForm->conenforced)
11582 GetForeignKeyCheckTriggers(trigrel, constrForm->oid,
11583 constrForm->confrelid, constrForm->conrelid,
11584 &insertTriggerOid, &updateTriggerOid);
11585
11586 /*
11587 * Before creating a new constraint, see whether any existing FKs are
11588 * fit for the purpose. If one is, attach the parent constraint to
11589 * it, and don't clone anything. This way we avoid the expensive
11590 * verification step and don't end up with a duplicate FK, and we
11591 * don't need to recurse to partitions for this constraint.
11592 */
11593 attached = false;
11594 foreach(lc, partFKs)
11595 {
11596 ForeignKeyCacheInfo *fk = lfirst_node(ForeignKeyCacheInfo, lc);
11597
11598 if (tryAttachPartitionForeignKey(wqueue,
11599 fk,
11600 partRel,
11601 parentConstrOid,
11602 numfks,
11603 mapped_conkey,
11604 confkey,
11605 conpfeqop,
11606 insertTriggerOid,
11607 updateTriggerOid,
11608 trigrel))
11609 {
11610 attached = true;
11611 table_close(pkrel, NoLock);
11612 break;
11613 }
11614 }
11615 if (attached)
11616 {
11617 ReleaseSysCache(tuple);
11618 continue;
11619 }
11620
11621 /* No dice. Set up to create our own constraint */
11622 fkconstraint = makeNode(Constraint);
11623 fkconstraint->contype = CONSTRAINT_FOREIGN;
11624 /* ->conname determined below */
11625 fkconstraint->deferrable = constrForm->condeferrable;
11626 fkconstraint->initdeferred = constrForm->condeferred;
11627 fkconstraint->location = -1;
11628 fkconstraint->pktable = NULL;
11629 /* ->fk_attrs determined below */
11630 fkconstraint->pk_attrs = NIL;
11631 fkconstraint->fk_matchtype = constrForm->confmatchtype;
11632 fkconstraint->fk_upd_action = constrForm->confupdtype;
11633 fkconstraint->fk_del_action = constrForm->confdeltype;
11634 fkconstraint->fk_del_set_cols = NIL;
11635 fkconstraint->old_conpfeqop = NIL;
11636 fkconstraint->old_pktable_oid = InvalidOid;
11637 fkconstraint->is_enforced = constrForm->conenforced;
11638 fkconstraint->skip_validation = false;
11639 fkconstraint->initially_valid = constrForm->convalidated;
11640 for (int i = 0; i < numfks; i++)
11641 {
11642 Form_pg_attribute att;
11643
11644 att = TupleDescAttr(RelationGetDescr(partRel),
11645 mapped_conkey[i] - 1);
11646 fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11647 makeString(NameStr(att->attname)));
11648 }
11649
11650 indexOid = constrForm->conindid;
11651 with_period = constrForm->conperiod;
11652
11653 /* Create the pg_constraint entry at this level */
11654 address = addFkConstraint(addFkReferencingSide,
11655 NameStr(constrForm->conname), fkconstraint,
11656 partRel, pkrel, indexOid, parentConstrOid,
11657 numfks, confkey,
11658 mapped_conkey, conpfeqop,
11659 conppeqop, conffeqop,
11660 numfkdelsetcols, confdelsetcols,
11661 false, with_period);
11662
11663 /* Done with the cloned constraint's tuple */
11664 ReleaseSysCache(tuple);
11665
11666 /* Create the check triggers, and recurse to partitions, if any */
11667 addFkRecurseReferencing(wqueue,
11668 fkconstraint,
11669 partRel,
11670 pkrel,
11671 indexOid,
11672 address.objectId,
11673 numfks,
11674 confkey,
11675 mapped_conkey,
11676 conpfeqop,
11677 conppeqop,
11678 conffeqop,
11679 numfkdelsetcols,
11680 confdelsetcols,
11681 false, /* no old check exists */
11682 AccessExclusiveLock,
11683 insertTriggerOid,
11684 updateTriggerOid,
11685 with_period);
11686 table_close(pkrel, NoLock);
11687 }
11688
11689 table_close(trigrel, RowExclusiveLock);
11690 }
11691
11692 /*
11693 * When the parent of a partition receives [the referencing side of] a foreign
11694 * key, we must propagate that foreign key to the partition. However, the
11695 * partition might already have an equivalent foreign key; this routine
11696 * compares the given ForeignKeyCacheInfo (in the partition) to the FK defined
11697 * by the other parameters. If they are equivalent, create the link between
11698 * the two constraints and return true.
11699 *
11700 * If the given FK does not match the one defined by rest of the params,
11701 * return false.
11702 */
11703 static bool
11704 tryAttachPartitionForeignKey(List **wqueue,
11705 ForeignKeyCacheInfo *fk,
11706 Relation partition,
11707 Oid parentConstrOid,
11708 int numfks,
11709 AttrNumber *mapped_conkey,
11710 AttrNumber *confkey,
11711 Oid *conpfeqop,
11712 Oid parentInsTrigger,
11713 Oid parentUpdTrigger,
11714 Relation trigrel)
11715 {
11716 HeapTuple parentConstrTup;
11717 Form_pg_constraint parentConstr;
11718 HeapTuple partcontup;
11719 Form_pg_constraint partConstr;
11720
11721 parentConstrTup = SearchSysCache1(CONSTROID,
11722 ObjectIdGetDatum(parentConstrOid));
11723 if (!HeapTupleIsValid(parentConstrTup))
11724 elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11725 parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11726
11727 /*
11728 * Do some quick & easy initial checks. If any of these fail, we cannot
11729 * use this constraint.
11730 */
11731 if (fk->confrelid != parentConstr->confrelid || fk->nkeys != numfks)
11732 {
11733 ReleaseSysCache(parentConstrTup);
11734 return false;
11735 }
11736 for (int i = 0; i < numfks; i++)
11737 {
11738 if (fk->conkey[i] != mapped_conkey[i] ||
11739 fk->confkey[i] != confkey[i] ||
11740 fk->conpfeqop[i] != conpfeqop[i])
11741 {
11742 ReleaseSysCache(parentConstrTup);
11743 return false;
11744 }
11745 }
11746
11747 /* Looks good so far; perform more extensive checks. */
11748 partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
11749 if (!HeapTupleIsValid(partcontup))
11750 elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
11751 partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11752
11753 /*
11754 * An error should be raised if the constraint enforceability is
11755 * different. Returning false without raising an error, as we do for other
11756 * attributes, could lead to a duplicate constraint with the same
11757 * enforceability as the parent. While this may be acceptable, it may not
11758 * be ideal. Therefore, it's better to raise an error and allow the user
11759 * to correct the enforceability before proceeding.
11760 */
11761 if (partConstr->conenforced != parentConstr->conenforced)
11762 ereport(ERROR,
11763 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
11764 errmsg("constraint \"%s\" enforceability conflicts with constraint \"%s\" on relation \"%s\"",
11765 NameStr(parentConstr->conname),
11766 NameStr(partConstr->conname),
11767 RelationGetRelationName(partition))));
11768
11769 if (OidIsValid(partConstr->conparentid) ||
11770 partConstr->condeferrable != parentConstr->condeferrable ||
11771 partConstr->condeferred != parentConstr->condeferred ||
11772 partConstr->confupdtype != parentConstr->confupdtype ||
11773 partConstr->confdeltype != parentConstr->confdeltype ||
11774 partConstr->confmatchtype != parentConstr->confmatchtype)
11775 {
11776 ReleaseSysCache(parentConstrTup);
11777 ReleaseSysCache(partcontup);
11778 return false;
11779 }
11780
11781 ReleaseSysCache(parentConstrTup);
11782 ReleaseSysCache(partcontup);
11783
11784 /* Looks good! Attach this constraint. */
11785 AttachPartitionForeignKey(wqueue, partition, fk->conoid,
11786 parentConstrOid, parentInsTrigger,
11787 parentUpdTrigger, trigrel);
11788
11789 return true;
11790 }
11791
11792 /*
11793 * AttachPartitionForeignKey
11794 *
11795 * The subroutine for tryAttachPartitionForeignKey performs the final tasks of
11796 * attaching the constraint, removing redundant triggers and entries from
11797 * pg_constraint, and setting the constraint's parent.
11798 */
11799 static void
11800 AttachPartitionForeignKey(List **wqueue,
11801 Relation partition,
11802 Oid partConstrOid,
11803 Oid parentConstrOid,
11804 Oid parentInsTrigger,
11805 Oid parentUpdTrigger,
11806 Relation trigrel)
11807 {
11808 HeapTuple parentConstrTup;
11809 Form_pg_constraint parentConstr;
11810 HeapTuple partcontup;
11811 Form_pg_constraint partConstr;
11812 bool queueValidation;
11813 Oid partConstrFrelid;
11814 Oid partConstrRelid;
11815 bool parentConstrIsEnforced;
11816
11817 /* Fetch the parent constraint tuple */
11818 parentConstrTup = SearchSysCache1(CONSTROID,
11819 ObjectIdGetDatum(parentConstrOid));
11820 if (!HeapTupleIsValid(parentConstrTup))
11821 elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11822 parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11823 parentConstrIsEnforced = parentConstr->conenforced;
11824
11825 /* Fetch the child constraint tuple */
11826 partcontup = SearchSysCache1(CONSTROID,
11827 ObjectIdGetDatum(partConstrOid));
11828 if (!HeapTupleIsValid(partcontup))
11829 elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
11830 partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11831 partConstrFrelid = partConstr->confrelid;
11832 partConstrRelid = partConstr->conrelid;
11833
11834 /*
11835 * If the referenced table is partitioned, then the partition we're
11836 * attaching now has extra pg_constraint rows and action triggers that are
11837 * no longer needed. Remove those.
11838 */
11839 if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
11840 {
11841 Relation pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11842
11843 RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
11844 partConstrRelid);
11845
11846 table_close(pg_constraint, RowShareLock);
11847 }
11848
11849 /*
11850 * Will we need to validate this constraint? A valid parent constraint
11851 * implies that all child constraints have been validated, so if this one
11852 * isn't, we must trigger phase 3 validation.
11853 */
11854 queueValidation = parentConstr->convalidated && !partConstr->convalidated;
11855
11856 ReleaseSysCache(partcontup);
11857 ReleaseSysCache(parentConstrTup);
11858
11859 /*
11860 * The action triggers in the new partition become redundant -- the parent
11861 * table already has equivalent ones, and those will be able to reach the
11862 * partition. Remove the ones in the partition. We identify them because
11863 * they have our constraint OID, as well as being on the referenced rel.
11864 */
11865 DropForeignKeyConstraintTriggers(trigrel, partConstrOid, partConstrFrelid,
11866 partConstrRelid);
11867
11868 ConstraintSetParentConstraint(partConstrOid, parentConstrOid,
11869 RelationGetRelid(partition));
11870
11871 /*
11872 * Like the constraint, attach partition's "check" triggers to the
11873 * corresponding parent triggers if the constraint is ENFORCED. NOT
11874 * ENFORCED constraints do not have these triggers.
11875 */
11876 if (parentConstrIsEnforced)
11877 {
11878 Oid insertTriggerOid,
11879 updateTriggerOid;
11880
11881 GetForeignKeyCheckTriggers(trigrel,
11882 partConstrOid, partConstrFrelid, partConstrRelid,
11883 &insertTriggerOid, &updateTriggerOid);
11884 Assert(OidIsValid(insertTriggerOid) && OidIsValid(parentInsTrigger));
11885 TriggerSetParentTrigger(trigrel, insertTriggerOid, parentInsTrigger,
11886 RelationGetRelid(partition));
11887 Assert(OidIsValid(updateTriggerOid) && OidIsValid(parentUpdTrigger));
11888 TriggerSetParentTrigger(trigrel, updateTriggerOid, parentUpdTrigger,
11889 RelationGetRelid(partition));
11890 }
11891
11892 /*
11893 * We updated this pg_constraint row above to set its parent; validating
11894 * it will cause its convalidated flag to change, so we need CCI here. In
11895 * addition, we need it unconditionally for the rare case where the parent
11896 * table has *two* identical constraints; when reaching this function for
11897 * the second one, we must have made our changes visible, otherwise we
11898 * would try to attach both to this one.
11899 */
11900 CommandCounterIncrement();
11901
11902 /* If validation is needed, put it in the queue now. */
11903 if (queueValidation)
11904 {
11905 Relation conrel;
11906 Oid confrelid;
11907
11908 conrel = table_open(ConstraintRelationId, RowExclusiveLock);
11909
11910 partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(partConstrOid));
11911 if (!HeapTupleIsValid(partcontup))
11912 elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
11913
11914 confrelid = ((Form_pg_constraint) GETSTRUCT(partcontup))->confrelid;
11915
11916 /* Use the same lock as for AT_ValidateConstraint */
11917 QueueFKConstraintValidation(wqueue, conrel, partition, confrelid,
11918 partcontup, ShareUpdateExclusiveLock);
11919 ReleaseSysCache(partcontup);
11920 table_close(conrel, RowExclusiveLock);
11921 }
11922 }
11923
11924 /*
11925 * RemoveInheritedConstraint
11926 *
11927 * Removes the constraint and its associated trigger from the specified
11928 * relation, which inherited the given constraint.
11929 */
11930 static void
11931 RemoveInheritedConstraint(Relation conrel, Relation trigrel, Oid conoid,
11932 Oid conrelid)
11933 {
11934 ObjectAddresses *objs;
11935 HeapTuple consttup;
11936 ScanKeyData key;
11937 SysScanDesc scan;
11938 HeapTuple trigtup;
11939
11940 ScanKeyInit(&key,
11941 Anum_pg_constraint_conrelid,
11942 BTEqualStrategyNumber, F_OIDEQ,
11943 ObjectIdGetDatum(conrelid));
11944
11945 scan = systable_beginscan(conrel,
11946 ConstraintRelidTypidNameIndexId,
11947 true, NULL, 1, &key);
11948 objs = new_object_addresses();
11949 while ((consttup = systable_getnext(scan)) != NULL)
11950 {
11951 Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(consttup);
11952
11953 if (conform->conparentid != conoid)
11954 continue;
11955 else
11956 {
11957 ObjectAddress addr;
11958 SysScanDesc scan2;
11959 ScanKeyData key2;
11960 int n PG_USED_FOR_ASSERTS_ONLY;
11961
11962 ObjectAddressSet(addr, ConstraintRelationId, conform->oid);
11963 add_exact_object_address(&addr, objs);
11964
11965 /*
11966 * First we must delete the dependency record that binds the
11967 * constraint records together.
11968 */
11969 n = deleteDependencyRecordsForSpecific(ConstraintRelationId,
11970 conform->oid,
11971 DEPENDENCY_INTERNAL,
11972 ConstraintRelationId,
11973 conoid);
11974 Assert(n == 1); /* actually only one is expected */
11975
11976 /*
11977 * Now search for the triggers for this constraint and set them up
11978 * for deletion too
11979 */
11980 ScanKeyInit(&key2,
11981 Anum_pg_trigger_tgconstraint,
11982 BTEqualStrategyNumber, F_OIDEQ,
11983 ObjectIdGetDatum(conform->oid));
11984 scan2 = systable_beginscan(trigrel, TriggerConstraintIndexId,
11985 true, NULL, 1, &key2);
11986 while ((trigtup = systable_getnext(scan2)) != NULL)
11987 {
11988 ObjectAddressSet(addr, TriggerRelationId,
11989 ((Form_pg_trigger) GETSTRUCT(trigtup))->oid);
11990 add_exact_object_address(&addr, objs);
11991 }
11992 systable_endscan(scan2);
11993 }
11994 }
11995 /* make the dependency deletions visible */
11996 CommandCounterIncrement();
11997 performMultipleDeletions(objs, DROP_RESTRICT,
11998 PERFORM_DELETION_INTERNAL);
11999 systable_endscan(scan);
12000 }
12001
12002 /*
12003 * DropForeignKeyConstraintTriggers
12004 *
12005 * The subroutine for tryAttachPartitionForeignKey handles the deletion of
12006 * action triggers for the foreign key constraint.
12007 *
12008 * If valid confrelid and conrelid values are not provided, the respective
12009 * trigger check will be skipped, and the trigger will be considered for
12010 * removal.
12011 */
12012 static void
12013 DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid, Oid confrelid,
12014 Oid conrelid)
12015 {
12016 ScanKeyData key;
12017 SysScanDesc scan;
12018 HeapTuple trigtup;
12019
12020 ScanKeyInit(&key,
12021 Anum_pg_trigger_tgconstraint,
12022 BTEqualStrategyNumber, F_OIDEQ,
12023 ObjectIdGetDatum(conoid));
12024 scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12025 NULL, 1, &key);
12026 while ((trigtup = systable_getnext(scan)) != NULL)
12027 {
12028 Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12029 ObjectAddress trigger;
12030
12031 /* Invalid if trigger is not for a referential integrity constraint */
12032 if (!OidIsValid(trgform->tgconstrrelid))
12033 continue;
12034 if (OidIsValid(conrelid) && trgform->tgconstrrelid != conrelid)
12035 continue;
12036 if (OidIsValid(confrelid) && trgform->tgrelid != confrelid)
12037 continue;
12038
12039 /* We should be dropping trigger related to foreign key constraint */
12040 Assert(trgform->tgfoid == F_RI_FKEY_CHECK_INS ||
12041 trgform->tgfoid == F_RI_FKEY_CHECK_UPD ||
12042 trgform->tgfoid == F_RI_FKEY_CASCADE_DEL ||
12043 trgform->tgfoid == F_RI_FKEY_CASCADE_UPD ||
12044 trgform->tgfoid == F_RI_FKEY_RESTRICT_DEL ||
12045 trgform->tgfoid == F_RI_FKEY_RESTRICT_UPD ||
12046 trgform->tgfoid == F_RI_FKEY_SETNULL_DEL ||
12047 trgform->tgfoid == F_RI_FKEY_SETNULL_UPD ||
12048 trgform->tgfoid == F_RI_FKEY_SETDEFAULT_DEL ||
12049 trgform->tgfoid == F_RI_FKEY_SETDEFAULT_UPD ||
12050 trgform->tgfoid == F_RI_FKEY_NOACTION_DEL ||
12051 trgform->tgfoid == F_RI_FKEY_NOACTION_UPD);
12052
12053 /*
12054 * The constraint is originally set up to contain this trigger as an
12055 * implementation object, so there's a dependency record that links
12056 * the two; however, since the trigger is no longer needed, we remove
12057 * the dependency link in order to be able to drop the trigger while
12058 * keeping the constraint intact.
12059 */
12060 deleteDependencyRecordsFor(TriggerRelationId,
12061 trgform->oid,
12062 false);
12063 /* make dependency deletion visible to performDeletion */
12064 CommandCounterIncrement();
12065 ObjectAddressSet(trigger, TriggerRelationId,
12066 trgform->oid);
12067 performDeletion(&trigger, DROP_RESTRICT, 0);
12068 /* make trigger drop visible, in case the loop iterates */
12069 CommandCounterIncrement();
12070 }
12071
12072 systable_endscan(scan);
12073 }
12074
12075 /*
12076 * GetForeignKeyActionTriggers
12077 * Returns delete and update "action" triggers of the given relation
12078 * belonging to the given constraint
12079 */
12080 static void
12081 GetForeignKeyActionTriggers(Relation trigrel,
12082 Oid conoid, Oid confrelid, Oid conrelid,
12083 Oid *deleteTriggerOid,
12084 Oid *updateTriggerOid)
12085 {
12086 ScanKeyData key;
12087 SysScanDesc scan;
12088 HeapTuple trigtup;
12089
12090 *deleteTriggerOid = *updateTriggerOid = InvalidOid;
12091 ScanKeyInit(&key,
12092 Anum_pg_trigger_tgconstraint,
12093 BTEqualStrategyNumber, F_OIDEQ,
12094 ObjectIdGetDatum(conoid));
12095
12096 scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12097 NULL, 1, &key);
12098 while ((trigtup = systable_getnext(scan)) != NULL)
12099 {
12100 Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12101
12102 if (trgform->tgconstrrelid != conrelid)
12103 continue;
12104 if (trgform->tgrelid != confrelid)
12105 continue;
12106 /* Only ever look at "action" triggers on the PK side. */
12107 if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_PK)
12108 continue;
12109 if (TRIGGER_FOR_DELETE(trgform->tgtype))
12110 {
12111 Assert(*deleteTriggerOid == InvalidOid);
12112 *deleteTriggerOid = trgform->oid;
12113 }
12114 else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12115 {
12116 Assert(*updateTriggerOid == InvalidOid);
12117 *updateTriggerOid = trgform->oid;
12118 }
12119 #ifndef USE_ASSERT_CHECKING
12120 /* In an assert-enabled build, continue looking to find duplicates */
12121 if (OidIsValid(*deleteTriggerOid) && OidIsValid(*updateTriggerOid))
12122 break;
12123 #endif
12124 }
12125
12126 if (!OidIsValid(*deleteTriggerOid))
12127 elog(ERROR, "could not find ON DELETE action trigger of foreign key constraint %u",
12128 conoid);
12129 if (!OidIsValid(*updateTriggerOid))
12130 elog(ERROR, "could not find ON UPDATE action trigger of foreign key constraint %u",
12131 conoid);
12132
12133 systable_endscan(scan);
12134 }
12135
12136 /*
12137 * GetForeignKeyCheckTriggers
12138 * Returns insert and update "check" triggers of the given relation
12139 * belonging to the given constraint
12140 */
12141 static void
12142 GetForeignKeyCheckTriggers(Relation trigrel,
12143 Oid conoid, Oid confrelid, Oid conrelid,
12144 Oid *insertTriggerOid,
12145 Oid *updateTriggerOid)
12146 {
12147 ScanKeyData key;
12148 SysScanDesc scan;
12149 HeapTuple trigtup;
12150
12151 *insertTriggerOid = *updateTriggerOid = InvalidOid;
12152 ScanKeyInit(&key,
12153 Anum_pg_trigger_tgconstraint,
12154 BTEqualStrategyNumber, F_OIDEQ,
12155 ObjectIdGetDatum(conoid));
12156
12157 scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12158 NULL, 1, &key);
12159 while ((trigtup = systable_getnext(scan)) != NULL)
12160 {
12161 Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12162
12163 if (trgform->tgconstrrelid != confrelid)
12164 continue;
12165 if (trgform->tgrelid != conrelid)
12166 continue;
12167 /* Only ever look at "check" triggers on the FK side. */
12168 if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_FK)
12169 continue;
12170 if (TRIGGER_FOR_INSERT(trgform->tgtype))
12171 {
12172 Assert(*insertTriggerOid == InvalidOid);
12173 *insertTriggerOid = trgform->oid;
12174 }
12175 else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12176 {
12177 Assert(*updateTriggerOid == InvalidOid);
12178 *updateTriggerOid = trgform->oid;
12179 }
12180 #ifndef USE_ASSERT_CHECKING
12181 /* In an assert-enabled build, continue looking to find duplicates. */
12182 if (OidIsValid(*insertTriggerOid) && OidIsValid(*updateTriggerOid))
12183 break;
12184 #endif
12185 }
12186
12187 if (!OidIsValid(*insertTriggerOid))
12188 elog(ERROR, "could not find ON INSERT check triggers of foreign key constraint %u",
12189 conoid);
12190 if (!OidIsValid(*updateTriggerOid))
12191 elog(ERROR, "could not find ON UPDATE check triggers of foreign key constraint %u",
12192 conoid);
12193
12194 systable_endscan(scan);
12195 }
12196
12197 /*
12198 * ALTER TABLE ALTER CONSTRAINT
12199 *
12200 * Update the attributes of a constraint.
12201 *
12202 * Currently only works for Foreign Key and not null constraints.
12203 *
12204 * If the constraint is modified, returns its address; otherwise, return
12205 * InvalidObjectAddress.
12206 */
12207 static ObjectAddress
12208 ATExecAlterConstraint(List **wqueue, Relation rel, ATAlterConstraint *cmdcon,
12209 bool recurse, LOCKMODE lockmode)
12210 {
12211 Relation conrel;
12212 Relation tgrel;
12213 SysScanDesc scan;
12214 ScanKeyData skey[3];
12215 HeapTuple contuple;
12216 Form_pg_constraint currcon;
12217 ObjectAddress address;
12218
12219 /*
12220 * Disallow altering ONLY a partitioned table, as it would make no sense.
12221 * This is okay for legacy inheritance.
12222 */
12223 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
12224 ereport(ERROR,
12225 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12226 errmsg("constraint must be altered in child tables too"),
12227 errhint("Do not specify the ONLY keyword."));
12228
12229
12230 conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12231 tgrel = table_open(TriggerRelationId, RowExclusiveLock);
12232
12233 /*
12234 * Find and check the target constraint
12235 */
12236 ScanKeyInit(&skey[0],
12237 Anum_pg_constraint_conrelid,
12238 BTEqualStrategyNumber, F_OIDEQ,
12239 ObjectIdGetDatum(RelationGetRelid(rel)));
12240 ScanKeyInit(&skey[1],
12241 Anum_pg_constraint_contypid,
12242 BTEqualStrategyNumber, F_OIDEQ,
12243 ObjectIdGetDatum(InvalidOid));
12244 ScanKeyInit(&skey[2],
12245 Anum_pg_constraint_conname,
12246 BTEqualStrategyNumber, F_NAMEEQ,
12247 CStringGetDatum(cmdcon->conname));
12248 scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12249 true, NULL, 3, skey);
12250
12251 /* There can be at most one matching row */
12252 if (!HeapTupleIsValid(contuple = systable_getnext(scan)))
12253 ereport(ERROR,
12254 (errcode(ERRCODE_UNDEFINED_OBJECT),
12255 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12256 cmdcon->conname, RelationGetRelationName(rel))));
12257
12258 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12259 if (cmdcon->alterDeferrability && currcon->contype != CONSTRAINT_FOREIGN)
12260 ereport(ERROR,
12261 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12262 errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
12263 cmdcon->conname, RelationGetRelationName(rel))));
12264 if (cmdcon->alterEnforceability && currcon->contype != CONSTRAINT_FOREIGN)
12265 ereport(ERROR,
12266 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12267 errmsg("cannot alter enforceability of constraint \"%s\" of relation \"%s\"",
12268 cmdcon->conname, RelationGetRelationName(rel))));
12269 if (cmdcon->alterInheritability &&
12270 currcon->contype != CONSTRAINT_NOTNULL)
12271 ereport(ERROR,
12272 errcode(ERRCODE_WRONG_OBJECT_TYPE),
12273 errmsg("constraint \"%s\" of relation \"%s\" is not a not-null constraint",
12274 cmdcon->conname, RelationGetRelationName(rel)));
12275 if (cmdcon->alterInheritability &&
12276 cmdcon->noinherit && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12277 ereport(ERROR,
12278 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12279 errmsg("not-null constraint \"%s\" on partitioned table \"%s\" cannot be NO INHERIT",
12280 cmdcon->conname, RelationGetRelationName(rel)));
12281
12282 /* Refuse to modify inheritability of inherited constraints */
12283 if (cmdcon->alterInheritability &&
12284 cmdcon->noinherit && currcon->coninhcount > 0)
12285 ereport(ERROR,
12286 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12287 errmsg("cannot alter inherited constraint \"%s\" on relation \"%s\"",
12288 NameStr(currcon->conname),
12289 RelationGetRelationName(rel)));
12290
12291 /*
12292 * If it's not the topmost constraint, raise an error.
12293 *
12294 * Altering a non-topmost constraint leaves some triggers untouched, since
12295 * they are not directly connected to this constraint; also, pg_dump would
12296 * ignore the deferrability status of the individual constraint, since it
12297 * only dumps topmost constraints. Avoid these problems by refusing this
12298 * operation and telling the user to alter the parent constraint instead.
12299 */
12300 if (OidIsValid(currcon->conparentid))
12301 {
12302 HeapTuple tp;
12303 Oid parent = currcon->conparentid;
12304 char *ancestorname = NULL;
12305 char *ancestortable = NULL;
12306
12307 /* Loop to find the topmost constraint */
12308 while (HeapTupleIsValid(tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parent))))
12309 {
12310 Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
12311
12312 /* If no parent, this is the constraint we want */
12313 if (!OidIsValid(contup->conparentid))
12314 {
12315 ancestorname = pstrdup(NameStr(contup->conname));
12316 ancestortable = get_rel_name(contup->conrelid);
12317 ReleaseSysCache(tp);
12318 break;
12319 }
12320
12321 parent = contup->conparentid;
12322 ReleaseSysCache(tp);
12323 }
12324
12325 ereport(ERROR,
12326 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12327 errmsg("cannot alter constraint \"%s\" on relation \"%s\"",
12328 cmdcon->conname, RelationGetRelationName(rel)),
12329 ancestorname && ancestortable ?
12330 errdetail("Constraint \"%s\" is derived from constraint \"%s\" of relation \"%s\".",
12331 cmdcon->conname, ancestorname, ancestortable) : 0,
12332 errhint("You may alter the constraint it derives from instead.")));
12333 }
12334
12335 address = InvalidObjectAddress;
12336
12337 /*
12338 * Do the actual catalog work, and recurse if necessary.
12339 */
12340 if (ATExecAlterConstraintInternal(wqueue, cmdcon, conrel, tgrel, rel,
12341 contuple, recurse, lockmode))
12342 ObjectAddressSet(address, ConstraintRelationId, currcon->oid);
12343
12344 systable_endscan(scan);
12345
12346 table_close(tgrel, RowExclusiveLock);
12347 table_close(conrel, RowExclusiveLock);
12348
12349 return address;
12350 }
12351
12352 /*
12353 * A subroutine of ATExecAlterConstraint that calls the respective routines for
12354 * altering constraint's enforceability, deferrability or inheritability.
12355 */
12356 static bool
12357 ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon,
12358 Relation conrel, Relation tgrel, Relation rel,
12359 HeapTuple contuple, bool recurse,
12360 LOCKMODE lockmode)
12361 {
12362 Form_pg_constraint currcon;
12363 bool changed = false;
12364 List *otherrelids = NIL;
12365
12366 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12367
12368 /*
12369 * Do the catalog work for the enforceability or deferrability change,
12370 * recurse if necessary.
12371 *
12372 * Note that even if deferrability is requested to be altered along with
12373 * enforceability, we don't need to explicitly update multiple entries in
12374 * pg_trigger related to deferrability.
12375 *
12376 * Modifying enforceability involves either creating or dropping the
12377 * trigger, during which the deferrability setting will be adjusted
12378 * automatically.
12379 */
12380 if (cmdcon->alterEnforceability &&
12381 ATExecAlterConstrEnforceability(wqueue, cmdcon, conrel, tgrel,
12382 currcon->conrelid, currcon->confrelid,
12383 contuple, lockmode, InvalidOid,
12384 InvalidOid, InvalidOid, InvalidOid))
12385 changed = true;
12386
12387 else if (cmdcon->alterDeferrability &&
12388 ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel,
12389 contuple, recurse, &otherrelids,
12390 lockmode))
12391 {
12392 /*
12393 * AlterConstrUpdateConstraintEntry already invalidated relcache for
12394 * the relations having the constraint itself; here we also invalidate
12395 * for relations that have any triggers that are part of the
12396 * constraint.
12397 */
12398 foreach_oid(relid, otherrelids)
12399 CacheInvalidateRelcacheByRelid(relid);
12400
12401 changed = true;
12402 }
12403
12404 /*
12405 * Do the catalog work for the inheritability change.
12406 */
12407 if (cmdcon->alterInheritability &&
12408 ATExecAlterConstrInheritability(wqueue, cmdcon, conrel, rel, contuple,
12409 lockmode))
12410 changed = true;
12411
12412 return changed;
12413 }
12414
12415 /*
12416 * Returns true if the constraint's enforceability is altered.
12417 *
12418 * Depending on whether the constraint is being set to ENFORCED or NOT
12419 * ENFORCED, it creates or drops the trigger accordingly.
12420 *
12421 * Note that we must recurse even when trying to change a constraint to not
12422 * enforced if it is already not enforced, in case descendant constraints
12423 * might be enforced and need to be changed to not enforced. Conversely, we
12424 * should do nothing if a constraint is being set to enforced and is already
12425 * enforced, as descendant constraints cannot be different in that case.
12426 */
12427 static bool
12428 ATExecAlterConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
12429 Relation conrel, Relation tgrel,
12430 Oid fkrelid, Oid pkrelid,
12431 HeapTuple contuple, LOCKMODE lockmode,
12432 Oid ReferencedParentDelTrigger,
12433 Oid ReferencedParentUpdTrigger,
12434 Oid ReferencingParentInsTrigger,
12435 Oid ReferencingParentUpdTrigger)
12436 {
12437 Form_pg_constraint currcon;
12438 Oid conoid;
12439 Relation rel;
12440 bool changed = false;
12441
12442 /* Since this function recurses, it could be driven to stack overflow */
12443 check_stack_depth();
12444
12445 Assert(cmdcon->alterEnforceability);
12446
12447 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12448 conoid = currcon->oid;
12449
12450 /* Should be foreign key constraint */
12451 Assert(currcon->contype == CONSTRAINT_FOREIGN);
12452
12453 rel = table_open(currcon->conrelid, lockmode);
12454
12455 if (currcon->conenforced != cmdcon->is_enforced)
12456 {
12457 AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12458 changed = true;
12459 }
12460
12461 /* Drop triggers */
12462 if (!cmdcon->is_enforced)
12463 {
12464 /*
12465 * When setting a constraint to NOT ENFORCED, the constraint triggers
12466 * need to be dropped. Therefore, we must process the child relations
12467 * first, followed by the parent, to account for dependencies.
12468 */
12469 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12470 get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12471 AlterConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12472 fkrelid, pkrelid, contuple,
12473 lockmode, InvalidOid, InvalidOid,
12474 InvalidOid, InvalidOid);
12475
12476 /* Drop all the triggers */
12477 DropForeignKeyConstraintTriggers(tgrel, conoid, InvalidOid, InvalidOid);
12478 }
12479 else if (changed) /* Create triggers */
12480 {
12481 Oid ReferencedDelTriggerOid = InvalidOid,
12482 ReferencedUpdTriggerOid = InvalidOid,
12483 ReferencingInsTriggerOid = InvalidOid,
12484 ReferencingUpdTriggerOid = InvalidOid;
12485
12486 /* Prepare the minimal information required for trigger creation. */
12487 Constraint *fkconstraint = makeNode(Constraint);
12488
12489 fkconstraint->conname = pstrdup(NameStr(currcon->conname));
12490 fkconstraint->fk_matchtype = currcon->confmatchtype;
12491 fkconstraint->fk_upd_action = currcon->confupdtype;
12492 fkconstraint->fk_del_action = currcon->confdeltype;
12493 fkconstraint->deferrable = currcon->condeferrable;
12494 fkconstraint->initdeferred = currcon->condeferred;
12495
12496 /* Create referenced triggers */
12497 if (currcon->conrelid == fkrelid)
12498 createForeignKeyActionTriggers(currcon->conrelid,
12499 currcon->confrelid,
12500 fkconstraint,
12501 conoid,
12502 currcon->conindid,
12503 ReferencedParentDelTrigger,
12504 ReferencedParentUpdTrigger,
12505 &ReferencedDelTriggerOid,
12506 &ReferencedUpdTriggerOid);
12507
12508 /* Create referencing triggers */
12509 if (currcon->confrelid == pkrelid)
12510 createForeignKeyCheckTriggers(currcon->conrelid,
12511 pkrelid,
12512 fkconstraint,
12513 conoid,
12514 currcon->conindid,
12515 ReferencingParentInsTrigger,
12516 ReferencingParentUpdTrigger,
12517 &ReferencingInsTriggerOid,
12518 &ReferencingUpdTriggerOid);
12519
12520 /*
12521 * Tell Phase 3 to check that the constraint is satisfied by existing
12522 * rows. Only applies to leaf partitions, and (for constraints that
12523 * reference a partitioned table) only if this is not one of the
12524 * pg_constraint rows that exist solely to support action triggers.
12525 */
12526 if (rel->rd_rel->relkind == RELKIND_RELATION &&
12527 currcon->confrelid == pkrelid)
12528 {
12529 AlteredTableInfo *tab;
12530 NewConstraint *newcon;
12531
12532 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
12533 newcon->name = fkconstraint->conname;
12534 newcon->contype = CONSTR_FOREIGN;
12535 newcon->refrelid = currcon->confrelid;
12536 newcon->refindid = currcon->conindid;
12537 newcon->conid = currcon->oid;
12538 newcon->qual = (Node *) fkconstraint;
12539
12540 /* Find or create work queue entry for this table */
12541 tab = ATGetQueueEntry(wqueue, rel);
12542 tab->constraints = lappend(tab->constraints, newcon);
12543 }
12544
12545 /*
12546 * If the table at either end of the constraint is partitioned, we
12547 * need to recurse and create triggers for each constraint that is a
12548 * child of this one.
12549 */
12550 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12551 get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12552 AlterConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12553 fkrelid, pkrelid, contuple,
12554 lockmode, ReferencedDelTriggerOid,
12555 ReferencedUpdTriggerOid,
12556 ReferencingInsTriggerOid,
12557 ReferencingUpdTriggerOid);
12558 }
12559
12560 table_close(rel, NoLock);
12561
12562 return changed;
12563 }
12564
12565 /*
12566 * Returns true if the constraint's deferrability is altered.
12567 *
12568 * *otherrelids is appended OIDs of relations containing affected triggers.
12569 *
12570 * Note that we must recurse even when the values are correct, in case
12571 * indirect descendants have had their constraints altered locally.
12572 * (This could be avoided if we forbade altering constraints in partitions
12573 * but existing releases don't do that.)
12574 */
12575 static bool
12576 ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
12577 Relation conrel, Relation tgrel, Relation rel,
12578 HeapTuple contuple, bool recurse,
12579 List **otherrelids, LOCKMODE lockmode)
12580 {
12581 Form_pg_constraint currcon;
12582 Oid refrelid;
12583 bool changed = false;
12584
12585 /* since this function recurses, it could be driven to stack overflow */
12586 check_stack_depth();
12587
12588 Assert(cmdcon->alterDeferrability);
12589
12590 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12591 refrelid = currcon->confrelid;
12592
12593 /* Should be foreign key constraint */
12594 Assert(currcon->contype == CONSTRAINT_FOREIGN);
12595
12596 /*
12597 * If called to modify a constraint that's already in the desired state,
12598 * silently do nothing.
12599 */
12600 if (currcon->condeferrable != cmdcon->deferrable ||
12601 currcon->condeferred != cmdcon->initdeferred)
12602 {
12603 AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12604 changed = true;
12605
12606 /*
12607 * Now we need to update the multiple entries in pg_trigger that
12608 * implement the constraint.
12609 */
12610 AlterConstrTriggerDeferrability(currcon->oid, tgrel, rel,
12611 cmdcon->deferrable,
12612 cmdcon->initdeferred, otherrelids);
12613 }
12614
12615 /*
12616 * If the table at either end of the constraint is partitioned, we need to
12617 * handle every constraint that is a child of this one.
12618 */
12619 if (recurse && changed &&
12620 (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12621 get_rel_relkind(refrelid) == RELKIND_PARTITIONED_TABLE))
12622 AlterConstrDeferrabilityRecurse(wqueue, cmdcon, conrel, tgrel, rel,
12623 contuple, recurse, otherrelids,
12624 lockmode);
12625
12626 return changed;
12627 }
12628
12629 /*
12630 * Returns true if the constraint's inheritability is altered.
12631 */
12632 static bool
12633 ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
12634 Relation conrel, Relation rel,
12635 HeapTuple contuple, LOCKMODE lockmode)
12636 {
12637 Form_pg_constraint currcon;
12638 AttrNumber colNum;
12639 char *colName;
12640 List *children;
12641
12642 Assert(cmdcon->alterInheritability);
12643
12644 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12645
12646 /* The current implementation only works for NOT NULL constraints */
12647 Assert(currcon->contype == CONSTRAINT_NOTNULL);
12648
12649 /*
12650 * If called to modify a constraint that's already in the desired state,
12651 * silently do nothing.
12652 */
12653 if (cmdcon->noinherit == currcon->connoinherit)
12654 return false;
12655
12656 AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12657 CommandCounterIncrement();
12658
12659 /* Fetch the column number and name */
12660 colNum = extractNotNullColumn(contuple);
12661 colName = get_attname(currcon->conrelid, colNum, false);
12662
12663 /*
12664 * Propagate the change to children. For this subcommand type we don't
12665 * recursively affect children, just the immediate level.
12666 */
12667 children = find_inheritance_children(RelationGetRelid(rel),
12668 lockmode);
12669 foreach_oid(childoid, children)
12670 {
12671 ObjectAddress addr;
12672
12673 if (cmdcon->noinherit)
12674 {
12675 HeapTuple childtup;
12676 Form_pg_constraint childcon;
12677
12678 childtup = findNotNullConstraint(childoid, colName);
12679 if (!childtup)
12680 elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
12681 colName, childoid);
12682 childcon = (Form_pg_constraint) GETSTRUCT(childtup);
12683 Assert(childcon->coninhcount > 0);
12684 childcon->coninhcount--;
12685 childcon->conislocal = true;
12686 CatalogTupleUpdate(conrel, &childtup->t_self, childtup);
12687 heap_freetuple(childtup);
12688 }
12689 else
12690 {
12691 Relation childrel = table_open(childoid, NoLock);
12692
12693 addr = ATExecSetNotNull(wqueue, childrel, NameStr(currcon->conname),
12694 colName, true, true, lockmode);
12695 if (OidIsValid(addr.objectId))
12696 CommandCounterIncrement();
12697 table_close(childrel, NoLock);
12698 }
12699 }
12700
12701 return true;
12702 }
12703
12704 /*
12705 * A subroutine of ATExecAlterConstrDeferrability that updated constraint
12706 * trigger's deferrability.
12707 *
12708 * The arguments to this function have the same meaning as the arguments to
12709 * ATExecAlterConstrDeferrability.
12710 */
12711 static void
12712 AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
12713 bool deferrable, bool initdeferred,
12714 List **otherrelids)
12715 {
12716 HeapTuple tgtuple;
12717 ScanKeyData tgkey;
12718 SysScanDesc tgscan;
12719
12720 ScanKeyInit(&tgkey,
12721 Anum_pg_trigger_tgconstraint,
12722 BTEqualStrategyNumber, F_OIDEQ,
12723 ObjectIdGetDatum(conoid));
12724 tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
12725 NULL, 1, &tgkey);
12726 while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
12727 {
12728 Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
12729 Form_pg_trigger copy_tg;
12730 HeapTuple tgCopyTuple;
12731
12732 /*
12733 * Remember OIDs of other relation(s) involved in FK constraint.
12734 * (Note: it's likely that we could skip forcing a relcache inval for
12735 * other rels that don't have a trigger whose properties change, but
12736 * let's be conservative.)
12737 */
12738 if (tgform->tgrelid != RelationGetRelid(rel))
12739 *otherrelids = list_append_unique_oid(*otherrelids,
12740 tgform->tgrelid);
12741
12742 /*
12743 * Update enable status and deferrability of RI_FKey_noaction_del,
12744 * RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
12745 * triggers, but not others; see createForeignKeyActionTriggers and
12746 * CreateFKCheckTrigger.
12747 */
12748 if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
12749 tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
12750 tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
12751 tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
12752 continue;
12753
12754 tgCopyTuple = heap_copytuple(tgtuple);
12755 copy_tg = (Form_pg_trigger) GETSTRUCT(tgCopyTuple);
12756
12757 copy_tg->tgdeferrable = deferrable;
12758 copy_tg->tginitdeferred = initdeferred;
12759 CatalogTupleUpdate(tgrel, &tgCopyTuple->t_self, tgCopyTuple);
12760
12761 InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
12762
12763 heap_freetuple(tgCopyTuple);
12764 }
12765
12766 systable_endscan(tgscan);
12767 }
12768
12769 /*
12770 * Invokes ATExecAlterConstrEnforceability for each constraint that is a child of
12771 * the specified constraint.
12772 *
12773 * Note that this doesn't handle recursion the normal way, viz. by scanning the
12774 * list of child relations and recursing; instead it uses the conparentid
12775 * relationships. This may need to be reconsidered.
12776 *
12777 * The arguments to this function have the same meaning as the arguments to
12778 * ATExecAlterConstrEnforceability.
12779 */
12780 static void
12781 AlterConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
12782 Relation conrel, Relation tgrel,
12783 Oid fkrelid, Oid pkrelid,
12784 HeapTuple contuple, LOCKMODE lockmode,
12785 Oid ReferencedParentDelTrigger,
12786 Oid ReferencedParentUpdTrigger,
12787 Oid ReferencingParentInsTrigger,
12788 Oid ReferencingParentUpdTrigger)
12789 {
12790 Form_pg_constraint currcon;
12791 Oid conoid;
12792 ScanKeyData pkey;
12793 SysScanDesc pscan;
12794 HeapTuple childtup;
12795
12796 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12797 conoid = currcon->oid;
12798
12799 ScanKeyInit(&pkey,
12800 Anum_pg_constraint_conparentid,
12801 BTEqualStrategyNumber, F_OIDEQ,
12802 ObjectIdGetDatum(conoid));
12803
12804 pscan = systable_beginscan(conrel, ConstraintParentIndexId,
12805 true, NULL, 1, &pkey);
12806
12807 while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
12808 ATExecAlterConstrEnforceability(wqueue, cmdcon, conrel, tgrel, fkrelid,
12809 pkrelid, childtup, lockmode,
12810 ReferencedParentDelTrigger,
12811 ReferencedParentUpdTrigger,
12812 ReferencingParentInsTrigger,
12813 ReferencingParentUpdTrigger);
12814
12815 systable_endscan(pscan);
12816 }
12817
12818 /*
12819 * Invokes ATExecAlterConstrDeferrability for each constraint that is a child of
12820 * the specified constraint.
12821 *
12822 * Note that this doesn't handle recursion the normal way, viz. by scanning the
12823 * list of child relations and recursing; instead it uses the conparentid
12824 * relationships. This may need to be reconsidered.
12825 *
12826 * The arguments to this function have the same meaning as the arguments to
12827 * ATExecAlterConstrDeferrability.
12828 */
12829 static void
12830 AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
12831 Relation conrel, Relation tgrel, Relation rel,
12832 HeapTuple contuple, bool recurse,
12833 List **otherrelids, LOCKMODE lockmode)
12834 {
12835 Form_pg_constraint currcon;
12836 Oid conoid;
12837 ScanKeyData pkey;
12838 SysScanDesc pscan;
12839 HeapTuple childtup;
12840
12841 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12842 conoid = currcon->oid;
12843
12844 ScanKeyInit(&pkey,
12845 Anum_pg_constraint_conparentid,
12846 BTEqualStrategyNumber, F_OIDEQ,
12847 ObjectIdGetDatum(conoid));
12848
12849 pscan = systable_beginscan(conrel, ConstraintParentIndexId,
12850 true, NULL, 1, &pkey);
12851
12852 while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
12853 {
12854 Form_pg_constraint childcon = (Form_pg_constraint) GETSTRUCT(childtup);
12855 Relation childrel;
12856
12857 childrel = table_open(childcon->conrelid, lockmode);
12858
12859 ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, childrel,
12860 childtup, recurse, otherrelids, lockmode);
12861 table_close(childrel, NoLock);
12862 }
12863
12864 systable_endscan(pscan);
12865 }
12866
12867 /*
12868 * Update the constraint entry for the given ATAlterConstraint command, and
12869 * invoke the appropriate hooks.
12870 */
12871 static void
12872 AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
12873 HeapTuple contuple)
12874 {
12875 HeapTuple copyTuple;
12876 Form_pg_constraint copy_con;
12877
12878 Assert(cmdcon->alterEnforceability || cmdcon->alterDeferrability ||
12879 cmdcon->alterInheritability);
12880
12881 copyTuple = heap_copytuple(contuple);
12882 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
12883
12884 if (cmdcon->alterEnforceability)
12885 {
12886 copy_con->conenforced = cmdcon->is_enforced;
12887
12888 /*
12889 * NB: The convalidated status is irrelevant when the constraint is
12890 * set to NOT ENFORCED, but for consistency, it should still be set
12891 * appropriately. Similarly, if the constraint is later changed to
12892 * ENFORCED, validation will be performed during phase 3, so it makes
12893 * sense to mark it as valid in that case.
12894 */
12895 copy_con->convalidated = cmdcon->is_enforced;
12896 }
12897 if (cmdcon->alterDeferrability)
12898 {
12899 copy_con->condeferrable = cmdcon->deferrable;
12900 copy_con->condeferred = cmdcon->initdeferred;
12901 }
12902 if (cmdcon->alterInheritability)
12903 copy_con->connoinherit = cmdcon->noinherit;
12904
12905 CatalogTupleUpdate(conrel, &copyTuple->t_self, copyTuple);
12906 InvokeObjectPostAlterHook(ConstraintRelationId, copy_con->oid, 0);
12907
12908 /* Make new constraint flags visible to others */
12909 CacheInvalidateRelcacheByRelid(copy_con->conrelid);
12910
12911 heap_freetuple(copyTuple);
12912 }
12913
12914 /*
12915 * ALTER TABLE VALIDATE CONSTRAINT
12916 *
12917 * XXX The reason we handle recursion here rather than at Phase 1 is because
12918 * there's no good way to skip recursing when handling foreign keys: there is
12919 * no need to lock children in that case, yet we wouldn't be able to avoid
12920 * doing so at that level.
12921 *
12922 * Return value is the address of the validated constraint. If the constraint
12923 * was already validated, InvalidObjectAddress is returned.
12924 */
12925 static ObjectAddress
12926 ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName,
12927 bool recurse, bool recursing, LOCKMODE lockmode)
12928 {
12929 Relation conrel;
12930 SysScanDesc scan;
12931 ScanKeyData skey[3];
12932 HeapTuple tuple;
12933 Form_pg_constraint con;
12934 ObjectAddress address;
12935
12936 conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12937
12938 /*
12939 * Find and check the target constraint
12940 */
12941 ScanKeyInit(&skey[0],
12942 Anum_pg_constraint_conrelid,
12943 BTEqualStrategyNumber, F_OIDEQ,
12944 ObjectIdGetDatum(RelationGetRelid(rel)));
12945 ScanKeyInit(&skey[1],
12946 Anum_pg_constraint_contypid,
12947 BTEqualStrategyNumber, F_OIDEQ,
12948 ObjectIdGetDatum(InvalidOid));
12949 ScanKeyInit(&skey[2],
12950 Anum_pg_constraint_conname,
12951 BTEqualStrategyNumber, F_NAMEEQ,
12952 CStringGetDatum(constrName));
12953 scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12954 true, NULL, 3, skey);
12955
12956 /* There can be at most one matching row */
12957 if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
12958 ereport(ERROR,
12959 (errcode(ERRCODE_UNDEFINED_OBJECT),
12960 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12961 constrName, RelationGetRelationName(rel))));
12962
12963 con = (Form_pg_constraint) GETSTRUCT(tuple);
12964 if (con->contype != CONSTRAINT_FOREIGN &&
12965 con->contype != CONSTRAINT_CHECK &&
12966 con->contype != CONSTRAINT_NOTNULL)
12967 ereport(ERROR,
12968 errcode(ERRCODE_WRONG_OBJECT_TYPE),
12969 errmsg("cannot validate constraint \"%s\" of relation \"%s\"",
12970 constrName, RelationGetRelationName(rel)),
12971 errdetail("This operation is not supported for this type of constraint."));
12972
12973 if (!con->conenforced)
12974 ereport(ERROR,
12975 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12976 errmsg("cannot validate NOT ENFORCED constraint")));
12977
12978 if (!con->convalidated)
12979 {
12980 if (con->contype == CONSTRAINT_FOREIGN)
12981 {
12982 QueueFKConstraintValidation(wqueue, conrel, rel, con->confrelid,
12983 tuple, lockmode);
12984 }
12985 else if (con->contype == CONSTRAINT_CHECK)
12986 {
12987 QueueCheckConstraintValidation(wqueue, conrel, rel, constrName,
12988 tuple, recurse, recursing, lockmode);
12989 }
12990 else if (con->contype == CONSTRAINT_NOTNULL)
12991 {
12992 QueueNNConstraintValidation(wqueue, conrel, rel,
12993 tuple, recurse, recursing, lockmode);
12994 }
12995
12996 ObjectAddressSet(address, ConstraintRelationId, con->oid);
12997 }
12998 else
12999 address = InvalidObjectAddress; /* already validated */
13000
13001 systable_endscan(scan);
13002
13003 table_close(conrel, RowExclusiveLock);
13004
13005 return address;
13006 }
13007
13008 /*
13009 * QueueFKConstraintValidation
13010 *
13011 * Add an entry to the wqueue to validate the given foreign key constraint in
13012 * Phase 3 and update the convalidated field in the pg_constraint catalog
13013 * for the specified relation and all its children.
13014 */
13015 static void
13016 QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
13017 Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode)
13018 {
13019 Form_pg_constraint con;
13020 AlteredTableInfo *tab;
13021 HeapTuple copyTuple;
13022 Form_pg_constraint copy_con;
13023
13024 /* since this function recurses, it could be driven to stack overflow */
13025 check_stack_depth();
13026
13027 con = (Form_pg_constraint) GETSTRUCT(contuple);
13028 Assert(con->contype == CONSTRAINT_FOREIGN);
13029 Assert(!con->convalidated);
13030
13031 /*
13032 * Add the validation to phase 3's queue; not needed for partitioned
13033 * tables themselves, only for their partitions.
13034 *
13035 * When the referenced table (pkrelid) is partitioned, the referencing
13036 * table (fkrel) has one pg_constraint row pointing to each partition
13037 * thereof. These rows are there only to support action triggers and no
13038 * table scan is needed, therefore skip this for them as well.
13039 */
13040 if (fkrel->rd_rel->relkind == RELKIND_RELATION &&
13041 con->confrelid == pkrelid)
13042 {
13043 NewConstraint *newcon;
13044 Constraint *fkconstraint;
13045
13046 /* Queue validation for phase 3 */
13047 fkconstraint = makeNode(Constraint);
13048 /* for now this is all we need */
13049 fkconstraint->conname = pstrdup(NameStr(con->conname));
13050
13051 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
13052 newcon->name = fkconstraint->conname;
13053 newcon->contype = CONSTR_FOREIGN;
13054 newcon->refrelid = con->confrelid;
13055 newcon->refindid = con->conindid;
13056 newcon->conid = con->oid;
13057 newcon->qual = (Node *) fkconstraint;
13058
13059 /* Find or create work queue entry for this table */
13060 tab = ATGetQueueEntry(wqueue, fkrel);
13061 tab->constraints = lappend(tab->constraints, newcon);
13062 }
13063
13064 /*
13065 * If the table at either end of the constraint is partitioned, we need to
13066 * recurse and handle every unvalidate constraint that is a child of this
13067 * constraint.
13068 */
13069 if (fkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13070 get_rel_relkind(con->confrelid) == RELKIND_PARTITIONED_TABLE)
13071 {
13072 ScanKeyData pkey;
13073 SysScanDesc pscan;
13074 HeapTuple childtup;
13075
13076 ScanKeyInit(&pkey,
13077 Anum_pg_constraint_conparentid,
13078 BTEqualStrategyNumber, F_OIDEQ,
13079 ObjectIdGetDatum(con->oid));
13080
13081 pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13082 true, NULL, 1, &pkey);
13083
13084 while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13085 {
13086 Form_pg_constraint childcon;
13087 Relation childrel;
13088
13089 childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13090
13091 /*
13092 * If the child constraint has already been validated, no further
13093 * action is required for it or its descendants, as they are all
13094 * valid.
13095 */
13096 if (childcon->convalidated)
13097 continue;
13098
13099 childrel = table_open(childcon->conrelid, lockmode);
13100
13101 /*
13102 * NB: Note that pkrelid should be passed as-is during recursion,
13103 * as it is required to identify the root referenced table.
13104 */
13105 QueueFKConstraintValidation(wqueue, conrel, childrel, pkrelid,
13106 childtup, lockmode);
13107 table_close(childrel, NoLock);
13108 }
13109
13110 systable_endscan(pscan);
13111 }
13112
13113 /*
13114 * Now mark the pg_constraint row as validated (even if we didn't check,
13115 * notably the ones for partitions on the referenced side).
13116 *
13117 * We rely on transaction abort to roll back this change if phase 3
13118 * ultimately finds violating rows. This is a bit ugly.
13119 */
13120 copyTuple = heap_copytuple(contuple);
13121 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13122 copy_con->convalidated = true;
13123 CatalogTupleUpdate(conrel, &copyTuple->t_self, copyTuple);
13124
13125 InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13126
13127 heap_freetuple(copyTuple);
13128 }
13129
13130 /*
13131 * QueueCheckConstraintValidation
13132 *
13133 * Add an entry to the wqueue to validate the given check constraint in Phase 3
13134 * and update the convalidated field in the pg_constraint catalog for the
13135 * specified relation and all its inheriting children.
13136 */
13137 static void
13138 QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13139 char *constrName, HeapTuple contuple,
13140 bool recurse, bool recursing, LOCKMODE lockmode)
13141 {
13142 Form_pg_constraint con;
13143 AlteredTableInfo *tab;
13144 HeapTuple copyTuple;
13145 Form_pg_constraint copy_con;
13146
13147 List *children = NIL;
13148 ListCell *child;
13149 NewConstraint *newcon;
13150 Datum val;
13151 char *conbin;
13152
13153 con = (Form_pg_constraint) GETSTRUCT(contuple);
13154 Assert(con->contype == CONSTRAINT_CHECK);
13155
13156 /*
13157 * If we're recursing, the parent has already done this, so skip it. Also,
13158 * if the constraint is a NO INHERIT constraint, we shouldn't try to look
13159 * for it in the children.
13160 */
13161 if (!recursing && !con->connoinherit)
13162 children = find_all_inheritors(RelationGetRelid(rel),
13163 lockmode, NULL);
13164
13165 /*
13166 * For CHECK constraints, we must ensure that we only mark the constraint
13167 * as validated on the parent if it's already validated on the children.
13168 *
13169 * We recurse before validating on the parent, to reduce risk of
13170 * deadlocks.
13171 */
13172 foreach(child, children)
13173 {
13174 Oid childoid = lfirst_oid(child);
13175 Relation childrel;
13176
13177 if (childoid == RelationGetRelid(rel))
13178 continue;
13179
13180 /*
13181 * If we are told not to recurse, there had better not be any child
13182 * tables, because we can't mark the constraint on the parent valid
13183 * unless it is valid for all child tables.
13184 */
13185 if (!recurse)
13186 ereport(ERROR,
13187 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13188 errmsg("constraint must be validated on child tables too")));
13189
13190 /* find_all_inheritors already got lock */
13191 childrel = table_open(childoid, NoLock);
13192
13193 ATExecValidateConstraint(wqueue, childrel, constrName, false,
13194 true, lockmode);
13195 table_close(childrel, NoLock);
13196 }
13197
13198 /* Queue validation for phase 3 */
13199 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
13200 newcon->name = constrName;
13201 newcon->contype = CONSTR_CHECK;
13202 newcon->refrelid = InvalidOid;
13203 newcon->refindid = InvalidOid;
13204 newcon->conid = con->oid;
13205
13206 val = SysCacheGetAttrNotNull(CONSTROID, contuple,
13207 Anum_pg_constraint_conbin);
13208 conbin = TextDatumGetCString(val);
13209 newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
13210
13211 /* Find or create work queue entry for this table */
13212 tab = ATGetQueueEntry(wqueue, rel);
13213 tab->constraints = lappend(tab->constraints, newcon);
13214
13215 /*
13216 * Invalidate relcache so that others see the new validated constraint.
13217 */
13218 CacheInvalidateRelcache(rel);
13219
13220 /*
13221 * Now update the catalog, while we have the door open.
13222 */
13223 copyTuple = heap_copytuple(contuple);
13224 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13225 copy_con->convalidated = true;
13226 CatalogTupleUpdate(conrel, &copyTuple->t_self, copyTuple);
13227
13228 InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13229
13230 heap_freetuple(copyTuple);
13231 }
13232
13233 /*
13234 * QueueNNConstraintValidation
13235 *
13236 * Add an entry to the wqueue to validate the given not-null constraint in
13237 * Phase 3 and update the convalidated field in the pg_constraint catalog for
13238 * the specified relation and all its inheriting children.
13239 */
13240 static void
13241 QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13242 HeapTuple contuple, bool recurse, bool recursing,
13243 LOCKMODE lockmode)
13244 {
13245 Form_pg_constraint con;
13246 AlteredTableInfo *tab;
13247 HeapTuple copyTuple;
13248 Form_pg_constraint copy_con;
13249 List *children = NIL;
13250 AttrNumber attnum;
13251 char *colname;
13252
13253 con = (Form_pg_constraint) GETSTRUCT(contuple);
13254 Assert(con->contype == CONSTRAINT_NOTNULL);
13255
13256 attnum = extractNotNullColumn(contuple);
13257
13258 /*
13259 * If we're recursing, we've already done this for parent, so skip it.
13260 * Also, if the constraint is a NO INHERIT constraint, we shouldn't try to
13261 * look for it in the children.
13262 *
13263 * We recurse before validating on the parent, to reduce risk of
13264 * deadlocks.
13265 */
13266 if (!recursing && !con->connoinherit)
13267 children = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
13268
13269 colname = get_attname(RelationGetRelid(rel), attnum, false);
13270 foreach_oid(childoid, children)
13271 {
13272 Relation childrel;
13273 HeapTuple contup;
13274 Form_pg_constraint childcon;
13275 char *conname;
13276
13277 if (childoid == RelationGetRelid(rel))
13278 continue;
13279
13280 /*
13281 * If we are told not to recurse, there had better not be any child
13282 * tables, because we can't mark the constraint on the parent valid
13283 * unless it is valid for all child tables.
13284 */
13285 if (!recurse)
13286 ereport(ERROR,
13287 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13288 errmsg("constraint must be validated on child tables too"));
13289
13290 /*
13291 * The column on child might have a different attnum, so search by
13292 * column name.
13293 */
13294 contup = findNotNullConstraint(childoid, colname);
13295 if (!contup)
13296 elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
13297 colname, get_rel_name(childoid));
13298 childcon = (Form_pg_constraint) GETSTRUCT(contup);
13299 if (childcon->convalidated)
13300 continue;
13301
13302 /* find_all_inheritors already got lock */
13303 childrel = table_open(childoid, NoLock);
13304 conname = pstrdup(NameStr(childcon->conname));
13305
13306 /* XXX improve ATExecValidateConstraint API to avoid double search */
13307 ATExecValidateConstraint(wqueue, childrel, conname,
13308 false, true, lockmode);
13309 table_close(childrel, NoLock);
13310 }
13311
13312 /* Set attnotnull appropriately without queueing another validation */
13313 set_attnotnull(NULL, rel, attnum, false);
13314
13315 tab = ATGetQueueEntry(wqueue, rel);
13316 tab->verify_new_notnull = true;
13317
13318 /*
13319 * Invalidate relcache so that others see the new validated constraint.
13320 */
13321 CacheInvalidateRelcache(rel);
13322
13323 /*
13324 * Now update the catalogs, while we have the door open.
13325 */
13326 copyTuple = heap_copytuple(contuple);
13327 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13328 copy_con->convalidated = true;
13329 CatalogTupleUpdate(conrel, &copyTuple->t_self, copyTuple);
13330
13331 InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13332
13333 heap_freetuple(copyTuple);
13334 }
13335
13336 /*
13337 * transformColumnNameList - transform list of column names
13338 *
13339 * Lookup each name and return its attnum and, optionally, type and collation
13340 * OIDs
13341 *
13342 * Note: the name of this function suggests that it's general-purpose,
13343 * but actually it's only used to look up names appearing in foreign-key
13344 * clauses. The error messages would need work to use it in other cases,
13345 * and perhaps the validity checks as well.
13346 */
13347 static int
13348 transformColumnNameList(Oid relId, List *colList,
13349 int16 *attnums, Oid *atttypids, Oid *attcollids)
13350 {
13351 ListCell *l;
13352 int attnum;
13353
13354 attnum = 0;
13355 foreach(l, colList)
13356 {
13357 char *attname = strVal(lfirst(l));
13358 HeapTuple atttuple;
13359 Form_pg_attribute attform;
13360
13361 atttuple = SearchSysCacheAttName(relId, attname);
13362 if (!HeapTupleIsValid(atttuple))
13363 ereport(ERROR,
13364 (errcode(ERRCODE_UNDEFINED_COLUMN),
13365 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
13366 attname)));
13367 attform = (Form_pg_attribute) GETSTRUCT(atttuple);
13368 if (attform->attnum < 0)
13369 ereport(ERROR,
13370 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
13371 errmsg("system columns cannot be used in foreign keys")));
13372 if (attnum >= INDEX_MAX_KEYS)
13373 ereport(ERROR,
13374 (errcode(ERRCODE_TOO_MANY_COLUMNS),
13375 errmsg("cannot have more than %d keys in a foreign key",
13376 INDEX_MAX_KEYS)));
13377 attnums[attnum] = attform->attnum;
13378 if (atttypids != NULL)
13379 atttypids[attnum] = attform->atttypid;
13380 if (attcollids != NULL)
13381 attcollids[attnum] = attform->attcollation;
13382 ReleaseSysCache(atttuple);
13383 attnum++;
13384 }
13385
13386 return attnum;
13387 }
13388
13389 /*
13390 * transformFkeyGetPrimaryKey -
13391 *
13392 * Look up the names, attnums, types, and collations of the primary key attributes
13393 * for the pkrel. Also return the index OID and index opclasses of the
13394 * index supporting the primary key. Also return whether the index has
13395 * WITHOUT OVERLAPS.
13396 *
13397 * All parameters except pkrel are output parameters. Also, the function
13398 * return value is the number of attributes in the primary key.
13399 *
13400 * Used when the column list in the REFERENCES specification is omitted.
13401 */
13402 static int
13403 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
13404 List **attnamelist,
13405 int16 *attnums, Oid *atttypids, Oid *attcollids,
13406 Oid *opclasses, bool *pk_has_without_overlaps)
13407 {
13408 List *indexoidlist;
13409 ListCell *indexoidscan;
13410 HeapTuple indexTuple = NULL;
13411 Form_pg_index indexStruct = NULL;
13412 Datum indclassDatum;
13413 oidvector *indclass;
13414 int i;
13415
13416 /*
13417 * Get the list of index OIDs for the table from the relcache, and look up
13418 * each one in the pg_index syscache until we find one marked primary key
13419 * (hopefully there isn't more than one such). Insist it's valid, too.
13420 */
13421 *indexOid = InvalidOid;
13422
13423 indexoidlist = RelationGetIndexList(pkrel);
13424
13425 foreach(indexoidscan, indexoidlist)
13426 {
13427 Oid indexoid = lfirst_oid(indexoidscan);
13428
13429 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
13430 if (!HeapTupleIsValid(indexTuple))
13431 elog(ERROR, "cache lookup failed for index %u", indexoid);
13432 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
13433 if (indexStruct->indisprimary && indexStruct->indisvalid)
13434 {
13435 /*
13436 * Refuse to use a deferrable primary key. This is per SQL spec,
13437 * and there would be a lot of interesting semantic problems if we
13438 * tried to allow it.
13439 */
13440 if (!indexStruct->indimmediate)
13441 ereport(ERROR,
13442 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13443 errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
13444 RelationGetRelationName(pkrel))));
13445
13446 *indexOid = indexoid;
13447 break;
13448 }
13449 ReleaseSysCache(indexTuple);
13450 }
13451
13452 list_free(indexoidlist);
13453
13454 /*
13455 * Check that we found it
13456 */
13457 if (!OidIsValid(*indexOid))
13458 ereport(ERROR,
13459 (errcode(ERRCODE_UNDEFINED_OBJECT),
13460 errmsg("there is no primary key for referenced table \"%s\"",
13461 RelationGetRelationName(pkrel))));
13462
13463 /* Must get indclass the hard way */
13464 indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
13465 Anum_pg_index_indclass);
13466 indclass = (oidvector *) DatumGetPointer(indclassDatum);
13467
13468 /*
13469 * Now build the list of PK attributes from the indkey definition (we
13470 * assume a primary key cannot have expressional elements)
13471 */
13472 *attnamelist = NIL;
13473 for (i = 0; i < indexStruct->indnkeyatts; i++)
13474 {
13475 int pkattno = indexStruct->indkey.values[i];
13476
13477 attnums[i] = pkattno;
13478 atttypids[i] = attnumTypeId(pkrel, pkattno);
13479 attcollids[i] = attnumCollationId(pkrel, pkattno);
13480 opclasses[i] = indclass->values[i];
13481 *attnamelist = lappend(*attnamelist,
13482 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
13483 }
13484
13485 *pk_has_without_overlaps = indexStruct->indisexclusion;
13486
13487 ReleaseSysCache(indexTuple);
13488
13489 return i;
13490 }
13491
13492 /*
13493 * transformFkeyCheckAttrs -
13494 *
13495 * Validate that the 'attnums' columns in the 'pkrel' relation are valid to
13496 * reference as part of a foreign key constraint.
13497 *
13498 * Returns the OID of the unique index supporting the constraint and
13499 * populates the caller-provided 'opclasses' array with the opclasses
13500 * associated with the index columns. Also sets whether the index
13501 * uses WITHOUT OVERLAPS.
13502 *
13503 * Raises an ERROR on validation failure.
13504 */
13505 static Oid
13506 transformFkeyCheckAttrs(Relation pkrel,
13507 int numattrs, int16 *attnums,
13508 bool with_period, Oid *opclasses,
13509 bool *pk_has_without_overlaps)
13510 {
13511 Oid indexoid = InvalidOid;
13512 bool found = false;
13513 bool found_deferrable = false;
13514 List *indexoidlist;
13515 ListCell *indexoidscan;
13516 int i,
13517 j;
13518
13519 /*
13520 * Reject duplicate appearances of columns in the referenced-columns list.
13521 * Such a case is forbidden by the SQL standard, and even if we thought it
13522 * useful to allow it, there would be ambiguity about how to match the
13523 * list to unique indexes (in particular, it'd be unclear which index
13524 * opclass goes with which FK column).
13525 */
13526 for (i = 0; i < numattrs; i++)
13527 {
13528 for (j = i + 1; j < numattrs; j++)
13529 {
13530 if (attnums[i] == attnums[j])
13531 ereport(ERROR,
13532 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
13533 errmsg("foreign key referenced-columns list must not contain duplicates")));
13534 }
13535 }
13536
13537 /*
13538 * Get the list of index OIDs for the table from the relcache, and look up
13539 * each one in the pg_index syscache, and match unique indexes to the list
13540 * of attnums we are given.
13541 */
13542 indexoidlist = RelationGetIndexList(pkrel);
13543
13544 foreach(indexoidscan, indexoidlist)
13545 {
13546 HeapTuple indexTuple;
13547 Form_pg_index indexStruct;
13548
13549 indexoid = lfirst_oid(indexoidscan);
13550 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
13551 if (!HeapTupleIsValid(indexTuple))
13552 elog(ERROR, "cache lookup failed for index %u", indexoid);
13553 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
13554
13555 /*
13556 * Must have the right number of columns; must be unique (or if
13557 * temporal then exclusion instead) and not a partial index; forget it
13558 * if there are any expressions, too. Invalid indexes are out as well.
13559 */
13560 if (indexStruct->indnkeyatts == numattrs &&
13561 (with_period ? indexStruct->indisexclusion : indexStruct->indisunique) &&
13562 indexStruct->indisvalid &&
13563 heap_attisnull(indexTuple, Anum_pg_index_indpred, NULL) &&
13564 heap_attisnull(indexTuple, Anum_pg_index_indexprs, NULL))
13565 {
13566 Datum indclassDatum;
13567 oidvector *indclass;
13568
13569 /* Must get indclass the hard way */
13570 indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
13571 Anum_pg_index_indclass);
13572 indclass = (oidvector *) DatumGetPointer(indclassDatum);
13573
13574 /*
13575 * The given attnum list may match the index columns in any order.
13576 * Check for a match, and extract the appropriate opclasses while
13577 * we're at it.
13578 *
13579 * We know that attnums[] is duplicate-free per the test at the
13580 * start of this function, and we checked above that the number of
13581 * index columns agrees, so if we find a match for each attnums[]
13582 * entry then we must have a one-to-one match in some order.
13583 */
13584 for (i = 0; i < numattrs; i++)
13585 {
13586 found = false;
13587 for (j = 0; j < numattrs; j++)
13588 {
13589 if (attnums[i] == indexStruct->indkey.values[j])
13590 {
13591 opclasses[i] = indclass->values[j];
13592 found = true;
13593 break;
13594 }
13595 }
13596 if (!found)
13597 break;
13598 }
13599 /* The last attribute in the index must be the PERIOD FK part */
13600 if (found && with_period)
13601 {
13602 int16 periodattnum = attnums[numattrs - 1];
13603
13604 found = (periodattnum == indexStruct->indkey.values[numattrs - 1]);
13605 }
13606
13607 /*
13608 * Refuse to use a deferrable unique/primary key. This is per SQL
13609 * spec, and there would be a lot of interesting semantic problems
13610 * if we tried to allow it.
13611 */
13612 if (found && !indexStruct->indimmediate)
13613 {
13614 /*
13615 * Remember that we found an otherwise matching index, so that
13616 * we can generate a more appropriate error message.
13617 */
13618 found_deferrable = true;
13619 found = false;
13620 }
13621
13622 /* We need to know whether the index has WITHOUT OVERLAPS */
13623 if (found)
13624 *pk_has_without_overlaps = indexStruct->indisexclusion;
13625 }
13626 ReleaseSysCache(indexTuple);
13627 if (found)
13628 break;
13629 }
13630
13631 if (!found)
13632 {
13633 if (found_deferrable)
13634 ereport(ERROR,
13635 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13636 errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
13637 RelationGetRelationName(pkrel))));
13638 else
13639 ereport(ERROR,
13640 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
13641 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
13642 RelationGetRelationName(pkrel))));
13643 }
13644
13645 list_free(indexoidlist);
13646
13647 return indexoid;
13648 }
13649
13650 /*
13651 * findFkeyCast -
13652 *
13653 * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
13654 * Caller has equal regard for binary coercibility and for an exact match.
13655 */
13656 static CoercionPathType
13657 findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
13658 {
13659 CoercionPathType ret;
13660
13661 if (targetTypeId == sourceTypeId)
13662 {
13663 ret = COERCION_PATH_RELABELTYPE;
13664 *funcid = InvalidOid;
13665 }
13666 else
13667 {
13668 ret = find_coercion_pathway(targetTypeId, sourceTypeId,
13669 COERCION_IMPLICIT, funcid);
13670 if (ret == COERCION_PATH_NONE)
13671 /* A previously-relied-upon cast is now gone. */
13672 elog(ERROR, "could not find cast from %u to %u",
13673 sourceTypeId, targetTypeId);
13674 }
13675
13676 return ret;
13677 }
13678
13679 /*
13680 * Permissions checks on the referenced table for ADD FOREIGN KEY
13681 *
13682 * Note: we have already checked that the user owns the referencing table,
13683 * else we'd have failed much earlier; no additional checks are needed for it.
13684 */
13685 static void
13686 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
13687 {
13688 Oid roleid = GetUserId();
13689 AclResult aclresult;
13690 int i;
13691
13692 /* Okay if we have relation-level REFERENCES permission */
13693 aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
13694 ACL_REFERENCES);
13695 if (aclresult == ACLCHECK_OK)
13696 return;
13697 /* Else we must have REFERENCES on each column */
13698 for (i = 0; i < natts; i++)
13699 {
13700 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
13701 roleid, ACL_REFERENCES);
13702 if (aclresult != ACLCHECK_OK)
13703 aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
13704 RelationGetRelationName(rel));
13705 }
13706 }
13707
13708 /*
13709 * Scan the existing rows in a table to verify they meet a proposed FK
13710 * constraint.
13711 *
13712 * Caller must have opened and locked both relations appropriately.
13713 */
13714 static void
13715 validateForeignKeyConstraint(char *conname,
13716 Relation rel,
13717 Relation pkrel,
13718 Oid pkindOid,
13719 Oid constraintOid,
13720 bool hasperiod)
13721 {
13722 TupleTableSlot *slot;
13723 TableScanDesc scan;
13724 Trigger trig = {0};
13725 Snapshot snapshot;
13726 MemoryContext oldcxt;
13727 MemoryContext perTupCxt;
13728
13729 ereport(DEBUG1,
13730 (errmsg_internal("validating foreign key constraint \"%s\"", conname)));
13731
13732 /*
13733 * Build a trigger call structure; we'll need it either way.
13734 */
13735 trig.tgoid = InvalidOid;
13736 trig.tgname = conname;
13737 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
13738 trig.tgisinternal = true;
13739 trig.tgconstrrelid = RelationGetRelid(pkrel);
13740 trig.tgconstrindid = pkindOid;
13741 trig.tgconstraint = constraintOid;
13742 trig.tgdeferrable = false;
13743 trig.tginitdeferred = false;
13744 /* we needn't fill in remaining fields */
13745
13746 /*
13747 * See if we can do it with a single LEFT JOIN query. A false result
13748 * indicates we must proceed with the fire-the-trigger method. We can't do
13749 * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
13750 * left joins.
13751 */
13752 if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
13753 return;
13754
13755 /*
13756 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
13757 * if that tuple had just been inserted. If any of those fail, it should
13758 * ereport(ERROR) and that's that.
13759 */
13760 snapshot = RegisterSnapshot(GetLatestSnapshot());
13761 slot = table_slot_create(rel, NULL);
13762 scan = table_beginscan(rel, snapshot, 0, NULL);
13763
13764 perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
13765 "validateForeignKeyConstraint",
13766 ALLOCSET_SMALL_SIZES);
13767 oldcxt = MemoryContextSwitchTo(perTupCxt);
13768
13769 while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
13770 {
13771 LOCAL_FCINFO(fcinfo, 0);
13772 TriggerData trigdata = {0};
13773
13774 CHECK_FOR_INTERRUPTS();
13775
13776 /*
13777 * Make a call to the trigger function
13778 *
13779 * No parameters are passed, but we do set a context
13780 */
13781 MemSet(fcinfo, 0, SizeForFunctionCallInfo(0));
13782
13783 /*
13784 * We assume RI_FKey_check_ins won't look at flinfo...
13785 */
13786 trigdata.type = T_TriggerData;
13787 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
13788 trigdata.tg_relation = rel;
13789 trigdata.tg_trigtuple = ExecFetchSlotHeapTuple(slot, false, NULL);
13790 trigdata.tg_trigslot = slot;
13791 trigdata.tg_trigger = &trig;
13792
13793 fcinfo->context = (Node *) &trigdata;
13794
13795 RI_FKey_check_ins(fcinfo);
13796
13797 MemoryContextReset(perTupCxt);
13798 }
13799
13800 MemoryContextSwitchTo(oldcxt);
13801 MemoryContextDelete(perTupCxt);
13802 table_endscan(scan);
13803 UnregisterSnapshot(snapshot);
13804 ExecDropSingleTupleTableSlot(slot);
13805 }
13806
13807 /*
13808 * CreateFKCheckTrigger
13809 * Creates the insert (on_insert=true) or update "check" trigger that
13810 * implements a given foreign key
13811 *
13812 * Returns the OID of the so created trigger.
13813 */
13814 static Oid
13815 CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
13816 Oid constraintOid, Oid indexOid, Oid parentTrigOid,
13817 bool on_insert)
13818 {
13819 ObjectAddress trigAddress;
13820 CreateTrigStmt *fk_trigger;
13821
13822 /*
13823 * Note: for a self-referential FK (referencing and referenced tables are
13824 * the same), it is important that the ON UPDATE action fires before the
13825 * CHECK action, since both triggers will fire on the same row during an
13826 * UPDATE event; otherwise the CHECK trigger will be checking a non-final
13827 * state of the row. Triggers fire in name order, so we ensure this by
13828 * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
13829 * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
13830 */
13831 fk_trigger = makeNode(CreateTrigStmt);
13832 fk_trigger->replace = false;
13833 fk_trigger->isconstraint = true;
13834 fk_trigger->trigname = "RI_ConstraintTrigger_c";
13835 fk_trigger->relation = NULL;
13836
13837 /* Either ON INSERT or ON UPDATE */
13838 if (on_insert)
13839 {
13840 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
13841 fk_trigger->events = TRIGGER_TYPE_INSERT;
13842 }
13843 else
13844 {
13845 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
13846 fk_trigger->events = TRIGGER_TYPE_UPDATE;
13847 }
13848
13849 fk_trigger->args = NIL;
13850 fk_trigger->row = true;
13851 fk_trigger->timing = TRIGGER_TYPE_AFTER;
13852 fk_trigger->columns = NIL;
13853 fk_trigger->whenClause = NULL;
13854 fk_trigger->transitionRels = NIL;
13855 fk_trigger->deferrable = fkconstraint->deferrable;
13856 fk_trigger->initdeferred = fkconstraint->initdeferred;
13857 fk_trigger->constrrel = NULL;
13858
13859 trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
13860 constraintOid, indexOid, InvalidOid,
13861 parentTrigOid, NULL, true, false);
13862
13863 /* Make changes-so-far visible */
13864 CommandCounterIncrement();
13865
13866 return trigAddress.objectId;
13867 }
13868
13869 /*
13870 * createForeignKeyActionTriggers
13871 * Create the referenced-side "action" triggers that implement a foreign
13872 * key.
13873 *
13874 * Returns the OIDs of the so created triggers in *deleteTrigOid and
13875 * *updateTrigOid.
13876 */
13877 static void
13878 createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
13879 Oid constraintOid, Oid indexOid,
13880 Oid parentDelTrigger, Oid parentUpdTrigger,
13881 Oid *deleteTrigOid, Oid *updateTrigOid)
13882 {
13883 CreateTrigStmt *fk_trigger;
13884 ObjectAddress trigAddress;
13885
13886 /*
13887 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
13888 * DELETE action on the referenced table.
13889 */
13890 fk_trigger = makeNode(CreateTrigStmt);
13891 fk_trigger->replace = false;
13892 fk_trigger->isconstraint = true;
13893 fk_trigger->trigname = "RI_ConstraintTrigger_a";
13894 fk_trigger->relation = NULL;
13895 fk_trigger->args = NIL;
13896 fk_trigger->row = true;
13897 fk_trigger->timing = TRIGGER_TYPE_AFTER;
13898 fk_trigger->events = TRIGGER_TYPE_DELETE;
13899 fk_trigger->columns = NIL;
13900 fk_trigger->whenClause = NULL;
13901 fk_trigger->transitionRels = NIL;
13902 fk_trigger->constrrel = NULL;
13903
13904 switch (fkconstraint->fk_del_action)
13905 {
13906 case FKCONSTR_ACTION_NOACTION:
13907 fk_trigger->deferrable = fkconstraint->deferrable;
13908 fk_trigger->initdeferred = fkconstraint->initdeferred;
13909 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
13910 break;
13911 case FKCONSTR_ACTION_RESTRICT:
13912 fk_trigger->deferrable = false;
13913 fk_trigger->initdeferred = false;
13914 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
13915 break;
13916 case FKCONSTR_ACTION_CASCADE:
13917 fk_trigger->deferrable = false;
13918 fk_trigger->initdeferred = false;
13919 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
13920 break;
13921 case FKCONSTR_ACTION_SETNULL:
13922 fk_trigger->deferrable = false;
13923 fk_trigger->initdeferred = false;
13924 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
13925 break;
13926 case FKCONSTR_ACTION_SETDEFAULT:
13927 fk_trigger->deferrable = false;
13928 fk_trigger->initdeferred = false;
13929 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
13930 break;
13931 default:
13932 elog(ERROR, "unrecognized FK action type: %d",
13933 (int) fkconstraint->fk_del_action);
13934 break;
13935 }
13936
13937 trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
13938 constraintOid, indexOid, InvalidOid,
13939 parentDelTrigger, NULL, true, false);
13940 if (deleteTrigOid)
13941 *deleteTrigOid = trigAddress.objectId;
13942
13943 /* Make changes-so-far visible */
13944 CommandCounterIncrement();
13945
13946 /*
13947 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
13948 * UPDATE action on the referenced table.
13949 */
13950 fk_trigger = makeNode(CreateTrigStmt);
13951 fk_trigger->replace = false;
13952 fk_trigger->isconstraint = true;
13953 fk_trigger->trigname = "RI_ConstraintTrigger_a";
13954 fk_trigger->relation = NULL;
13955 fk_trigger->args = NIL;
13956 fk_trigger->row = true;
13957 fk_trigger->timing = TRIGGER_TYPE_AFTER;
13958 fk_trigger->events = TRIGGER_TYPE_UPDATE;
13959 fk_trigger->columns = NIL;
13960 fk_trigger->whenClause = NULL;
13961 fk_trigger->transitionRels = NIL;
13962 fk_trigger->constrrel = NULL;
13963
13964 switch (fkconstraint->fk_upd_action)
13965 {
13966 case FKCONSTR_ACTION_NOACTION:
13967 fk_trigger->deferrable = fkconstraint->deferrable;
13968 fk_trigger->initdeferred = fkconstraint->initdeferred;
13969 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
13970 break;
13971 case FKCONSTR_ACTION_RESTRICT:
13972 fk_trigger->deferrable = false;
13973 fk_trigger->initdeferred = false;
13974 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
13975 break;
13976 case FKCONSTR_ACTION_CASCADE:
13977 fk_trigger->deferrable = false;
13978 fk_trigger->initdeferred = false;
13979 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
13980 break;
13981 case FKCONSTR_ACTION_SETNULL:
13982 fk_trigger->deferrable = false;
13983 fk_trigger->initdeferred = false;
13984 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
13985 break;
13986 case FKCONSTR_ACTION_SETDEFAULT:
13987 fk_trigger->deferrable = false;
13988 fk_trigger->initdeferred = false;
13989 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
13990 break;
13991 default:
13992 elog(ERROR, "unrecognized FK action type: %d",
13993 (int) fkconstraint->fk_upd_action);
13994 break;
13995 }
13996
13997 trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
13998 constraintOid, indexOid, InvalidOid,
13999 parentUpdTrigger, NULL, true, false);
14000 if (updateTrigOid)
14001 *updateTrigOid = trigAddress.objectId;
14002 }
14003
14004 /*
14005 * createForeignKeyCheckTriggers
14006 * Create the referencing-side "check" triggers that implement a foreign
14007 * key.
14008 *
14009 * Returns the OIDs of the so created triggers in *insertTrigOid and
14010 * *updateTrigOid.
14011 */
14012 static void
14013 createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
14014 Constraint *fkconstraint, Oid constraintOid,
14015 Oid indexOid,
14016 Oid parentInsTrigger, Oid parentUpdTrigger,
14017 Oid *insertTrigOid, Oid *updateTrigOid)
14018 {
14019 *insertTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14020 constraintOid, indexOid,
14021 parentInsTrigger, true);
14022 *updateTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14023 constraintOid, indexOid,
14024 parentUpdTrigger, false);
14025 }
14026
14027 /*
14028 * ALTER TABLE DROP CONSTRAINT
14029 *
14030 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
14031 */
14032 static void
14033 ATExecDropConstraint(Relation rel, const char *constrName,
14034 DropBehavior behavior, bool recurse,
14035 bool missing_ok, LOCKMODE lockmode)
14036 {
14037 Relation conrel;
14038 SysScanDesc scan;
14039 ScanKeyData skey[3];
14040 HeapTuple tuple;
14041 bool found = false;
14042
14043 conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14044
14045 /*
14046 * Find and drop the target constraint
14047 */
14048 ScanKeyInit(&skey[0],
14049 Anum_pg_constraint_conrelid,
14050 BTEqualStrategyNumber, F_OIDEQ,
14051 ObjectIdGetDatum(RelationGetRelid(rel)));
14052 ScanKeyInit(&skey[1],
14053 Anum_pg_constraint_contypid,
14054 BTEqualStrategyNumber, F_OIDEQ,
14055 ObjectIdGetDatum(InvalidOid));
14056 ScanKeyInit(&skey[2],
14057 Anum_pg_constraint_conname,
14058 BTEqualStrategyNumber, F_NAMEEQ,
14059 CStringGetDatum(constrName));
14060 scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14061 true, NULL, 3, skey);
14062
14063 /* There can be at most one matching row */
14064 if (HeapTupleIsValid(tuple = systable_getnext(scan)))
14065 {
14066 dropconstraint_internal(rel, tuple, behavior, recurse, false,
14067 missing_ok, lockmode);
14068 found = true;
14069 }
14070
14071 systable_endscan(scan);
14072
14073 if (!found)
14074 {
14075 if (!missing_ok)
14076 ereport(ERROR,
14077 errcode(ERRCODE_UNDEFINED_OBJECT),
14078 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14079 constrName, RelationGetRelationName(rel)));
14080 else
14081 ereport(NOTICE,
14082 errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
14083 constrName, RelationGetRelationName(rel)));
14084 }
14085
14086 table_close(conrel, RowExclusiveLock);
14087 }
14088
14089 /*
14090 * Remove a constraint, using its pg_constraint tuple
14091 *
14092 * Implementation for ALTER TABLE DROP CONSTRAINT and ALTER TABLE ALTER COLUMN
14093 * DROP NOT NULL.
14094 *
14095 * Returns the address of the constraint being removed.
14096 */
14097 static ObjectAddress
14098 dropconstraint_internal(Relation rel, HeapTuple constraintTup, DropBehavior behavior,
14099 bool recurse, bool recursing, bool missing_ok,
14100 LOCKMODE lockmode)
14101 {
14102 Relation conrel;
14103 Form_pg_constraint con;
14104 ObjectAddress conobj;
14105 List *children;
14106 bool is_no_inherit_constraint = false;
14107 char *constrName;
14108 char *colname = NULL;
14109
14110 /* Guard against stack overflow due to overly deep inheritance tree. */
14111 check_stack_depth();
14112
14113 /* At top level, permission check was done in ATPrepCmd, else do it */
14114 if (recursing)
14115 ATSimplePermissions(AT_DropConstraint, rel,
14116 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
14117
14118 conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14119
14120 con = (Form_pg_constraint) GETSTRUCT(constraintTup);
14121 constrName = NameStr(con->conname);
14122
14123 /* Don't allow drop of inherited constraints */
14124 if (con->coninhcount > 0 && !recursing)
14125 ereport(ERROR,
14126 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14127 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
14128 constrName, RelationGetRelationName(rel))));
14129
14130 /*
14131 * Reset pg_constraint.attnotnull, if this is a not-null constraint.
14132 *
14133 * While doing that, we're in a good position to disallow dropping a not-
14134 * null constraint underneath a primary key, a replica identity index, or
14135 * a generated identity column.
14136 */
14137 if (con->contype == CONSTRAINT_NOTNULL)
14138 {
14139 Relation attrel = table_open(AttributeRelationId, RowExclusiveLock);
14140 AttrNumber attnum = extractNotNullColumn(constraintTup);
14141 Bitmapset *pkattrs;
14142 Bitmapset *irattrs;
14143 HeapTuple atttup;
14144 Form_pg_attribute attForm;
14145
14146 /* save column name for recursion step */
14147 colname = get_attname(RelationGetRelid(rel), attnum, false);
14148
14149 /*
14150 * Disallow if it's in the primary key. For partitioned tables we
14151 * cannot rely solely on RelationGetIndexAttrBitmap, because it'll
14152 * return NULL if the primary key is invalid; but we still need to
14153 * protect not-null constraints under such a constraint, so check the
14154 * slow way.
14155 */
14156 pkattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_PRIMARY_KEY);
14157
14158 if (pkattrs == NULL &&
14159 rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14160 {
14161 Oid pkindex = RelationGetPrimaryKeyIndex(rel, true);
14162
14163 if (OidIsValid(pkindex))
14164 {
14165 Relation pk = relation_open(pkindex, AccessShareLock);
14166
14167 pkattrs = NULL;
14168 for (int i = 0; i < pk->rd_index->indnkeyatts; i++)
14169 pkattrs = bms_add_member(pkattrs, pk->rd_index->indkey.values[i]);
14170
14171 relation_close(pk, AccessShareLock);
14172 }
14173 }
14174
14175 if (pkattrs &&
14176 bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, pkattrs))
14177 ereport(ERROR,
14178 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14179 errmsg("column \"%s\" is in a primary key",
14180 get_attname(RelationGetRelid(rel), attnum, false)));
14181
14182 /* Disallow if it's in the replica identity */
14183 irattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_IDENTITY_KEY);
14184 if (bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, irattrs))
14185 ereport(ERROR,
14186 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14187 errmsg("column \"%s\" is in index used as replica identity",
14188 get_attname(RelationGetRelid(rel), attnum, false)));
14189
14190 /* Disallow if it's a GENERATED AS IDENTITY column */
14191 atttup = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
14192 if (!HeapTupleIsValid(atttup))
14193 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
14194 attnum, RelationGetRelid(rel));
14195 attForm = (Form_pg_attribute) GETSTRUCT(atttup);
14196 if (attForm->attidentity != '\0')
14197 ereport(ERROR,
14198 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14199 errmsg("column \"%s\" of relation \"%s\" is an identity column",
14200 get_attname(RelationGetRelid(rel), attnum,
14201 false),
14202 RelationGetRelationName(rel)));
14203
14204 /* All good -- reset attnotnull if needed */
14205 if (attForm->attnotnull)
14206 {
14207 attForm->attnotnull = false;
14208 CatalogTupleUpdate(attrel, &atttup->t_self, atttup);
14209 }
14210
14211 table_close(attrel, RowExclusiveLock);
14212 }
14213
14214 is_no_inherit_constraint = con->connoinherit;
14215
14216 /*
14217 * If it's a foreign-key constraint, we'd better lock the referenced table
14218 * and check that that's not in use, just as we've already done for the
14219 * constrained table (else we might, eg, be dropping a trigger that has
14220 * unfired events). But we can/must skip that in the self-referential
14221 * case.
14222 */
14223 if (con->contype == CONSTRAINT_FOREIGN &&
14224 con->confrelid != RelationGetRelid(rel))
14225 {
14226 Relation frel;
14227
14228 /* Must match lock taken by RemoveTriggerById: */
14229 frel = table_open(con->confrelid, AccessExclusiveLock);
14230 CheckAlterTableIsSafe(frel);
14231 table_close(frel, NoLock);
14232 }
14233
14234 /*
14235 * Perform the actual constraint deletion
14236 */
14237 ObjectAddressSet(conobj, ConstraintRelationId, con->oid);
14238 performDeletion(&conobj, behavior, 0);
14239
14240 /*
14241 * For partitioned tables, non-CHECK, non-NOT-NULL inherited constraints
14242 * are dropped via the dependency mechanism, so we're done here.
14243 */
14244 if (con->contype != CONSTRAINT_CHECK &&
14245 con->contype != CONSTRAINT_NOTNULL &&
14246 rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14247 {
14248 table_close(conrel, RowExclusiveLock);
14249 return conobj;
14250 }
14251
14252 /*
14253 * Propagate to children as appropriate. Unlike most other ALTER
14254 * routines, we have to do this one level of recursion at a time; we can't
14255 * use find_all_inheritors to do it in one pass.
14256 */
14257 if (!is_no_inherit_constraint)
14258 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
14259 else
14260 children = NIL;
14261
14262 foreach_oid(childrelid, children)
14263 {
14264 Relation childrel;
14265 HeapTuple tuple;
14266 Form_pg_constraint childcon;
14267
14268 /* find_inheritance_children already got lock */
14269 childrel = table_open(childrelid, NoLock);
14270 CheckAlterTableIsSafe(childrel);
14271
14272 /*
14273 * We search for not-null constraints by column name, and others by
14274 * constraint name.
14275 */
14276 if (con->contype == CONSTRAINT_NOTNULL)
14277 {
14278 tuple = findNotNullConstraint(childrelid, colname);
14279 if (!HeapTupleIsValid(tuple))
14280 elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
14281 colname, RelationGetRelid(childrel));
14282 }
14283 else
14284 {
14285 SysScanDesc scan;
14286 ScanKeyData skey[3];
14287
14288 ScanKeyInit(&skey[0],
14289 Anum_pg_constraint_conrelid,
14290 BTEqualStrategyNumber, F_OIDEQ,
14291 ObjectIdGetDatum(childrelid));
14292 ScanKeyInit(&skey[1],
14293 Anum_pg_constraint_contypid,
14294 BTEqualStrategyNumber, F_OIDEQ,
14295 ObjectIdGetDatum(InvalidOid));
14296 ScanKeyInit(&skey[2],
14297 Anum_pg_constraint_conname,
14298 BTEqualStrategyNumber, F_NAMEEQ,
14299 CStringGetDatum(constrName));
14300 scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14301 true, NULL, 3, skey);
14302 /* There can only be one, so no need to loop */
14303 tuple = systable_getnext(scan);
14304 if (!HeapTupleIsValid(tuple))
14305 ereport(ERROR,
14306 (errcode(ERRCODE_UNDEFINED_OBJECT),
14307 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14308 constrName,
14309 RelationGetRelationName(childrel))));
14310 tuple = heap_copytuple(tuple);
14311 systable_endscan(scan);
14312 }
14313
14314 childcon = (Form_pg_constraint) GETSTRUCT(tuple);
14315
14316 /* Right now only CHECK and not-null constraints can be inherited */
14317 if (childcon->contype != CONSTRAINT_CHECK &&
14318 childcon->contype != CONSTRAINT_NOTNULL)
14319 elog(ERROR, "inherited constraint is not a CHECK or not-null constraint");
14320
14321 if (childcon->coninhcount <= 0) /* shouldn't happen */
14322 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
14323 childrelid, NameStr(childcon->conname));
14324
14325 if (recurse)
14326 {
14327 /*
14328 * If the child constraint has other definition sources, just
14329 * decrement its inheritance count; if not, recurse to delete it.
14330 */
14331 if (childcon->coninhcount == 1 && !childcon->conislocal)
14332 {
14333 /* Time to delete this child constraint, too */
14334 dropconstraint_internal(childrel, tuple, behavior,
14335 recurse, true, missing_ok,
14336 lockmode);
14337 }
14338 else
14339 {
14340 /* Child constraint must survive my deletion */
14341 childcon->coninhcount--;
14342 CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14343
14344 /* Make update visible */
14345 CommandCounterIncrement();
14346 }
14347 }
14348 else
14349 {
14350 /*
14351 * If we were told to drop ONLY in this table (no recursion) and
14352 * there are no further parents for this constraint, we need to
14353 * mark the inheritors' constraints as locally defined rather than
14354 * inherited.
14355 */
14356 childcon->coninhcount--;
14357 if (childcon->coninhcount == 0)
14358 childcon->conislocal = true;
14359
14360 CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14361
14362 /* Make update visible */
14363 CommandCounterIncrement();
14364 }
14365
14366 heap_freetuple(tuple);
14367
14368 table_close(childrel, NoLock);
14369 }
14370
14371 table_close(conrel, RowExclusiveLock);
14372
14373 return conobj;
14374 }
14375
14376 /*
14377 * ALTER COLUMN TYPE
14378 *
14379 * Unlike other subcommand types, we do parse transformation for ALTER COLUMN
14380 * TYPE during phase 1 --- the AlterTableCmd passed in here is already
14381 * transformed (and must be, because we rely on some transformed fields).
14382 *
14383 * The point of this is that the execution of all ALTER COLUMN TYPEs for a
14384 * table will be done "in parallel" during phase 3, so all the USING
14385 * expressions should be parsed assuming the original column types. Also,
14386 * this allows a USING expression to refer to a field that will be dropped.
14387 *
14388 * To make this work safely, AT_PASS_DROP then AT_PASS_ALTER_TYPE must be
14389 * the first two execution steps in phase 2; they must not see the effects
14390 * of any other subcommand types, since the USING expressions are parsed
14391 * against the unmodified table's state.
14392 */
14393 static void
14394 ATPrepAlterColumnType(List **wqueue,
14395 AlteredTableInfo *tab, Relation rel,
14396 bool recurse, bool recursing,
14397 AlterTableCmd *cmd, LOCKMODE lockmode,
14398 AlterTableUtilityContext *context)
14399 {
14400 char *colName = cmd->name;
14401 ColumnDef *def = (ColumnDef *) cmd->def;
14402 TypeName *typeName = def->typeName;
14403 Node *transform = def->cooked_default;
14404 HeapTuple tuple;
14405 Form_pg_attribute attTup;
14406 AttrNumber attnum;
14407 Oid targettype;
14408 int32 targettypmod;
14409 Oid targetcollid;
14410 NewColumnValue *newval;
14411 ParseState *pstate = make_parsestate(NULL);
14412 AclResult aclresult;
14413 bool is_expr;
14414
14415 pstate->p_sourcetext = context->queryString;
14416
14417 if (rel->rd_rel->reloftype && !recursing)
14418 ereport(ERROR,
14419 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14420 errmsg("cannot alter column type of typed table"),
14421 parser_errposition(pstate, def->location)));
14422
14423 /* lookup the attribute so we can check inheritance status */
14424 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
14425 if (!HeapTupleIsValid(tuple))
14426 ereport(ERROR,
14427 (errcode(ERRCODE_UNDEFINED_COLUMN),
14428 errmsg("column \"%s\" of relation \"%s\" does not exist",
14429 colName, RelationGetRelationName(rel)),
14430 parser_errposition(pstate, def->location)));
14431 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
14432 attnum = attTup->attnum;
14433
14434 /* Can't alter a system attribute */
14435 if (attnum <= 0)
14436 ereport(ERROR,
14437 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14438 errmsg("cannot alter system column \"%s\"", colName),
14439 parser_errposition(pstate, def->location)));
14440
14441 /*
14442 * Cannot specify USING when altering type of a generated column, because
14443 * that would violate the generation expression.
14444 */
14445 if (attTup->attgenerated && def->cooked_default)
14446 ereport(ERROR,
14447 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
14448 errmsg("cannot specify USING when altering type of generated column"),
14449 errdetail("Column \"%s\" is a generated column.", colName),
14450 parser_errposition(pstate, def->location)));
14451
14452 /*
14453 * Don't alter inherited columns. At outer level, there had better not be
14454 * any inherited definition; when recursing, we assume this was checked at
14455 * the parent level (see below).
14456 */
14457 if (attTup->attinhcount > 0 && !recursing)
14458 ereport(ERROR,
14459 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14460 errmsg("cannot alter inherited column \"%s\"", colName),
14461 parser_errposition(pstate, def->location)));
14462
14463 /* Don't alter columns used in the partition key */
14464 if (has_partition_attrs(rel,
14465 bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
14466 &is_expr))
14467 ereport(ERROR,
14468 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14469 errmsg("cannot alter column \"%s\" because it is part of the partition key of relation \"%s\"",
14470 colName, RelationGetRelationName(rel)),
14471 parser_errposition(pstate, def->location)));
14472
14473 /* Look up the target type */
14474 typenameTypeIdAndMod(pstate, typeName, &targettype, &targettypmod);
14475
14476 aclresult = object_aclcheck(TypeRelationId, targettype, GetUserId(), ACL_USAGE);
14477 if (aclresult != ACLCHECK_OK)
14478 aclcheck_error_type(aclresult, targettype);
14479
14480 /* And the collation */
14481 targetcollid = GetColumnDefCollation(pstate, def, targettype);
14482
14483 /* make sure datatype is legal for a column */
14484 CheckAttributeType(colName, targettype, targetcollid,
14485 list_make1_oid(rel->rd_rel->reltype),
14486 (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
14487
14488 if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
14489 {
14490 /* do nothing */
14491 }
14492 else if (tab->relkind == RELKIND_RELATION ||
14493 tab->relkind == RELKIND_PARTITIONED_TABLE)
14494 {
14495 /*
14496 * Set up an expression to transform the old data value to the new
14497 * type. If a USING option was given, use the expression as
14498 * transformed by transformAlterTableStmt, else just take the old
14499 * value and try to coerce it. We do this first so that type
14500 * incompatibility can be detected before we waste effort, and because
14501 * we need the expression to be parsed against the original table row
14502 * type.
14503 */
14504 if (!transform)
14505 {
14506 transform = (Node *) makeVar(1, attnum,
14507 attTup->atttypid, attTup->atttypmod,
14508 attTup->attcollation,
14509 0);
14510 }
14511
14512 transform = coerce_to_target_type(pstate,
14513 transform, exprType(transform),
14514 targettype, targettypmod,
14515 COERCION_ASSIGNMENT,
14516 COERCE_IMPLICIT_CAST,
14517 -1);
14518 if (transform == NULL)
14519 {
14520 /* error text depends on whether USING was specified or not */
14521 if (def->cooked_default != NULL)
14522 ereport(ERROR,
14523 (errcode(ERRCODE_DATATYPE_MISMATCH),
14524 errmsg("result of USING clause for column \"%s\""
14525 " cannot be cast automatically to type %s",
14526 colName, format_type_be(targettype)),
14527 errhint("You might need to add an explicit cast.")));
14528 else
14529 ereport(ERROR,
14530 (errcode(ERRCODE_DATATYPE_MISMATCH),
14531 errmsg("column \"%s\" cannot be cast automatically to type %s",
14532 colName, format_type_be(targettype)),
14533 !attTup->attgenerated ?
14534 /* translator: USING is SQL, don't translate it */
14535 errhint("You might need to specify \"USING %s::%s\".",
14536 quote_identifier(colName),
14537 format_type_with_typemod(targettype,
14538 targettypmod)) : 0));
14539 }
14540
14541 /* Fix collations after all else */
14542 assign_expr_collations(pstate, transform);
14543
14544 /* Expand virtual generated columns in the expr. */
14545 transform = expand_generated_columns_in_expr(transform, rel, 1);
14546
14547 /* Plan the expr now so we can accurately assess the need to rewrite. */
14548 transform = (Node *) expression_planner((Expr *) transform);
14549
14550 /*
14551 * Add a work queue item to make ATRewriteTable update the column
14552 * contents.
14553 */
14554 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
14555 newval->attnum = attnum;
14556 newval->expr = (Expr *) transform;
14557 newval->is_generated = false;
14558
14559 tab->newvals = lappend(tab->newvals, newval);
14560 if (ATColumnChangeRequiresRewrite(transform, attnum))
14561 tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
14562 }
14563 else if (transform)
14564 ereport(ERROR,
14565 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14566 errmsg("\"%s\" is not a table",
14567 RelationGetRelationName(rel))));
14568
14569 if (!RELKIND_HAS_STORAGE(tab->relkind) || attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
14570 {
14571 /*
14572 * For relations or columns without storage, do this check now.
14573 * Regular tables will check it later when the table is being
14574 * rewritten.
14575 */
14576 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
14577 }
14578
14579 ReleaseSysCache(tuple);
14580
14581 /*
14582 * Recurse manually by queueing a new command for each child, if
14583 * necessary. We cannot apply ATSimpleRecursion here because we need to
14584 * remap attribute numbers in the USING expression, if any.
14585 *
14586 * If we are told not to recurse, there had better not be any child
14587 * tables; else the alter would put them out of step.
14588 */
14589 if (recurse)
14590 {
14591 Oid relid = RelationGetRelid(rel);
14592 List *child_oids,
14593 *child_numparents;
14594 ListCell *lo,
14595 *li;
14596
14597 child_oids = find_all_inheritors(relid, lockmode,
14598 &child_numparents);
14599
14600 /*
14601 * find_all_inheritors does the recursive search of the inheritance
14602 * hierarchy, so all we have to do is process all of the relids in the
14603 * list that it returns.
14604 */
14605 forboth(lo, child_oids, li, child_numparents)
14606 {
14607 Oid childrelid = lfirst_oid(lo);
14608 int numparents = lfirst_int(li);
14609 Relation childrel;
14610 HeapTuple childtuple;
14611 Form_pg_attribute childattTup;
14612
14613 if (childrelid == relid)
14614 continue;
14615
14616 /* find_all_inheritors already got lock */
14617 childrel = relation_open(childrelid, NoLock);
14618 CheckAlterTableIsSafe(childrel);
14619
14620 /*
14621 * Verify that the child doesn't have any inherited definitions of
14622 * this column that came from outside this inheritance hierarchy.
14623 * (renameatt makes a similar test, though in a different way
14624 * because of its different recursion mechanism.)
14625 */
14626 childtuple = SearchSysCacheAttName(RelationGetRelid(childrel),
14627 colName);
14628 if (!HeapTupleIsValid(childtuple))
14629 ereport(ERROR,
14630 (errcode(ERRCODE_UNDEFINED_COLUMN),
14631 errmsg("column \"%s\" of relation \"%s\" does not exist",
14632 colName, RelationGetRelationName(childrel))));
14633 childattTup = (Form_pg_attribute) GETSTRUCT(childtuple);
14634
14635 if (childattTup->attinhcount > numparents)
14636 ereport(ERROR,
14637 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14638 errmsg("cannot alter inherited column \"%s\" of relation \"%s\"",
14639 colName, RelationGetRelationName(childrel))));
14640
14641 ReleaseSysCache(childtuple);
14642
14643 /*
14644 * Remap the attribute numbers. If no USING expression was
14645 * specified, there is no need for this step.
14646 */
14647 if (def->cooked_default)
14648 {
14649 AttrMap *attmap;
14650 bool found_whole_row;
14651
14652 /* create a copy to scribble on */
14653 cmd = copyObject(cmd);
14654
14655 attmap = build_attrmap_by_name(RelationGetDescr(childrel),
14656 RelationGetDescr(rel),
14657 false);
14658 ((ColumnDef *) cmd->def)->cooked_default =
14659 map_variable_attnos(def->cooked_default,
14660 1, 0,
14661 attmap,
14662 InvalidOid, &found_whole_row);
14663 if (found_whole_row)
14664 ereport(ERROR,
14665 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14666 errmsg("cannot convert whole-row table reference"),
14667 errdetail("USING expression contains a whole-row table reference.")));
14668 pfree(attmap);
14669 }
14670 ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
14671 relation_close(childrel, NoLock);
14672 }
14673 }
14674 else if (!recursing &&
14675 find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
14676 ereport(ERROR,
14677 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14678 errmsg("type of inherited column \"%s\" must be changed in child tables too",
14679 colName)));
14680
14681 if (tab->relkind == RELKIND_COMPOSITE_TYPE)
14682 ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
14683 }
14684
14685 /*
14686 * When the data type of a column is changed, a rewrite might not be required
14687 * if the new type is sufficiently identical to the old one, and the USING
14688 * clause isn't trying to insert some other value. It's safe to skip the
14689 * rewrite in these cases:
14690 *
14691 * - the old type is binary coercible to the new type
14692 * - the new type is an unconstrained domain over the old type
14693 * - {NEW,OLD} or {OLD,NEW} is {timestamptz,timestamp} and the timezone is UTC
14694 *
14695 * In the case of a constrained domain, we could get by with scanning the
14696 * table and checking the constraint rather than actually rewriting it, but we
14697 * don't currently try to do that.
14698 */
14699 static bool
14700 ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
14701 {
14702 Assert(expr != NULL);
14703
14704 for (;;)
14705 {
14706 /* only one varno, so no need to check that */
14707 if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
14708 return false;
14709 else if (IsA(expr, RelabelType))
14710 expr = (Node *) ((RelabelType *) expr)->arg;
14711 else if (IsA(expr, CoerceToDomain))
14712 {
14713 CoerceToDomain *d = (CoerceToDomain *) expr;
14714
14715 if (DomainHasConstraints(d->resulttype))
14716 return true;
14717 expr = (Node *) d->arg;
14718 }
14719 else if (IsA(expr, FuncExpr))
14720 {
14721 FuncExpr *f = (FuncExpr *) expr;
14722
14723 switch (f->funcid)
14724 {
14725 case F_TIMESTAMPTZ_TIMESTAMP:
14726 case F_TIMESTAMP_TIMESTAMPTZ:
14727 if (TimestampTimestampTzRequiresRewrite())
14728 return true;
14729 else
14730 expr = linitial(f->args);
14731 break;
14732 default:
14733 return true;
14734 }
14735 }
14736 else
14737 return true;
14738 }
14739 }
14740
14741 /*
14742 * ALTER COLUMN .. SET DATA TYPE
14743 *
14744 * Return the address of the modified column.
14745 */
14746 static ObjectAddress
14747 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
14748 AlterTableCmd *cmd, LOCKMODE lockmode)
14749 {
14750 char *colName = cmd->name;
14751 ColumnDef *def = (ColumnDef *) cmd->def;
14752 TypeName *typeName = def->typeName;
14753 HeapTuple heapTup;
14754 Form_pg_attribute attTup,
14755 attOldTup;
14756 AttrNumber attnum;
14757 HeapTuple typeTuple;
14758 Form_pg_type tform;
14759 Oid targettype;
14760 int32 targettypmod;
14761 Oid targetcollid;
14762 Node *defaultexpr;
14763 Relation attrelation;
14764 Relation depRel;
14765 ScanKeyData key[3];
14766 SysScanDesc scan;
14767 HeapTuple depTup;
14768 ObjectAddress address;
14769
14770 /*
14771 * Clear all the missing values if we're rewriting the table, since this
14772 * renders them pointless.
14773 */
14774 if (tab->rewrite)
14775 {
14776 Relation newrel;
14777
14778 newrel = table_open(RelationGetRelid(rel), NoLock);
14779 RelationClearMissing(newrel);
14780 relation_close(newrel, NoLock);
14781 /* make sure we don't conflict with later attribute modifications */
14782 CommandCounterIncrement();
14783 }
14784
14785 attrelation = table_open(AttributeRelationId, RowExclusiveLock);
14786
14787 /* Look up the target column */
14788 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
14789 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
14790 ereport(ERROR,
14791 (errcode(ERRCODE_UNDEFINED_COLUMN),
14792 errmsg("column \"%s\" of relation \"%s\" does not exist",
14793 colName, RelationGetRelationName(rel))));
14794 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
14795 attnum = attTup->attnum;
14796 attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
14797
14798 /* Check for multiple ALTER TYPE on same column --- can't cope */
14799 if (attTup->atttypid != attOldTup->atttypid ||
14800 attTup->atttypmod != attOldTup->atttypmod)
14801 ereport(ERROR,
14802 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14803 errmsg("cannot alter type of column \"%s\" twice",
14804 colName)));
14805
14806 /* Look up the target type (should not fail, since prep found it) */
14807 typeTuple = typenameType(NULL, typeName, &targettypmod);
14808 tform = (Form_pg_type) GETSTRUCT(typeTuple);
14809 targettype = tform->oid;
14810 /* And the collation */
14811 targetcollid = GetColumnDefCollation(NULL, def, targettype);
14812
14813 /*
14814 * If there is a default expression for the column, get it and ensure we
14815 * can coerce it to the new datatype. (We must do this before changing
14816 * the column type, because build_column_default itself will try to
14817 * coerce, and will not issue the error message we want if it fails.)
14818 *
14819 * We remove any implicit coercion steps at the top level of the old
14820 * default expression; this has been agreed to satisfy the principle of
14821 * least surprise. (The conversion to the new column type should act like
14822 * it started from what the user sees as the stored expression, and the
14823 * implicit coercions aren't going to be shown.)
14824 */
14825 if (attTup->atthasdef)
14826 {
14827 defaultexpr = build_column_default(rel, attnum);
14828 Assert(defaultexpr);
14829 defaultexpr = strip_implicit_coercions(defaultexpr);
14830 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
14831 defaultexpr, exprType(defaultexpr),
14832 targettype, targettypmod,
14833 COERCION_ASSIGNMENT,
14834 COERCE_IMPLICIT_CAST,
14835 -1);
14836 if (defaultexpr == NULL)
14837 {
14838 if (attTup->attgenerated)
14839 ereport(ERROR,
14840 (errcode(ERRCODE_DATATYPE_MISMATCH),
14841 errmsg("generation expression for column \"%s\" cannot be cast automatically to type %s",
14842 colName, format_type_be(targettype))));
14843 else
14844 ereport(ERROR,
14845 (errcode(ERRCODE_DATATYPE_MISMATCH),
14846 errmsg("default for column \"%s\" cannot be cast automatically to type %s",
14847 colName, format_type_be(targettype))));
14848 }
14849 }
14850 else
14851 defaultexpr = NULL;
14852
14853 /*
14854 * Find everything that depends on the column (constraints, indexes, etc),
14855 * and record enough information to let us recreate the objects.
14856 *
14857 * The actual recreation does not happen here, but only after we have
14858 * performed all the individual ALTER TYPE operations. We have to save
14859 * the info before executing ALTER TYPE, though, else the deparser will
14860 * get confused.
14861 */
14862 RememberAllDependentForRebuilding(tab, AT_AlterColumnType, rel, attnum, colName);
14863
14864 /*
14865 * Now scan for dependencies of this column on other things. The only
14866 * things we should find are the dependency on the column datatype and
14867 * possibly a collation dependency. Those can be removed.
14868 */
14869 depRel = table_open(DependRelationId, RowExclusiveLock);
14870
14871 ScanKeyInit(&key[0],
14872 Anum_pg_depend_classid,
14873 BTEqualStrategyNumber, F_OIDEQ,
14874 ObjectIdGetDatum(RelationRelationId));
14875 ScanKeyInit(&key[1],
14876 Anum_pg_depend_objid,
14877 BTEqualStrategyNumber, F_OIDEQ,
14878 ObjectIdGetDatum(RelationGetRelid(rel)));
14879 ScanKeyInit(&key[2],
14880 Anum_pg_depend_objsubid,
14881 BTEqualStrategyNumber, F_INT4EQ,
14882 Int32GetDatum((int32) attnum));
14883
14884 scan = systable_beginscan(depRel, DependDependerIndexId, true,
14885 NULL, 3, key);
14886
14887 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
14888 {
14889 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
14890 ObjectAddress foundObject;
14891
14892 foundObject.classId = foundDep->refclassid;
14893 foundObject.objectId = foundDep->refobjid;
14894 foundObject.objectSubId = foundDep->refobjsubid;
14895
14896 if (foundDep->deptype != DEPENDENCY_NORMAL)
14897 elog(ERROR, "found unexpected dependency type '%c'",
14898 foundDep->deptype);
14899 if (!(foundDep->refclassid == TypeRelationId &&
14900 foundDep->refobjid == attTup->atttypid) &&
14901 !(foundDep->refclassid == CollationRelationId &&
14902 foundDep->refobjid == attTup->attcollation))
14903 elog(ERROR, "found unexpected dependency for column: %s",
14904 getObjectDescription(&foundObject, false));
14905
14906 CatalogTupleDelete(depRel, &depTup->t_self);
14907 }
14908
14909 systable_endscan(scan);
14910
14911 table_close(depRel, RowExclusiveLock);
14912
14913 /*
14914 * Here we go --- change the recorded column type and collation. (Note
14915 * heapTup is a copy of the syscache entry, so okay to scribble on.) First
14916 * fix up the missing value if any.
14917 */
14918 if (attTup->atthasmissing)
14919 {
14920 Datum missingval;
14921 bool missingNull;
14922
14923 /* if rewrite is true the missing value should already be cleared */
14924 Assert(tab->rewrite == 0);
14925
14926 /* Get the missing value datum */
14927 missingval = heap_getattr(heapTup,
14928 Anum_pg_attribute_attmissingval,
14929 attrelation->rd_att,
14930 &missingNull);
14931
14932 /* if it's a null array there is nothing to do */
14933
14934 if (!missingNull)
14935 {
14936 /*
14937 * Get the datum out of the array and repack it in a new array
14938 * built with the new type data. We assume that since the table
14939 * doesn't need rewriting, the actual Datum doesn't need to be
14940 * changed, only the array metadata.
14941 */
14942
14943 int one = 1;
14944 bool isNull;
14945 Datum valuesAtt[Natts_pg_attribute] = {0};
14946 bool nullsAtt[Natts_pg_attribute] = {0};
14947 bool replacesAtt[Natts_pg_attribute] = {0};
14948 HeapTuple newTup;
14949
14950 missingval = array_get_element(missingval,
14951 1,
14952 &one,
14953 0,
14954 attTup->attlen,
14955 attTup->attbyval,
14956 attTup->attalign,
14957 &isNull);
14958 missingval = PointerGetDatum(construct_array(&missingval,
14959 1,
14960 targettype,
14961 tform->typlen,
14962 tform->typbyval,
14963 tform->typalign));
14964
14965 valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
14966 replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
14967 nullsAtt[Anum_pg_attribute_attmissingval - 1] = false;
14968
14969 newTup = heap_modify_tuple(heapTup, RelationGetDescr(attrelation),
14970 valuesAtt, nullsAtt, replacesAtt);
14971 heap_freetuple(heapTup);
14972 heapTup = newTup;
14973 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
14974 }
14975 }
14976
14977 attTup->atttypid = targettype;
14978 attTup->atttypmod = targettypmod;
14979 attTup->attcollation = targetcollid;
14980 if (list_length(typeName->arrayBounds) > PG_INT16_MAX)
14981 ereport(ERROR,
14982 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
14983 errmsg("too many array dimensions"));
14984 attTup->attndims = list_length(typeName->arrayBounds);
14985 attTup->attlen = tform->typlen;
14986 attTup->attbyval = tform->typbyval;
14987 attTup->attalign = tform->typalign;
14988 attTup->attstorage = tform->typstorage;
14989 attTup->attcompression = InvalidCompressionMethod;
14990
14991 ReleaseSysCache(typeTuple);
14992
14993 CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
14994
14995 table_close(attrelation, RowExclusiveLock);
14996
14997 /* Install dependencies on new datatype and collation */
14998 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
14999 add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
15000
15001 /*
15002 * Drop any pg_statistic entry for the column, since it's now wrong type
15003 */
15004 RemoveStatistics(RelationGetRelid(rel), attnum);
15005
15006 InvokeObjectPostAlterHook(RelationRelationId,
15007 RelationGetRelid(rel), attnum);
15008
15009 /*
15010 * Update the default, if present, by brute force --- remove and re-add
15011 * the default. Probably unsafe to take shortcuts, since the new version
15012 * may well have additional dependencies. (It's okay to do this now,
15013 * rather than after other ALTER TYPE commands, since the default won't
15014 * depend on other column types.)
15015 */
15016 if (defaultexpr)
15017 {
15018 /*
15019 * If it's a GENERATED default, drop its dependency records, in
15020 * particular its INTERNAL dependency on the column, which would
15021 * otherwise cause dependency.c to refuse to perform the deletion.
15022 */
15023 if (attTup->attgenerated)
15024 {
15025 Oid attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
15026
15027 if (!OidIsValid(attrdefoid))
15028 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
15029 RelationGetRelid(rel), attnum);
15030 (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
15031 }
15032
15033 /*
15034 * Make updates-so-far visible, particularly the new pg_attribute row
15035 * which will be updated again.
15036 */
15037 CommandCounterIncrement();
15038
15039 /*
15040 * We use RESTRICT here for safety, but at present we do not expect
15041 * anything to depend on the default.
15042 */
15043 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
15044 true);
15045
15046 (void) StoreAttrDefault(rel, attnum, defaultexpr, true);
15047 }
15048
15049 ObjectAddressSubSet(address, RelationRelationId,
15050 RelationGetRelid(rel), attnum);
15051
15052 /* Cleanup */
15053 heap_freetuple(heapTup);
15054
15055 return address;
15056 }
15057
15058 /*
15059 * Subroutine for ATExecAlterColumnType and ATExecSetExpression: Find everything
15060 * that depends on the column (constraints, indexes, etc), and record enough
15061 * information to let us recreate the objects.
15062 */
15063 static void
15064 RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
15065 Relation rel, AttrNumber attnum, const char *colName)
15066 {
15067 Relation depRel;
15068 ScanKeyData key[3];
15069 SysScanDesc scan;
15070 HeapTuple depTup;
15071
15072 Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression);
15073
15074 depRel = table_open(DependRelationId, RowExclusiveLock);
15075
15076 ScanKeyInit(&key[0],
15077 Anum_pg_depend_refclassid,
15078 BTEqualStrategyNumber, F_OIDEQ,
15079 ObjectIdGetDatum(RelationRelationId));
15080 ScanKeyInit(&key[1],
15081 Anum_pg_depend_refobjid,
15082 BTEqualStrategyNumber, F_OIDEQ,
15083 ObjectIdGetDatum(RelationGetRelid(rel)));
15084 ScanKeyInit(&key[2],
15085 Anum_pg_depend_refobjsubid,
15086 BTEqualStrategyNumber, F_INT4EQ,
15087 Int32GetDatum((int32) attnum));
15088
15089 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
15090 NULL, 3, key);
15091
15092 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15093 {
15094 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15095 ObjectAddress foundObject;
15096
15097 foundObject.classId = foundDep->classid;
15098 foundObject.objectId = foundDep->objid;
15099 foundObject.objectSubId = foundDep->objsubid;
15100
15101 switch (foundObject.classId)
15102 {
15103 case RelationRelationId:
15104 {
15105 char relKind = get_rel_relkind(foundObject.objectId);
15106
15107 if (relKind == RELKIND_INDEX ||
15108 relKind == RELKIND_PARTITIONED_INDEX)
15109 {
15110 Assert(foundObject.objectSubId == 0);
15111 RememberIndexForRebuilding(foundObject.objectId, tab);
15112 }
15113 else if (relKind == RELKIND_SEQUENCE)
15114 {
15115 /*
15116 * This must be a SERIAL column's sequence. We need
15117 * not do anything to it.
15118 */
15119 Assert(foundObject.objectSubId == 0);
15120 }
15121 else
15122 {
15123 /* Not expecting any other direct dependencies... */
15124 elog(ERROR, "unexpected object depending on column: %s",
15125 getObjectDescription(&foundObject, false));
15126 }
15127 break;
15128 }
15129
15130 case ConstraintRelationId:
15131 Assert(foundObject.objectSubId == 0);
15132 RememberConstraintForRebuilding(foundObject.objectId, tab);
15133 break;
15134
15135 case ProcedureRelationId:
15136
15137 /*
15138 * A new-style SQL function can depend on a column, if that
15139 * column is referenced in the parsed function body. Ideally
15140 * we'd automatically update the function by deparsing and
15141 * reparsing it, but that's risky and might well fail anyhow.
15142 * FIXME someday.
15143 *
15144 * This is only a problem for AT_AlterColumnType, not
15145 * AT_SetExpression.
15146 */
15147 if (subtype == AT_AlterColumnType)
15148 ereport(ERROR,
15149 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15150 errmsg("cannot alter type of a column used by a function or procedure"),
15151 errdetail("%s depends on column \"%s\"",
15152 getObjectDescription(&foundObject, false),
15153 colName)));
15154 break;
15155
15156 case RewriteRelationId:
15157
15158 /*
15159 * View/rule bodies have pretty much the same issues as
15160 * function bodies. FIXME someday.
15161 */
15162 if (subtype == AT_AlterColumnType)
15163 ereport(ERROR,
15164 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15165 errmsg("cannot alter type of a column used by a view or rule"),
15166 errdetail("%s depends on column \"%s\"",
15167 getObjectDescription(&foundObject, false),
15168 colName)));
15169 break;
15170
15171 case TriggerRelationId:
15172
15173 /*
15174 * A trigger can depend on a column because the column is
15175 * specified as an update target, or because the column is
15176 * used in the trigger's WHEN condition. The first case would
15177 * not require any extra work, but the second case would
15178 * require updating the WHEN expression, which has the same
15179 * issues as above. Since we can't easily tell which case
15180 * applies, we punt for both. FIXME someday.
15181 */
15182 if (subtype == AT_AlterColumnType)
15183 ereport(ERROR,
15184 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15185 errmsg("cannot alter type of a column used in a trigger definition"),
15186 errdetail("%s depends on column \"%s\"",
15187 getObjectDescription(&foundObject, false),
15188 colName)));
15189 break;
15190
15191 case PolicyRelationId:
15192
15193 /*
15194 * A policy can depend on a column because the column is
15195 * specified in the policy's USING or WITH CHECK qual
15196 * expressions. It might be possible to rewrite and recheck
15197 * the policy expression, but punt for now. It's certainly
15198 * easy enough to remove and recreate the policy; still, FIXME
15199 * someday.
15200 */
15201 if (subtype == AT_AlterColumnType)
15202 ereport(ERROR,
15203 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15204 errmsg("cannot alter type of a column used in a policy definition"),
15205 errdetail("%s depends on column \"%s\"",
15206 getObjectDescription(&foundObject, false),
15207 colName)));
15208 break;
15209
15210 case AttrDefaultRelationId:
15211 {
15212 ObjectAddress col = GetAttrDefaultColumnAddress(foundObject.objectId);
15213
15214 if (col.objectId == RelationGetRelid(rel) &&
15215 col.objectSubId == attnum)
15216 {
15217 /*
15218 * Ignore the column's own default expression. The
15219 * caller deals with it.
15220 */
15221 }
15222 else
15223 {
15224 /*
15225 * This must be a reference from the expression of a
15226 * generated column elsewhere in the same table.
15227 * Changing the type/generated expression of a column
15228 * that is used by a generated column is not allowed
15229 * by SQL standard, so just punt for now. It might be
15230 * doable with some thinking and effort.
15231 */
15232 if (subtype == AT_AlterColumnType)
15233 ereport(ERROR,
15234 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15235 errmsg("cannot alter type of a column used by a generated column"),
15236 errdetail("Column \"%s\" is used by generated column \"%s\".",
15237 colName,
15238 get_attname(col.objectId,
15239 col.objectSubId,
15240 false))));
15241 }
15242 break;
15243 }
15244
15245 case StatisticExtRelationId:
15246
15247 /*
15248 * Give the extended-stats machinery a chance to fix anything
15249 * that this column type change would break.
15250 */
15251 RememberStatisticsForRebuilding(foundObject.objectId, tab);
15252 break;
15253
15254 case PublicationRelRelationId:
15255
15256 /*
15257 * Column reference in a PUBLICATION ... FOR TABLE ... WHERE
15258 * clause. Same issues as above. FIXME someday.
15259 */
15260 if (subtype == AT_AlterColumnType)
15261 ereport(ERROR,
15262 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15263 errmsg("cannot alter type of a column used by a publication WHERE clause"),
15264 errdetail("%s depends on column \"%s\"",
15265 getObjectDescription(&foundObject, false),
15266 colName)));
15267 break;
15268
15269 default:
15270
15271 /*
15272 * We don't expect any other sorts of objects to depend on a
15273 * column.
15274 */
15275 elog(ERROR, "unexpected object depending on column: %s",
15276 getObjectDescription(&foundObject, false));
15277 break;
15278 }
15279 }
15280
15281 systable_endscan(scan);
15282 table_close(depRel, NoLock);
15283 }
15284
15285 /*
15286 * Subroutine for ATExecAlterColumnType: remember that a replica identity
15287 * needs to be reset.
15288 */
15289 static void
15290 RememberReplicaIdentityForRebuilding(Oid indoid, AlteredTableInfo *tab)
15291 {
15292 if (!get_index_isreplident(indoid))
15293 return;
15294
15295 if (tab->replicaIdentityIndex)
15296 elog(ERROR, "relation %u has multiple indexes marked as replica identity", tab->relid);
15297
15298 tab->replicaIdentityIndex = get_rel_name(indoid);
15299 }
15300
15301 /*
15302 * Subroutine for ATExecAlterColumnType: remember any clustered index.
15303 */
15304 static void
15305 RememberClusterOnForRebuilding(Oid indoid, AlteredTableInfo *tab)
15306 {
15307 if (!get_index_isclustered(indoid))
15308 return;
15309
15310 if (tab->clusterOnIndex)
15311 elog(ERROR, "relation %u has multiple clustered indexes", tab->relid);
15312
15313 tab->clusterOnIndex = get_rel_name(indoid);
15314 }
15315
15316 /*
15317 * Subroutine for ATExecAlterColumnType: remember that a constraint needs
15318 * to be rebuilt (which we might already know).
15319 */
15320 static void
15321 RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab)
15322 {
15323 /*
15324 * This de-duplication check is critical for two independent reasons: we
15325 * mustn't try to recreate the same constraint twice, and if a constraint
15326 * depends on more than one column whose type is to be altered, we must
15327 * capture its definition string before applying any of the column type
15328 * changes. ruleutils.c will get confused if we ask again later.
15329 */
15330 if (!list_member_oid(tab->changedConstraintOids, conoid))
15331 {
15332 /* OK, capture the constraint's existing definition string */
15333 char *defstring = pg_get_constraintdef_command(conoid);
15334 Oid indoid;
15335
15336 /*
15337 * It is critical to create not-null constraints ahead of primary key
15338 * indexes; otherwise, the not-null constraint would be created by the
15339 * primary key, and the constraint name would be wrong.
15340 */
15341 if (get_constraint_type(conoid) == CONSTRAINT_NOTNULL)
15342 {
15343 tab->changedConstraintOids = lcons_oid(conoid,
15344 tab->changedConstraintOids);
15345 tab->changedConstraintDefs = lcons(defstring,
15346 tab->changedConstraintDefs);
15347 }
15348 else
15349 {
15350
15351 tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
15352 conoid);
15353 tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
15354 defstring);
15355 }
15356
15357 /*
15358 * For the index of a constraint, if any, remember if it is used for
15359 * the table's replica identity or if it is a clustered index, so that
15360 * ATPostAlterTypeCleanup() can queue up commands necessary to restore
15361 * those properties.
15362 */
15363 indoid = get_constraint_index(conoid);
15364 if (OidIsValid(indoid))
15365 {
15366 RememberReplicaIdentityForRebuilding(indoid, tab);
15367 RememberClusterOnForRebuilding(indoid, tab);
15368 }
15369 }
15370 }
15371
15372 /*
15373 * Subroutine for ATExecAlterColumnType: remember that an index needs
15374 * to be rebuilt (which we might already know).
15375 */
15376 static void
15377 RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab)
15378 {
15379 /*
15380 * This de-duplication check is critical for two independent reasons: we
15381 * mustn't try to recreate the same index twice, and if an index depends
15382 * on more than one column whose type is to be altered, we must capture
15383 * its definition string before applying any of the column type changes.
15384 * ruleutils.c will get confused if we ask again later.
15385 */
15386 if (!list_member_oid(tab->changedIndexOids, indoid))
15387 {
15388 /*
15389 * Before adding it as an index-to-rebuild, we'd better see if it
15390 * belongs to a constraint, and if so rebuild the constraint instead.
15391 * Typically this check fails, because constraint indexes normally
15392 * have only dependencies on their constraint. But it's possible for
15393 * such an index to also have direct dependencies on table columns,
15394 * for example with a partial exclusion constraint.
15395 */
15396 Oid conoid = get_index_constraint(indoid);
15397
15398 if (OidIsValid(conoid))
15399 {
15400 RememberConstraintForRebuilding(conoid, tab);
15401 }
15402 else
15403 {
15404 /* OK, capture the index's existing definition string */
15405 char *defstring = pg_get_indexdef_string(indoid);
15406
15407 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
15408 indoid);
15409 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
15410 defstring);
15411
15412 /*
15413 * Remember if this index is used for the table's replica identity
15414 * or if it is a clustered index, so that ATPostAlterTypeCleanup()
15415 * can queue up commands necessary to restore those properties.
15416 */
15417 RememberReplicaIdentityForRebuilding(indoid, tab);
15418 RememberClusterOnForRebuilding(indoid, tab);
15419 }
15420 }
15421 }
15422
15423 /*
15424 * Subroutine for ATExecAlterColumnType: remember that a statistics object
15425 * needs to be rebuilt (which we might already know).
15426 */
15427 static void
15428 RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
15429 {
15430 /*
15431 * This de-duplication check is critical for two independent reasons: we
15432 * mustn't try to recreate the same statistics object twice, and if the
15433 * statistics object depends on more than one column whose type is to be
15434 * altered, we must capture its definition string before applying any of
15435 * the type changes. ruleutils.c will get confused if we ask again later.
15436 */
15437 if (!list_member_oid(tab->changedStatisticsOids, stxoid))
15438 {
15439 /* OK, capture the statistics object's existing definition string */
15440 char *defstring = pg_get_statisticsobjdef_string(stxoid);
15441 HeapTuple tup;
15442 Form_pg_statistic_ext statext;
15443
15444 tup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxoid));
15445
15446 if (!HeapTupleIsValid(tup)) /* should not happen */
15447 elog(ERROR, "cache lookup failed for statistics object %u", stxoid);
15448
15449 statext = (Form_pg_statistic_ext) GETSTRUCT(tup);
15450
15451 tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
15452 stxoid);
15453 tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
15454 defstring);
15455
15456 tab->changedStatisticsOwners = lappend_oid(tab->changedStatisticsOwners,
15457 statext->stxowner);
15458
15459 ReleaseSysCache(tup);
15460 }
15461 }
15462
15463 /*
15464 * Cleanup after we've finished all the ALTER TYPE or SET EXPRESSION
15465 * operations for a particular relation. We have to drop and recreate all the
15466 * indexes and constraints that depend on the altered columns. We do the
15467 * actual dropping here, but re-creation is managed by adding work queue
15468 * entries to do those steps later.
15469 */
15470 static void
15471 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
15472 {
15473 ObjectAddress obj;
15474 ObjectAddresses *objects;
15475 ListCell *def_item;
15476 ListCell *oid_item;
15477 ListCell *owner_item;
15478
15479 /*
15480 * Collect all the constraints and indexes to drop so we can process them
15481 * in a single call. That way we don't have to worry about dependencies
15482 * among them.
15483 */
15484 objects = new_object_addresses();
15485
15486 /*
15487 * Re-parse the index and constraint definitions, and attach them to the
15488 * appropriate work queue entries. We do this before dropping because in
15489 * the case of a constraint on another table, we might not yet have
15490 * exclusive lock on the table the constraint is attached to, and we need
15491 * to get that before reparsing/dropping. (That's possible at least for
15492 * FOREIGN KEY, CHECK, and EXCLUSION constraints; in non-FK cases it
15493 * requires a dependency on the target table's composite type in the other
15494 * table's constraint expressions.)
15495 *
15496 * We can't rely on the output of deparsing to tell us which relation to
15497 * operate on, because concurrent activity might have made the name
15498 * resolve differently. Instead, we've got to use the OID of the
15499 * constraint or index we're processing to figure out which relation to
15500 * operate on.
15501 */
15502 forboth(oid_item, tab->changedConstraintOids,
15503 def_item, tab->changedConstraintDefs)
15504 {
15505 Oid oldId = lfirst_oid(oid_item);
15506 HeapTuple tup;
15507 Form_pg_constraint con;
15508 Oid relid;
15509 Oid confrelid;
15510 bool conislocal;
15511
15512 tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
15513 if (!HeapTupleIsValid(tup)) /* should not happen */
15514 elog(ERROR, "cache lookup failed for constraint %u", oldId);
15515 con = (Form_pg_constraint) GETSTRUCT(tup);
15516 if (OidIsValid(con->conrelid))
15517 relid = con->conrelid;
15518 else
15519 {
15520 /* must be a domain constraint */
15521 relid = get_typ_typrelid(getBaseType(con->contypid));
15522 if (!OidIsValid(relid))
15523 elog(ERROR, "could not identify relation associated with constraint %u", oldId);
15524 }
15525 confrelid = con->confrelid;
15526 conislocal = con->conislocal;
15527 ReleaseSysCache(tup);
15528
15529 ObjectAddressSet(obj, ConstraintRelationId, oldId);
15530 add_exact_object_address(&obj, objects);
15531
15532 /*
15533 * If the constraint is inherited (only), we don't want to inject a
15534 * new definition here; it'll get recreated when
15535 * ATAddCheckNNConstraint recurses from adding the parent table's
15536 * constraint. But we had to carry the info this far so that we can
15537 * drop the constraint below.
15538 */
15539 if (!conislocal)
15540 continue;
15541
15542 /*
15543 * When rebuilding another table's constraint that references the
15544 * table we're modifying, we might not yet have any lock on the other
15545 * table, so get one now. We'll need AccessExclusiveLock for the DROP
15546 * CONSTRAINT step, so there's no value in asking for anything weaker.
15547 */
15548 if (relid != tab->relid)
15549 LockRelationOid(relid, AccessExclusiveLock);
15550
15551 ATPostAlterTypeParse(oldId, relid, confrelid, InvalidOid,
15552 (char *) lfirst(def_item),
15553 wqueue, lockmode, tab->rewrite);
15554 }
15555 forboth(oid_item, tab->changedIndexOids,
15556 def_item, tab->changedIndexDefs)
15557 {
15558 Oid oldId = lfirst_oid(oid_item);
15559 Oid relid;
15560
15561 relid = IndexGetRelation(oldId, false);
15562
15563 /*
15564 * As above, make sure we have lock on the index's table if it's not
15565 * the same table.
15566 */
15567 if (relid != tab->relid)
15568 LockRelationOid(relid, AccessExclusiveLock);
15569
15570 ATPostAlterTypeParse(oldId, relid, InvalidOid, InvalidOid,
15571 (char *) lfirst(def_item),
15572 wqueue, lockmode, tab->rewrite);
15573
15574 ObjectAddressSet(obj, RelationRelationId, oldId);
15575 add_exact_object_address(&obj, objects);
15576 }
15577
15578 /* add dependencies for new statistics */
15579 forthree(oid_item, tab->changedStatisticsOids,
15580 def_item, tab->changedStatisticsDefs,
15581 owner_item, tab->changedStatisticsOwners)
15582 {
15583 Oid oldId = lfirst_oid(oid_item);
15584 Oid relid;
15585
15586 relid = StatisticsGetRelation(oldId, false);
15587
15588 /*
15589 * As above, make sure we have lock on the statistics object's table
15590 * if it's not the same table. However, we take
15591 * ShareUpdateExclusiveLock here, aligning with the lock level used in
15592 * CreateStatistics and RemoveStatisticsById.
15593 *
15594 * CAUTION: this should be done after all cases that grab
15595 * AccessExclusiveLock, else we risk causing deadlock due to needing
15596 * to promote our table lock.
15597 */
15598 if (relid != tab->relid)
15599 LockRelationOid(relid, ShareUpdateExclusiveLock);
15600
15601 ATPostAlterTypeParse(oldId, relid, InvalidOid, lfirst_oid(owner_item),
15602 (char *) lfirst(def_item),
15603 wqueue, lockmode, tab->rewrite);
15604
15605 ObjectAddressSet(obj, StatisticExtRelationId, oldId);
15606 add_exact_object_address(&obj, objects);
15607 }
15608
15609 /*
15610 * Queue up command to restore replica identity index marking
15611 */
15612 if (tab->replicaIdentityIndex)
15613 {
15614 AlterTableCmd *cmd = makeNode(AlterTableCmd);
15615 ReplicaIdentityStmt *subcmd = makeNode(ReplicaIdentityStmt);
15616
15617 subcmd->identity_type = REPLICA_IDENTITY_INDEX;
15618 subcmd->name = tab->replicaIdentityIndex;
15619 cmd->subtype = AT_ReplicaIdentity;
15620 cmd->def = (Node *) subcmd;
15621
15622 /* do it after indexes and constraints */
15623 tab->subcmds[AT_PASS_OLD_CONSTR] =
15624 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15625 }
15626
15627 /*
15628 * Queue up command to restore marking of index used for cluster.
15629 */
15630 if (tab->clusterOnIndex)
15631 {
15632 AlterTableCmd *cmd = makeNode(AlterTableCmd);
15633
15634 cmd->subtype = AT_ClusterOn;
15635 cmd->name = tab->clusterOnIndex;
15636
15637 /* do it after indexes and constraints */
15638 tab->subcmds[AT_PASS_OLD_CONSTR] =
15639 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15640 }
15641
15642 /*
15643 * It should be okay to use DROP_RESTRICT here, since nothing else should
15644 * be depending on these objects.
15645 */
15646 performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
15647
15648 free_object_addresses(objects);
15649
15650 /*
15651 * The objects will get recreated during subsequent passes over the work
15652 * queue.
15653 */
15654 }
15655
15656 /*
15657 * Parse the previously-saved definition string for a constraint, index or
15658 * statistics object against the newly-established column data type(s), and
15659 * queue up the resulting command parsetrees for execution.
15660 *
15661 * This might fail if, for example, you have a WHERE clause that uses an
15662 * operator that's not available for the new column type.
15663 */
15664 static void
15665 ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
15666 char *cmd, List **wqueue, LOCKMODE lockmode,
15667 bool rewrite)
15668 {
15669 List *raw_parsetree_list;
15670 List *querytree_list;
15671 ListCell *list_item;
15672 Relation rel;
15673
15674 /*
15675 * We expect that we will get only ALTER TABLE and CREATE INDEX
15676 * statements. Hence, there is no need to pass them through
15677 * parse_analyze_*() or the rewriter, but instead we need to pass them
15678 * through parse_utilcmd.c to make them ready for execution.
15679 */
15680 raw_parsetree_list = raw_parser(cmd, RAW_PARSE_DEFAULT);
15681 querytree_list = NIL;
15682 foreach(list_item, raw_parsetree_list)
15683 {
15684 RawStmt *rs = lfirst_node(RawStmt, list_item);
15685 Node *stmt = rs->stmt;
15686
15687 if (IsA(stmt, IndexStmt))
15688 querytree_list = lappend(querytree_list,
15689 transformIndexStmt(oldRelId,
15690 (IndexStmt *) stmt,
15691 cmd));
15692 else if (IsA(stmt, AlterTableStmt))
15693 {
15694 List *beforeStmts;
15695 List *afterStmts;
15696
15697 stmt = (Node *) transformAlterTableStmt(oldRelId,
15698 (AlterTableStmt *) stmt,
15699 cmd,
15700 &beforeStmts,
15701 &afterStmts);
15702 querytree_list = list_concat(querytree_list, beforeStmts);
15703 querytree_list = lappend(querytree_list, stmt);
15704 querytree_list = list_concat(querytree_list, afterStmts);
15705 }
15706 else if (IsA(stmt, CreateStatsStmt))
15707 {
15708 CreateStatsStmt *csstmt;
15709
15710 csstmt = transformStatsStmt(oldRelId, (CreateStatsStmt *) stmt, cmd);
15711 csstmt->owner = ownerId;
15712
15713 querytree_list = lappend(querytree_list, csstmt);
15714 }
15715 else
15716 querytree_list = lappend(querytree_list, stmt);
15717 }
15718
15719 /* Caller should already have acquired whatever lock we need. */
15720 rel = relation_open(oldRelId, NoLock);
15721
15722 /*
15723 * Attach each generated command to the proper place in the work queue.
15724 * Note this could result in creation of entirely new work-queue entries.
15725 *
15726 * Also note that we have to tweak the command subtypes, because it turns
15727 * out that re-creation of indexes and constraints has to act a bit
15728 * differently from initial creation.
15729 */
15730 foreach(list_item, querytree_list)
15731 {
15732 Node *stm = (Node *) lfirst(list_item);
15733 AlteredTableInfo *tab;
15734
15735 tab = ATGetQueueEntry(wqueue, rel);
15736
15737 if (IsA(stm, IndexStmt))
15738 {
15739 IndexStmt *stmt = (IndexStmt *) stm;
15740 AlterTableCmd *newcmd;
15741
15742 if (!rewrite)
15743 TryReuseIndex(oldId, stmt);
15744 stmt->reset_default_tblspc = true;
15745 /* keep the index's comment */
15746 stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
15747
15748 newcmd = makeNode(AlterTableCmd);
15749 newcmd->subtype = AT_ReAddIndex;
15750 newcmd->def = (Node *) stmt;
15751 tab->subcmds[AT_PASS_OLD_INDEX] =
15752 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
15753 }
15754 else if (IsA(stm, AlterTableStmt))
15755 {
15756 AlterTableStmt *stmt = (AlterTableStmt *) stm;
15757 ListCell *lcmd;
15758
15759 foreach(lcmd, stmt->cmds)
15760 {
15761 AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
15762
15763 if (cmd->subtype == AT_AddIndex)
15764 {
15765 IndexStmt *indstmt;
15766 Oid indoid;
15767
15768 indstmt = castNode(IndexStmt, cmd->def);
15769 indoid = get_constraint_index(oldId);
15770
15771 if (!rewrite)
15772 TryReuseIndex(indoid, indstmt);
15773 /* keep any comment on the index */
15774 indstmt->idxcomment = GetComment(indoid,
15775 RelationRelationId, 0);
15776 indstmt->reset_default_tblspc = true;
15777
15778 cmd->subtype = AT_ReAddIndex;
15779 tab->subcmds[AT_PASS_OLD_INDEX] =
15780 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
15781
15782 /* recreate any comment on the constraint */
15783 RebuildConstraintComment(tab,
15784 AT_PASS_OLD_INDEX,
15785 oldId,
15786 rel,
15787 NIL,
15788 indstmt->idxname);
15789 }
15790 else if (cmd->subtype == AT_AddConstraint)
15791 {
15792 Constraint *con = castNode(Constraint, cmd->def);
15793
15794 con->old_pktable_oid = refRelId;
15795 /* rewriting neither side of a FK */
15796 if (con->contype == CONSTR_FOREIGN &&
15797 !rewrite && tab->rewrite == 0)
15798 TryReuseForeignKey(oldId, con);
15799 con->reset_default_tblspc = true;
15800 cmd->subtype = AT_ReAddConstraint;
15801 tab->subcmds[AT_PASS_OLD_CONSTR] =
15802 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15803
15804 /*
15805 * Recreate any comment on the constraint. If we have
15806 * recreated a primary key, then transformTableConstraint
15807 * has added an unnamed not-null constraint here; skip
15808 * this in that case.
15809 */
15810 if (con->conname)
15811 RebuildConstraintComment(tab,
15812 AT_PASS_OLD_CONSTR,
15813 oldId,
15814 rel,
15815 NIL,
15816 con->conname);
15817 else
15818 Assert(con->contype == CONSTR_NOTNULL);
15819 }
15820 else
15821 elog(ERROR, "unexpected statement subtype: %d",
15822 (int) cmd->subtype);
15823 }
15824 }
15825 else if (IsA(stm, AlterDomainStmt))
15826 {
15827 AlterDomainStmt *stmt = (AlterDomainStmt *) stm;
15828
15829 if (stmt->subtype == 'C') /* ADD CONSTRAINT */
15830 {
15831 Constraint *con = castNode(Constraint, stmt->def);
15832 AlterTableCmd *cmd = makeNode(AlterTableCmd);
15833
15834 cmd->subtype = AT_ReAddDomainConstraint;
15835 cmd->def = (Node *) stmt;
15836 tab->subcmds[AT_PASS_OLD_CONSTR] =
15837 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15838
15839 /* recreate any comment on the constraint */
15840 RebuildConstraintComment(tab,
15841 AT_PASS_OLD_CONSTR,
15842 oldId,
15843 NULL,
15844 stmt->typeName,
15845 con->conname);
15846 }
15847 else
15848 elog(ERROR, "unexpected statement subtype: %d",
15849 (int) stmt->subtype);
15850 }
15851 else if (IsA(stm, CreateStatsStmt))
15852 {
15853 CreateStatsStmt *stmt = (CreateStatsStmt *) stm;
15854 AlterTableCmd *newcmd;
15855
15856 /* keep the statistics object's comment */
15857 stmt->stxcomment = GetComment(oldId, StatisticExtRelationId, 0);
15858
15859 newcmd = makeNode(AlterTableCmd);
15860 newcmd->subtype = AT_ReAddStatistics;
15861 newcmd->def = (Node *) stmt;
15862 tab->subcmds[AT_PASS_MISC] =
15863 lappend(tab->subcmds[AT_PASS_MISC], newcmd);
15864 }
15865 else
15866 elog(ERROR, "unexpected statement type: %d",
15867 (int) nodeTag(stm));
15868 }
15869
15870 relation_close(rel, NoLock);
15871 }
15872
15873 /*
15874 * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
15875 * for a table or domain constraint that is being rebuilt.
15876 *
15877 * objid is the OID of the constraint.
15878 * Pass "rel" for a table constraint, or "domname" (domain's qualified name
15879 * as a string list) for a domain constraint.
15880 * (We could dig that info, as well as the conname, out of the pg_constraint
15881 * entry; but callers already have them so might as well pass them.)
15882 */
15883 static void
15884 RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
15885 Relation rel, List *domname,
15886 const char *conname)
15887 {
15888 CommentStmt *cmd;
15889 char *comment_str;
15890 AlterTableCmd *newcmd;
15891
15892 /* Look for comment for object wanted, and leave if none */
15893 comment_str = GetComment(objid, ConstraintRelationId, 0);
15894 if (comment_str == NULL)
15895 return;
15896
15897 /* Build CommentStmt node, copying all input data for safety */
15898 cmd = makeNode(CommentStmt);
15899 if (rel)
15900 {
15901 cmd->objtype = OBJECT_TABCONSTRAINT;
15902 cmd->object = (Node *)
15903 list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
15904 makeString(pstrdup(RelationGetRelationName(rel))),
15905 makeString(pstrdup(conname)));
15906 }
15907 else
15908 {
15909 cmd->objtype = OBJECT_DOMCONSTRAINT;
15910 cmd->object = (Node *)
15911 list_make2(makeTypeNameFromNameList(copyObject(domname)),
15912 makeString(pstrdup(conname)));
15913 }
15914 cmd->comment = comment_str;
15915
15916 /* Append it to list of commands */
15917 newcmd = makeNode(AlterTableCmd);
15918 newcmd->subtype = AT_ReAddComment;
15919 newcmd->def = (Node *) cmd;
15920 tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
15921 }
15922
15923 /*
15924 * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
15925 * for the real analysis, then mutates the IndexStmt based on that verdict.
15926 */
15927 static void
15928 TryReuseIndex(Oid oldId, IndexStmt *stmt)
15929 {
15930 if (CheckIndexCompatible(oldId,
15931 stmt->accessMethod,
15932 stmt->indexParams,
15933 stmt->excludeOpNames,
15934 stmt->iswithoutoverlaps))
15935 {
15936 Relation irel = index_open(oldId, NoLock);
15937
15938 /* If it's a partitioned index, there is no storage to share. */
15939 if (irel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
15940 {
15941 stmt->oldNumber = irel->rd_locator.relNumber;
15942 stmt->oldCreateSubid = irel->rd_createSubid;
15943 stmt->oldFirstRelfilelocatorSubid = irel->rd_firstRelfilelocatorSubid;
15944 }
15945 index_close(irel, NoLock);
15946 }
15947 }
15948
15949 /*
15950 * Subroutine for ATPostAlterTypeParse().
15951 *
15952 * Stash the old P-F equality operator into the Constraint node, for possible
15953 * use by ATAddForeignKeyConstraint() in determining whether revalidation of
15954 * this constraint can be skipped.
15955 */
15956 static void
15957 TryReuseForeignKey(Oid oldId, Constraint *con)
15958 {
15959 HeapTuple tup;
15960 Datum adatum;
15961 ArrayType *arr;
15962 Oid *rawarr;
15963 int numkeys;
15964 int i;
15965
15966 Assert(con->contype == CONSTR_FOREIGN);
15967 Assert(con->old_conpfeqop == NIL); /* already prepared this node */
15968
15969 tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
15970 if (!HeapTupleIsValid(tup)) /* should not happen */
15971 elog(ERROR, "cache lookup failed for constraint %u", oldId);
15972
15973 adatum = SysCacheGetAttrNotNull(CONSTROID, tup,
15974 Anum_pg_constraint_conpfeqop);
15975 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
15976 numkeys = ARR_DIMS(arr)[0];
15977 /* test follows the one in ri_FetchConstraintInfo() */
15978 if (ARR_NDIM(arr) != 1 ||
15979 ARR_HASNULL(arr) ||
15980 ARR_ELEMTYPE(arr) != OIDOID)
15981 elog(ERROR, "conpfeqop is not a 1-D Oid array");
15982 rawarr = (Oid *) ARR_DATA_PTR(arr);
15983
15984 /* stash a List of the operator Oids in our Constraint node */
15985 for (i = 0; i < numkeys; i++)
15986 con->old_conpfeqop = lappend_oid(con->old_conpfeqop, rawarr[i]);
15987
15988 ReleaseSysCache(tup);
15989 }
15990
15991 /*
15992 * ALTER COLUMN .. OPTIONS ( ... )
15993 *
15994 * Returns the address of the modified column
15995 */
15996 static ObjectAddress
15997 ATExecAlterColumnGenericOptions(Relation rel,
15998 const char *colName,
15999 List *options,
16000 LOCKMODE lockmode)
16001 {
16002 Relation ftrel;
16003 Relation attrel;
16004 ForeignServer *server;
16005 ForeignDataWrapper *fdw;
16006 HeapTuple tuple;
16007 HeapTuple newtuple;
16008 bool isnull;
16009 Datum repl_val[Natts_pg_attribute];
16010 bool repl_null[Natts_pg_attribute];
16011 bool repl_repl[Natts_pg_attribute];
16012 Datum datum;
16013 Form_pg_foreign_table fttableform;
16014 Form_pg_attribute atttableform;
16015 AttrNumber attnum;
16016 ObjectAddress address;
16017
16018 if (options == NIL)
16019 return InvalidObjectAddress;
16020
16021 /* First, determine FDW validator associated to the foreign table. */
16022 ftrel = table_open(ForeignTableRelationId, AccessShareLock);
16023 tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(rel->rd_id));
16024 if (!HeapTupleIsValid(tuple))
16025 ereport(ERROR,
16026 (errcode(ERRCODE_UNDEFINED_OBJECT),
16027 errmsg("foreign table \"%s\" does not exist",
16028 RelationGetRelationName(rel))));
16029 fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
16030 server = GetForeignServer(fttableform->ftserver);
16031 fdw = GetForeignDataWrapper(server->fdwid);
16032
16033 table_close(ftrel, AccessShareLock);
16034 ReleaseSysCache(tuple);
16035
16036 attrel = table_open(AttributeRelationId, RowExclusiveLock);
16037 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
16038 if (!HeapTupleIsValid(tuple))
16039 ereport(ERROR,
16040 (errcode(ERRCODE_UNDEFINED_COLUMN),
16041 errmsg("column \"%s\" of relation \"%s\" does not exist",
16042 colName, RelationGetRelationName(rel))));
16043
16044 /* Prevent them from altering a system attribute */
16045 atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
16046 attnum = atttableform->attnum;
16047 if (attnum <= 0)
16048 ereport(ERROR,
16049 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16050 errmsg("cannot alter system column \"%s\"", colName)));
16051
16052
16053 /* Initialize buffers for new tuple values */
16054 memset(repl_val, 0, sizeof(repl_val));
16055 memset(repl_null, false, sizeof(repl_null));
16056 memset(repl_repl, false, sizeof(repl_repl));
16057
16058 /* Extract the current options */
16059 datum = SysCacheGetAttr(ATTNAME,
16060 tuple,
16061 Anum_pg_attribute_attfdwoptions,
16062 &isnull);
16063 if (isnull)
16064 datum = PointerGetDatum(NULL);
16065
16066 /* Transform the options */
16067 datum = transformGenericOptions(AttributeRelationId,
16068 datum,
16069 options,
16070 fdw->fdwvalidator);
16071
16072 if (PointerIsValid(DatumGetPointer(datum)))
16073 repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
16074 else
16075 repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
16076
16077 repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
16078
16079 /* Everything looks good - update the tuple */
16080
16081 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
16082 repl_val, repl_null, repl_repl);
16083
16084 CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
16085
16086 InvokeObjectPostAlterHook(RelationRelationId,
16087 RelationGetRelid(rel),
16088 atttableform->attnum);
16089 ObjectAddressSubSet(address, RelationRelationId,
16090 RelationGetRelid(rel), attnum);
16091
16092 ReleaseSysCache(tuple);
16093
16094 table_close(attrel, RowExclusiveLock);
16095
16096 heap_freetuple(newtuple);
16097
16098 return address;
16099 }
16100
16101 /*
16102 * ALTER TABLE OWNER
16103 *
16104 * recursing is true if we are recursing from a table to its indexes,
16105 * sequences, or toast table. We don't allow the ownership of those things to
16106 * be changed separately from the parent table. Also, we can skip permission
16107 * checks (this is necessary not just an optimization, else we'd fail to
16108 * handle toast tables properly).
16109 *
16110 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
16111 * free-standing composite type.
16112 */
16113 void
16114 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
16115 {
16116 Relation target_rel;
16117 Relation class_rel;
16118 HeapTuple tuple;
16119 Form_pg_class tuple_class;
16120
16121 /*
16122 * Get exclusive lock till end of transaction on the target table. Use
16123 * relation_open so that we can work on indexes and sequences.
16124 */
16125 target_rel = relation_open(relationOid, lockmode);
16126
16127 /* Get its pg_class tuple, too */
16128 class_rel = table_open(RelationRelationId, RowExclusiveLock);
16129
16130 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16131 if (!HeapTupleIsValid(tuple))
16132 elog(ERROR, "cache lookup failed for relation %u", relationOid);
16133 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
16134
16135 /* Can we change the ownership of this tuple? */
16136 switch (tuple_class->relkind)
16137 {
16138 case RELKIND_RELATION:
16139 case RELKIND_VIEW:
16140 case RELKIND_MATVIEW:
16141 case RELKIND_FOREIGN_TABLE:
16142 case RELKIND_PARTITIONED_TABLE:
16143 /* ok to change owner */
16144 break;
16145 case RELKIND_INDEX:
16146 if (!recursing)
16147 {
16148 /*
16149 * Because ALTER INDEX OWNER used to be allowed, and in fact
16150 * is generated by old versions of pg_dump, we give a warning
16151 * and do nothing rather than erroring out. Also, to avoid
16152 * unnecessary chatter while restoring those old dumps, say
16153 * nothing at all if the command would be a no-op anyway.
16154 */
16155 if (tuple_class->relowner != newOwnerId)
16156 ereport(WARNING,
16157 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16158 errmsg("cannot change owner of index \"%s\"",
16159 NameStr(tuple_class->relname)),
16160 errhint("Change the ownership of the index's table instead.")));
16161 /* quick hack to exit via the no-op path */
16162 newOwnerId = tuple_class->relowner;
16163 }
16164 break;
16165 case RELKIND_PARTITIONED_INDEX:
16166 if (recursing)
16167 break;
16168 ereport(ERROR,
16169 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16170 errmsg("cannot change owner of index \"%s\"",
16171 NameStr(tuple_class->relname)),
16172 errhint("Change the ownership of the index's table instead.")));
16173 break;
16174 case RELKIND_SEQUENCE:
16175 if (!recursing &&
16176 tuple_class->relowner != newOwnerId)
16177 {
16178 /* if it's an owned sequence, disallow changing it by itself */
16179 Oid tableId;
16180 int32 colId;
16181
16182 if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16183 sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
16184 ereport(ERROR,
16185 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16186 errmsg("cannot change owner of sequence \"%s\"",
16187 NameStr(tuple_class->relname)),
16188 errdetail("Sequence \"%s\" is linked to table \"%s\".",
16189 NameStr(tuple_class->relname),
16190 get_rel_name(tableId))));
16191 }
16192 break;
16193 case RELKIND_COMPOSITE_TYPE:
16194 if (recursing)
16195 break;
16196 ereport(ERROR,
16197 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16198 errmsg("\"%s\" is a composite type",
16199 NameStr(tuple_class->relname)),
16200 /* translator: %s is an SQL ALTER command */
16201 errhint("Use %s instead.",
16202 "ALTER TYPE")));
16203 break;
16204 case RELKIND_TOASTVALUE:
16205 if (recursing)
16206 break;
16207 /* FALL THRU */
16208 default:
16209 ereport(ERROR,
16210 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16211 errmsg("cannot change owner of relation \"%s\"",
16212 NameStr(tuple_class->relname)),
16213 errdetail_relkind_not_supported(tuple_class->relkind)));
16214 }
16215
16216 /*
16217 * If the new owner is the same as the existing owner, consider the
16218 * command to have succeeded. This is for dump restoration purposes.
16219 */
16220 if (tuple_class->relowner != newOwnerId)
16221 {
16222 Datum repl_val[Natts_pg_class];
16223 bool repl_null[Natts_pg_class];
16224 bool repl_repl[Natts_pg_class];
16225 Acl *newAcl;
16226 Datum aclDatum;
16227 bool isNull;
16228 HeapTuple newtuple;
16229
16230 /* skip permission checks when recursing to index or toast table */
16231 if (!recursing)
16232 {
16233 /* Superusers can always do it */
16234 if (!superuser())
16235 {
16236 Oid namespaceOid = tuple_class->relnamespace;
16237 AclResult aclresult;
16238
16239 /* Otherwise, must be owner of the existing object */
16240 if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16241 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relationOid)),
16242 RelationGetRelationName(target_rel));
16243
16244 /* Must be able to become new owner */
16245 check_can_set_role(GetUserId(), newOwnerId);
16246
16247 /* New owner must have CREATE privilege on namespace */
16248 aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
16249 ACL_CREATE);
16250 if (aclresult != ACLCHECK_OK)
16251 aclcheck_error(aclresult, OBJECT_SCHEMA,
16252 get_namespace_name(namespaceOid));
16253 }
16254 }
16255
16256 memset(repl_null, false, sizeof(repl_null));
16257 memset(repl_repl, false, sizeof(repl_repl));
16258
16259 repl_repl[Anum_pg_class_relowner - 1] = true;
16260 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
16261
16262 /*
16263 * Determine the modified ACL for the new owner. This is only
16264 * necessary when the ACL is non-null.
16265 */
16266 aclDatum = SysCacheGetAttr(RELOID, tuple,
16267 Anum_pg_class_relacl,
16268 &isNull);
16269 if (!isNull)
16270 {
16271 newAcl = aclnewowner(DatumGetAclP(aclDatum),
16272 tuple_class->relowner, newOwnerId);
16273 repl_repl[Anum_pg_class_relacl - 1] = true;
16274 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
16275 }
16276
16277 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
16278
16279 CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16280
16281 heap_freetuple(newtuple);
16282
16283 /*
16284 * We must similarly update any per-column ACLs to reflect the new
16285 * owner; for neatness reasons that's split out as a subroutine.
16286 */
16287 change_owner_fix_column_acls(relationOid,
16288 tuple_class->relowner,
16289 newOwnerId);
16290
16291 /*
16292 * Update owner dependency reference, if any. A composite type has
16293 * none, because it's tracked for the pg_type entry instead of here;
16294 * indexes and TOAST tables don't have their own entries either.
16295 */
16296 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16297 tuple_class->relkind != RELKIND_INDEX &&
16298 tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
16299 tuple_class->relkind != RELKIND_TOASTVALUE)
16300 changeDependencyOnOwner(RelationRelationId, relationOid,
16301 newOwnerId);
16302
16303 /*
16304 * Also change the ownership of the table's row type, if it has one
16305 */
16306 if (OidIsValid(tuple_class->reltype))
16307 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
16308
16309 /*
16310 * If we are operating on a table or materialized view, also change
16311 * the ownership of any indexes and sequences that belong to the
16312 * relation, as well as its toast table (if it has one).
16313 */
16314 if (tuple_class->relkind == RELKIND_RELATION ||
16315 tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
16316 tuple_class->relkind == RELKIND_MATVIEW ||
16317 tuple_class->relkind == RELKIND_TOASTVALUE)
16318 {
16319 List *index_oid_list;
16320 ListCell *i;
16321
16322 /* Find all the indexes belonging to this relation */
16323 index_oid_list = RelationGetIndexList(target_rel);
16324
16325 /* For each index, recursively change its ownership */
16326 foreach(i, index_oid_list)
16327 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16328
16329 list_free(index_oid_list);
16330 }
16331
16332 /* If it has a toast table, recurse to change its ownership */
16333 if (tuple_class->reltoastrelid != InvalidOid)
16334 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
16335 true, lockmode);
16336
16337 /* If it has dependent sequences, recurse to change them too */
16338 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16339 }
16340
16341 InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
16342
16343 ReleaseSysCache(tuple);
16344 table_close(class_rel, RowExclusiveLock);
16345 relation_close(target_rel, NoLock);
16346 }
16347
16348 /*
16349 * change_owner_fix_column_acls
16350 *
16351 * Helper function for ATExecChangeOwner. Scan the columns of the table
16352 * and fix any non-null column ACLs to reflect the new owner.
16353 */
16354 static void
16355 change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
16356 {
16357 Relation attRelation;
16358 SysScanDesc scan;
16359 ScanKeyData key[1];
16360 HeapTuple attributeTuple;
16361
16362 attRelation = table_open(AttributeRelationId, RowExclusiveLock);
16363 ScanKeyInit(&key[0],
16364 Anum_pg_attribute_attrelid,
16365 BTEqualStrategyNumber, F_OIDEQ,
16366 ObjectIdGetDatum(relationOid));
16367 scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
16368 true, NULL, 1, key);
16369 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
16370 {
16371 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
16372 Datum repl_val[Natts_pg_attribute];
16373 bool repl_null[Natts_pg_attribute];
16374 bool repl_repl[Natts_pg_attribute];
16375 Acl *newAcl;
16376 Datum aclDatum;
16377 bool isNull;
16378 HeapTuple newtuple;
16379
16380 /* Ignore dropped columns */
16381 if (att->attisdropped)
16382 continue;
16383
16384 aclDatum = heap_getattr(attributeTuple,
16385 Anum_pg_attribute_attacl,
16386 RelationGetDescr(attRelation),
16387 &isNull);
16388 /* Null ACLs do not require changes */
16389 if (isNull)
16390 continue;
16391
16392 memset(repl_null, false, sizeof(repl_null));
16393 memset(repl_repl, false, sizeof(repl_repl));
16394
16395 newAcl = aclnewowner(DatumGetAclP(aclDatum),
16396 oldOwnerId, newOwnerId);
16397 repl_repl[Anum_pg_attribute_attacl - 1] = true;
16398 repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
16399
16400 newtuple = heap_modify_tuple(attributeTuple,
16401 RelationGetDescr(attRelation),
16402 repl_val, repl_null, repl_repl);
16403
16404 CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
16405
16406 heap_freetuple(newtuple);
16407 }
16408 systable_endscan(scan);
16409 table_close(attRelation, RowExclusiveLock);
16410 }
16411
16412 /*
16413 * change_owner_recurse_to_sequences
16414 *
16415 * Helper function for ATExecChangeOwner. Examines pg_depend searching
16416 * for sequences that are dependent on serial columns, and changes their
16417 * ownership.
16418 */
16419 static void
16420 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
16421 {
16422 Relation depRel;
16423 SysScanDesc scan;
16424 ScanKeyData key[2];
16425 HeapTuple tup;
16426
16427 /*
16428 * SERIAL sequences are those having an auto dependency on one of the
16429 * table's columns (we don't care *which* column, exactly).
16430 */
16431 depRel = table_open(DependRelationId, AccessShareLock);
16432
16433 ScanKeyInit(&key[0],
16434 Anum_pg_depend_refclassid,
16435 BTEqualStrategyNumber, F_OIDEQ,
16436 ObjectIdGetDatum(RelationRelationId));
16437 ScanKeyInit(&key[1],
16438 Anum_pg_depend_refobjid,
16439 BTEqualStrategyNumber, F_OIDEQ,
16440 ObjectIdGetDatum(relationOid));
16441 /* we leave refobjsubid unspecified */
16442
16443 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
16444 NULL, 2, key);
16445
16446 while (HeapTupleIsValid(tup = systable_getnext(scan)))
16447 {
16448 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
16449 Relation seqRel;
16450
16451 /* skip dependencies other than auto dependencies on columns */
16452 if (depForm->refobjsubid == 0 ||
16453 depForm->classid != RelationRelationId ||
16454 depForm->objsubid != 0 ||
16455 !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
16456 continue;
16457
16458 /* Use relation_open just in case it's an index */
16459 seqRel = relation_open(depForm->objid, lockmode);
16460
16461 /* skip non-sequence relations */
16462 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
16463 {
16464 /* No need to keep the lock */
16465 relation_close(seqRel, lockmode);
16466 continue;
16467 }
16468
16469 /* We don't need to close the sequence while we alter it. */
16470 ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
16471
16472 /* Now we can close it. Keep the lock till end of transaction. */
16473 relation_close(seqRel, NoLock);
16474 }
16475
16476 systable_endscan(scan);
16477
16478 relation_close(depRel, AccessShareLock);
16479 }
16480
16481 /*
16482 * ALTER TABLE CLUSTER ON
16483 *
16484 * The only thing we have to do is to change the indisclustered bits.
16485 *
16486 * Return the address of the new clustering index.
16487 */
16488 static ObjectAddress
16489 ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
16490 {
16491 Oid indexOid;
16492 ObjectAddress address;
16493
16494 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
16495
16496 if (!OidIsValid(indexOid))
16497 ereport(ERROR,
16498 (errcode(ERRCODE_UNDEFINED_OBJECT),
16499 errmsg("index \"%s\" for table \"%s\" does not exist",
16500 indexName, RelationGetRelationName(rel))));
16501
16502 /* Check index is valid to cluster on */
16503 check_index_is_clusterable(rel, indexOid, lockmode);
16504
16505 /* And do the work */
16506 mark_index_clustered(rel, indexOid, false);
16507
16508 ObjectAddressSet(address,
16509 RelationRelationId, indexOid);
16510
16511 return address;
16512 }
16513
16514 /*
16515 * ALTER TABLE SET WITHOUT CLUSTER
16516 *
16517 * We have to find any indexes on the table that have indisclustered bit
16518 * set and turn it off.
16519 */
16520 static void
16521 ATExecDropCluster(Relation rel, LOCKMODE lockmode)
16522 {
16523 mark_index_clustered(rel, InvalidOid, false);
16524 }
16525
16526 /*
16527 * Preparation phase for SET ACCESS METHOD
16528 *
16529 * Check that the access method exists and determine whether a change is
16530 * actually needed.
16531 */
16532 static void
16533 ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname)
16534 {
16535 Oid amoid;
16536
16537 /*
16538 * Look up the access method name and check that it differs from the
16539 * table's current AM. If DEFAULT was specified for a partitioned table
16540 * (amname is NULL), set it to InvalidOid to reset the catalogued AM.
16541 */
16542 if (amname != NULL)
16543 amoid = get_table_am_oid(amname, false);
16544 else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
16545 amoid = InvalidOid;
16546 else
16547 amoid = get_table_am_oid(default_table_access_method, false);
16548
16549 /* if it's a match, phase 3 doesn't need to do anything */
16550 if (rel->rd_rel->relam == amoid)
16551 return;
16552
16553 /* Save info for Phase 3 to do the real work */
16554 tab->rewrite |= AT_REWRITE_ACCESS_METHOD;
16555 tab->newAccessMethod = amoid;
16556 tab->chgAccessMethod = true;
16557 }
16558
16559 /*
16560 * Special handling of ALTER TABLE SET ACCESS METHOD for relations with no
16561 * storage that have an interest in preserving AM.
16562 *
16563 * Since these have no storage, setting the access method is a catalog only
16564 * operation.
16565 */
16566 static void
16567 ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId)
16568 {
16569 Relation pg_class;
16570 Oid oldAccessMethodId;
16571 HeapTuple tuple;
16572 Form_pg_class rd_rel;
16573 Oid reloid = RelationGetRelid(rel);
16574
16575 /*
16576 * Shouldn't be called on relations having storage; these are processed in
16577 * phase 3.
16578 */
16579 Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
16580
16581 /* Get a modifiable copy of the relation's pg_class row. */
16582 pg_class = table_open(RelationRelationId, RowExclusiveLock);
16583
16584 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
16585 if (!HeapTupleIsValid(tuple))
16586 elog(ERROR, "cache lookup failed for relation %u", reloid);
16587 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
16588
16589 /* Update the pg_class row. */
16590 oldAccessMethodId = rd_rel->relam;
16591 rd_rel->relam = newAccessMethodId;
16592
16593 /* Leave if no update required */
16594 if (rd_rel->relam == oldAccessMethodId)
16595 {
16596 heap_freetuple(tuple);
16597 table_close(pg_class, RowExclusiveLock);
16598 return;
16599 }
16600
16601 CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
16602
16603 /*
16604 * Update the dependency on the new access method. No dependency is added
16605 * if the new access method is InvalidOid (default case). Be very careful
16606 * that this has to compare the previous value stored in pg_class with the
16607 * new one.
16608 */
16609 if (!OidIsValid(oldAccessMethodId) && OidIsValid(rd_rel->relam))
16610 {
16611 ObjectAddress relobj,
16612 referenced;
16613
16614 /*
16615 * New access method is defined and there was no dependency
16616 * previously, so record a new one.
16617 */
16618 ObjectAddressSet(relobj, RelationRelationId, reloid);
16619 ObjectAddressSet(referenced, AccessMethodRelationId, rd_rel->relam);
16620 recordDependencyOn(&relobj, &referenced, DEPENDENCY_NORMAL);
16621 }
16622 else if (OidIsValid(oldAccessMethodId) &&
16623 !OidIsValid(rd_rel->relam))
16624 {
16625 /*
16626 * There was an access method defined, and no new one, so just remove
16627 * the existing dependency.
16628 */
16629 deleteDependencyRecordsForClass(RelationRelationId, reloid,
16630 AccessMethodRelationId,
16631 DEPENDENCY_NORMAL);
16632 }
16633 else
16634 {
16635 Assert(OidIsValid(oldAccessMethodId) &&
16636 OidIsValid(rd_rel->relam));
16637
16638 /* Both are valid, so update the dependency */
16639 changeDependencyFor(RelationRelationId, reloid,
16640 AccessMethodRelationId,
16641 oldAccessMethodId, rd_rel->relam);
16642 }
16643
16644 /* make the relam and dependency changes visible */
16645 CommandCounterIncrement();
16646
16647 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
16648
16649 heap_freetuple(tuple);
16650 table_close(pg_class, RowExclusiveLock);
16651 }
16652
16653 /*
16654 * ALTER TABLE SET TABLESPACE
16655 */
16656 static void
16657 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
16658 {
16659 Oid tablespaceId;
16660
16661 /* Check that the tablespace exists */
16662 tablespaceId = get_tablespace_oid(tablespacename, false);
16663
16664 /* Check permissions except when moving to database's default */
16665 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
16666 {
16667 AclResult aclresult;
16668
16669 aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(), ACL_CREATE);
16670 if (aclresult != ACLCHECK_OK)
16671 aclcheck_error(aclresult, OBJECT_TABLESPACE, tablespacename);
16672 }
16673
16674 /* Save info for Phase 3 to do the real work */
16675 if (OidIsValid(tab->newTableSpace))
16676 ereport(ERROR,
16677 (errcode(ERRCODE_SYNTAX_ERROR),
16678 errmsg("cannot have multiple SET TABLESPACE subcommands")));
16679
16680 tab->newTableSpace = tablespaceId;
16681 }
16682
16683 /*
16684 * Set, reset, or replace reloptions.
16685 */
16686 static void
16687 ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
16688 LOCKMODE lockmode)
16689 {
16690 Oid relid;
16691 Relation pgclass;
16692 HeapTuple tuple;
16693 HeapTuple newtuple;
16694 Datum datum;
16695 Datum newOptions;
16696 Datum repl_val[Natts_pg_class];
16697 bool repl_null[Natts_pg_class];
16698 bool repl_repl[Natts_pg_class];
16699 const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
16700
16701 if (defList == NIL && operation != AT_ReplaceRelOptions)
16702 return; /* nothing to do */
16703
16704 pgclass = table_open(RelationRelationId, RowExclusiveLock);
16705
16706 /* Fetch heap tuple */
16707 relid = RelationGetRelid(rel);
16708 tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relid));
16709 if (!HeapTupleIsValid(tuple))
16710 elog(ERROR, "cache lookup failed for relation %u", relid);
16711
16712 if (operation == AT_ReplaceRelOptions)
16713 {
16714 /*
16715 * If we're supposed to replace the reloptions list, we just pretend
16716 * there were none before.
16717 */
16718 datum = (Datum) 0;
16719 }
16720 else
16721 {
16722 bool isnull;
16723
16724 /* Get the old reloptions */
16725 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
16726 &isnull);
16727 if (isnull)
16728 datum = (Datum) 0;
16729 }
16730
16731 /* Generate new proposed reloptions (text array) */
16732 newOptions = transformRelOptions(datum, defList, NULL, validnsps, false,
16733 operation == AT_ResetRelOptions);
16734
16735 /* Validate */
16736 switch (rel->rd_rel->relkind)
16737 {
16738 case RELKIND_RELATION:
16739 case RELKIND_MATVIEW:
16740 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
16741 break;
16742 case RELKIND_PARTITIONED_TABLE:
16743 (void) partitioned_table_reloptions(newOptions, true);
16744 break;
16745 case RELKIND_VIEW:
16746 (void) view_reloptions(newOptions, true);
16747 break;
16748 case RELKIND_INDEX:
16749 case RELKIND_PARTITIONED_INDEX:
16750 (void) index_reloptions(rel->rd_indam->amoptions, newOptions, true);
16751 break;
16752 case RELKIND_TOASTVALUE:
16753 /* fall through to error -- shouldn't ever get here */
16754 default:
16755 ereport(ERROR,
16756 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16757 errmsg("cannot set options for relation \"%s\"",
16758 RelationGetRelationName(rel)),
16759 errdetail_relkind_not_supported(rel->rd_rel->relkind)));
16760 break;
16761 }
16762
16763 /* Special-case validation of view options */
16764 if (rel->rd_rel->relkind == RELKIND_VIEW)
16765 {
16766 Query *view_query = get_view_query(rel);
16767 List *view_options = untransformRelOptions(newOptions);
16768 ListCell *cell;
16769 bool check_option = false;
16770
16771 foreach(cell, view_options)
16772 {
16773 DefElem *defel = (DefElem *) lfirst(cell);
16774
16775 if (strcmp(defel->defname, "check_option") == 0)
16776 check_option = true;
16777 }
16778
16779 /*
16780 * If the check option is specified, look to see if the view is
16781 * actually auto-updatable or not.
16782 */
16783 if (check_option)
16784 {
16785 const char *view_updatable_error =
16786 view_query_is_auto_updatable(view_query, true);
16787
16788 if (view_updatable_error)
16789 ereport(ERROR,
16790 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16791 errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
16792 errhint("%s", _(view_updatable_error))));
16793 }
16794 }
16795
16796 /*
16797 * All we need do here is update the pg_class row; the new options will be
16798 * propagated into relcaches during post-commit cache inval.
16799 */
16800 memset(repl_val, 0, sizeof(repl_val));
16801 memset(repl_null, false, sizeof(repl_null));
16802 memset(repl_repl, false, sizeof(repl_repl));
16803
16804 if (newOptions != (Datum) 0)
16805 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
16806 else
16807 repl_null[Anum_pg_class_reloptions - 1] = true;
16808
16809 repl_repl[Anum_pg_class_reloptions - 1] = true;
16810
16811 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
16812 repl_val, repl_null, repl_repl);
16813
16814 CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
16815 UnlockTuple(pgclass, &tuple->t_self, InplaceUpdateTupleLock);
16816
16817 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
16818
16819 heap_freetuple(newtuple);
16820
16821 ReleaseSysCache(tuple);
16822
16823 /* repeat the whole exercise for the toast table, if there's one */
16824 if (OidIsValid(rel->rd_rel->reltoastrelid))
16825 {
16826 Relation toastrel;
16827 Oid toastid = rel->rd_rel->reltoastrelid;
16828
16829 toastrel = table_open(toastid, lockmode);
16830
16831 /* Fetch heap tuple */
16832 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
16833 if (!HeapTupleIsValid(tuple))
16834 elog(ERROR, "cache lookup failed for relation %u", toastid);
16835
16836 if (operation == AT_ReplaceRelOptions)
16837 {
16838 /*
16839 * If we're supposed to replace the reloptions list, we just
16840 * pretend there were none before.
16841 */
16842 datum = (Datum) 0;
16843 }
16844 else
16845 {
16846 bool isnull;
16847
16848 /* Get the old reloptions */
16849 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
16850 &isnull);
16851 if (isnull)
16852 datum = (Datum) 0;
16853 }
16854
16855 newOptions = transformRelOptions(datum, defList, "toast", validnsps,
16856 false, operation == AT_ResetRelOptions);
16857
16858 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
16859
16860 memset(repl_val, 0, sizeof(repl_val));
16861 memset(repl_null, false, sizeof(repl_null));
16862 memset(repl_repl, false, sizeof(repl_repl));
16863
16864 if (newOptions != (Datum) 0)
16865 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
16866 else
16867 repl_null[Anum_pg_class_reloptions - 1] = true;
16868
16869 repl_repl[Anum_pg_class_reloptions - 1] = true;
16870
16871 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
16872 repl_val, repl_null, repl_repl);
16873
16874 CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
16875
16876 InvokeObjectPostAlterHookArg(RelationRelationId,
16877 RelationGetRelid(toastrel), 0,
16878 InvalidOid, true);
16879
16880 heap_freetuple(newtuple);
16881
16882 ReleaseSysCache(tuple);
16883
16884 table_close(toastrel, NoLock);
16885 }
16886
16887 table_close(pgclass, RowExclusiveLock);
16888 }
16889
16890 /*
16891 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
16892 * rewriting to be done, so we just want to copy the data as fast as possible.
16893 */
16894 static void
16895 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
16896 {
16897 Relation rel;
16898 Oid reltoastrelid;
16899 RelFileNumber newrelfilenumber;
16900 RelFileLocator newrlocator;
16901 List *reltoastidxids = NIL;
16902 ListCell *lc;
16903
16904 /*
16905 * Need lock here in case we are recursing to toast table or index
16906 */
16907 rel = relation_open(tableOid, lockmode);
16908
16909 /* Check first if relation can be moved to new tablespace */
16910 if (!CheckRelationTableSpaceMove(rel, newTableSpace))
16911 {
16912 InvokeObjectPostAlterHook(RelationRelationId,
16913 RelationGetRelid(rel), 0);
16914 relation_close(rel, NoLock);
16915 return;
16916 }
16917
16918 reltoastrelid = rel->rd_rel->reltoastrelid;
16919 /* Fetch the list of indexes on toast relation if necessary */
16920 if (OidIsValid(reltoastrelid))
16921 {
16922 Relation toastRel = relation_open(reltoastrelid, lockmode);
16923
16924 reltoastidxids = RelationGetIndexList(toastRel);
16925 relation_close(toastRel, lockmode);
16926 }
16927
16928 /*
16929 * Relfilenumbers are not unique in databases across tablespaces, so we
16930 * need to allocate a new one in the new tablespace.
16931 */
16932 newrelfilenumber = GetNewRelFileNumber(newTableSpace, NULL,
16933 rel->rd_rel->relpersistence);
16934
16935 /* Open old and new relation */
16936 newrlocator = rel->rd_locator;
16937 newrlocator.relNumber = newrelfilenumber;
16938 newrlocator.spcOid = newTableSpace;
16939
16940 /* hand off to AM to actually create new rel storage and copy the data */
16941 if (rel->rd_rel->relkind == RELKIND_INDEX)
16942 {
16943 index_copy_data(rel, newrlocator);
16944 }
16945 else
16946 {
16947 Assert(RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind));
16948 table_relation_copy_data(rel, &newrlocator);
16949 }
16950
16951 /*
16952 * Update the pg_class row.
16953 *
16954 * NB: This wouldn't work if ATExecSetTableSpace() were allowed to be
16955 * executed on pg_class or its indexes (the above copy wouldn't contain
16956 * the updated pg_class entry), but that's forbidden with
16957 * CheckRelationTableSpaceMove().
16958 */
16959 SetRelationTableSpace(rel, newTableSpace, newrelfilenumber);
16960
16961 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
16962
16963 RelationAssumeNewRelfilelocator(rel);
16964
16965 relation_close(rel, NoLock);
16966
16967 /* Make sure the reltablespace change is visible */
16968 CommandCounterIncrement();
16969
16970 /* Move associated toast relation and/or indexes, too */
16971 if (OidIsValid(reltoastrelid))
16972 ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
16973 foreach(lc, reltoastidxids)
16974 ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
16975
16976 /* Clean up */
16977 list_free(reltoastidxids);
16978 }
16979
16980 /*
16981 * Special handling of ALTER TABLE SET TABLESPACE for relations with no
16982 * storage that have an interest in preserving tablespace.
16983 *
16984 * Since these have no storage the tablespace can be updated with a simple
16985 * metadata only operation to update the tablespace.
16986 */
16987 static void
16988 ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace)
16989 {
16990 /*
16991 * Shouldn't be called on relations having storage; these are processed in
16992 * phase 3.
16993 */
16994 Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
16995
16996 /* check if relation can be moved to its new tablespace */
16997 if (!CheckRelationTableSpaceMove(rel, newTableSpace))
16998 {
16999 InvokeObjectPostAlterHook(RelationRelationId,
17000 RelationGetRelid(rel),
17001 0);
17002 return;
17003 }
17004
17005 /* Update can be done, so change reltablespace */
17006 SetRelationTableSpace(rel, newTableSpace, InvalidOid);
17007
17008 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17009
17010 /* Make sure the reltablespace change is visible */
17011 CommandCounterIncrement();
17012 }
17013
17014 /*
17015 * Alter Table ALL ... SET TABLESPACE
17016 *
17017 * Allows a user to move all objects of some type in a given tablespace in the
17018 * current database to another tablespace. Objects can be chosen based on the
17019 * owner of the object also, to allow users to move only their objects.
17020 * The user must have CREATE rights on the new tablespace, as usual. The main
17021 * permissions handling is done by the lower-level table move function.
17022 *
17023 * All to-be-moved objects are locked first. If NOWAIT is specified and the
17024 * lock can't be acquired then we ereport(ERROR).
17025 */
17026 Oid
17027 AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
17028 {
17029 List *relations = NIL;
17030 ListCell *l;
17031 ScanKeyData key[1];
17032 Relation rel;
17033 TableScanDesc scan;
17034 HeapTuple tuple;
17035 Oid orig_tablespaceoid;
17036 Oid new_tablespaceoid;
17037 List *role_oids = roleSpecsToIds(stmt->roles);
17038
17039 /* Ensure we were not asked to move something we can't */
17040 if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
17041 stmt->objtype != OBJECT_MATVIEW)
17042 ereport(ERROR,
17043 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17044 errmsg("only tables, indexes, and materialized views exist in tablespaces")));
17045
17046 /* Get the orig and new tablespace OIDs */
17047 orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
17048 new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
17049
17050 /* Can't move shared relations in to or out of pg_global */
17051 /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
17052 if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
17053 new_tablespaceoid == GLOBALTABLESPACE_OID)
17054 ereport(ERROR,
17055 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17056 errmsg("cannot move relations in to or out of pg_global tablespace")));
17057
17058 /*
17059 * Must have CREATE rights on the new tablespace, unless it is the
17060 * database default tablespace (which all users implicitly have CREATE
17061 * rights on).
17062 */
17063 if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
17064 {
17065 AclResult aclresult;
17066
17067 aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
17068 ACL_CREATE);
17069 if (aclresult != ACLCHECK_OK)
17070 aclcheck_error(aclresult, OBJECT_TABLESPACE,
17071 get_tablespace_name(new_tablespaceoid));
17072 }
17073
17074 /*
17075 * Now that the checks are done, check if we should set either to
17076 * InvalidOid because it is our database's default tablespace.
17077 */
17078 if (orig_tablespaceoid == MyDatabaseTableSpace)
17079 orig_tablespaceoid = InvalidOid;
17080
17081 if (new_tablespaceoid == MyDatabaseTableSpace)
17082 new_tablespaceoid = InvalidOid;
17083
17084 /* no-op */
17085 if (orig_tablespaceoid == new_tablespaceoid)
17086 return new_tablespaceoid;
17087
17088 /*
17089 * Walk the list of objects in the tablespace and move them. This will
17090 * only find objects in our database, of course.
17091 */
17092 ScanKeyInit(&key[0],
17093 Anum_pg_class_reltablespace,
17094 BTEqualStrategyNumber, F_OIDEQ,
17095 ObjectIdGetDatum(orig_tablespaceoid));
17096
17097 rel = table_open(RelationRelationId, AccessShareLock);
17098 scan = table_beginscan_catalog(rel, 1, key);
17099 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17100 {
17101 Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
17102 Oid relOid = relForm->oid;
17103
17104 /*
17105 * Do not move objects in pg_catalog as part of this, if an admin
17106 * really wishes to do so, they can issue the individual ALTER
17107 * commands directly.
17108 *
17109 * Also, explicitly avoid any shared tables, temp tables, or TOAST
17110 * (TOAST will be moved with the main table).
17111 */
17112 if (IsCatalogNamespace(relForm->relnamespace) ||
17113 relForm->relisshared ||
17114 isAnyTempNamespace(relForm->relnamespace) ||
17115 IsToastNamespace(relForm->relnamespace))
17116 continue;
17117
17118 /* Only move the object type requested */
17119 if ((stmt->objtype == OBJECT_TABLE &&
17120 relForm->relkind != RELKIND_RELATION &&
17121 relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17122 (stmt->objtype == OBJECT_INDEX &&
17123 relForm->relkind != RELKIND_INDEX &&
17124 relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17125 (stmt->objtype == OBJECT_MATVIEW &&
17126 relForm->relkind != RELKIND_MATVIEW))
17127 continue;
17128
17129 /* Check if we are only moving objects owned by certain roles */
17130 if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17131 continue;
17132
17133 /*
17134 * Handle permissions-checking here since we are locking the tables
17135 * and also to avoid doing a bunch of work only to fail part-way. Note
17136 * that permissions will also be checked by AlterTableInternal().
17137 *
17138 * Caller must be considered an owner on the table to move it.
17139 */
17140 if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
17141 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relOid)),
17142 NameStr(relForm->relname));
17143
17144 if (stmt->nowait &&
17145 !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
17146 ereport(ERROR,
17147 (errcode(ERRCODE_OBJECT_IN_USE),
17148 errmsg("aborting because lock on relation \"%s.%s\" is not available",
17149 get_namespace_name(relForm->relnamespace),
17150 NameStr(relForm->relname))));
17151 else
17152 LockRelationOid(relOid, AccessExclusiveLock);
17153
17154 /* Add to our list of objects to move */
17155 relations = lappend_oid(relations, relOid);
17156 }
17157
17158 table_endscan(scan);
17159 table_close(rel, AccessShareLock);
17160
17161 if (relations == NIL)
17162 ereport(NOTICE,
17163 (errcode(ERRCODE_NO_DATA_FOUND),
17164 errmsg("no matching relations in tablespace \"%s\" found",
17165 orig_tablespaceoid == InvalidOid ? "(database default)" :
17166 get_tablespace_name(orig_tablespaceoid))));
17167
17168 /* Everything is locked, loop through and move all of the relations. */
17169 foreach(l, relations)
17170 {
17171 List *cmds = NIL;
17172 AlterTableCmd *cmd = makeNode(AlterTableCmd);
17173
17174 cmd->subtype = AT_SetTableSpace;
17175 cmd->name = stmt->new_tablespacename;
17176
17177 cmds = lappend(cmds, cmd);
17178
17179 EventTriggerAlterTableStart((Node *) stmt);
17180 /* OID is set by AlterTableInternal */
17181 AlterTableInternal(lfirst_oid(l), cmds, false);
17182 EventTriggerAlterTableEnd();
17183 }
17184
17185 return new_tablespaceoid;
17186 }
17187
17188 static void
17189 index_copy_data(Relation rel, RelFileLocator newrlocator)
17190 {
17191 SMgrRelation dstrel;
17192
17193 /*
17194 * Since we copy the file directly without looking at the shared buffers,
17195 * we'd better first flush out any pages of the source relation that are
17196 * in shared buffers. We assume no new changes will be made while we are
17197 * holding exclusive lock on the rel.
17198 */
17199 FlushRelationBuffers(rel);
17200
17201 /*
17202 * Create and copy all forks of the relation, and schedule unlinking of
17203 * old physical files.
17204 *
17205 * NOTE: any conflict in relfilenumber value will be caught in
17206 * RelationCreateStorage().
17207 */
17208 dstrel = RelationCreateStorage(newrlocator, rel->rd_rel->relpersistence, true);
17209
17210 /* copy main fork */
17211 RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
17212 rel->rd_rel->relpersistence);
17213
17214 /* copy those extra forks that exist */
17215 for (ForkNumber forkNum = MAIN_FORKNUM + 1;
17216 forkNum <= MAX_FORKNUM; forkNum++)
17217 {
17218 if (smgrexists(RelationGetSmgr(rel), forkNum))
17219 {
17220 smgrcreate(dstrel, forkNum, false);
17221
17222 /*
17223 * WAL log creation if the relation is persistent, or this is the
17224 * init fork of an unlogged relation.
17225 */
17226 if (RelationIsPermanent(rel) ||
17227 (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
17228 forkNum == INIT_FORKNUM))
17229 log_smgrcreate(&newrlocator, forkNum);
17230 RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
17231 rel->rd_rel->relpersistence);
17232 }
17233 }
17234
17235 /* drop old relation, and close new one */
17236 RelationDropStorage(rel);
17237 smgrclose(dstrel);
17238 }
17239
17240 /*
17241 * ALTER TABLE ENABLE/DISABLE TRIGGER
17242 *
17243 * We just pass this off to trigger.c.
17244 */
17245 static void
17246 ATExecEnableDisableTrigger(Relation rel, const char *trigname,
17247 char fires_when, bool skip_system, bool recurse,
17248 LOCKMODE lockmode)
17249 {
17250 EnableDisableTrigger(rel, trigname, InvalidOid,
17251 fires_when, skip_system, recurse,
17252 lockmode);
17253
17254 InvokeObjectPostAlterHook(RelationRelationId,
17255 RelationGetRelid(rel), 0);
17256 }
17257
17258 /*
17259 * ALTER TABLE ENABLE/DISABLE RULE
17260 *
17261 * We just pass this off to rewriteDefine.c.
17262 */
17263 static void
17264 ATExecEnableDisableRule(Relation rel, const char *rulename,
17265 char fires_when, LOCKMODE lockmode)
17266 {
17267 EnableDisableRule(rel, rulename, fires_when);
17268
17269 InvokeObjectPostAlterHook(RelationRelationId,
17270 RelationGetRelid(rel), 0);
17271 }
17272
17273 /*
17274 * ALTER TABLE INHERIT
17275 *
17276 * Add a parent to the child's parents. This verifies that all the columns and
17277 * check constraints of the parent appear in the child and that they have the
17278 * same data types and expressions.
17279 */
17280 static void
17281 ATPrepAddInherit(Relation child_rel)
17282 {
17283 if (child_rel->rd_rel->reloftype)
17284 ereport(ERROR,
17285 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17286 errmsg("cannot change inheritance of typed table")));
17287
17288 if (child_rel->rd_rel->relispartition)
17289 ereport(ERROR,
17290 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17291 errmsg("cannot change inheritance of a partition")));
17292
17293 if (child_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17294 ereport(ERROR,
17295 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17296 errmsg("cannot change inheritance of partitioned table")));
17297 }
17298
17299 /*
17300 * Return the address of the new parent relation.
17301 */
17302 static ObjectAddress
17303 ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
17304 {
17305 Relation parent_rel;
17306 List *children;
17307 ObjectAddress address;
17308 const char *trigger_name;
17309
17310 /*
17311 * A self-exclusive lock is needed here. See the similar case in
17312 * MergeAttributes() for a full explanation.
17313 */
17314 parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
17315
17316 /*
17317 * Must be owner of both parent and child -- child was checked by
17318 * ATSimplePermissions call in ATPrepCmd
17319 */
17320 ATSimplePermissions(AT_AddInherit, parent_rel,
17321 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
17322
17323 /* Permanent rels cannot inherit from temporary ones */
17324 if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17325 child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
17326 ereport(ERROR,
17327 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17328 errmsg("cannot inherit from temporary relation \"%s\"",
17329 RelationGetRelationName(parent_rel))));
17330
17331 /* If parent rel is temp, it must belong to this session */
17332 if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17333 !parent_rel->rd_islocaltemp)
17334 ereport(ERROR,
17335 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17336 errmsg("cannot inherit from temporary relation of another session")));
17337
17338 /* Ditto for the child */
17339 if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17340 !child_rel->rd_islocaltemp)
17341 ereport(ERROR,
17342 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17343 errmsg("cannot inherit to temporary relation of another session")));
17344
17345 /* Prevent partitioned tables from becoming inheritance parents */
17346 if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17347 ereport(ERROR,
17348 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17349 errmsg("cannot inherit from partitioned table \"%s\"",
17350 parent->relname)));
17351
17352 /* Likewise for partitions */
17353 if (parent_rel->rd_rel->relispartition)
17354 ereport(ERROR,
17355 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17356 errmsg("cannot inherit from a partition")));
17357
17358 /*
17359 * Prevent circularity by seeing if proposed parent inherits from child.
17360 * (In particular, this disallows making a rel inherit from itself.)
17361 *
17362 * This is not completely bulletproof because of race conditions: in
17363 * multi-level inheritance trees, someone else could concurrently be
17364 * making another inheritance link that closes the loop but does not join
17365 * either of the rels we have locked. Preventing that seems to require
17366 * exclusive locks on the entire inheritance tree, which is a cure worse
17367 * than the disease. find_all_inheritors() will cope with circularity
17368 * anyway, so don't sweat it too much.
17369 *
17370 * We use weakest lock we can on child's children, namely AccessShareLock.
17371 */
17372 children = find_all_inheritors(RelationGetRelid(child_rel),
17373 AccessShareLock, NULL);
17374
17375 if (list_member_oid(children, RelationGetRelid(parent_rel)))
17376 ereport(ERROR,
17377 (errcode(ERRCODE_DUPLICATE_TABLE),
17378 errmsg("circular inheritance not allowed"),
17379 errdetail("\"%s\" is already a child of \"%s\".",
17380 parent->relname,
17381 RelationGetRelationName(child_rel))));
17382
17383 /*
17384 * If child_rel has row-level triggers with transition tables, we
17385 * currently don't allow it to become an inheritance child. See also
17386 * prohibitions in ATExecAttachPartition() and CreateTrigger().
17387 */
17388 trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
17389 if (trigger_name != NULL)
17390 ereport(ERROR,
17391 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17392 errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
17393 trigger_name, RelationGetRelationName(child_rel)),
17394 errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
17395
17396 /* OK to create inheritance */
17397 CreateInheritance(child_rel, parent_rel, false);
17398
17399 ObjectAddressSet(address, RelationRelationId,
17400 RelationGetRelid(parent_rel));
17401
17402 /* keep our lock on the parent relation until commit */
17403 table_close(parent_rel, NoLock);
17404
17405 return address;
17406 }
17407
17408 /*
17409 * CreateInheritance
17410 * Catalog manipulation portion of creating inheritance between a child
17411 * table and a parent table.
17412 *
17413 * Common to ATExecAddInherit() and ATExecAttachPartition().
17414 */
17415 static void
17416 CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
17417 {
17418 Relation catalogRelation;
17419 SysScanDesc scan;
17420 ScanKeyData key;
17421 HeapTuple inheritsTuple;
17422 int32 inhseqno;
17423
17424 /* Note: get RowExclusiveLock because we will write pg_inherits below. */
17425 catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
17426
17427 /*
17428 * Check for duplicates in the list of parents, and determine the highest
17429 * inhseqno already present; we'll use the next one for the new parent.
17430 * Also, if proposed child is a partition, it cannot already be
17431 * inheriting.
17432 *
17433 * Note: we do not reject the case where the child already inherits from
17434 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
17435 */
17436 ScanKeyInit(&key,
17437 Anum_pg_inherits_inhrelid,
17438 BTEqualStrategyNumber, F_OIDEQ,
17439 ObjectIdGetDatum(RelationGetRelid(child_rel)));
17440 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
17441 true, NULL, 1, &key);
17442
17443 /* inhseqno sequences start at 1 */
17444 inhseqno = 0;
17445 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
17446 {
17447 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
17448
17449 if (inh->inhparent == RelationGetRelid(parent_rel))
17450 ereport(ERROR,
17451 (errcode(ERRCODE_DUPLICATE_TABLE),
17452 errmsg("relation \"%s\" would be inherited from more than once",
17453 RelationGetRelationName(parent_rel))));
17454
17455 if (inh->inhseqno > inhseqno)
17456 inhseqno = inh->inhseqno;
17457 }
17458 systable_endscan(scan);
17459
17460 /* Match up the columns and bump attinhcount as needed */
17461 MergeAttributesIntoExisting(child_rel, parent_rel, ispartition);
17462
17463 /* Match up the constraints and bump coninhcount as needed */
17464 MergeConstraintsIntoExisting(child_rel, parent_rel);
17465
17466 /*
17467 * OK, it looks valid. Make the catalog entries that show inheritance.
17468 */
17469 StoreCatalogInheritance1(RelationGetRelid(child_rel),
17470 RelationGetRelid(parent_rel),
17471 inhseqno + 1,
17472 catalogRelation,
17473 parent_rel->rd_rel->relkind ==
17474 RELKIND_PARTITIONED_TABLE);
17475
17476 /* Now we're done with pg_inherits */
17477 table_close(catalogRelation, RowExclusiveLock);
17478 }
17479
17480 /*
17481 * Obtain the source-text form of the constraint expression for a check
17482 * constraint, given its pg_constraint tuple
17483 */
17484 static char *
17485 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
17486 {
17487 Form_pg_constraint con;
17488 bool isnull;
17489 Datum attr;
17490 Datum expr;
17491
17492 con = (Form_pg_constraint) GETSTRUCT(contup);
17493 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
17494 if (isnull)
17495 elog(ERROR, "null conbin for constraint %u", con->oid);
17496
17497 expr = DirectFunctionCall2(pg_get_expr, attr,
17498 ObjectIdGetDatum(con->conrelid));
17499 return TextDatumGetCString(expr);
17500 }
17501
17502 /*
17503 * Determine whether two check constraints are functionally equivalent
17504 *
17505 * The test we apply is to see whether they reverse-compile to the same
17506 * source string. This insulates us from issues like whether attributes
17507 * have the same physical column numbers in parent and child relations.
17508 *
17509 * Note that we ignore enforceability as there are cases where constraints
17510 * with differing enforceability are allowed.
17511 */
17512 static bool
17513 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
17514 {
17515 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
17516 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
17517
17518 if (acon->condeferrable != bcon->condeferrable ||
17519 acon->condeferred != bcon->condeferred ||
17520 strcmp(decompile_conbin(a, tupleDesc),
17521 decompile_conbin(b, tupleDesc)) != 0)
17522 return false;
17523 else
17524 return true;
17525 }
17526
17527 /*
17528 * Check columns in child table match up with columns in parent, and increment
17529 * their attinhcount.
17530 *
17531 * Called by CreateInheritance
17532 *
17533 * Currently all parent columns must be found in child. Missing columns are an
17534 * error. One day we might consider creating new columns like CREATE TABLE
17535 * does. However, that is widely unpopular --- in the common use case of
17536 * partitioned tables it's a foot-gun.
17537 *
17538 * The data type must match exactly. If the parent column is NOT NULL then
17539 * the child must be as well. Defaults are not compared, however.
17540 */
17541 static void
17542 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition)
17543 {
17544 Relation attrrel;
17545 TupleDesc parent_desc;
17546
17547 attrrel = table_open(AttributeRelationId, RowExclusiveLock);
17548 parent_desc = RelationGetDescr(parent_rel);
17549
17550 for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++)
17551 {
17552 Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1);
17553 char *parent_attname = NameStr(parent_att->attname);
17554 HeapTuple tuple;
17555
17556 /* Ignore dropped columns in the parent. */
17557 if (parent_att->attisdropped)
17558 continue;
17559
17560 /* Find same column in child (matching on column name). */
17561 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel), parent_attname);
17562 if (HeapTupleIsValid(tuple))
17563 {
17564 Form_pg_attribute child_att = (Form_pg_attribute) GETSTRUCT(tuple);
17565
17566 if (parent_att->atttypid != child_att->atttypid ||
17567 parent_att->atttypmod != child_att->atttypmod)
17568 ereport(ERROR,
17569 (errcode(ERRCODE_DATATYPE_MISMATCH),
17570 errmsg("child table \"%s\" has different type for column \"%s\"",
17571 RelationGetRelationName(child_rel), parent_attname)));
17572
17573 if (parent_att->attcollation != child_att->attcollation)
17574 ereport(ERROR,
17575 (errcode(ERRCODE_COLLATION_MISMATCH),
17576 errmsg("child table \"%s\" has different collation for column \"%s\"",
17577 RelationGetRelationName(child_rel), parent_attname)));
17578
17579 /*
17580 * If the parent has a not-null constraint that's not NO INHERIT,
17581 * make sure the child has one too.
17582 *
17583 * Other constraints are checked elsewhere.
17584 */
17585 if (parent_att->attnotnull && !child_att->attnotnull)
17586 {
17587 HeapTuple contup;
17588
17589 contup = findNotNullConstraintAttnum(RelationGetRelid(parent_rel),
17590 parent_att->attnum);
17591 if (HeapTupleIsValid(contup) &&
17592 !((Form_pg_constraint) GETSTRUCT(contup))->connoinherit)
17593 ereport(ERROR,
17594 errcode(ERRCODE_DATATYPE_MISMATCH),
17595 errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
17596 parent_attname, RelationGetRelationName(child_rel)));
17597 }
17598
17599 /*
17600 * Child column must be generated if and only if parent column is.
17601 */
17602 if (parent_att->attgenerated && !child_att->attgenerated)
17603 ereport(ERROR,
17604 (errcode(ERRCODE_DATATYPE_MISMATCH),
17605 errmsg("column \"%s\" in child table must be a generated column", parent_attname)));
17606 if (child_att->attgenerated && !parent_att->attgenerated)
17607 ereport(ERROR,
17608 (errcode(ERRCODE_DATATYPE_MISMATCH),
17609 errmsg("column \"%s\" in child table must not be a generated column", parent_attname)));
17610
17611 if (parent_att->attgenerated && child_att->attgenerated && child_att->attgenerated != parent_att->attgenerated)
17612 ereport(ERROR,
17613 (errcode(ERRCODE_DATATYPE_MISMATCH),
17614 errmsg("column \"%s\" inherits from generated column of different kind", parent_attname),
17615 errdetail("Parent column is %s, child column is %s.",
17616 parent_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
17617 child_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
17618
17619 /*
17620 * Regular inheritance children are independent enough not to
17621 * inherit identity columns. But partitions are integral part of
17622 * a partitioned table and inherit identity column.
17623 */
17624 if (ispartition)
17625 child_att->attidentity = parent_att->attidentity;
17626
17627 /*
17628 * OK, bump the child column's inheritance count. (If we fail
17629 * later on, this change will just roll back.)
17630 */
17631 if (pg_add_s16_overflow(child_att->attinhcount, 1,
17632 &child_att->attinhcount))
17633 ereport(ERROR,
17634 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
17635 errmsg("too many inheritance parents"));
17636
17637 /*
17638 * In case of partitions, we must enforce that value of attislocal
17639 * is same in all partitions. (Note: there are only inherited
17640 * attributes in partitions)
17641 */
17642 if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17643 {
17644 Assert(child_att->attinhcount == 1);
17645 child_att->attislocal = false;
17646 }
17647
17648 CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
17649 heap_freetuple(tuple);
17650 }
17651 else
17652 {
17653 ereport(ERROR,
17654 (errcode(ERRCODE_DATATYPE_MISMATCH),
17655 errmsg("child table is missing column \"%s\"", parent_attname)));
17656 }
17657 }
17658
17659 table_close(attrrel, RowExclusiveLock);
17660 }
17661
17662 /*
17663 * Check constraints in child table match up with constraints in parent,
17664 * and increment their coninhcount.
17665 *
17666 * Constraints that are marked ONLY in the parent are ignored.
17667 *
17668 * Called by CreateInheritance
17669 *
17670 * Currently all constraints in parent must be present in the child. One day we
17671 * may consider adding new constraints like CREATE TABLE does.
17672 *
17673 * XXX This is O(N^2) which may be an issue with tables with hundreds of
17674 * constraints. As long as tables have more like 10 constraints it shouldn't be
17675 * a problem though. Even 100 constraints ought not be the end of the world.
17676 *
17677 * XXX See MergeWithExistingConstraint too if you change this code.
17678 */
17679 static void
17680 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
17681 {
17682 Relation constraintrel;
17683 SysScanDesc parent_scan;
17684 ScanKeyData parent_key;
17685 HeapTuple parent_tuple;
17686 Oid parent_relid = RelationGetRelid(parent_rel);
17687 AttrMap *attmap;
17688
17689 constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
17690
17691 /* Outer loop scans through the parent's constraint definitions */
17692 ScanKeyInit(&parent_key,
17693 Anum_pg_constraint_conrelid,
17694 BTEqualStrategyNumber, F_OIDEQ,
17695 ObjectIdGetDatum(parent_relid));
17696 parent_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
17697 true, NULL, 1, &parent_key);
17698
17699 attmap = build_attrmap_by_name(RelationGetDescr(parent_rel),
17700 RelationGetDescr(child_rel),
17701 true);
17702
17703 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
17704 {
17705 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
17706 SysScanDesc child_scan;
17707 ScanKeyData child_key;
17708 HeapTuple child_tuple;
17709 AttrNumber parent_attno;
17710 bool found = false;
17711
17712 if (parent_con->contype != CONSTRAINT_CHECK &&
17713 parent_con->contype != CONSTRAINT_NOTNULL)
17714 continue;
17715
17716 /* if the parent's constraint is marked NO INHERIT, it's not inherited */
17717 if (parent_con->connoinherit)
17718 continue;
17719
17720 if (parent_con->contype == CONSTRAINT_NOTNULL)
17721 parent_attno = extractNotNullColumn(parent_tuple);
17722 else
17723 parent_attno = InvalidAttrNumber;
17724
17725 /* Search for a child constraint matching this one */
17726 ScanKeyInit(&child_key,
17727 Anum_pg_constraint_conrelid,
17728 BTEqualStrategyNumber, F_OIDEQ,
17729 ObjectIdGetDatum(RelationGetRelid(child_rel)));
17730 child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
17731 true, NULL, 1, &child_key);
17732
17733 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
17734 {
17735 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
17736 HeapTuple child_copy;
17737
17738 if (child_con->contype != parent_con->contype)
17739 continue;
17740
17741 /*
17742 * CHECK constraint are matched by constraint name, NOT NULL ones
17743 * by attribute number.
17744 */
17745 if (child_con->contype == CONSTRAINT_CHECK)
17746 {
17747 if (strcmp(NameStr(parent_con->conname),
17748 NameStr(child_con->conname)) != 0)
17749 continue;
17750 }
17751 else if (child_con->contype == CONSTRAINT_NOTNULL)
17752 {
17753 Form_pg_attribute parent_attr;
17754 Form_pg_attribute child_attr;
17755 AttrNumber child_attno;
17756
17757 parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
17758 child_attno = extractNotNullColumn(child_tuple);
17759 if (parent_attno != attmap->attnums[child_attno - 1])
17760 continue;
17761
17762 child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
17763 /* there shouldn't be constraints on dropped columns */
17764 if (parent_attr->attisdropped || child_attr->attisdropped)
17765 elog(ERROR, "found not-null constraint on dropped columns");
17766 }
17767
17768 if (child_con->contype == CONSTRAINT_CHECK &&
17769 !constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
17770 ereport(ERROR,
17771 (errcode(ERRCODE_DATATYPE_MISMATCH),
17772 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
17773 RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
17774
17775 /*
17776 * If the child constraint is "no inherit" then cannot merge
17777 */
17778 if (child_con->connoinherit)
17779 ereport(ERROR,
17780 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
17781 errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
17782 NameStr(child_con->conname), RelationGetRelationName(child_rel))));
17783
17784 /*
17785 * If the child constraint is "not valid" then cannot merge with a
17786 * valid parent constraint
17787 */
17788 if (parent_con->convalidated && child_con->conenforced &&
17789 !child_con->convalidated)
17790 ereport(ERROR,
17791 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
17792 errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
17793 NameStr(child_con->conname), RelationGetRelationName(child_rel))));
17794
17795 /*
17796 * A NOT ENFORCED child constraint cannot be merged with an
17797 * ENFORCED parent constraint. However, the reverse is allowed,
17798 * where the child constraint is ENFORCED.
17799 */
17800 if (parent_con->conenforced && !child_con->conenforced)
17801 ereport(ERROR,
17802 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
17803 errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
17804 NameStr(child_con->conname), RelationGetRelationName(child_rel))));
17805
17806 /*
17807 * OK, bump the child constraint's inheritance count. (If we fail
17808 * later on, this change will just roll back.)
17809 */
17810 child_copy = heap_copytuple(child_tuple);
17811 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
17812
17813 if (pg_add_s16_overflow(child_con->coninhcount, 1,
17814 &child_con->coninhcount))
17815 ereport(ERROR,
17816 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
17817 errmsg("too many inheritance parents"));
17818
17819 /*
17820 * In case of partitions, an inherited constraint must be
17821 * inherited only once since it cannot have multiple parents and
17822 * it is never considered local.
17823 */
17824 if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17825 {
17826 Assert(child_con->coninhcount == 1);
17827 child_con->conislocal = false;
17828 }
17829
17830 CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
17831 heap_freetuple(child_copy);
17832
17833 found = true;
17834 break;
17835 }
17836
17837 systable_endscan(child_scan);
17838
17839 if (!found)
17840 {
17841 if (parent_con->contype == CONSTRAINT_NOTNULL)
17842 ereport(ERROR,
17843 errcode(ERRCODE_DATATYPE_MISMATCH),
17844 errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
17845 get_attname(parent_relid,
17846 extractNotNullColumn(parent_tuple),
17847 false),
17848 RelationGetRelationName(child_rel)));
17849
17850 ereport(ERROR,
17851 (errcode(ERRCODE_DATATYPE_MISMATCH),
17852 errmsg("child table is missing constraint \"%s\"",
17853 NameStr(parent_con->conname))));
17854 }
17855 }
17856
17857 systable_endscan(parent_scan);
17858 table_close(constraintrel, RowExclusiveLock);
17859 }
17860
17861 /*
17862 * ALTER TABLE NO INHERIT
17863 *
17864 * Return value is the address of the relation that is no longer parent.
17865 */
17866 static ObjectAddress
17867 ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
17868 {
17869 ObjectAddress address;
17870 Relation parent_rel;
17871
17872 if (rel->rd_rel->relispartition)
17873 ereport(ERROR,
17874 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17875 errmsg("cannot change inheritance of a partition")));
17876
17877 /*
17878 * AccessShareLock on the parent is probably enough, seeing that DROP
17879 * TABLE doesn't lock parent tables at all. We need some lock since we'll
17880 * be inspecting the parent's schema.
17881 */
17882 parent_rel = table_openrv(parent, AccessShareLock);
17883
17884 /*
17885 * We don't bother to check ownership of the parent table --- ownership of
17886 * the child is presumed enough rights.
17887 */
17888
17889 /* Off to RemoveInheritance() where most of the work happens */
17890 RemoveInheritance(rel, parent_rel, false);
17891
17892 ObjectAddressSet(address, RelationRelationId,
17893 RelationGetRelid(parent_rel));
17894
17895 /* keep our lock on the parent relation until commit */
17896 table_close(parent_rel, NoLock);
17897
17898 return address;
17899 }
17900
17901 /*
17902 * MarkInheritDetached
17903 *
17904 * Set inhdetachpending for a partition, for ATExecDetachPartition
17905 * in concurrent mode. While at it, verify that no other partition is
17906 * already pending detach.
17907 */
17908 static void
17909 MarkInheritDetached(Relation child_rel, Relation parent_rel)
17910 {
17911 Relation catalogRelation;
17912 SysScanDesc scan;
17913 ScanKeyData key;
17914 HeapTuple inheritsTuple;
17915 bool found = false;
17916
17917 Assert(parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
17918
17919 /*
17920 * Find pg_inherits entries by inhparent. (We need to scan them all in
17921 * order to verify that no other partition is pending detach.)
17922 */
17923 catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
17924 ScanKeyInit(&key,
17925 Anum_pg_inherits_inhparent,
17926 BTEqualStrategyNumber, F_OIDEQ,
17927 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
17928 scan = systable_beginscan(catalogRelation, InheritsParentIndexId,
17929 true, NULL, 1, &key);
17930
17931 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
17932 {
17933 Form_pg_inherits inhForm;
17934
17935 inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
17936 if (inhForm->inhdetachpending)
17937 ereport(ERROR,
17938 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
17939 errmsg("partition \"%s\" already pending detach in partitioned table \"%s.%s\"",
17940 get_rel_name(inhForm->inhrelid),
17941 get_namespace_name(parent_rel->rd_rel->relnamespace),
17942 RelationGetRelationName(parent_rel)),
17943 errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
17944
17945 if (inhForm->inhrelid == RelationGetRelid(child_rel))
17946 {
17947 HeapTuple newtup;
17948
17949 newtup = heap_copytuple(inheritsTuple);
17950 ((Form_pg_inherits) GETSTRUCT(newtup))->inhdetachpending = true;
17951
17952 CatalogTupleUpdate(catalogRelation,
17953 &inheritsTuple->t_self,
17954 newtup);
17955 found = true;
17956 heap_freetuple(newtup);
17957 /* keep looking, to ensure we catch others pending detach */
17958 }
17959 }
17960
17961 /* Done */
17962 systable_endscan(scan);
17963 table_close(catalogRelation, RowExclusiveLock);
17964
17965 if (!found)
17966 ereport(ERROR,
17967 (errcode(ERRCODE_UNDEFINED_TABLE),
17968 errmsg("relation \"%s\" is not a partition of relation \"%s\"",
17969 RelationGetRelationName(child_rel),
17970 RelationGetRelationName(parent_rel))));
17971 }
17972
17973 /*
17974 * RemoveInheritance
17975 *
17976 * Drop a parent from the child's parents. This just adjusts the attinhcount
17977 * and attislocal of the columns and removes the pg_inherit and pg_depend
17978 * entries. expect_detached is passed down to DeleteInheritsTuple, q.v..
17979 *
17980 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
17981 * up attislocal stays true, which means if a child is ever removed from a
17982 * parent then its columns will never be automatically dropped which may
17983 * surprise. But at least we'll never surprise by dropping columns someone
17984 * isn't expecting to be dropped which would actually mean data loss.
17985 *
17986 * coninhcount and conislocal for inherited constraints are adjusted in
17987 * exactly the same way.
17988 *
17989 * Common to ATExecDropInherit() and ATExecDetachPartition().
17990 */
17991 static void
17992 RemoveInheritance(Relation child_rel, Relation parent_rel, bool expect_detached)
17993 {
17994 Relation catalogRelation;
17995 SysScanDesc scan;
17996 ScanKeyData key[3];
17997 HeapTuple attributeTuple,
17998 constraintTuple;
17999 AttrMap *attmap;
18000 List *connames;
18001 List *nncolumns;
18002 bool found;
18003 bool is_partitioning;
18004
18005 is_partitioning = (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
18006
18007 found = DeleteInheritsTuple(RelationGetRelid(child_rel),
18008 RelationGetRelid(parent_rel),
18009 expect_detached,
18010 RelationGetRelationName(child_rel));
18011 if (!found)
18012 {
18013 if (is_partitioning)
18014 ereport(ERROR,
18015 (errcode(ERRCODE_UNDEFINED_TABLE),
18016 errmsg("relation \"%s\" is not a partition of relation \"%s\"",
18017 RelationGetRelationName(child_rel),
18018 RelationGetRelationName(parent_rel))));
18019 else
18020 ereport(ERROR,
18021 (errcode(ERRCODE_UNDEFINED_TABLE),
18022 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
18023 RelationGetRelationName(parent_rel),
18024 RelationGetRelationName(child_rel))));
18025 }
18026
18027 /*
18028 * Search through child columns looking for ones matching parent rel
18029 */
18030 catalogRelation = table_open(AttributeRelationId, RowExclusiveLock);
18031 ScanKeyInit(&key[0],
18032 Anum_pg_attribute_attrelid,
18033 BTEqualStrategyNumber, F_OIDEQ,
18034 ObjectIdGetDatum(RelationGetRelid(child_rel)));
18035 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
18036 true, NULL, 1, key);
18037 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
18038 {
18039 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
18040
18041 /* Ignore if dropped or not inherited */
18042 if (att->attisdropped)
18043 continue;
18044 if (att->attinhcount <= 0)
18045 continue;
18046
18047 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
18048 NameStr(att->attname)))
18049 {
18050 /* Decrement inhcount and possibly set islocal to true */
18051 HeapTuple copyTuple = heap_copytuple(attributeTuple);
18052 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
18053
18054 copy_att->attinhcount--;
18055 if (copy_att->attinhcount == 0)
18056 copy_att->attislocal = true;
18057
18058 CatalogTupleUpdate(catalogRelation, &copyTuple->t_self, copyTuple);
18059 heap_freetuple(copyTuple);
18060 }
18061 }
18062 systable_endscan(scan);
18063 table_close(catalogRelation, RowExclusiveLock);
18064
18065 /*
18066 * Likewise, find inherited check and not-null constraints and disinherit
18067 * them. To do this, we first need a list of the names of the parent's
18068 * check constraints. (We cheat a bit by only checking for name matches,
18069 * assuming that the expressions will match.)
18070 *
18071 * For NOT NULL columns, we store column numbers to match, mapping them in
18072 * to the child rel's attribute numbers.
18073 */
18074 attmap = build_attrmap_by_name(RelationGetDescr(child_rel),
18075 RelationGetDescr(parent_rel),
18076 false);
18077
18078 catalogRelation = table_open(ConstraintRelationId, RowExclusiveLock);
18079 ScanKeyInit(&key[0],
18080 Anum_pg_constraint_conrelid,
18081 BTEqualStrategyNumber, F_OIDEQ,
18082 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
18083 scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18084 true, NULL, 1, key);
18085
18086 connames = NIL;
18087 nncolumns = NIL;
18088
18089 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18090 {
18091 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18092
18093 if (con->connoinherit)
18094 continue;
18095
18096 if (con->contype == CONSTRAINT_CHECK)
18097 connames = lappend(connames, pstrdup(NameStr(con->conname)));
18098 if (con->contype == CONSTRAINT_NOTNULL)
18099 {
18100 AttrNumber parent_attno = extractNotNullColumn(constraintTuple);
18101
18102 nncolumns = lappend_int(nncolumns, attmap->attnums[parent_attno - 1]);
18103 }
18104 }
18105
18106 systable_endscan(scan);
18107
18108 /* Now scan the child's constraints to find matches */
18109 ScanKeyInit(&key[0],
18110 Anum_pg_constraint_conrelid,
18111 BTEqualStrategyNumber, F_OIDEQ,
18112 ObjectIdGetDatum(RelationGetRelid(child_rel)));
18113 scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18114 true, NULL, 1, key);
18115
18116 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18117 {
18118 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18119 bool match = false;
18120
18121 /*
18122 * Match CHECK constraints by name, not-null constraints by column
18123 * number, and ignore all others.
18124 */
18125 if (con->contype == CONSTRAINT_CHECK)
18126 {
18127 foreach_ptr(char, chkname, connames)
18128 {
18129 if (con->contype == CONSTRAINT_CHECK &&
18130 strcmp(NameStr(con->conname), chkname) == 0)
18131 {
18132 match = true;
18133 connames = foreach_delete_current(connames, chkname);
18134 break;
18135 }
18136 }
18137 }
18138 else if (con->contype == CONSTRAINT_NOTNULL)
18139 {
18140 AttrNumber child_attno = extractNotNullColumn(constraintTuple);
18141
18142 foreach_int(prevattno, nncolumns)
18143 {
18144 if (prevattno == child_attno)
18145 {
18146 match = true;
18147 nncolumns = foreach_delete_current(nncolumns, prevattno);
18148 break;
18149 }
18150 }
18151 }
18152 else
18153 continue;
18154
18155 if (match)
18156 {
18157 /* Decrement inhcount and possibly set islocal to true */
18158 HeapTuple copyTuple = heap_copytuple(constraintTuple);
18159 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
18160
18161 if (copy_con->coninhcount <= 0) /* shouldn't happen */
18162 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
18163 RelationGetRelid(child_rel), NameStr(copy_con->conname));
18164
18165 copy_con->coninhcount--;
18166 if (copy_con->coninhcount == 0)
18167 copy_con->conislocal = true;
18168
18169 CatalogTupleUpdate(catalogRelation, &copyTuple->t_self, copyTuple);
18170 heap_freetuple(copyTuple);
18171 }
18172 }
18173
18174 /* We should have matched all constraints */
18175 if (connames != NIL || nncolumns != NIL)
18176 elog(ERROR, "%d unmatched constraints while removing inheritance from \"%s\" to \"%s\"",
18177 list_length(connames) + list_length(nncolumns),
18178 RelationGetRelationName(child_rel), RelationGetRelationName(parent_rel));
18179
18180 systable_endscan(scan);
18181 table_close(catalogRelation, RowExclusiveLock);
18182
18183 drop_parent_dependency(RelationGetRelid(child_rel),
18184 RelationRelationId,
18185 RelationGetRelid(parent_rel),
18186 child_dependency_type(is_partitioning));
18187
18188 /*
18189 * Post alter hook of this inherits. Since object_access_hook doesn't take
18190 * multiple object identifiers, we relay oid of parent relation using
18191 * auxiliary_id argument.
18192 */
18193 InvokeObjectPostAlterHookArg(InheritsRelationId,
18194 RelationGetRelid(child_rel), 0,
18195 RelationGetRelid(parent_rel), false);
18196 }
18197
18198 /*
18199 * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
18200 * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
18201 * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
18202 * be TypeRelationId). There's no convenient way to do this, so go trawling
18203 * through pg_depend.
18204 */
18205 static void
18206 drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
18207 DependencyType deptype)
18208 {
18209 Relation catalogRelation;
18210 SysScanDesc scan;
18211 ScanKeyData key[3];
18212 HeapTuple depTuple;
18213
18214 catalogRelation = table_open(DependRelationId, RowExclusiveLock);
18215
18216 ScanKeyInit(&key[0],
18217 Anum_pg_depend_classid,
18218 BTEqualStrategyNumber, F_OIDEQ,
18219 ObjectIdGetDatum(RelationRelationId));
18220 ScanKeyInit(&key[1],
18221 Anum_pg_depend_objid,
18222 BTEqualStrategyNumber, F_OIDEQ,
18223 ObjectIdGetDatum(relid));
18224 ScanKeyInit(&key[2],
18225 Anum_pg_depend_objsubid,
18226 BTEqualStrategyNumber, F_INT4EQ,
18227 Int32GetDatum(0));
18228
18229 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
18230 NULL, 3, key);
18231
18232 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
18233 {
18234 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
18235
18236 if (dep->refclassid == refclassid &&
18237 dep->refobjid == refobjid &&
18238 dep->refobjsubid == 0 &&
18239 dep->deptype == deptype)
18240 CatalogTupleDelete(catalogRelation, &depTuple->t_self);
18241 }
18242
18243 systable_endscan(scan);
18244 table_close(catalogRelation, RowExclusiveLock);
18245 }
18246
18247 /*
18248 * ALTER TABLE OF
18249 *
18250 * Attach a table to a composite type, as though it had been created with CREATE
18251 * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
18252 * subject table must not have inheritance parents. These restrictions ensure
18253 * that you cannot create a configuration impossible with CREATE TABLE OF alone.
18254 *
18255 * The address of the type is returned.
18256 */
18257 static ObjectAddress
18258 ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
18259 {
18260 Oid relid = RelationGetRelid(rel);
18261 Type typetuple;
18262 Form_pg_type typeform;
18263 Oid typeid;
18264 Relation inheritsRelation,
18265 relationRelation;
18266 SysScanDesc scan;
18267 ScanKeyData key;
18268 AttrNumber table_attno,
18269 type_attno;
18270 TupleDesc typeTupleDesc,
18271 tableTupleDesc;
18272 ObjectAddress tableobj,
18273 typeobj;
18274 HeapTuple classtuple;
18275 AclResult aclresult;
18276
18277 /* Validate the type. */
18278 typetuple = typenameType(NULL, ofTypename, NULL);
18279 check_of_type(typetuple);
18280 typeform = (Form_pg_type) GETSTRUCT(typetuple);
18281 typeid = typeform->oid;
18282
18283 aclresult = object_aclcheck(TypeRelationId, typeid, GetUserId(), ACL_USAGE);
18284 if (aclresult != ACLCHECK_OK)
18285 aclcheck_error_type(aclresult, typeid);
18286
18287 /* Fail if the table has any inheritance parents. */
18288 inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
18289 ScanKeyInit(&key,
18290 Anum_pg_inherits_inhrelid,
18291 BTEqualStrategyNumber, F_OIDEQ,
18292 ObjectIdGetDatum(relid));
18293 scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
18294 true, NULL, 1, &key);
18295 if (HeapTupleIsValid(systable_getnext(scan)))
18296 ereport(ERROR,
18297 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18298 errmsg("typed tables cannot inherit")));
18299 systable_endscan(scan);
18300 table_close(inheritsRelation, AccessShareLock);
18301
18302 /*
18303 * Check the tuple descriptors for compatibility. Unlike inheritance, we
18304 * require that the order also match. However, attnotnull need not match.
18305 */
18306 typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
18307 tableTupleDesc = RelationGetDescr(rel);
18308 table_attno = 1;
18309 for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
18310 {
18311 Form_pg_attribute type_attr,
18312 table_attr;
18313 const char *type_attname,
18314 *table_attname;
18315
18316 /* Get the next non-dropped type attribute. */
18317 type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
18318 if (type_attr->attisdropped)
18319 continue;
18320 type_attname = NameStr(type_attr->attname);
18321
18322 /* Get the next non-dropped table attribute. */
18323 do
18324 {
18325 if (table_attno > tableTupleDesc->natts)
18326 ereport(ERROR,
18327 (errcode(ERRCODE_DATATYPE_MISMATCH),
18328 errmsg("table is missing column \"%s\"",
18329 type_attname)));
18330 table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
18331 table_attno++;
18332 } while (table_attr->attisdropped);
18333 table_attname = NameStr(table_attr->attname);
18334
18335 /* Compare name. */
18336 if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
18337 ereport(ERROR,
18338 (errcode(ERRCODE_DATATYPE_MISMATCH),
18339 errmsg("table has column \"%s\" where type requires \"%s\"",
18340 table_attname, type_attname)));
18341
18342 /* Compare type. */
18343 if (table_attr->atttypid != type_attr->atttypid ||
18344 table_attr->atttypmod != type_attr->atttypmod ||
18345 table_attr->attcollation != type_attr->attcollation)
18346 ereport(ERROR,
18347 (errcode(ERRCODE_DATATYPE_MISMATCH),
18348 errmsg("table \"%s\" has different type for column \"%s\"",
18349 RelationGetRelationName(rel), type_attname)));
18350 }
18351 ReleaseTupleDesc(typeTupleDesc);
18352
18353 /* Any remaining columns at the end of the table had better be dropped. */
18354 for (; table_attno <= tableTupleDesc->natts; table_attno++)
18355 {
18356 Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
18357 table_attno - 1);
18358
18359 if (!table_attr->attisdropped)
18360 ereport(ERROR,
18361 (errcode(ERRCODE_DATATYPE_MISMATCH),
18362 errmsg("table has extra column \"%s\"",
18363 NameStr(table_attr->attname))));
18364 }
18365
18366 /* If the table was already typed, drop the existing dependency. */
18367 if (rel->rd_rel->reloftype)
18368 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
18369 DEPENDENCY_NORMAL);
18370
18371 /* Record a dependency on the new type. */
18372 tableobj.classId = RelationRelationId;
18373 tableobj.objectId = relid;
18374 tableobj.objectSubId = 0;
18375 typeobj.classId = TypeRelationId;
18376 typeobj.objectId = typeid;
18377 typeobj.objectSubId = 0;
18378 recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
18379
18380 /* Update pg_class.reloftype */
18381 relationRelation = table_open(RelationRelationId, RowExclusiveLock);
18382 classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18383 if (!HeapTupleIsValid(classtuple))
18384 elog(ERROR, "cache lookup failed for relation %u", relid);
18385 ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
18386 CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
18387
18388 InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
18389
18390 heap_freetuple(classtuple);
18391 table_close(relationRelation, RowExclusiveLock);
18392
18393 ReleaseSysCache(typetuple);
18394
18395 return typeobj;
18396 }
18397
18398 /*
18399 * ALTER TABLE NOT OF
18400 *
18401 * Detach a typed table from its originating type. Just clear reloftype and
18402 * remove the dependency.
18403 */
18404 static void
18405 ATExecDropOf(Relation rel, LOCKMODE lockmode)
18406 {
18407 Oid relid = RelationGetRelid(rel);
18408 Relation relationRelation;
18409 HeapTuple tuple;
18410
18411 if (!OidIsValid(rel->rd_rel->reloftype))
18412 ereport(ERROR,
18413 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18414 errmsg("\"%s\" is not a typed table",
18415 RelationGetRelationName(rel))));
18416
18417 /*
18418 * We don't bother to check ownership of the type --- ownership of the
18419 * table is presumed enough rights. No lock required on the type, either.
18420 */
18421
18422 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
18423 DEPENDENCY_NORMAL);
18424
18425 /* Clear pg_class.reloftype */
18426 relationRelation = table_open(RelationRelationId, RowExclusiveLock);
18427 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18428 if (!HeapTupleIsValid(tuple))
18429 elog(ERROR, "cache lookup failed for relation %u", relid);
18430 ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
18431 CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
18432
18433 InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
18434
18435 heap_freetuple(tuple);
18436 table_close(relationRelation, RowExclusiveLock);
18437 }
18438
18439 /*
18440 * relation_mark_replica_identity: Update a table's replica identity
18441 *
18442 * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
18443 * index. Otherwise, it must be InvalidOid.
18444 *
18445 * Caller had better hold an exclusive lock on the relation, as the results
18446 * of running two of these concurrently wouldn't be pretty.
18447 */
18448 static void
18449 relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
18450 bool is_internal)
18451 {
18452 Relation pg_index;
18453 Relation pg_class;
18454 HeapTuple pg_class_tuple;
18455 HeapTuple pg_index_tuple;
18456 Form_pg_class pg_class_form;
18457 Form_pg_index pg_index_form;
18458 ListCell *index;
18459
18460 /*
18461 * Check whether relreplident has changed, and update it if so.
18462 */
18463 pg_class = table_open(RelationRelationId, RowExclusiveLock);
18464 pg_class_tuple = SearchSysCacheCopy1(RELOID,
18465 ObjectIdGetDatum(RelationGetRelid(rel)));
18466 if (!HeapTupleIsValid(pg_class_tuple))
18467 elog(ERROR, "cache lookup failed for relation \"%s\"",
18468 RelationGetRelationName(rel));
18469 pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
18470 if (pg_class_form->relreplident != ri_type)
18471 {
18472 pg_class_form->relreplident = ri_type;
18473 CatalogTupleUpdate(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
18474 }
18475 table_close(pg_class, RowExclusiveLock);
18476 heap_freetuple(pg_class_tuple);
18477
18478 /*
18479 * Update the per-index indisreplident flags correctly.
18480 */
18481 pg_index = table_open(IndexRelationId, RowExclusiveLock);
18482 foreach(index, RelationGetIndexList(rel))
18483 {
18484 Oid thisIndexOid = lfirst_oid(index);
18485 bool dirty = false;
18486
18487 pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
18488 ObjectIdGetDatum(thisIndexOid));
18489 if (!HeapTupleIsValid(pg_index_tuple))
18490 elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
18491 pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
18492
18493 if (thisIndexOid == indexOid)
18494 {
18495 /* Set the bit if not already set. */
18496 if (!pg_index_form->indisreplident)
18497 {
18498 dirty = true;
18499 pg_index_form->indisreplident = true;
18500 }
18501 }
18502 else
18503 {
18504 /* Unset the bit if set. */
18505 if (pg_index_form->indisreplident)
18506 {
18507 dirty = true;
18508 pg_index_form->indisreplident = false;
18509 }
18510 }
18511
18512 if (dirty)
18513 {
18514 CatalogTupleUpdate(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
18515 InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
18516 InvalidOid, is_internal);
18517
18518 /*
18519 * Invalidate the relcache for the table, so that after we commit
18520 * all sessions will refresh the table's replica identity index
18521 * before attempting any UPDATE or DELETE on the table. (If we
18522 * changed the table's pg_class row above, then a relcache inval
18523 * is already queued due to that; but we might not have.)
18524 */
18525 CacheInvalidateRelcache(rel);
18526 }
18527 heap_freetuple(pg_index_tuple);
18528 }
18529
18530 table_close(pg_index, RowExclusiveLock);
18531 }
18532
18533 /*
18534 * ALTER TABLE <name> REPLICA IDENTITY ...
18535 */
18536 static void
18537 ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
18538 {
18539 Oid indexOid;
18540 Relation indexRel;
18541 int key;
18542
18543 if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
18544 {
18545 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
18546 return;
18547 }
18548 else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
18549 {
18550 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
18551 return;
18552 }
18553 else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
18554 {
18555 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
18556 return;
18557 }
18558 else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
18559 {
18560 /* fallthrough */ ;
18561 }
18562 else
18563 elog(ERROR, "unexpected identity type %u", stmt->identity_type);
18564
18565 /* Check that the index exists */
18566 indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
18567 if (!OidIsValid(indexOid))
18568 ereport(ERROR,
18569 (errcode(ERRCODE_UNDEFINED_OBJECT),
18570 errmsg("index \"%s\" for table \"%s\" does not exist",
18571 stmt->name, RelationGetRelationName(rel))));
18572
18573 indexRel = index_open(indexOid, ShareLock);
18574
18575 /* Check that the index is on the relation we're altering. */
18576 if (indexRel->rd_index == NULL ||
18577 indexRel->rd_index->indrelid != RelationGetRelid(rel))
18578 ereport(ERROR,
18579 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18580 errmsg("\"%s\" is not an index for table \"%s\"",
18581 RelationGetRelationName(indexRel),
18582 RelationGetRelationName(rel))));
18583
18584 /*
18585 * The AM must support uniqueness, and the index must in fact be unique.
18586 * If we have a WITHOUT OVERLAPS constraint (identified by uniqueness +
18587 * exclusion), we can use that too.
18588 */
18589 if ((!indexRel->rd_indam->amcanunique ||
18590 !indexRel->rd_index->indisunique) &&
18591 !(indexRel->rd_index->indisunique && indexRel->rd_index->indisexclusion))
18592 ereport(ERROR,
18593 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18594 errmsg("cannot use non-unique index \"%s\" as replica identity",
18595 RelationGetRelationName(indexRel))));
18596 /* Deferred indexes are not guaranteed to be always unique. */
18597 if (!indexRel->rd_index->indimmediate)
18598 ereport(ERROR,
18599 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18600 errmsg("cannot use non-immediate index \"%s\" as replica identity",
18601 RelationGetRelationName(indexRel))));
18602 /* Expression indexes aren't supported. */
18603 if (RelationGetIndexExpressions(indexRel) != NIL)
18604 ereport(ERROR,
18605 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18606 errmsg("cannot use expression index \"%s\" as replica identity",
18607 RelationGetRelationName(indexRel))));
18608 /* Predicate indexes aren't supported. */
18609 if (RelationGetIndexPredicate(indexRel) != NIL)
18610 ereport(ERROR,
18611 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18612 errmsg("cannot use partial index \"%s\" as replica identity",
18613 RelationGetRelationName(indexRel))));
18614
18615 /* Check index for nullable columns. */
18616 for (key = 0; key < IndexRelationGetNumberOfKeyAttributes(indexRel); key++)
18617 {
18618 int16 attno = indexRel->rd_index->indkey.values[key];
18619 Form_pg_attribute attr;
18620
18621 /*
18622 * Reject any other system columns. (Going forward, we'll disallow
18623 * indexes containing such columns in the first place, but they might
18624 * exist in older branches.)
18625 */
18626 if (attno <= 0)
18627 ereport(ERROR,
18628 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
18629 errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
18630 RelationGetRelationName(indexRel), attno)));
18631
18632 attr = TupleDescAttr(rel->rd_att, attno - 1);
18633 if (!attr->attnotnull)
18634 ereport(ERROR,
18635 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18636 errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
18637 RelationGetRelationName(indexRel),
18638 NameStr(attr->attname))));
18639 }
18640
18641 /* This index is suitable for use as a replica identity. Mark it. */
18642 relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
18643
18644 index_close(indexRel, NoLock);
18645 }
18646
18647 /*
18648 * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
18649 */
18650 static void
18651 ATExecSetRowSecurity(Relation rel, bool rls)
18652 {
18653 Relation pg_class;
18654 Oid relid;
18655 HeapTuple tuple;
18656
18657 relid = RelationGetRelid(rel);
18658
18659 /* Pull the record for this relation and update it */
18660 pg_class = table_open(RelationRelationId, RowExclusiveLock);
18661
18662 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18663
18664 if (!HeapTupleIsValid(tuple))
18665 elog(ERROR, "cache lookup failed for relation %u", relid);
18666
18667 ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = rls;
18668 CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
18669
18670 InvokeObjectPostAlterHook(RelationRelationId,
18671 RelationGetRelid(rel), 0);
18672
18673 table_close(pg_class, RowExclusiveLock);
18674 heap_freetuple(tuple);
18675 }
18676
18677 /*
18678 * ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
18679 */
18680 static void
18681 ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
18682 {
18683 Relation pg_class;
18684 Oid relid;
18685 HeapTuple tuple;
18686
18687 relid = RelationGetRelid(rel);
18688
18689 pg_class = table_open(RelationRelationId, RowExclusiveLock);
18690
18691 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18692
18693 if (!HeapTupleIsValid(tuple))
18694 elog(ERROR, "cache lookup failed for relation %u", relid);
18695
18696 ((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
18697 CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
18698
18699 InvokeObjectPostAlterHook(RelationRelationId,
18700 RelationGetRelid(rel), 0);
18701
18702 table_close(pg_class, RowExclusiveLock);
18703 heap_freetuple(tuple);
18704 }
18705
18706 /*
18707 * ALTER FOREIGN TABLE <name> OPTIONS (...)
18708 */
18709 static void
18710 ATExecGenericOptions(Relation rel, List *options)
18711 {
18712 Relation ftrel;
18713 ForeignServer *server;
18714 ForeignDataWrapper *fdw;
18715 HeapTuple tuple;
18716 bool isnull;
18717 Datum repl_val[Natts_pg_foreign_table];
18718 bool repl_null[Natts_pg_foreign_table];
18719 bool repl_repl[Natts_pg_foreign_table];
18720 Datum datum;
18721 Form_pg_foreign_table tableform;
18722
18723 if (options == NIL)
18724 return;
18725
18726 ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
18727
18728 tuple = SearchSysCacheCopy1(FOREIGNTABLEREL,
18729 ObjectIdGetDatum(rel->rd_id));
18730 if (!HeapTupleIsValid(tuple))
18731 ereport(ERROR,
18732 (errcode(ERRCODE_UNDEFINED_OBJECT),
18733 errmsg("foreign table \"%s\" does not exist",
18734 RelationGetRelationName(rel))));
18735 tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
18736 server = GetForeignServer(tableform->ftserver);
18737 fdw = GetForeignDataWrapper(server->fdwid);
18738
18739 memset(repl_val, 0, sizeof(repl_val));
18740 memset(repl_null, false, sizeof(repl_null));
18741 memset(repl_repl, false, sizeof(repl_repl));
18742
18743 /* Extract the current options */
18744 datum = SysCacheGetAttr(FOREIGNTABLEREL,
18745 tuple,
18746 Anum_pg_foreign_table_ftoptions,
18747 &isnull);
18748 if (isnull)
18749 datum = PointerGetDatum(NULL);
18750
18751 /* Transform the options */
18752 datum = transformGenericOptions(ForeignTableRelationId,
18753 datum,
18754 options,
18755 fdw->fdwvalidator);
18756
18757 if (PointerIsValid(DatumGetPointer(datum)))
18758 repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
18759 else
18760 repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
18761
18762 repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
18763
18764 /* Everything looks good - update the tuple */
18765
18766 tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
18767 repl_val, repl_null, repl_repl);
18768
18769 CatalogTupleUpdate(ftrel, &tuple->t_self, tuple);
18770
18771 /*
18772 * Invalidate relcache so that all sessions will refresh any cached plans
18773 * that might depend on the old options.
18774 */
18775 CacheInvalidateRelcache(rel);
18776
18777 InvokeObjectPostAlterHook(ForeignTableRelationId,
18778 RelationGetRelid(rel), 0);
18779
18780 table_close(ftrel, RowExclusiveLock);
18781
18782 heap_freetuple(tuple);
18783 }
18784
18785 /*
18786 * ALTER TABLE ALTER COLUMN SET COMPRESSION
18787 *
18788 * Return value is the address of the modified column
18789 */
18790 static ObjectAddress
18791 ATExecSetCompression(Relation rel,
18792 const char *column,
18793 Node *newValue,
18794 LOCKMODE lockmode)
18795 {
18796 Relation attrel;
18797 HeapTuple tuple;
18798 Form_pg_attribute atttableform;
18799 AttrNumber attnum;
18800 char *compression;
18801 char cmethod;
18802 ObjectAddress address;
18803
18804 compression = strVal(newValue);
18805
18806 attrel = table_open(AttributeRelationId, RowExclusiveLock);
18807
18808 /* copy the cache entry so we can scribble on it below */
18809 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), column);
18810 if (!HeapTupleIsValid(tuple))
18811 ereport(ERROR,
18812 (errcode(ERRCODE_UNDEFINED_COLUMN),
18813 errmsg("column \"%s\" of relation \"%s\" does not exist",
18814 column, RelationGetRelationName(rel))));
18815
18816 /* prevent them from altering a system attribute */
18817 atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
18818 attnum = atttableform->attnum;
18819 if (attnum <= 0)
18820 ereport(ERROR,
18821 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18822 errmsg("cannot alter system column \"%s\"", column)));
18823
18824 /*
18825 * Check that column type is compressible, then get the attribute
18826 * compression method code
18827 */
18828 cmethod = GetAttributeCompression(atttableform->atttypid, compression);
18829
18830 /* update pg_attribute entry */
18831 atttableform->attcompression = cmethod;
18832 CatalogTupleUpdate(attrel, &tuple->t_self, tuple);
18833
18834 InvokeObjectPostAlterHook(RelationRelationId,
18835 RelationGetRelid(rel),
18836 attnum);
18837
18838 /*
18839 * Apply the change to indexes as well (only for simple index columns,
18840 * matching behavior of index.c ConstructTupleDescriptor()).
18841 */
18842 SetIndexStorageProperties(rel, attrel, attnum,
18843 false, 0,
18844 true, cmethod,
18845 lockmode);
18846
18847 heap_freetuple(tuple);
18848
18849 table_close(attrel, RowExclusiveLock);
18850
18851 /* make changes visible */
18852 CommandCounterIncrement();
18853
18854 ObjectAddressSubSet(address, RelationRelationId,
18855 RelationGetRelid(rel), attnum);
18856 return address;
18857 }
18858
18859
18860 /*
18861 * Preparation phase for SET LOGGED/UNLOGGED
18862 *
18863 * This verifies that we're not trying to change a temp table. Also,
18864 * existing foreign key constraints are checked to avoid ending up with
18865 * permanent tables referencing unlogged tables.
18866 */
18867 static void
18868 ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel, bool toLogged)
18869 {
18870 Relation pg_constraint;
18871 HeapTuple tuple;
18872 SysScanDesc scan;
18873 ScanKeyData skey[1];
18874
18875 /*
18876 * Disallow changing status for a temp table. Also verify whether we can
18877 * get away with doing nothing; in such cases we don't need to run the
18878 * checks below, either.
18879 */
18880 switch (rel->rd_rel->relpersistence)
18881 {
18882 case RELPERSISTENCE_TEMP:
18883 ereport(ERROR,
18884 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
18885 errmsg("cannot change logged status of table \"%s\" because it is temporary",
18886 RelationGetRelationName(rel)),
18887 errtable(rel)));
18888 break;
18889 case RELPERSISTENCE_PERMANENT:
18890 if (toLogged)
18891 /* nothing to do */
18892 return;
18893 break;
18894 case RELPERSISTENCE_UNLOGGED:
18895 if (!toLogged)
18896 /* nothing to do */
18897 return;
18898 break;
18899 }
18900
18901 /*
18902 * Check that the table is not part of any publication when changing to
18903 * UNLOGGED, as UNLOGGED tables can't be published.
18904 */
18905 if (!toLogged &&
18906 GetRelationPublications(RelationGetRelid(rel)) != NIL)
18907 ereport(ERROR,
18908 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
18909 errmsg("cannot change table \"%s\" to unlogged because it is part of a publication",
18910 RelationGetRelationName(rel)),
18911 errdetail("Unlogged relations cannot be replicated.")));
18912
18913 /*
18914 * Check existing foreign key constraints to preserve the invariant that
18915 * permanent tables cannot reference unlogged ones. Self-referencing
18916 * foreign keys can safely be ignored.
18917 */
18918 pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
18919
18920 /*
18921 * Scan conrelid if changing to permanent, else confrelid. This also
18922 * determines whether a useful index exists.
18923 */
18924 ScanKeyInit(&skey[0],
18925 toLogged ? Anum_pg_constraint_conrelid :
18926 Anum_pg_constraint_confrelid,
18927 BTEqualStrategyNumber, F_OIDEQ,
18928 ObjectIdGetDatum(RelationGetRelid(rel)));
18929 scan = systable_beginscan(pg_constraint,
18930 toLogged ? ConstraintRelidTypidNameIndexId : InvalidOid,
18931 true, NULL, 1, skey);
18932
18933 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
18934 {
18935 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
18936
18937 if (con->contype == CONSTRAINT_FOREIGN)
18938 {
18939 Oid foreignrelid;
18940 Relation foreignrel;
18941
18942 /* the opposite end of what we used as scankey */
18943 foreignrelid = toLogged ? con->confrelid : con->conrelid;
18944
18945 /* ignore if self-referencing */
18946 if (RelationGetRelid(rel) == foreignrelid)
18947 continue;
18948
18949 foreignrel = relation_open(foreignrelid, AccessShareLock);
18950
18951 if (toLogged)
18952 {
18953 if (!RelationIsPermanent(foreignrel))
18954 ereport(ERROR,
18955 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
18956 errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
18957 RelationGetRelationName(rel),
18958 RelationGetRelationName(foreignrel)),
18959 errtableconstraint(rel, NameStr(con->conname))));
18960 }
18961 else
18962 {
18963 if (RelationIsPermanent(foreignrel))
18964 ereport(ERROR,
18965 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
18966 errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
18967 RelationGetRelationName(rel),
18968 RelationGetRelationName(foreignrel)),
18969 errtableconstraint(rel, NameStr(con->conname))));
18970 }
18971
18972 relation_close(foreignrel, AccessShareLock);
18973 }
18974 }
18975
18976 systable_endscan(scan);
18977
18978 table_close(pg_constraint, AccessShareLock);
18979
18980 /* force rewrite if necessary; see comment in ATRewriteTables */
18981 tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
18982 if (toLogged)
18983 tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
18984 else
18985 tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
18986 tab->chgPersistence = true;
18987 }
18988
18989 /*
18990 * Execute ALTER TABLE SET SCHEMA
18991 */
18992 ObjectAddress
18993 AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
18994 {
18995 Relation rel;
18996 Oid relid;
18997 Oid oldNspOid;
18998 Oid nspOid;
18999 RangeVar *newrv;
19000 ObjectAddresses *objsMoved;
19001 ObjectAddress myself;
19002
19003 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
19004 stmt->missing_ok ? RVR_MISSING_OK : 0,
19005 RangeVarCallbackForAlterRelation,
19006 stmt);
19007
19008 if (!OidIsValid(relid))
19009 {
19010 ereport(NOTICE,
19011 (errmsg("relation \"%s\" does not exist, skipping",
19012 stmt->relation->relname)));
19013 return InvalidObjectAddress;
19014 }
19015
19016 rel = relation_open(relid, NoLock);
19017
19018 oldNspOid = RelationGetNamespace(rel);
19019
19020 /* If it's an owned sequence, disallow moving it by itself. */
19021 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
19022 {
19023 Oid tableId;
19024 int32 colId;
19025
19026 if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
19027 sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
19028 ereport(ERROR,
19029 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19030 errmsg("cannot move an owned sequence into another schema"),
19031 errdetail("Sequence \"%s\" is linked to table \"%s\".",
19032 RelationGetRelationName(rel),
19033 get_rel_name(tableId))));
19034 }
19035
19036 /* Get and lock schema OID and check its permissions. */
19037 newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
19038 nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
19039
19040 /* common checks on switching namespaces */
19041 CheckSetNamespace(oldNspOid, nspOid);
19042
19043 objsMoved = new_object_addresses();
19044 AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
19045 free_object_addresses(objsMoved);
19046
19047 ObjectAddressSet(myself, RelationRelationId, relid);
19048
19049 if (oldschema)
19050 *oldschema = oldNspOid;
19051
19052 /* close rel, but keep lock until commit */
19053 relation_close(rel, NoLock);
19054
19055 return myself;
19056 }
19057
19058 /*
19059 * The guts of relocating a table or materialized view to another namespace:
19060 * besides moving the relation itself, its dependent objects are relocated to
19061 * the new schema.
19062 */
19063 void
19064 AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
19065 ObjectAddresses *objsMoved)
19066 {
19067 Relation classRel;
19068
19069 Assert(objsMoved != NULL);
19070
19071 /* OK, modify the pg_class row and pg_depend entry */
19072 classRel = table_open(RelationRelationId, RowExclusiveLock);
19073
19074 AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
19075 nspOid, true, objsMoved);
19076
19077 /* Fix the table's row type too, if it has one */
19078 if (OidIsValid(rel->rd_rel->reltype))
19079 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
19080 false, /* isImplicitArray */
19081 false, /* ignoreDependent */
19082 false, /* errorOnTableType */
19083 objsMoved);
19084
19085 /* Fix other dependent stuff */
19086 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
19087 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
19088 objsMoved, AccessExclusiveLock);
19089 AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
19090 false, objsMoved);
19091
19092 table_close(classRel, RowExclusiveLock);
19093 }
19094
19095 /*
19096 * The guts of relocating a relation to another namespace: fix the pg_class
19097 * entry, and the pg_depend entry if any. Caller must already have
19098 * opened and write-locked pg_class.
19099 */
19100 void
19101 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
19102 Oid oldNspOid, Oid newNspOid,
19103 bool hasDependEntry,
19104 ObjectAddresses *objsMoved)
19105 {
19106 HeapTuple classTup;
19107 Form_pg_class classForm;
19108 ObjectAddress thisobj;
19109 bool already_done = false;
19110
19111 /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19112 classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
19113 if (!HeapTupleIsValid(classTup))
19114 elog(ERROR, "cache lookup failed for relation %u", relOid);
19115 classForm = (Form_pg_class) GETSTRUCT(classTup);
19116
19117 Assert(classForm->relnamespace == oldNspOid);
19118
19119 thisobj.classId = RelationRelationId;
19120 thisobj.objectId = relOid;
19121 thisobj.objectSubId = 0;
19122
19123 /*
19124 * If the object has already been moved, don't move it again. If it's
19125 * already in the right place, don't move it, but still fire the object
19126 * access hook.
19127 */
19128 already_done = object_address_present(&thisobj, objsMoved);
19129 if (!already_done && oldNspOid != newNspOid)
19130 {
19131 ItemPointerData otid = classTup->t_self;
19132
19133 /* check for duplicate name (more friendly than unique-index failure) */
19134 if (get_relname_relid(NameStr(classForm->relname),
19135 newNspOid) != InvalidOid)
19136 ereport(ERROR,
19137 (errcode(ERRCODE_DUPLICATE_TABLE),
19138 errmsg("relation \"%s\" already exists in schema \"%s\"",
19139 NameStr(classForm->relname),
19140 get_namespace_name(newNspOid))));
19141
19142 /* classTup is a copy, so OK to scribble on */
19143 classForm->relnamespace = newNspOid;
19144
19145 CatalogTupleUpdate(classRel, &otid, classTup);
19146 UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
19147
19148
19149 /* Update dependency on schema if caller said so */
19150 if (hasDependEntry &&
19151 changeDependencyFor(RelationRelationId,
19152 relOid,
19153 NamespaceRelationId,
19154 oldNspOid,
19155 newNspOid) != 1)
19156 elog(ERROR, "could not change schema dependency for relation \"%s\"",
19157 NameStr(classForm->relname));
19158 }
19159 else
19160 UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
19161 if (!already_done)
19162 {
19163 add_exact_object_address(&thisobj, objsMoved);
19164
19165 InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
19166 }
19167
19168 heap_freetuple(classTup);
19169 }
19170
19171 /*
19172 * Move all indexes for the specified relation to another namespace.
19173 *
19174 * Note: we assume adequate permission checking was done by the caller,
19175 * and that the caller has a suitable lock on the owning relation.
19176 */
19177 static void
19178 AlterIndexNamespaces(Relation classRel, Relation rel,
19179 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
19180 {
19181 List *indexList;
19182 ListCell *l;
19183
19184 indexList = RelationGetIndexList(rel);
19185
19186 foreach(l, indexList)
19187 {
19188 Oid indexOid = lfirst_oid(l);
19189 ObjectAddress thisobj;
19190
19191 thisobj.classId = RelationRelationId;
19192 thisobj.objectId = indexOid;
19193 thisobj.objectSubId = 0;
19194
19195 /*
19196 * Note: currently, the index will not have its own dependency on the
19197 * namespace, so we don't need to do changeDependencyFor(). There's no
19198 * row type in pg_type, either.
19199 *
19200 * XXX this objsMoved test may be pointless -- surely we have a single
19201 * dependency link from a relation to each index?
19202 */
19203 if (!object_address_present(&thisobj, objsMoved))
19204 {
19205 AlterRelationNamespaceInternal(classRel, indexOid,
19206 oldNspOid, newNspOid,
19207 false, objsMoved);
19208 add_exact_object_address(&thisobj, objsMoved);
19209 }
19210 }
19211
19212 list_free(indexList);
19213 }
19214
19215 /*
19216 * Move all identity and SERIAL-column sequences of the specified relation to another
19217 * namespace.
19218 *
19219 * Note: we assume adequate permission checking was done by the caller,
19220 * and that the caller has a suitable lock on the owning relation.
19221 */
19222 static void
19223 AlterSeqNamespaces(Relation classRel, Relation rel,
19224 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
19225 LOCKMODE lockmode)
19226 {
19227 Relation depRel;
19228 SysScanDesc scan;
19229 ScanKeyData key[2];
19230 HeapTuple tup;
19231
19232 /*
19233 * SERIAL sequences are those having an auto dependency on one of the
19234 * table's columns (we don't care *which* column, exactly).
19235 */
19236 depRel = table_open(DependRelationId, AccessShareLock);
19237
19238 ScanKeyInit(&key[0],
19239 Anum_pg_depend_refclassid,
19240 BTEqualStrategyNumber, F_OIDEQ,
19241 ObjectIdGetDatum(RelationRelationId));
19242 ScanKeyInit(&key[1],
19243 Anum_pg_depend_refobjid,
19244 BTEqualStrategyNumber, F_OIDEQ,
19245 ObjectIdGetDatum(RelationGetRelid(rel)));
19246 /* we leave refobjsubid unspecified */
19247
19248 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
19249 NULL, 2, key);
19250
19251 while (HeapTupleIsValid(tup = systable_getnext(scan)))
19252 {
19253 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
19254 Relation seqRel;
19255
19256 /* skip dependencies other than auto dependencies on columns */
19257 if (depForm->refobjsubid == 0 ||
19258 depForm->classid != RelationRelationId ||
19259 depForm->objsubid != 0 ||
19260 !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
19261 continue;
19262
19263 /* Use relation_open just in case it's an index */
19264 seqRel = relation_open(depForm->objid, lockmode);
19265
19266 /* skip non-sequence relations */
19267 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
19268 {
19269 /* No need to keep the lock */
19270 relation_close(seqRel, lockmode);
19271 continue;
19272 }
19273
19274 /* Fix the pg_class and pg_depend entries */
19275 AlterRelationNamespaceInternal(classRel, depForm->objid,
19276 oldNspOid, newNspOid,
19277 true, objsMoved);
19278
19279 /*
19280 * Sequences used to have entries in pg_type, but no longer do. If we
19281 * ever re-instate that, we'll need to move the pg_type entry to the
19282 * new namespace, too (using AlterTypeNamespaceInternal).
19283 */
19284 Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
19285
19286 /* Now we can close it. Keep the lock till end of transaction. */
19287 relation_close(seqRel, NoLock);
19288 }
19289
19290 systable_endscan(scan);
19291
19292 relation_close(depRel, AccessShareLock);
19293 }
19294
19295
19296 /*
19297 * This code supports
19298 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
19299 *
19300 * Because we only support this for TEMP tables, it's sufficient to remember
19301 * the state in a backend-local data structure.
19302 */
19303
19304 /*
19305 * Register a newly-created relation's ON COMMIT action.
19306 */
19307 void
19308 register_on_commit_action(Oid relid, OnCommitAction action)
19309 {
19310 OnCommitItem *oc;
19311 MemoryContext oldcxt;
19312
19313 /*
19314 * We needn't bother registering the relation unless there is an ON COMMIT
19315 * action we need to take.
19316 */
19317 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
19318 return;
19319
19320 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
19321
19322 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
19323 oc->relid = relid;
19324 oc->oncommit = action;
19325 oc->creating_subid = GetCurrentSubTransactionId();
19326 oc->deleting_subid = InvalidSubTransactionId;
19327
19328 /*
19329 * We use lcons() here so that ON COMMIT actions are processed in reverse
19330 * order of registration. That might not be essential but it seems
19331 * reasonable.
19332 */
19333 on_commits = lcons(oc, on_commits);
19334
19335 MemoryContextSwitchTo(oldcxt);
19336 }
19337
19338 /*
19339 * Unregister any ON COMMIT action when a relation is deleted.
19340 *
19341 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
19342 */
19343 void
19344 remove_on_commit_action(Oid relid)
19345 {
19346 ListCell *l;
19347
19348 foreach(l, on_commits)
19349 {
19350 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19351
19352 if (oc->relid == relid)
19353 {
19354 oc->deleting_subid = GetCurrentSubTransactionId();
19355 break;
19356 }
19357 }
19358 }
19359
19360 /*
19361 * Perform ON COMMIT actions.
19362 *
19363 * This is invoked just before actually committing, since it's possible
19364 * to encounter errors.
19365 */
19366 void
19367 PreCommit_on_commit_actions(void)
19368 {
19369 ListCell *l;
19370 List *oids_to_truncate = NIL;
19371 List *oids_to_drop = NIL;
19372
19373 foreach(l, on_commits)
19374 {
19375 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19376
19377 /* Ignore entry if already dropped in this xact */
19378 if (oc->deleting_subid != InvalidSubTransactionId)
19379 continue;
19380
19381 switch (oc->oncommit)
19382 {
19383 case ONCOMMIT_NOOP:
19384 case ONCOMMIT_PRESERVE_ROWS:
19385 /* Do nothing (there shouldn't be such entries, actually) */
19386 break;
19387 case ONCOMMIT_DELETE_ROWS:
19388
19389 /*
19390 * If this transaction hasn't accessed any temporary
19391 * relations, we can skip truncating ON COMMIT DELETE ROWS
19392 * tables, as they must still be empty.
19393 */
19394 if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
19395 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
19396 break;
19397 case ONCOMMIT_DROP:
19398 oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
19399 break;
19400 }
19401 }
19402
19403 /*
19404 * Truncate relations before dropping so that all dependencies between
19405 * relations are removed after they are worked on. Doing it like this
19406 * might be a waste as it is possible that a relation being truncated will
19407 * be dropped anyway due to its parent being dropped, but this makes the
19408 * code more robust because of not having to re-check that the relation
19409 * exists at truncation time.
19410 */
19411 if (oids_to_truncate != NIL)
19412 heap_truncate(oids_to_truncate);
19413
19414 if (oids_to_drop != NIL)
19415 {
19416 ObjectAddresses *targetObjects = new_object_addresses();
19417
19418 foreach(l, oids_to_drop)
19419 {
19420 ObjectAddress object;
19421
19422 object.classId = RelationRelationId;
19423 object.objectId = lfirst_oid(l);
19424 object.objectSubId = 0;
19425
19426 Assert(!object_address_present(&object, targetObjects));
19427
19428 add_exact_object_address(&object, targetObjects);
19429 }
19430
19431 /*
19432 * Object deletion might involve toast table access (to clean up
19433 * toasted catalog entries), so ensure we have a valid snapshot.
19434 */
19435 PushActiveSnapshot(GetTransactionSnapshot());
19436
19437 /*
19438 * Since this is an automatic drop, rather than one directly initiated
19439 * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
19440 */
19441 performMultipleDeletions(targetObjects, DROP_CASCADE,
19442 PERFORM_DELETION_INTERNAL | PERFORM_DELETION_QUIETLY);
19443
19444 PopActiveSnapshot();
19445
19446 #ifdef USE_ASSERT_CHECKING
19447
19448 /*
19449 * Note that table deletion will call remove_on_commit_action, so the
19450 * entry should get marked as deleted.
19451 */
19452 foreach(l, on_commits)
19453 {
19454 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19455
19456 if (oc->oncommit != ONCOMMIT_DROP)
19457 continue;
19458
19459 Assert(oc->deleting_subid != InvalidSubTransactionId);
19460 }
19461 #endif
19462 }
19463 }
19464
19465 /*
19466 * Post-commit or post-abort cleanup for ON COMMIT management.
19467 *
19468 * All we do here is remove no-longer-needed OnCommitItem entries.
19469 *
19470 * During commit, remove entries that were deleted during this transaction;
19471 * during abort, remove those created during this transaction.
19472 */
19473 void
19474 AtEOXact_on_commit_actions(bool isCommit)
19475 {
19476 ListCell *cur_item;
19477
19478 foreach(cur_item, on_commits)
19479 {
19480 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19481
19482 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
19483 oc->creating_subid != InvalidSubTransactionId)
19484 {
19485 /* cur_item must be removed */
19486 on_commits = foreach_delete_current(on_commits, cur_item);
19487 pfree(oc);
19488 }
19489 else
19490 {
19491 /* cur_item must be preserved */
19492 oc->creating_subid = InvalidSubTransactionId;
19493 oc->deleting_subid = InvalidSubTransactionId;
19494 }
19495 }
19496 }
19497
19498 /*
19499 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
19500 *
19501 * During subabort, we can immediately remove entries created during this
19502 * subtransaction. During subcommit, just relabel entries marked during
19503 * this subtransaction as being the parent's responsibility.
19504 */
19505 void
19506 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
19507 SubTransactionId parentSubid)
19508 {
19509 ListCell *cur_item;
19510
19511 foreach(cur_item, on_commits)
19512 {
19513 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19514
19515 if (!isCommit && oc->creating_subid == mySubid)
19516 {
19517 /* cur_item must be removed */
19518 on_commits = foreach_delete_current(on_commits, cur_item);
19519 pfree(oc);
19520 }
19521 else
19522 {
19523 /* cur_item must be preserved */
19524 if (oc->creating_subid == mySubid)
19525 oc->creating_subid = parentSubid;
19526 if (oc->deleting_subid == mySubid)
19527 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
19528 }
19529 }
19530 }
19531
19532 /*
19533 * This is intended as a callback for RangeVarGetRelidExtended(). It allows
19534 * the relation to be locked only if (1) it's a plain or partitioned table,
19535 * materialized view, or TOAST table and (2) the current user is the owner (or
19536 * the superuser) or has been granted MAINTAIN. This meets the
19537 * permission-checking needs of CLUSTER, REINDEX TABLE, and REFRESH
19538 * MATERIALIZED VIEW; we expose it here so that it can be used by all.
19539 */
19540 void
19541 RangeVarCallbackMaintainsTable(const RangeVar *relation,
19542 Oid relId, Oid oldRelId, void *arg)
19543 {
19544 char relkind;
19545 AclResult aclresult;
19546
19547 /* Nothing to do if the relation was not found. */
19548 if (!OidIsValid(relId))
19549 return;
19550
19551 /*
19552 * If the relation does exist, check whether it's an index. But note that
19553 * the relation might have been dropped between the time we did the name
19554 * lookup and now. In that case, there's nothing to do.
19555 */
19556 relkind = get_rel_relkind(relId);
19557 if (!relkind)
19558 return;
19559 if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
19560 relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
19561 ereport(ERROR,
19562 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19563 errmsg("\"%s\" is not a table or materialized view", relation->relname)));
19564
19565 /* Check permissions */
19566 aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
19567 if (aclresult != ACLCHECK_OK)
19568 aclcheck_error(aclresult,
19569 get_relkind_objtype(get_rel_relkind(relId)),
19570 relation->relname);
19571 }
19572
19573 /*
19574 * Callback to RangeVarGetRelidExtended() for TRUNCATE processing.
19575 */
19576 static void
19577 RangeVarCallbackForTruncate(const RangeVar *relation,
19578 Oid relId, Oid oldRelId, void *arg)
19579 {
19580 HeapTuple tuple;
19581
19582 /* Nothing to do if the relation was not found. */
19583 if (!OidIsValid(relId))
19584 return;
19585
19586 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19587 if (!HeapTupleIsValid(tuple)) /* should not happen */
19588 elog(ERROR, "cache lookup failed for relation %u", relId);
19589
19590 truncate_check_rel(relId, (Form_pg_class) GETSTRUCT(tuple));
19591 truncate_check_perms(relId, (Form_pg_class) GETSTRUCT(tuple));
19592
19593 ReleaseSysCache(tuple);
19594 }
19595
19596 /*
19597 * Callback for RangeVarGetRelidExtended(). Checks that the current user is
19598 * the owner of the relation, or superuser.
19599 */
19600 void
19601 RangeVarCallbackOwnsRelation(const RangeVar *relation,
19602 Oid relId, Oid oldRelId, void *arg)
19603 {
19604 HeapTuple tuple;
19605
19606 /* Nothing to do if the relation was not found. */
19607 if (!OidIsValid(relId))
19608 return;
19609
19610 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19611 if (!HeapTupleIsValid(tuple)) /* should not happen */
19612 elog(ERROR, "cache lookup failed for relation %u", relId);
19613
19614 if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
19615 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relId)),
19616 relation->relname);
19617
19618 if (!allowSystemTableMods &&
19619 IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
19620 ereport(ERROR,
19621 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
19622 errmsg("permission denied: \"%s\" is a system catalog",
19623 relation->relname)));
19624
19625 ReleaseSysCache(tuple);
19626 }
19627
19628 /*
19629 * Common RangeVarGetRelid callback for rename, set schema, and alter table
19630 * processing.
19631 */
19632 static void
19633 RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
19634 void *arg)
19635 {
19636 Node *stmt = (Node *) arg;
19637 ObjectType reltype;
19638 HeapTuple tuple;
19639 Form_pg_class classform;
19640 AclResult aclresult;
19641 char relkind;
19642
19643 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
19644 if (!HeapTupleIsValid(tuple))
19645 return; /* concurrently dropped */
19646 classform = (Form_pg_class) GETSTRUCT(tuple);
19647 relkind = classform->relkind;
19648
19649 /* Must own relation. */
19650 if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
19651 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
19652
19653 /* No system table modifications unless explicitly allowed. */
19654 if (!allowSystemTableMods && IsSystemClass(relid, classform))
19655 ereport(ERROR,
19656 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
19657 errmsg("permission denied: \"%s\" is a system catalog",
19658 rv->relname)));
19659
19660 /*
19661 * Extract the specified relation type from the statement parse tree.
19662 *
19663 * Also, for ALTER .. RENAME, check permissions: the user must (still)
19664 * have CREATE rights on the containing namespace.
19665 */
19666 if (IsA(stmt, RenameStmt))
19667 {
19668 aclresult = object_aclcheck(NamespaceRelationId, classform->relnamespace,
19669 GetUserId(), ACL_CREATE);
19670 if (aclresult != ACLCHECK_OK)
19671 aclcheck_error(aclresult, OBJECT_SCHEMA,
19672 get_namespace_name(classform->relnamespace));
19673 reltype = ((RenameStmt *) stmt)->renameType;
19674 }
19675 else if (IsA(stmt, AlterObjectSchemaStmt))
19676 reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
19677
19678 else if (IsA(stmt, AlterTableStmt))
19679 reltype = ((AlterTableStmt *) stmt)->objtype;
19680 else
19681 {
19682 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
19683 reltype = OBJECT_TABLE; /* placate compiler */
19684 }
19685
19686 /*
19687 * For compatibility with prior releases, we allow ALTER TABLE to be used
19688 * with most other types of relations (but not composite types). We allow
19689 * similar flexibility for ALTER INDEX in the case of RENAME, but not
19690 * otherwise. Otherwise, the user must select the correct form of the
19691 * command for the relation at issue.
19692 */
19693 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
19694 ereport(ERROR,
19695 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19696 errmsg("\"%s\" is not a sequence", rv->relname)));
19697
19698 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
19699 ereport(ERROR,
19700 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19701 errmsg("\"%s\" is not a view", rv->relname)));
19702
19703 if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
19704 ereport(ERROR,
19705 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19706 errmsg("\"%s\" is not a materialized view", rv->relname)));
19707
19708 if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
19709 ereport(ERROR,
19710 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19711 errmsg("\"%s\" is not a foreign table", rv->relname)));
19712
19713 if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
19714 ereport(ERROR,
19715 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19716 errmsg("\"%s\" is not a composite type", rv->relname)));
19717
19718 if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX &&
19719 relkind != RELKIND_PARTITIONED_INDEX
19720 && !IsA(stmt, RenameStmt))
19721 ereport(ERROR,
19722 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19723 errmsg("\"%s\" is not an index", rv->relname)));
19724
19725 /*
19726 * Don't allow ALTER TABLE on composite types. We want people to use ALTER
19727 * TYPE for that.
19728 */
19729 if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
19730 ereport(ERROR,
19731 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19732 errmsg("\"%s\" is a composite type", rv->relname),
19733 /* translator: %s is an SQL ALTER command */
19734 errhint("Use %s instead.",
19735 "ALTER TYPE")));
19736
19737 /*
19738 * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
19739 * to a different schema, such as indexes and TOAST tables.
19740 */
19741 if (IsA(stmt, AlterObjectSchemaStmt))
19742 {
19743 if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX)
19744 ereport(ERROR,
19745 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19746 errmsg("cannot change schema of index \"%s\"",
19747 rv->relname),
19748 errhint("Change the schema of the table instead.")));
19749 else if (relkind == RELKIND_COMPOSITE_TYPE)
19750 ereport(ERROR,
19751 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19752 errmsg("cannot change schema of composite type \"%s\"",
19753 rv->relname),
19754 /* translator: %s is an SQL ALTER command */
19755 errhint("Use %s instead.",
19756 "ALTER TYPE")));
19757 else if (relkind == RELKIND_TOASTVALUE)
19758 ereport(ERROR,
19759 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19760 errmsg("cannot change schema of TOAST table \"%s\"",
19761 rv->relname),
19762 errhint("Change the schema of the table instead.")));
19763 }
19764
19765 ReleaseSysCache(tuple);
19766 }
19767
19768 /*
19769 * Transform any expressions present in the partition key
19770 *
19771 * Returns a transformed PartitionSpec.
19772 */
19773 static PartitionSpec *
19774 transformPartitionSpec(Relation rel, PartitionSpec *partspec)
19775 {
19776 PartitionSpec *newspec;
19777 ParseState *pstate;
19778 ParseNamespaceItem *nsitem;
19779 ListCell *l;
19780
19781 newspec = makeNode(PartitionSpec);
19782
19783 newspec->strategy = partspec->strategy;
19784 newspec->partParams = NIL;
19785 newspec->location = partspec->location;
19786
19787 /* Check valid number of columns for strategy */
19788 if (partspec->strategy == PARTITION_STRATEGY_LIST &&
19789 list_length(partspec->partParams) != 1)
19790 ereport(ERROR,
19791 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19792 errmsg("cannot use \"list\" partition strategy with more than one column")));
19793
19794 /*
19795 * Create a dummy ParseState and insert the target relation as its sole
19796 * rangetable entry. We need a ParseState for transformExpr.
19797 */
19798 pstate = make_parsestate(NULL);
19799 nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
19800 NULL, false, true);
19801 addNSItemToQuery(pstate, nsitem, true, true, true);
19802
19803 /* take care of any partition expressions */
19804 foreach(l, partspec->partParams)
19805 {
19806 PartitionElem *pelem = lfirst_node(PartitionElem, l);
19807
19808 if (pelem->expr)
19809 {
19810 /* Copy, to avoid scribbling on the input */
19811 pelem = copyObject(pelem);
19812
19813 /* Now do parse transformation of the expression */
19814 pelem->expr = transformExpr(pstate, pelem->expr,
19815 EXPR_KIND_PARTITION_EXPRESSION);
19816
19817 /* we have to fix its collations too */
19818 assign_expr_collations(pstate, pelem->expr);
19819 }
19820
19821 newspec->partParams = lappend(newspec->partParams, pelem);
19822 }
19823
19824 return newspec;
19825 }
19826
19827 /*
19828 * Compute per-partition-column information from a list of PartitionElems.
19829 * Expressions in the PartitionElems must be parse-analyzed already.
19830 */
19831 static void
19832 ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
19833 List **partexprs, Oid *partopclass, Oid *partcollation,
19834 PartitionStrategy strategy)
19835 {
19836 int attn;
19837 ListCell *lc;
19838 Oid am_oid;
19839
19840 attn = 0;
19841 foreach(lc, partParams)
19842 {
19843 PartitionElem *pelem = lfirst_node(PartitionElem, lc);
19844 Oid atttype;
19845 Oid attcollation;
19846
19847 if (pelem->name != NULL)
19848 {
19849 /* Simple attribute reference */
19850 HeapTuple atttuple;
19851 Form_pg_attribute attform;
19852
19853 atttuple = SearchSysCacheAttName(RelationGetRelid(rel),
19854 pelem->name);
19855 if (!HeapTupleIsValid(atttuple))
19856 ereport(ERROR,
19857 (errcode(ERRCODE_UNDEFINED_COLUMN),
19858 errmsg("column \"%s\" named in partition key does not exist",
19859 pelem->name),
19860 parser_errposition(pstate, pelem->location)));
19861 attform = (Form_pg_attribute) GETSTRUCT(atttuple);
19862
19863 if (attform->attnum <= 0)
19864 ereport(ERROR,
19865 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19866 errmsg("cannot use system column \"%s\" in partition key",
19867 pelem->name),
19868 parser_errposition(pstate, pelem->location)));
19869
19870 /*
19871 * Stored generated columns cannot work: They are computed after
19872 * BEFORE triggers, but partition routing is done before all
19873 * triggers. Maybe virtual generated columns could be made to
19874 * work, but then they would need to be handled as an expression
19875 * below.
19876 */
19877 if (attform->attgenerated)
19878 ereport(ERROR,
19879 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19880 errmsg("cannot use generated column in partition key"),
19881 errdetail("Column \"%s\" is a generated column.",
19882 pelem->name),
19883 parser_errposition(pstate, pelem->location)));
19884
19885 partattrs[attn] = attform->attnum;
19886 atttype = attform->atttypid;
19887 attcollation = attform->attcollation;
19888 ReleaseSysCache(atttuple);
19889 }
19890 else
19891 {
19892 /* Expression */
19893 Node *expr = pelem->expr;
19894 char partattname[16];
19895 Bitmapset *expr_attrs = NULL;
19896 int i;
19897
19898 Assert(expr != NULL);
19899 atttype = exprType(expr);
19900 attcollation = exprCollation(expr);
19901
19902 /*
19903 * The expression must be of a storable type (e.g., not RECORD).
19904 * The test is the same as for whether a table column is of a safe
19905 * type (which is why we needn't check for the non-expression
19906 * case).
19907 */
19908 snprintf(partattname, sizeof(partattname), "%d", attn + 1);
19909 CheckAttributeType(partattname,
19910 atttype, attcollation,
19911 NIL, CHKATYPE_IS_PARTKEY);
19912
19913 /*
19914 * Strip any top-level COLLATE clause. This ensures that we treat
19915 * "x COLLATE y" and "(x COLLATE y)" alike.
19916 */
19917 while (IsA(expr, CollateExpr))
19918 expr = (Node *) ((CollateExpr *) expr)->arg;
19919
19920 /*
19921 * Examine all the columns in the partition key expression. When
19922 * the whole-row reference is present, examine all the columns of
19923 * the partitioned table.
19924 */
19925 pull_varattnos(expr, 1, &expr_attrs);
19926 if (bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, expr_attrs))
19927 {
19928 expr_attrs = bms_add_range(expr_attrs,
19929 1 - FirstLowInvalidHeapAttributeNumber,
19930 RelationGetNumberOfAttributes(rel) - FirstLowInvalidHeapAttributeNumber);
19931 expr_attrs = bms_del_member(expr_attrs, 0 - FirstLowInvalidHeapAttributeNumber);
19932 }
19933
19934 i = -1;
19935 while ((i = bms_next_member(expr_attrs, i)) >= 0)
19936 {
19937 AttrNumber attno = i + FirstLowInvalidHeapAttributeNumber;
19938
19939 Assert(attno != 0);
19940
19941 /*
19942 * Cannot allow system column references, since that would
19943 * make partition routing impossible: their values won't be
19944 * known yet when we need to do that.
19945 */
19946 if (attno < 0)
19947 ereport(ERROR,
19948 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19949 errmsg("partition key expressions cannot contain system column references")));
19950
19951 /*
19952 * Stored generated columns cannot work: They are computed
19953 * after BEFORE triggers, but partition routing is done before
19954 * all triggers. Virtual generated columns could probably
19955 * work, but it would require more work elsewhere (for example
19956 * SET EXPRESSION would need to check whether the column is
19957 * used in partition keys). Seems safer to prohibit for now.
19958 */
19959 if (TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated)
19960 ereport(ERROR,
19961 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19962 errmsg("cannot use generated column in partition key"),
19963 errdetail("Column \"%s\" is a generated column.",
19964 get_attname(RelationGetRelid(rel), attno, false)),
19965 parser_errposition(pstate, pelem->location)));
19966 }
19967
19968 if (IsA(expr, Var) &&
19969 ((Var *) expr)->varattno > 0)
19970 {
19971
19972 /*
19973 * User wrote "(column)" or "(column COLLATE something)".
19974 * Treat it like simple attribute anyway.
19975 */
19976 partattrs[attn] = ((Var *) expr)->varattno;
19977 }
19978 else
19979 {
19980 partattrs[attn] = 0; /* marks the column as expression */
19981 *partexprs = lappend(*partexprs, expr);
19982
19983 /*
19984 * transformPartitionSpec() should have already rejected
19985 * subqueries, aggregates, window functions, and SRFs, based
19986 * on the EXPR_KIND_ for partition expressions.
19987 */
19988
19989 /*
19990 * Preprocess the expression before checking for mutability.
19991 * This is essential for the reasons described in
19992 * contain_mutable_functions_after_planning. However, we call
19993 * expression_planner for ourselves rather than using that
19994 * function, because if constant-folding reduces the
19995 * expression to a constant, we'd like to know that so we can
19996 * complain below.
19997 *
19998 * Like contain_mutable_functions_after_planning, assume that
19999 * expression_planner won't scribble on its input, so this
20000 * won't affect the partexprs entry we saved above.
20001 */
20002 expr = (Node *) expression_planner((Expr *) expr);
20003
20004 /*
20005 * Partition expressions cannot contain mutable functions,
20006 * because a given row must always map to the same partition
20007 * as long as there is no change in the partition boundary
20008 * structure.
20009 */
20010 if (contain_mutable_functions(expr))
20011 ereport(ERROR,
20012 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20013 errmsg("functions in partition key expression must be marked IMMUTABLE")));
20014
20015 /*
20016 * While it is not exactly *wrong* for a partition expression
20017 * to be a constant, it seems better to reject such keys.
20018 */
20019 if (IsA(expr, Const))
20020 ereport(ERROR,
20021 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20022 errmsg("cannot use constant expression as partition key")));
20023 }
20024 }
20025
20026 /*
20027 * Apply collation override if any
20028 */
20029 if (pelem->collation)
20030 attcollation = get_collation_oid(pelem->collation, false);
20031
20032 /*
20033 * Check we have a collation iff it's a collatable type. The only
20034 * expected failures here are (1) COLLATE applied to a noncollatable
20035 * type, or (2) partition expression had an unresolved collation. But
20036 * we might as well code this to be a complete consistency check.
20037 */
20038 if (type_is_collatable(atttype))
20039 {
20040 if (!OidIsValid(attcollation))
20041 ereport(ERROR,
20042 (errcode(ERRCODE_INDETERMINATE_COLLATION),
20043 errmsg("could not determine which collation to use for partition expression"),
20044 errhint("Use the COLLATE clause to set the collation explicitly.")));
20045 }
20046 else
20047 {
20048 if (OidIsValid(attcollation))
20049 ereport(ERROR,
20050 (errcode(ERRCODE_DATATYPE_MISMATCH),
20051 errmsg("collations are not supported by type %s",
20052 format_type_be(atttype))));
20053 }
20054
20055 partcollation[attn] = attcollation;
20056
20057 /*
20058 * Identify the appropriate operator class. For list and range
20059 * partitioning, we use a btree operator class; hash partitioning uses
20060 * a hash operator class.
20061 */
20062 if (strategy == PARTITION_STRATEGY_HASH)
20063 am_oid = HASH_AM_OID;
20064 else
20065 am_oid = BTREE_AM_OID;
20066
20067 if (!pelem->opclass)
20068 {
20069 partopclass[attn] = GetDefaultOpClass(atttype, am_oid);
20070
20071 if (!OidIsValid(partopclass[attn]))
20072 {
20073 if (strategy == PARTITION_STRATEGY_HASH)
20074 ereport(ERROR,
20075 (errcode(ERRCODE_UNDEFINED_OBJECT),
20076 errmsg("data type %s has no default operator class for access method \"%s\"",
20077 format_type_be(atttype), "hash"),
20078 errhint("You must specify a hash operator class or define a default hash operator class for the data type.")));
20079 else
20080 ereport(ERROR,
20081 (errcode(ERRCODE_UNDEFINED_OBJECT),
20082 errmsg("data type %s has no default operator class for access method \"%s\"",
20083 format_type_be(atttype), "btree"),
20084 errhint("You must specify a btree operator class or define a default btree operator class for the data type.")));
20085 }
20086 }
20087 else
20088 partopclass[attn] = ResolveOpClass(pelem->opclass,
20089 atttype,
20090 am_oid == HASH_AM_OID ? "hash" : "btree",
20091 am_oid);
20092
20093 attn++;
20094 }
20095 }
20096
20097 /*
20098 * PartConstraintImpliedByRelConstraint
20099 * Do scanrel's existing constraints imply the partition constraint?
20100 *
20101 * "Existing constraints" include its check constraints and column-level
20102 * not-null constraints. partConstraint describes the partition constraint,
20103 * in implicit-AND form.
20104 */
20105 bool
20106 PartConstraintImpliedByRelConstraint(Relation scanrel,
20107 List *partConstraint)
20108 {
20109 List *existConstraint = NIL;
20110 TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20111 int i;
20112
20113 if (constr && constr->has_not_null)
20114 {
20115 int natts = scanrel->rd_att->natts;
20116
20117 for (i = 1; i <= natts; i++)
20118 {
20119 CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
20120
20121 /* invalid not-null constraint must be ignored here */
20122 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20123 {
20124 Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
20125 NullTest *ntest = makeNode(NullTest);
20126
20127 ntest->arg = (Expr *) makeVar(1,
20128 i,
20129 wholeatt->atttypid,
20130 wholeatt->atttypmod,
20131 wholeatt->attcollation,
20132 0);
20133 ntest->nulltesttype = IS_NOT_NULL;
20134
20135 /*
20136 * argisrow=false is correct even for a composite column,
20137 * because attnotnull does not represent a SQL-spec IS NOT
20138 * NULL test in such a case, just IS DISTINCT FROM NULL.
20139 */
20140 ntest->argisrow = false;
20141 ntest->location = -1;
20142 existConstraint = lappend(existConstraint, ntest);
20143 }
20144 }
20145 }
20146
20147 return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
20148 }
20149
20150 /*
20151 * ConstraintImpliedByRelConstraint
20152 * Do scanrel's existing constraints imply the given constraint?
20153 *
20154 * testConstraint is the constraint to validate. provenConstraint is a
20155 * caller-provided list of conditions which this function may assume
20156 * to be true. Both provenConstraint and testConstraint must be in
20157 * implicit-AND form, must only contain immutable clauses, and must
20158 * contain only Vars with varno = 1.
20159 */
20160 bool
20161 ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
20162 {
20163 List *existConstraint = list_copy(provenConstraint);
20164 TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20165 int num_check,
20166 i;
20167
20168 num_check = (constr != NULL) ? constr->num_check : 0;
20169 for (i = 0; i < num_check; i++)
20170 {
20171 Node *cexpr;
20172
20173 /*
20174 * If this constraint hasn't been fully validated yet, we must ignore
20175 * it here.
20176 */
20177 if (!constr->check[i].ccvalid)
20178 continue;
20179
20180 /*
20181 * NOT ENFORCED constraints are always marked as invalid, which should
20182 * have been ignored.
20183 */
20184 Assert(constr->check[i].ccenforced);
20185
20186 cexpr = stringToNode(constr->check[i].ccbin);
20187
20188 /*
20189 * Run each expression through const-simplification and
20190 * canonicalization. It is necessary, because we will be comparing it
20191 * to similarly-processed partition constraint expressions, and may
20192 * fail to detect valid matches without this.
20193 */
20194 cexpr = eval_const_expressions(NULL, cexpr);
20195 cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
20196
20197 existConstraint = list_concat(existConstraint,
20198 make_ands_implicit((Expr *) cexpr));
20199 }
20200
20201 /*
20202 * Try to make the proof. Since we are comparing CHECK constraints, we
20203 * need to use weak implication, i.e., we assume existConstraint is
20204 * not-false and try to prove the same for testConstraint.
20205 *
20206 * Note that predicate_implied_by assumes its first argument is known
20207 * immutable. That should always be true for both NOT NULL and partition
20208 * constraints, so we don't test it here.
20209 */
20210 return predicate_implied_by(testConstraint, existConstraint, true);
20211 }
20212
20213 /*
20214 * QueuePartitionConstraintValidation
20215 *
20216 * Add an entry to wqueue to have the given partition constraint validated by
20217 * Phase 3, for the given relation, and all its children.
20218 *
20219 * We first verify whether the given constraint is implied by pre-existing
20220 * relation constraints; if it is, there's no need to scan the table to
20221 * validate, so don't queue in that case.
20222 */
20223 static void
20224 QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
20225 List *partConstraint,
20226 bool validate_default)
20227 {
20228 /*
20229 * Based on the table's existing constraints, determine whether or not we
20230 * may skip scanning the table.
20231 */
20232 if (PartConstraintImpliedByRelConstraint(scanrel, partConstraint))
20233 {
20234 if (!validate_default)
20235 ereport(DEBUG1,
20236 (errmsg_internal("partition constraint for table \"%s\" is implied by existing constraints",
20237 RelationGetRelationName(scanrel))));
20238 else
20239 ereport(DEBUG1,
20240 (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
20241 RelationGetRelationName(scanrel))));
20242 return;
20243 }
20244
20245 /*
20246 * Constraints proved insufficient. For plain relations, queue a
20247 * validation item now; for partitioned tables, recurse to process each
20248 * partition.
20249 */
20250 if (scanrel->rd_rel->relkind == RELKIND_RELATION)
20251 {
20252 AlteredTableInfo *tab;
20253
20254 /* Grab a work queue entry. */
20255 tab = ATGetQueueEntry(wqueue, scanrel);
20256 Assert(tab->partition_constraint == NULL);
20257 tab->partition_constraint = (Expr *) linitial(partConstraint);
20258 tab->validate_default = validate_default;
20259 }
20260 else if (scanrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
20261 {
20262 PartitionDesc partdesc = RelationGetPartitionDesc(scanrel, true);
20263 int i;
20264
20265 for (i = 0; i < partdesc->nparts; i++)
20266 {
20267 Relation part_rel;
20268 List *thisPartConstraint;
20269
20270 /*
20271 * This is the minimum lock we need to prevent deadlocks.
20272 */
20273 part_rel = table_open(partdesc->oids[i], AccessExclusiveLock);
20274
20275 /*
20276 * Adjust the constraint for scanrel so that it matches this
20277 * partition's attribute numbers.
20278 */
20279 thisPartConstraint =
20280 map_partition_varattnos(partConstraint, 1,
20281 part_rel, scanrel);
20282
20283 QueuePartitionConstraintValidation(wqueue, part_rel,
20284 thisPartConstraint,
20285 validate_default);
20286 table_close(part_rel, NoLock); /* keep lock till commit */
20287 }
20288 }
20289 }
20290
20291 /*
20292 * ALTER TABLE <name> ATTACH PARTITION <partition-name> FOR VALUES
20293 *
20294 * Return the address of the newly attached partition.
20295 */
20296 static ObjectAddress
20297 ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
20298 AlterTableUtilityContext *context)
20299 {
20300 Relation attachrel,
20301 catalog;
20302 List *attachrel_children;
20303 List *partConstraint;
20304 SysScanDesc scan;
20305 ScanKeyData skey;
20306 AttrNumber attno;
20307 int natts;
20308 TupleDesc tupleDesc;
20309 ObjectAddress address;
20310 const char *trigger_name;
20311 Oid defaultPartOid;
20312 List *partBoundConstraint;
20313 ParseState *pstate = make_parsestate(NULL);
20314
20315 pstate->p_sourcetext = context->queryString;
20316
20317 /*
20318 * We must lock the default partition if one exists, because attaching a
20319 * new partition will change its partition constraint.
20320 */
20321 defaultPartOid =
20322 get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
20323 if (OidIsValid(defaultPartOid))
20324 LockRelationOid(defaultPartOid, AccessExclusiveLock);
20325
20326 attachrel = table_openrv(cmd->name, AccessExclusiveLock);
20327
20328 /*
20329 * XXX I think it'd be a good idea to grab locks on all tables referenced
20330 * by FKs at this point also.
20331 */
20332
20333 /*
20334 * Must be owner of both parent and source table -- parent was checked by
20335 * ATSimplePermissions call in ATPrepCmd
20336 */
20337 ATSimplePermissions(AT_AttachPartition, attachrel,
20338 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
20339
20340 /* A partition can only have one parent */
20341 if (attachrel->rd_rel->relispartition)
20342 ereport(ERROR,
20343 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20344 errmsg("\"%s\" is already a partition",
20345 RelationGetRelationName(attachrel))));
20346
20347 if (OidIsValid(attachrel->rd_rel->reloftype))
20348 ereport(ERROR,
20349 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20350 errmsg("cannot attach a typed table as partition")));
20351
20352 /*
20353 * Table being attached should not already be part of inheritance; either
20354 * as a child table...
20355 */
20356 catalog = table_open(InheritsRelationId, AccessShareLock);
20357 ScanKeyInit(&skey,
20358 Anum_pg_inherits_inhrelid,
20359 BTEqualStrategyNumber, F_OIDEQ,
20360 ObjectIdGetDatum(RelationGetRelid(attachrel)));
20361 scan = systable_beginscan(catalog, InheritsRelidSeqnoIndexId, true,
20362 NULL, 1, &skey);
20363 if (HeapTupleIsValid(systable_getnext(scan)))
20364 ereport(ERROR,
20365 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20366 errmsg("cannot attach inheritance child as partition")));
20367 systable_endscan(scan);
20368
20369 /* ...or as a parent table (except the case when it is partitioned) */
20370 ScanKeyInit(&skey,
20371 Anum_pg_inherits_inhparent,
20372 BTEqualStrategyNumber, F_OIDEQ,
20373 ObjectIdGetDatum(RelationGetRelid(attachrel)));
20374 scan = systable_beginscan(catalog, InheritsParentIndexId, true, NULL,
20375 1, &skey);
20376 if (HeapTupleIsValid(systable_getnext(scan)) &&
20377 attachrel->rd_rel->relkind == RELKIND_RELATION)
20378 ereport(ERROR,
20379 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20380 errmsg("cannot attach inheritance parent as partition")));
20381 systable_endscan(scan);
20382 table_close(catalog, AccessShareLock);
20383
20384 /*
20385 * Prevent circularity by seeing if rel is a partition of attachrel. (In
20386 * particular, this disallows making a rel a partition of itself.)
20387 *
20388 * We do that by checking if rel is a member of the list of attachrel's
20389 * partitions provided the latter is partitioned at all. We want to avoid
20390 * having to construct this list again, so we request the strongest lock
20391 * on all partitions. We need the strongest lock, because we may decide
20392 * to scan them if we find out that the table being attached (or its leaf
20393 * partitions) may contain rows that violate the partition constraint. If
20394 * the table has a constraint that would prevent such rows, which by
20395 * definition is present in all the partitions, we need not scan the
20396 * table, nor its partitions. But we cannot risk a deadlock by taking a
20397 * weaker lock now and the stronger one only when needed.
20398 */
20399 attachrel_children = find_all_inheritors(RelationGetRelid(attachrel),
20400 AccessExclusiveLock, NULL);
20401 if (list_member_oid(attachrel_children, RelationGetRelid(rel)))
20402 ereport(ERROR,
20403 (errcode(ERRCODE_DUPLICATE_TABLE),
20404 errmsg("circular inheritance not allowed"),
20405 errdetail("\"%s\" is already a child of \"%s\".",
20406 RelationGetRelationName(rel),
20407 RelationGetRelationName(attachrel))));
20408
20409 /* If the parent is permanent, so must be all of its partitions. */
20410 if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
20411 attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
20412 ereport(ERROR,
20413 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20414 errmsg("cannot attach a temporary relation as partition of permanent relation \"%s\"",
20415 RelationGetRelationName(rel))));
20416
20417 /* Temp parent cannot have a partition that is itself not a temp */
20418 if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
20419 attachrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
20420 ereport(ERROR,
20421 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20422 errmsg("cannot attach a permanent relation as partition of temporary relation \"%s\"",
20423 RelationGetRelationName(rel))));
20424
20425 /* If the parent is temp, it must belong to this session */
20426 if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
20427 !rel->rd_islocaltemp)
20428 ereport(ERROR,
20429 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20430 errmsg("cannot attach as partition of temporary relation of another session")));
20431
20432 /* Ditto for the partition */
20433 if (attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
20434 !attachrel->rd_islocaltemp)
20435 ereport(ERROR,
20436 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20437 errmsg("cannot attach temporary relation of another session as partition")));
20438
20439 /*
20440 * Check if attachrel has any identity columns or any columns that aren't
20441 * in the parent.
20442 */
20443 tupleDesc = RelationGetDescr(attachrel);
20444 natts = tupleDesc->natts;
20445 for (attno = 1; attno <= natts; attno++)
20446 {
20447 Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
20448 char *attributeName = NameStr(attribute->attname);
20449
20450 /* Ignore dropped */
20451 if (attribute->attisdropped)
20452 continue;
20453
20454 if (attribute->attidentity)
20455 ereport(ERROR,
20456 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
20457 errmsg("table \"%s\" being attached contains an identity column \"%s\"",
20458 RelationGetRelationName(attachrel), attributeName),
20459 errdetail("The new partition may not contain an identity column."));
20460
20461 /* Try to find the column in parent (matching on column name) */
20462 if (!SearchSysCacheExists2(ATTNAME,
20463 ObjectIdGetDatum(RelationGetRelid(rel)),
20464 CStringGetDatum(attributeName)))
20465 ereport(ERROR,
20466 (errcode(ERRCODE_DATATYPE_MISMATCH),
20467 errmsg("table \"%s\" contains column \"%s\" not found in parent \"%s\"",
20468 RelationGetRelationName(attachrel), attributeName,
20469 RelationGetRelationName(rel)),
20470 errdetail("The new partition may contain only the columns present in parent.")));
20471 }
20472
20473 /*
20474 * If child_rel has row-level triggers with transition tables, we
20475 * currently don't allow it to become a partition. See also prohibitions
20476 * in ATExecAddInherit() and CreateTrigger().
20477 */
20478 trigger_name = FindTriggerIncompatibleWithInheritance(attachrel->trigdesc);
20479 if (trigger_name != NULL)
20480 ereport(ERROR,
20481 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
20482 errmsg("trigger \"%s\" prevents table \"%s\" from becoming a partition",
20483 trigger_name, RelationGetRelationName(attachrel)),
20484 errdetail("ROW triggers with transition tables are not supported on partitions.")));
20485
20486 /*
20487 * Check that the new partition's bound is valid and does not overlap any
20488 * of existing partitions of the parent - note that it does not return on
20489 * error.
20490 */
20491 check_new_partition_bound(RelationGetRelationName(attachrel), rel,
20492 cmd->bound, pstate);
20493
20494 /* OK to create inheritance. Rest of the checks performed there */
20495 CreateInheritance(attachrel, rel, true);
20496
20497 /* Update the pg_class entry. */
20498 StorePartitionBound(attachrel, rel, cmd->bound);
20499
20500 /* Ensure there exists a correct set of indexes in the partition. */
20501 AttachPartitionEnsureIndexes(wqueue, rel, attachrel);
20502
20503 /* and triggers */
20504 CloneRowTriggersToPartition(rel, attachrel);
20505
20506 /*
20507 * Clone foreign key constraints. Callee is responsible for setting up
20508 * for phase 3 constraint verification.
20509 */
20510 CloneForeignKeyConstraints(wqueue, rel, attachrel);
20511
20512 /*
20513 * Generate partition constraint from the partition bound specification.
20514 * If the parent itself is a partition, make sure to include its
20515 * constraint as well.
20516 */
20517 partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
20518
20519 /*
20520 * Use list_concat_copy() to avoid modifying partBoundConstraint in place,
20521 * since it's needed later to construct the constraint expression for
20522 * validating against the default partition, if any.
20523 */
20524 partConstraint = list_concat_copy(partBoundConstraint,
20525 RelationGetPartitionQual(rel));
20526
20527 /* Skip validation if there are no constraints to validate. */
20528 if (partConstraint)
20529 {
20530 /*
20531 * Run the partition quals through const-simplification similar to
20532 * check constraints. We skip canonicalize_qual, though, because
20533 * partition quals should be in canonical form already.
20534 */
20535 partConstraint =
20536 (List *) eval_const_expressions(NULL,
20537 (Node *) partConstraint);
20538
20539 /* XXX this sure looks wrong */
20540 partConstraint = list_make1(make_ands_explicit(partConstraint));
20541
20542 /*
20543 * Adjust the generated constraint to match this partition's attribute
20544 * numbers.
20545 */
20546 partConstraint = map_partition_varattnos(partConstraint, 1, attachrel,
20547 rel);
20548
20549 /* Validate partition constraints against the table being attached. */
20550 QueuePartitionConstraintValidation(wqueue, attachrel, partConstraint,
20551 false);
20552 }
20553
20554 /*
20555 * If we're attaching a partition other than the default partition and a
20556 * default one exists, then that partition's partition constraint changes,
20557 * so add an entry to the work queue to validate it, too. (We must not do
20558 * this when the partition being attached is the default one; we already
20559 * did it above!)
20560 */
20561 if (OidIsValid(defaultPartOid))
20562 {
20563 Relation defaultrel;
20564 List *defPartConstraint;
20565
20566 Assert(!cmd->bound->is_default);
20567
20568 /* we already hold a lock on the default partition */
20569 defaultrel = table_open(defaultPartOid, NoLock);
20570 defPartConstraint =
20571 get_proposed_default_constraint(partBoundConstraint);
20572
20573 /*
20574 * Map the Vars in the constraint expression from rel's attnos to
20575 * defaultrel's.
20576 */
20577 defPartConstraint =
20578 map_partition_varattnos(defPartConstraint,
20579 1, defaultrel, rel);
20580 QueuePartitionConstraintValidation(wqueue, defaultrel,
20581 defPartConstraint, true);
20582
20583 /* keep our lock until commit. */
20584 table_close(defaultrel, NoLock);
20585 }
20586
20587 ObjectAddressSet(address, RelationRelationId, RelationGetRelid(attachrel));
20588
20589 /*
20590 * If the partition we just attached is partitioned itself, invalidate
20591 * relcache for all descendent partitions too to ensure that their
20592 * rd_partcheck expression trees are rebuilt; partitions already locked at
20593 * the beginning of this function.
20594 */
20595 if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
20596 {
20597 ListCell *l;
20598
20599 foreach(l, attachrel_children)
20600 {
20601 CacheInvalidateRelcacheByRelid(lfirst_oid(l));
20602 }
20603 }
20604
20605 /* keep our lock until commit */
20606 table_close(attachrel, NoLock);
20607
20608 return address;
20609 }
20610
20611 /*
20612 * AttachPartitionEnsureIndexes
20613 * subroutine for ATExecAttachPartition to create/match indexes
20614 *
20615 * Enforce the indexing rule for partitioned tables during ALTER TABLE / ATTACH
20616 * PARTITION: every partition must have an index attached to each index on the
20617 * partitioned table.
20618 */
20619 static void
20620 AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
20621 {
20622 List *idxes;
20623 List *attachRelIdxs;
20624 Relation *attachrelIdxRels;
20625 IndexInfo **attachInfos;
20626 ListCell *cell;
20627 MemoryContext cxt;
20628 MemoryContext oldcxt;
20629
20630 cxt = AllocSetContextCreate(CurrentMemoryContext,
20631 "AttachPartitionEnsureIndexes",
20632 ALLOCSET_DEFAULT_SIZES);
20633 oldcxt = MemoryContextSwitchTo(cxt);
20634
20635 idxes = RelationGetIndexList(rel);
20636 attachRelIdxs = RelationGetIndexList(attachrel);
20637 attachrelIdxRels = palloc(sizeof(Relation) * list_length(attachRelIdxs));
20638 attachInfos = palloc(sizeof(IndexInfo *) * list_length(attachRelIdxs));
20639
20640 /* Build arrays of all existing indexes and their IndexInfos */
20641 foreach_oid(cldIdxId, attachRelIdxs)
20642 {
20643 int i = foreach_current_index(cldIdxId);
20644
20645 attachrelIdxRels[i] = index_open(cldIdxId, AccessShareLock);
20646 attachInfos[i] = BuildIndexInfo(attachrelIdxRels[i]);
20647 }
20648
20649 /*
20650 * If we're attaching a foreign table, we must fail if any of the indexes
20651 * is a constraint index; otherwise, there's nothing to do here. Do this
20652 * before starting work, to avoid wasting the effort of building a few
20653 * non-unique indexes before coming across a unique one.
20654 */
20655 if (attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
20656 {
20657 foreach(cell, idxes)
20658 {
20659 Oid idx = lfirst_oid(cell);
20660 Relation idxRel = index_open(idx, AccessShareLock);
20661
20662 if (idxRel->rd_index->indisunique ||
20663 idxRel->rd_index->indisprimary)
20664 ereport(ERROR,
20665 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20666 errmsg("cannot attach foreign table \"%s\" as partition of partitioned table \"%s\"",
20667 RelationGetRelationName(attachrel),
20668 RelationGetRelationName(rel)),
20669 errdetail("Partitioned table \"%s\" contains unique indexes.",
20670 RelationGetRelationName(rel))));
20671 index_close(idxRel, AccessShareLock);
20672 }
20673
20674 goto out;
20675 }
20676
20677 /*
20678 * For each index on the partitioned table, find a matching one in the
20679 * partition-to-be; if one is not found, create one.
20680 */
20681 foreach(cell, idxes)
20682 {
20683 Oid idx = lfirst_oid(cell);
20684 Relation idxRel = index_open(idx, AccessShareLock);
20685 IndexInfo *info;
20686 AttrMap *attmap;
20687 bool found = false;
20688 Oid constraintOid;
20689
20690 /*
20691 * Ignore indexes in the partitioned table other than partitioned
20692 * indexes.
20693 */
20694 if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
20695 {
20696 index_close(idxRel, AccessShareLock);
20697 continue;
20698 }
20699
20700 /* construct an indexinfo to compare existing indexes against */
20701 info = BuildIndexInfo(idxRel);
20702 attmap = build_attrmap_by_name(RelationGetDescr(attachrel),
20703 RelationGetDescr(rel),
20704 false);
20705 constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(rel), idx);
20706
20707 /*
20708 * Scan the list of existing indexes in the partition-to-be, and mark
20709 * the first matching, valid, unattached one we find, if any, as
20710 * partition of the parent index. If we find one, we're done.
20711 */
20712 for (int i = 0; i < list_length(attachRelIdxs); i++)
20713 {
20714 Oid cldIdxId = RelationGetRelid(attachrelIdxRels[i]);
20715 Oid cldConstrOid = InvalidOid;
20716
20717 /* does this index have a parent? if so, can't use it */
20718 if (attachrelIdxRels[i]->rd_rel->relispartition)
20719 continue;
20720
20721 /* If this index is invalid, can't use it */
20722 if (!attachrelIdxRels[i]->rd_index->indisvalid)
20723 continue;
20724
20725 if (CompareIndexInfo(attachInfos[i], info,
20726 attachrelIdxRels[i]->rd_indcollation,
20727 idxRel->rd_indcollation,
20728 attachrelIdxRels[i]->rd_opfamily,
20729 idxRel->rd_opfamily,
20730 attmap))
20731 {
20732 /*
20733 * If this index is being created in the parent because of a
20734 * constraint, then the child needs to have a constraint also,
20735 * so look for one. If there is no such constraint, this
20736 * index is no good, so keep looking.
20737 */
20738 if (OidIsValid(constraintOid))
20739 {
20740 cldConstrOid =
20741 get_relation_idx_constraint_oid(RelationGetRelid(attachrel),
20742 cldIdxId);
20743 /* no dice */
20744 if (!OidIsValid(cldConstrOid))
20745 continue;
20746
20747 /* Ensure they're both the same type of constraint */
20748 if (get_constraint_type(constraintOid) !=
20749 get_constraint_type(cldConstrOid))
20750 continue;
20751 }
20752
20753 /* bingo. */
20754 IndexSetParentIndex(attachrelIdxRels[i], idx);
20755 if (OidIsValid(constraintOid))
20756 ConstraintSetParentConstraint(cldConstrOid, constraintOid,
20757 RelationGetRelid(attachrel));
20758 found = true;
20759
20760 CommandCounterIncrement();
20761 break;
20762 }
20763 }
20764
20765 /*
20766 * If no suitable index was found in the partition-to-be, create one
20767 * now. Note that if this is a PK, not-null constraints must already
20768 * exist.
20769 */
20770 if (!found)
20771 {
20772 IndexStmt *stmt;
20773 Oid conOid;
20774
20775 stmt = generateClonedIndexStmt(NULL,
20776 idxRel, attmap,
20777 &conOid);
20778 DefineIndex(RelationGetRelid(attachrel), stmt, InvalidOid,
20779 RelationGetRelid(idxRel),
20780 conOid,
20781 -1,
20782 true, false, false, false, false);
20783 }
20784
20785 index_close(idxRel, AccessShareLock);
20786 }
20787
20788 out:
20789 /* Clean up. */
20790 for (int i = 0; i < list_length(attachRelIdxs); i++)
20791 index_close(attachrelIdxRels[i], AccessShareLock);
20792 MemoryContextSwitchTo(oldcxt);
20793 MemoryContextDelete(cxt);
20794 }
20795
20796 /*
20797 * CloneRowTriggersToPartition
20798 * subroutine for ATExecAttachPartition/DefineRelation to create row
20799 * triggers on partitions
20800 */
20801 static void
20802 CloneRowTriggersToPartition(Relation parent, Relation partition)
20803 {
20804 Relation pg_trigger;
20805 ScanKeyData key;
20806 SysScanDesc scan;
20807 HeapTuple tuple;
20808 MemoryContext perTupCxt;
20809
20810 ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
20811 F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
20812 pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
20813 scan = systable_beginscan(pg_trigger, TriggerRelidNameIndexId,
20814 true, NULL, 1, &key);
20815
20816 perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
20817 "clone trig", ALLOCSET_SMALL_SIZES);
20818
20819 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
20820 {
20821 Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
20822 CreateTrigStmt *trigStmt;
20823 Node *qual = NULL;
20824 Datum value;
20825 bool isnull;
20826 List *cols = NIL;
20827 List *trigargs = NIL;
20828 MemoryContext oldcxt;
20829
20830 /*
20831 * Ignore statement-level triggers; those are not cloned.
20832 */
20833 if (!TRIGGER_FOR_ROW(trigForm->tgtype))
20834 continue;
20835
20836 /*
20837 * Don't clone internal triggers, because the constraint cloning code
20838 * will.
20839 */
20840 if (trigForm->tgisinternal)
20841 continue;
20842
20843 /*
20844 * Complain if we find an unexpected trigger type.
20845 */
20846 if (!TRIGGER_FOR_BEFORE(trigForm->tgtype) &&
20847 !TRIGGER_FOR_AFTER(trigForm->tgtype))
20848 elog(ERROR, "unexpected trigger \"%s\" found",
20849 NameStr(trigForm->tgname));
20850
20851 /* Use short-lived context for CREATE TRIGGER */
20852 oldcxt = MemoryContextSwitchTo(perTupCxt);
20853
20854 /*
20855 * If there is a WHEN clause, generate a 'cooked' version of it that's
20856 * appropriate for the partition.
20857 */
20858 value = heap_getattr(tuple, Anum_pg_trigger_tgqual,
20859 RelationGetDescr(pg_trigger), &isnull);
20860 if (!isnull)
20861 {
20862 qual = stringToNode(TextDatumGetCString(value));
20863 qual = (Node *) map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
20864 partition, parent);
20865 qual = (Node *) map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
20866 partition, parent);
20867 }
20868
20869 /*
20870 * If there is a column list, transform it to a list of column names.
20871 * Note we don't need to map this list in any way ...
20872 */
20873 if (trigForm->tgattr.dim1 > 0)
20874 {
20875 int i;
20876
20877 for (i = 0; i < trigForm->tgattr.dim1; i++)
20878 {
20879 Form_pg_attribute col;
20880
20881 col = TupleDescAttr(parent->rd_att,
20882 trigForm->tgattr.values[i] - 1);
20883 cols = lappend(cols,
20884 makeString(pstrdup(NameStr(col->attname))));
20885 }
20886 }
20887
20888 /* Reconstruct trigger arguments list. */
20889 if (trigForm->tgnargs > 0)
20890 {
20891 char *p;
20892
20893 value = heap_getattr(tuple, Anum_pg_trigger_tgargs,
20894 RelationGetDescr(pg_trigger), &isnull);
20895 if (isnull)
20896 elog(ERROR, "tgargs is null for trigger \"%s\" in partition \"%s\"",
20897 NameStr(trigForm->tgname), RelationGetRelationName(partition));
20898
20899 p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
20900
20901 for (int i = 0; i < trigForm->tgnargs; i++)
20902 {
20903 trigargs = lappend(trigargs, makeString(pstrdup(p)));
20904 p += strlen(p) + 1;
20905 }
20906 }
20907
20908 trigStmt = makeNode(CreateTrigStmt);
20909 trigStmt->replace = false;
20910 trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
20911 trigStmt->trigname = NameStr(trigForm->tgname);
20912 trigStmt->relation = NULL;
20913 trigStmt->funcname = NULL; /* passed separately */
20914 trigStmt->args = trigargs;
20915 trigStmt->row = true;
20916 trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
20917 trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
20918 trigStmt->columns = cols;
20919 trigStmt->whenClause = NULL; /* passed separately */
20920 trigStmt->transitionRels = NIL; /* not supported at present */
20921 trigStmt->deferrable = trigForm->tgdeferrable;
20922 trigStmt->initdeferred = trigForm->tginitdeferred;
20923 trigStmt->constrrel = NULL; /* passed separately */
20924
20925 CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
20926 trigForm->tgconstrrelid, InvalidOid, InvalidOid,
20927 trigForm->tgfoid, trigForm->oid, qual,
20928 false, true, trigForm->tgenabled);
20929
20930 MemoryContextSwitchTo(oldcxt);
20931 MemoryContextReset(perTupCxt);
20932 }
20933
20934 MemoryContextDelete(perTupCxt);
20935
20936 systable_endscan(scan);
20937 table_close(pg_trigger, RowExclusiveLock);
20938 }
20939
20940 /*
20941 * ALTER TABLE DETACH PARTITION
20942 *
20943 * Return the address of the relation that is no longer a partition of rel.
20944 *
20945 * If concurrent mode is requested, we run in two transactions. A side-
20946 * effect is that this command cannot run in a multi-part ALTER TABLE.
20947 * Currently, that's enforced by the grammar.
20948 *
20949 * The strategy for concurrency is to first modify the partition's
20950 * pg_inherit catalog row to make it visible to everyone that the
20951 * partition is detached, lock the partition against writes, and commit
20952 * the transaction; anyone who requests the partition descriptor from
20953 * that point onwards has to ignore such a partition. In a second
20954 * transaction, we wait until all transactions that could have seen the
20955 * partition as attached are gone, then we remove the rest of partition
20956 * metadata (pg_inherits and pg_class.relpartbounds).
20957 */
20958 static ObjectAddress
20959 ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
20960 RangeVar *name, bool concurrent)
20961 {
20962 Relation partRel;
20963 ObjectAddress address;
20964 Oid defaultPartOid;
20965 PartitionDesc partdesc;
20966
20967 /*
20968 * We must lock the default partition, because detaching this partition
20969 * will change its partition constraint.
20970 */
20971 partdesc = RelationGetPartitionDesc(rel, true);
20972 defaultPartOid = get_default_oid_from_partdesc(partdesc);
20973 if (OidIsValid(defaultPartOid))
20974 {
20975 /*
20976 * Concurrent detaching when a default partition exists is not
20977 * supported. The main problem is that the default partition
20978 * constraint would change. And there's a definitional problem: what
20979 * should happen to the tuples that are being inserted that belong to
20980 * the partition being detached? Putting them on the partition being
20981 * detached would be wrong, since they'd become "lost" after the
20982 * detaching completes but we cannot put them in the default partition
20983 * either until we alter its partition constraint.
20984 *
20985 * I think we could solve this problem if we effected the constraint
20986 * change before committing the first transaction. But the lock would
20987 * have to remain AEL and it would cause concurrent query planning to
20988 * be blocked, so changing it that way would be even worse.
20989 */
20990 if (concurrent)
20991 ereport(ERROR,
20992 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
20993 errmsg("cannot detach partitions concurrently when a default partition exists")));
20994 LockRelationOid(defaultPartOid, AccessExclusiveLock);
20995 }
20996
20997 /*
20998 * In concurrent mode, the partition is locked with share-update-exclusive
20999 * in the first transaction. This allows concurrent transactions to be
21000 * doing DML to the partition.
21001 */
21002 partRel = table_openrv(name, concurrent ? ShareUpdateExclusiveLock :
21003 AccessExclusiveLock);
21004
21005 /*
21006 * Check inheritance conditions and either delete the pg_inherits row (in
21007 * non-concurrent mode) or just set the inhdetachpending flag.
21008 */
21009 if (!concurrent)
21010 RemoveInheritance(partRel, rel, false);
21011 else
21012 MarkInheritDetached(partRel, rel);
21013
21014 /*
21015 * Ensure that foreign keys still hold after this detach. This keeps
21016 * locks on the referencing tables, which prevents concurrent transactions
21017 * from adding rows that we wouldn't see. For this to work in concurrent
21018 * mode, it is critical that the partition appears as no longer attached
21019 * for the RI queries as soon as the first transaction commits.
21020 */
21021 ATDetachCheckNoForeignKeyRefs(partRel);
21022
21023 /*
21024 * Concurrent mode has to work harder; first we add a new constraint to
21025 * the partition that matches the partition constraint. Then we close our
21026 * existing transaction, and in a new one wait for all processes to catch
21027 * up on the catalog updates we've done so far; at that point we can
21028 * complete the operation.
21029 */
21030 if (concurrent)
21031 {
21032 Oid partrelid,
21033 parentrelid;
21034 LOCKTAG tag;
21035 char *parentrelname;
21036 char *partrelname;
21037
21038 /*
21039 * For strategies other than hash, add a constraint to the partition
21040 * being detached which supplants the partition constraint. For hash
21041 * we cannot do that, because the constraint would reference the
21042 * partitioned table OID, possibly causing problems later.
21043 */
21044 if (partdesc->boundinfo->strategy != PARTITION_STRATEGY_HASH)
21045 DetachAddConstraintIfNeeded(wqueue, partRel);
21046
21047 /*
21048 * We're almost done now; the only traces that remain are the
21049 * pg_inherits tuple and the partition's relpartbounds. Before we can
21050 * remove those, we need to wait until all transactions that know that
21051 * this is a partition are gone.
21052 */
21053
21054 /*
21055 * Remember relation OIDs to re-acquire them later; and relation names
21056 * too, for error messages if something is dropped in between.
21057 */
21058 partrelid = RelationGetRelid(partRel);
21059 parentrelid = RelationGetRelid(rel);
21060 parentrelname = MemoryContextStrdup(PortalContext,
21061 RelationGetRelationName(rel));
21062 partrelname = MemoryContextStrdup(PortalContext,
21063 RelationGetRelationName(partRel));
21064
21065 /* Invalidate relcache entries for the parent -- must be before close */
21066 CacheInvalidateRelcache(rel);
21067
21068 table_close(partRel, NoLock);
21069 table_close(rel, NoLock);
21070 tab->rel = NULL;
21071
21072 /* Make updated catalog entry visible */
21073 PopActiveSnapshot();
21074 CommitTransactionCommand();
21075
21076 StartTransactionCommand();
21077
21078 /*
21079 * Now wait. This ensures that all queries that were planned
21080 * including the partition are finished before we remove the rest of
21081 * catalog entries. We don't need or indeed want to acquire this
21082 * lock, though -- that would block later queries.
21083 *
21084 * We don't need to concern ourselves with waiting for a lock on the
21085 * partition itself, since we will acquire AccessExclusiveLock below.
21086 */
21087 SET_LOCKTAG_RELATION(tag, MyDatabaseId, parentrelid);
21088 WaitForLockersMultiple(list_make1(&tag), AccessExclusiveLock, false);
21089
21090 /*
21091 * Now acquire locks in both relations again. Note they may have been
21092 * removed in the meantime, so care is required.
21093 */
21094 rel = try_relation_open(parentrelid, ShareUpdateExclusiveLock);
21095 partRel = try_relation_open(partrelid, AccessExclusiveLock);
21096
21097 /* If the relations aren't there, something bad happened; bail out */
21098 if (rel == NULL)
21099 {
21100 if (partRel != NULL) /* shouldn't happen */
21101 elog(WARNING, "dangling partition \"%s\" remains, can't fix",
21102 partrelname);
21103 ereport(ERROR,
21104 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21105 errmsg("partitioned table \"%s\" was removed concurrently",
21106 parentrelname)));
21107 }
21108 if (partRel == NULL)
21109 ereport(ERROR,
21110 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21111 errmsg("partition \"%s\" was removed concurrently", partrelname)));
21112
21113 tab->rel = rel;
21114 }
21115
21116 /*
21117 * Detaching the partition might involve TOAST table access, so ensure we
21118 * have a valid snapshot.
21119 */
21120 PushActiveSnapshot(GetTransactionSnapshot());
21121
21122 /* Do the final part of detaching */
21123 DetachPartitionFinalize(rel, partRel, concurrent, defaultPartOid);
21124
21125 PopActiveSnapshot();
21126
21127 ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
21128
21129 /* keep our lock until commit */
21130 table_close(partRel, NoLock);
21131
21132 return address;
21133 }
21134
21135 /*
21136 * Second part of ALTER TABLE .. DETACH.
21137 *
21138 * This is separate so that it can be run independently when the second
21139 * transaction of the concurrent algorithm fails (crash or abort).
21140 */
21141 static void
21142 DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
21143 Oid defaultPartOid)
21144 {
21145 Relation classRel;
21146 List *fks;
21147 ListCell *cell;
21148 List *indexes;
21149 Datum new_val[Natts_pg_class];
21150 bool new_null[Natts_pg_class],
21151 new_repl[Natts_pg_class];
21152 HeapTuple tuple,
21153 newtuple;
21154 Relation trigrel = NULL;
21155 List *fkoids = NIL;
21156
21157 if (concurrent)
21158 {
21159 /*
21160 * We can remove the pg_inherits row now. (In the non-concurrent case,
21161 * this was already done).
21162 */
21163 RemoveInheritance(partRel, rel, true);
21164 }
21165
21166 /* Drop any triggers that were cloned on creation/attach. */
21167 DropClonedTriggersFromPartition(RelationGetRelid(partRel));
21168
21169 /*
21170 * Detach any foreign keys that are inherited. This includes creating
21171 * additional action triggers.
21172 */
21173 fks = copyObject(RelationGetFKeyList(partRel));
21174 if (fks != NIL)
21175 trigrel = table_open(TriggerRelationId, RowExclusiveLock);
21176
21177 /*
21178 * It's possible that the partition being detached has a foreign key that
21179 * references a partitioned table. When that happens, there are multiple
21180 * pg_constraint rows for the partition: one points to the partitioned
21181 * table itself, while the others point to each of its partitions. Only
21182 * the topmost one is to be considered here; the child constraints must be
21183 * left alone, because conceptually those aren't coming from our parent
21184 * partitioned table, but from this partition itself.
21185 *
21186 * We implement this by collecting all the constraint OIDs in a first scan
21187 * of the FK array, and skipping in the loop below those constraints whose
21188 * parents are listed here.
21189 */
21190 foreach_node(ForeignKeyCacheInfo, fk, fks)
21191 fkoids = lappend_oid(fkoids, fk->conoid);
21192
21193 foreach(cell, fks)
21194 {
21195 ForeignKeyCacheInfo *fk = lfirst(cell);
21196 HeapTuple contup;
21197 Form_pg_constraint conform;
21198
21199 contup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
21200 if (!HeapTupleIsValid(contup))
21201 elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
21202 conform = (Form_pg_constraint) GETSTRUCT(contup);
21203
21204 /*
21205 * Consider only inherited foreign keys, and only if their parents
21206 * aren't in the list.
21207 */
21208 if (conform->contype != CONSTRAINT_FOREIGN ||
21209 !OidIsValid(conform->conparentid) ||
21210 list_member_oid(fkoids, conform->conparentid))
21211 {
21212 ReleaseSysCache(contup);
21213 continue;
21214 }
21215
21216 /*
21217 * The constraint on this table must be marked no longer a child of
21218 * the parent's constraint, as do its check triggers.
21219 */
21220 ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
21221
21222 /*
21223 * Also, look up the partition's "check" triggers corresponding to the
21224 * ENFORCED constraint being detached and detach them from the parent
21225 * triggers. NOT ENFORCED constraints do not have these triggers;
21226 * therefore, this step is not needed.
21227 */
21228 if (fk->conenforced)
21229 {
21230 Oid insertTriggerOid,
21231 updateTriggerOid;
21232
21233 GetForeignKeyCheckTriggers(trigrel,
21234 fk->conoid, fk->confrelid, fk->conrelid,
21235 &insertTriggerOid, &updateTriggerOid);
21236 Assert(OidIsValid(insertTriggerOid));
21237 TriggerSetParentTrigger(trigrel, insertTriggerOid, InvalidOid,
21238 RelationGetRelid(partRel));
21239 Assert(OidIsValid(updateTriggerOid));
21240 TriggerSetParentTrigger(trigrel, updateTriggerOid, InvalidOid,
21241 RelationGetRelid(partRel));
21242 }
21243
21244 /*
21245 * Lastly, create the action triggers on the referenced table, using
21246 * addFkRecurseReferenced, which requires some elaborate setup (so put
21247 * it in a separate block). While at it, if the table is partitioned,
21248 * that function will recurse to create the pg_constraint rows and
21249 * action triggers for each partition.
21250 *
21251 * Note there's no need to do addFkConstraint() here, because the
21252 * pg_constraint row already exists.
21253 */
21254 {
21255 Constraint *fkconstraint;
21256 int numfks;
21257 AttrNumber conkey[INDEX_MAX_KEYS];
21258 AttrNumber confkey[INDEX_MAX_KEYS];
21259 Oid conpfeqop[INDEX_MAX_KEYS];
21260 Oid conppeqop[INDEX_MAX_KEYS];
21261 Oid conffeqop[INDEX_MAX_KEYS];
21262 int numfkdelsetcols;
21263 AttrNumber confdelsetcols[INDEX_MAX_KEYS];
21264 Relation refdRel;
21265
21266 DeconstructFkConstraintRow(contup,
21267 &numfks,
21268 conkey,
21269 confkey,
21270 conpfeqop,
21271 conppeqop,
21272 conffeqop,
21273 &numfkdelsetcols,
21274 confdelsetcols);
21275
21276 /* Create a synthetic node we'll use throughout */
21277 fkconstraint = makeNode(Constraint);
21278 fkconstraint->contype = CONSTRAINT_FOREIGN;
21279 fkconstraint->conname = pstrdup(NameStr(conform->conname));
21280 fkconstraint->deferrable = conform->condeferrable;
21281 fkconstraint->initdeferred = conform->condeferred;
21282 fkconstraint->is_enforced = conform->conenforced;
21283 fkconstraint->skip_validation = true;
21284 fkconstraint->initially_valid = conform->convalidated;
21285 /* a few irrelevant fields omitted here */
21286 fkconstraint->pktable = NULL;
21287 fkconstraint->fk_attrs = NIL;
21288 fkconstraint->pk_attrs = NIL;
21289 fkconstraint->fk_matchtype = conform->confmatchtype;
21290 fkconstraint->fk_upd_action = conform->confupdtype;
21291 fkconstraint->fk_del_action = conform->confdeltype;
21292 fkconstraint->fk_del_set_cols = NIL;
21293 fkconstraint->old_conpfeqop = NIL;
21294 fkconstraint->old_pktable_oid = InvalidOid;
21295 fkconstraint->location = -1;
21296
21297 /* set up colnames, used to generate the constraint name */
21298 for (int i = 0; i < numfks; i++)
21299 {
21300 Form_pg_attribute att;
21301
21302 att = TupleDescAttr(RelationGetDescr(partRel),
21303 conkey[i] - 1);
21304
21305 fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
21306 makeString(NameStr(att->attname)));
21307 }
21308
21309 refdRel = table_open(fk->confrelid, ShareRowExclusiveLock);
21310
21311 addFkRecurseReferenced(fkconstraint, partRel,
21312 refdRel,
21313 conform->conindid,
21314 fk->conoid,
21315 numfks,
21316 confkey,
21317 conkey,
21318 conpfeqop,
21319 conppeqop,
21320 conffeqop,
21321 numfkdelsetcols,
21322 confdelsetcols,
21323 true,
21324 InvalidOid, InvalidOid,
21325 conform->conperiod);
21326 table_close(refdRel, NoLock); /* keep lock till end of xact */
21327 }
21328
21329 ReleaseSysCache(contup);
21330 }
21331 list_free_deep(fks);
21332 if (trigrel)
21333 table_close(trigrel, RowExclusiveLock);
21334
21335 /*
21336 * Any sub-constraints that are in the referenced-side of a larger
21337 * constraint have to be removed. This partition is no longer part of the
21338 * key space of the constraint.
21339 */
21340 foreach(cell, GetParentedForeignKeyRefs(partRel))
21341 {
21342 Oid constrOid = lfirst_oid(cell);
21343 ObjectAddress constraint;
21344
21345 ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
21346 deleteDependencyRecordsForClass(ConstraintRelationId,
21347 constrOid,
21348 ConstraintRelationId,
21349 DEPENDENCY_INTERNAL);
21350 CommandCounterIncrement();
21351
21352 ObjectAddressSet(constraint, ConstraintRelationId, constrOid);
21353 performDeletion(&constraint, DROP_RESTRICT, 0);
21354 }
21355
21356 /* Now we can detach indexes */
21357 indexes = RelationGetIndexList(partRel);
21358 foreach(cell, indexes)
21359 {
21360 Oid idxid = lfirst_oid(cell);
21361 Oid parentidx;
21362 Relation idx;
21363 Oid constrOid;
21364 Oid parentConstrOid;
21365
21366 if (!has_superclass(idxid))
21367 continue;
21368
21369 parentidx = get_partition_parent(idxid, false);
21370 Assert((IndexGetRelation(parentidx, false) == RelationGetRelid(rel)));
21371
21372 idx = index_open(idxid, AccessExclusiveLock);
21373 IndexSetParentIndex(idx, InvalidOid);
21374
21375 /*
21376 * If there's a constraint associated with the index, detach it too.
21377 * Careful: it is possible for a constraint index in a partition to be
21378 * the child of a non-constraint index, so verify whether the parent
21379 * index does actually have a constraint.
21380 */
21381 constrOid = get_relation_idx_constraint_oid(RelationGetRelid(partRel),
21382 idxid);
21383 parentConstrOid = get_relation_idx_constraint_oid(RelationGetRelid(rel),
21384 parentidx);
21385 if (OidIsValid(parentConstrOid) && OidIsValid(constrOid))
21386 ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
21387
21388 index_close(idx, NoLock);
21389 }
21390
21391 /* Update pg_class tuple */
21392 classRel = table_open(RelationRelationId, RowExclusiveLock);
21393 tuple = SearchSysCacheCopy1(RELOID,
21394 ObjectIdGetDatum(RelationGetRelid(partRel)));
21395 if (!HeapTupleIsValid(tuple))
21396 elog(ERROR, "cache lookup failed for relation %u",
21397 RelationGetRelid(partRel));
21398 Assert(((Form_pg_class) GETSTRUCT(tuple))->relispartition);
21399
21400 /* Clear relpartbound and reset relispartition */
21401 memset(new_val, 0, sizeof(new_val));
21402 memset(new_null, false, sizeof(new_null));
21403 memset(new_repl, false, sizeof(new_repl));
21404 new_val[Anum_pg_class_relpartbound - 1] = (Datum) 0;
21405 new_null[Anum_pg_class_relpartbound - 1] = true;
21406 new_repl[Anum_pg_class_relpartbound - 1] = true;
21407 newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
21408 new_val, new_null, new_repl);
21409
21410 ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = false;
21411 CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
21412 heap_freetuple(newtuple);
21413 table_close(classRel, RowExclusiveLock);
21414
21415 /*
21416 * Drop identity property from all identity columns of partition.
21417 */
21418 for (int attno = 0; attno < RelationGetNumberOfAttributes(partRel); attno++)
21419 {
21420 Form_pg_attribute attr = TupleDescAttr(partRel->rd_att, attno);
21421
21422 if (!attr->attisdropped && attr->attidentity)
21423 ATExecDropIdentity(partRel, NameStr(attr->attname), false,
21424 AccessExclusiveLock, true, true);
21425 }
21426
21427 if (OidIsValid(defaultPartOid))
21428 {
21429 /*
21430 * If the relation being detached is the default partition itself,
21431 * remove it from the parent's pg_partitioned_table entry.
21432 *
21433 * If not, we must invalidate default partition's relcache entry, as
21434 * in StorePartitionBound: its partition constraint depends on every
21435 * other partition's partition constraint.
21436 */
21437 if (RelationGetRelid(partRel) == defaultPartOid)
21438 update_default_partition_oid(RelationGetRelid(rel), InvalidOid);
21439 else
21440 CacheInvalidateRelcacheByRelid(defaultPartOid);
21441 }
21442
21443 /*
21444 * Invalidate the parent's relcache so that the partition is no longer
21445 * included in its partition descriptor.
21446 */
21447 CacheInvalidateRelcache(rel);
21448
21449 /*
21450 * If the partition we just detached is partitioned itself, invalidate
21451 * relcache for all descendent partitions too to ensure that their
21452 * rd_partcheck expression trees are rebuilt; must lock partitions before
21453 * doing so, using the same lockmode as what partRel has been locked with
21454 * by the caller.
21455 */
21456 if (partRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
21457 {
21458 List *children;
21459
21460 children = find_all_inheritors(RelationGetRelid(partRel),
21461 AccessExclusiveLock, NULL);
21462 foreach(cell, children)
21463 {
21464 CacheInvalidateRelcacheByRelid(lfirst_oid(cell));
21465 }
21466 }
21467 }
21468
21469 /*
21470 * ALTER TABLE ... DETACH PARTITION ... FINALIZE
21471 *
21472 * To use when a DETACH PARTITION command previously did not run to
21473 * completion; this completes the detaching process.
21474 */
21475 static ObjectAddress
21476 ATExecDetachPartitionFinalize(Relation rel, RangeVar *name)
21477 {
21478 Relation partRel;
21479 ObjectAddress address;
21480 Snapshot snap = GetActiveSnapshot();
21481
21482 partRel = table_openrv(name, AccessExclusiveLock);
21483
21484 /*
21485 * Wait until existing snapshots are gone. This is important if the
21486 * second transaction of DETACH PARTITION CONCURRENTLY is canceled: the
21487 * user could immediately run DETACH FINALIZE without actually waiting for
21488 * existing transactions. We must not complete the detach action until
21489 * all such queries are complete (otherwise we would present them with an
21490 * inconsistent view of catalogs).
21491 */
21492 WaitForOlderSnapshots(snap->xmin, false);
21493
21494 DetachPartitionFinalize(rel, partRel, true, InvalidOid);
21495
21496 ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
21497
21498 table_close(partRel, NoLock);
21499
21500 return address;
21501 }
21502
21503 /*
21504 * DetachAddConstraintIfNeeded
21505 * Subroutine for ATExecDetachPartition. Create a constraint that
21506 * takes the place of the partition constraint, but avoid creating
21507 * a dupe if a constraint already exists which implies the needed
21508 * constraint.
21509 */
21510 static void
21511 DetachAddConstraintIfNeeded(List **wqueue, Relation partRel)
21512 {
21513 List *constraintExpr;
21514
21515 constraintExpr = RelationGetPartitionQual(partRel);
21516 constraintExpr = (List *) eval_const_expressions(NULL, (Node *) constraintExpr);
21517
21518 /*
21519 * Avoid adding a new constraint if the needed constraint is implied by an
21520 * existing constraint
21521 */
21522 if (!PartConstraintImpliedByRelConstraint(partRel, constraintExpr))
21523 {
21524 AlteredTableInfo *tab;
21525 Constraint *n;
21526
21527 tab = ATGetQueueEntry(wqueue, partRel);
21528
21529 /* Add constraint on partition, equivalent to the partition constraint */
21530 n = makeNode(Constraint);
21531 n->contype = CONSTR_CHECK;
21532 n->conname = NULL;
21533 n->location = -1;
21534 n->is_no_inherit = false;
21535 n->raw_expr = NULL;
21536 n->cooked_expr = nodeToString(make_ands_explicit(constraintExpr));
21537 n->is_enforced = true;
21538 n->initially_valid = true;
21539 n->skip_validation = true;
21540 /* It's a re-add, since it nominally already exists */
21541 ATAddCheckNNConstraint(wqueue, tab, partRel, n,
21542 true, false, true, ShareUpdateExclusiveLock);
21543 }
21544 }
21545
21546 /*
21547 * DropClonedTriggersFromPartition
21548 * subroutine for ATExecDetachPartition to remove any triggers that were
21549 * cloned to the partition when it was created-as-partition or attached.
21550 * This undoes what CloneRowTriggersToPartition did.
21551 */
21552 static void
21553 DropClonedTriggersFromPartition(Oid partitionId)
21554 {
21555 ScanKeyData skey;
21556 SysScanDesc scan;
21557 HeapTuple trigtup;
21558 Relation tgrel;
21559 ObjectAddresses *objects;
21560
21561 objects = new_object_addresses();
21562
21563 /*
21564 * Scan pg_trigger to search for all triggers on this rel.
21565 */
21566 ScanKeyInit(&skey, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
21567 F_OIDEQ, ObjectIdGetDatum(partitionId));
21568 tgrel = table_open(TriggerRelationId, RowExclusiveLock);
21569 scan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
21570 true, NULL, 1, &skey);
21571 while (HeapTupleIsValid(trigtup = systable_getnext(scan)))
21572 {
21573 Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(trigtup);
21574 ObjectAddress trig;
21575
21576 /* Ignore triggers that weren't cloned */
21577 if (!OidIsValid(pg_trigger->tgparentid))
21578 continue;
21579
21580 /*
21581 * Ignore internal triggers that are implementation objects of foreign
21582 * keys, because these will be detached when the foreign keys
21583 * themselves are.
21584 */
21585 if (OidIsValid(pg_trigger->tgconstrrelid))
21586 continue;
21587
21588 /*
21589 * This is ugly, but necessary: remove the dependency markings on the
21590 * trigger so that it can be removed.
21591 */
21592 deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
21593 TriggerRelationId,
21594 DEPENDENCY_PARTITION_PRI);
21595 deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
21596 RelationRelationId,
21597 DEPENDENCY_PARTITION_SEC);
21598
21599 /* remember this trigger to remove it below */
21600 ObjectAddressSet(trig, TriggerRelationId, pg_trigger->oid);
21601 add_exact_object_address(&trig, objects);
21602 }
21603
21604 /* make the dependency removal visible to the deletion below */
21605 CommandCounterIncrement();
21606 performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
21607
21608 /* done */
21609 free_object_addresses(objects);
21610 systable_endscan(scan);
21611 table_close(tgrel, RowExclusiveLock);
21612 }
21613
21614 /*
21615 * Before acquiring lock on an index, acquire the same lock on the owning
21616 * table.
21617 */
21618 struct AttachIndexCallbackState
21619 {
21620 Oid partitionOid;
21621 Oid parentTblOid;
21622 bool lockedParentTbl;
21623 };
21624
21625 static void
21626 RangeVarCallbackForAttachIndex(const RangeVar *rv, Oid relOid, Oid oldRelOid,
21627 void *arg)
21628 {
21629 struct AttachIndexCallbackState *state;
21630 Form_pg_class classform;
21631 HeapTuple tuple;
21632
21633 state = (struct AttachIndexCallbackState *) arg;
21634
21635 if (!state->lockedParentTbl)
21636 {
21637 LockRelationOid(state->parentTblOid, AccessShareLock);
21638 state->lockedParentTbl = true;
21639 }
21640
21641 /*
21642 * If we previously locked some other heap, and the name we're looking up
21643 * no longer refers to an index on that relation, release the now-useless
21644 * lock. XXX maybe we should do *after* we verify whether the index does
21645 * not actually belong to the same relation ...
21646 */
21647 if (relOid != oldRelOid && OidIsValid(state->partitionOid))
21648 {
21649 UnlockRelationOid(state->partitionOid, AccessShareLock);
21650 state->partitionOid = InvalidOid;
21651 }
21652
21653 /* Didn't find a relation, so no need for locking or permission checks. */
21654 if (!OidIsValid(relOid))
21655 return;
21656
21657 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
21658 if (!HeapTupleIsValid(tuple))
21659 return; /* concurrently dropped, so nothing to do */
21660 classform = (Form_pg_class) GETSTRUCT(tuple);
21661 if (classform->relkind != RELKIND_PARTITIONED_INDEX &&
21662 classform->relkind != RELKIND_INDEX)
21663 ereport(ERROR,
21664 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21665 errmsg("\"%s\" is not an index", rv->relname)));
21666 ReleaseSysCache(tuple);
21667
21668 /*
21669 * Since we need only examine the heap's tupledesc, an access share lock
21670 * on it (preventing any DDL) is sufficient.
21671 */
21672 state->partitionOid = IndexGetRelation(relOid, false);
21673 LockRelationOid(state->partitionOid, AccessShareLock);
21674 }
21675
21676 /*
21677 * ALTER INDEX i1 ATTACH PARTITION i2
21678 */
21679 static ObjectAddress
21680 ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx, RangeVar *name)
21681 {
21682 Relation partIdx;
21683 Relation partTbl;
21684 Relation parentTbl;
21685 ObjectAddress address;
21686 Oid partIdxId;
21687 Oid currParent;
21688 struct AttachIndexCallbackState state;
21689
21690 /*
21691 * We need to obtain lock on the index 'name' to modify it, but we also
21692 * need to read its owning table's tuple descriptor -- so we need to lock
21693 * both. To avoid deadlocks, obtain lock on the table before doing so on
21694 * the index. Furthermore, we need to examine the parent table of the
21695 * partition, so lock that one too.
21696 */
21697 state.partitionOid = InvalidOid;
21698 state.parentTblOid = parentIdx->rd_index->indrelid;
21699 state.lockedParentTbl = false;
21700 partIdxId =
21701 RangeVarGetRelidExtended(name, AccessExclusiveLock, 0,
21702 RangeVarCallbackForAttachIndex,
21703 &state);
21704 /* Not there? */
21705 if (!OidIsValid(partIdxId))
21706 ereport(ERROR,
21707 (errcode(ERRCODE_UNDEFINED_OBJECT),
21708 errmsg("index \"%s\" does not exist", name->relname)));
21709
21710 /* no deadlock risk: RangeVarGetRelidExtended already acquired the lock */
21711 partIdx = relation_open(partIdxId, AccessExclusiveLock);
21712
21713 /* we already hold locks on both tables, so this is safe: */
21714 parentTbl = relation_open(parentIdx->rd_index->indrelid, AccessShareLock);
21715 partTbl = relation_open(partIdx->rd_index->indrelid, NoLock);
21716
21717 ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partIdx));
21718
21719 /*
21720 * Check if the index is already attached to the correct parent,
21721 * ultimately attempting one round of validation if already the case.
21722 */
21723 currParent = partIdx->rd_rel->relispartition ?
21724 get_partition_parent(partIdxId, false) : InvalidOid;
21725 if (currParent != RelationGetRelid(parentIdx))
21726 {
21727 IndexInfo *childInfo;
21728 IndexInfo *parentInfo;
21729 AttrMap *attmap;
21730 bool found;
21731 int i;
21732 PartitionDesc partDesc;
21733 Oid constraintOid,
21734 cldConstrId = InvalidOid;
21735
21736 /*
21737 * If this partition already has an index attached, refuse the
21738 * operation.
21739 */
21740 refuseDupeIndexAttach(parentIdx, partIdx, partTbl);
21741
21742 if (OidIsValid(currParent))
21743 ereport(ERROR,
21744 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21745 errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21746 RelationGetRelationName(partIdx),
21747 RelationGetRelationName(parentIdx)),
21748 errdetail("Index \"%s\" is already attached to another index.",
21749 RelationGetRelationName(partIdx))));
21750
21751 /* Make sure it indexes a partition of the other index's table */
21752 partDesc = RelationGetPartitionDesc(parentTbl, true);
21753 found = false;
21754 for (i = 0; i < partDesc->nparts; i++)
21755 {
21756 if (partDesc->oids[i] == state.partitionOid)
21757 {
21758 found = true;
21759 break;
21760 }
21761 }
21762 if (!found)
21763 ereport(ERROR,
21764 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21765 errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21766 RelationGetRelationName(partIdx),
21767 RelationGetRelationName(parentIdx)),
21768 errdetail("Index \"%s\" is not an index on any partition of table \"%s\".",
21769 RelationGetRelationName(partIdx),
21770 RelationGetRelationName(parentTbl))));
21771
21772 /* Ensure the indexes are compatible */
21773 childInfo = BuildIndexInfo(partIdx);
21774 parentInfo = BuildIndexInfo(parentIdx);
21775 attmap = build_attrmap_by_name(RelationGetDescr(partTbl),
21776 RelationGetDescr(parentTbl),
21777 false);
21778 if (!CompareIndexInfo(childInfo, parentInfo,
21779 partIdx->rd_indcollation,
21780 parentIdx->rd_indcollation,
21781 partIdx->rd_opfamily,
21782 parentIdx->rd_opfamily,
21783 attmap))
21784 ereport(ERROR,
21785 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21786 errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21787 RelationGetRelationName(partIdx),
21788 RelationGetRelationName(parentIdx)),
21789 errdetail("The index definitions do not match.")));
21790
21791 /*
21792 * If there is a constraint in the parent, make sure there is one in
21793 * the child too.
21794 */
21795 constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(parentTbl),
21796 RelationGetRelid(parentIdx));
21797
21798 if (OidIsValid(constraintOid))
21799 {
21800 cldConstrId = get_relation_idx_constraint_oid(RelationGetRelid(partTbl),
21801 partIdxId);
21802 if (!OidIsValid(cldConstrId))
21803 ereport(ERROR,
21804 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21805 errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21806 RelationGetRelationName(partIdx),
21807 RelationGetRelationName(parentIdx)),
21808 errdetail("The index \"%s\" belongs to a constraint in table \"%s\" but no constraint exists for index \"%s\".",
21809 RelationGetRelationName(parentIdx),
21810 RelationGetRelationName(parentTbl),
21811 RelationGetRelationName(partIdx))));
21812 }
21813
21814 /*
21815 * If it's a primary key, make sure the columns in the partition are
21816 * NOT NULL.
21817 */
21818 if (parentIdx->rd_index->indisprimary)
21819 verifyPartitionIndexNotNull(childInfo, partTbl);
21820
21821 /* All good -- do it */
21822 IndexSetParentIndex(partIdx, RelationGetRelid(parentIdx));
21823 if (OidIsValid(constraintOid))
21824 ConstraintSetParentConstraint(cldConstrId, constraintOid,
21825 RelationGetRelid(partTbl));
21826
21827 free_attrmap(attmap);
21828
21829 validatePartitionedIndex(parentIdx, parentTbl);
21830 }
21831 else if (!parentIdx->rd_index->indisvalid)
21832 {
21833 /*
21834 * The index is attached, but the parent is still invalid; see if it
21835 * can be validated now.
21836 */
21837 validatePartitionedIndex(parentIdx, parentTbl);
21838 }
21839
21840 relation_close(parentTbl, AccessShareLock);
21841 /* keep these locks till commit */
21842 relation_close(partTbl, NoLock);
21843 relation_close(partIdx, NoLock);
21844
21845 return address;
21846 }
21847
21848 /*
21849 * Verify whether the given partition already contains an index attached
21850 * to the given partitioned index. If so, raise an error.
21851 */
21852 static void
21853 refuseDupeIndexAttach(Relation parentIdx, Relation partIdx, Relation partitionTbl)
21854 {
21855 Oid existingIdx;
21856
21857 existingIdx = index_get_partition(partitionTbl,
21858 RelationGetRelid(parentIdx));
21859 if (OidIsValid(existingIdx))
21860 ereport(ERROR,
21861 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21862 errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21863 RelationGetRelationName(partIdx),
21864 RelationGetRelationName(parentIdx)),
21865 errdetail("Another index is already attached for partition \"%s\".",
21866 RelationGetRelationName(partitionTbl))));
21867 }
21868
21869 /*
21870 * Verify whether the set of attached partition indexes to a parent index on
21871 * a partitioned table is complete. If it is, mark the parent index valid.
21872 *
21873 * This should be called each time a partition index is attached.
21874 */
21875 static void
21876 validatePartitionedIndex(Relation partedIdx, Relation partedTbl)
21877 {
21878 Relation inheritsRel;
21879 SysScanDesc scan;
21880 ScanKeyData key;
21881 int tuples = 0;
21882 HeapTuple inhTup;
21883 bool updated = false;
21884
21885 Assert(partedIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
21886
21887 /*
21888 * Scan pg_inherits for this parent index. Count each valid index we find
21889 * (verifying the pg_index entry for each), and if we reach the total
21890 * amount we expect, we can mark this parent index as valid.
21891 */
21892 inheritsRel = table_open(InheritsRelationId, AccessShareLock);
21893 ScanKeyInit(&key, Anum_pg_inherits_inhparent,
21894 BTEqualStrategyNumber, F_OIDEQ,
21895 ObjectIdGetDatum(RelationGetRelid(partedIdx)));
21896 scan = systable_beginscan(inheritsRel, InheritsParentIndexId, true,
21897 NULL, 1, &key);
21898 while ((inhTup = systable_getnext(scan)) != NULL)
21899 {
21900 Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(inhTup);
21901 HeapTuple indTup;
21902 Form_pg_index indexForm;
21903
21904 indTup = SearchSysCache1(INDEXRELID,
21905 ObjectIdGetDatum(inhForm->inhrelid));
21906 if (!HeapTupleIsValid(indTup))
21907 elog(ERROR, "cache lookup failed for index %u", inhForm->inhrelid);
21908 indexForm = (Form_pg_index) GETSTRUCT(indTup);
21909 if (indexForm->indisvalid)
21910 tuples += 1;
21911 ReleaseSysCache(indTup);
21912 }
21913
21914 /* Done with pg_inherits */
21915 systable_endscan(scan);
21916 table_close(inheritsRel, AccessShareLock);
21917
21918 /*
21919 * If we found as many inherited indexes as the partitioned table has
21920 * partitions, we're good; update pg_index to set indisvalid.
21921 */
21922 if (tuples == RelationGetPartitionDesc(partedTbl, true)->nparts)
21923 {
21924 Relation idxRel;
21925 HeapTuple indTup;
21926 Form_pg_index indexForm;
21927
21928 idxRel = table_open(IndexRelationId, RowExclusiveLock);
21929 indTup = SearchSysCacheCopy1(INDEXRELID,
21930 ObjectIdGetDatum(RelationGetRelid(partedIdx)));
21931 if (!HeapTupleIsValid(indTup))
21932 elog(ERROR, "cache lookup failed for index %u",
21933 RelationGetRelid(partedIdx));
21934 indexForm = (Form_pg_index) GETSTRUCT(indTup);
21935
21936 indexForm->indisvalid = true;
21937 updated = true;
21938
21939 CatalogTupleUpdate(idxRel, &indTup->t_self, indTup);
21940
21941 table_close(idxRel, RowExclusiveLock);
21942 heap_freetuple(indTup);
21943 }
21944
21945 /*
21946 * If this index is in turn a partition of a larger index, validating it
21947 * might cause the parent to become valid also. Try that.
21948 */
21949 if (updated && partedIdx->rd_rel->relispartition)
21950 {
21951 Oid parentIdxId,
21952 parentTblId;
21953 Relation parentIdx,
21954 parentTbl;
21955
21956 /* make sure we see the validation we just did */
21957 CommandCounterIncrement();
21958
21959 parentIdxId = get_partition_parent(RelationGetRelid(partedIdx), false);
21960 parentTblId = get_partition_parent(RelationGetRelid(partedTbl), false);
21961 parentIdx = relation_open(parentIdxId, AccessExclusiveLock);
21962 parentTbl = relation_open(parentTblId, AccessExclusiveLock);
21963 Assert(!parentIdx->rd_index->indisvalid);
21964
21965 validatePartitionedIndex(parentIdx, parentTbl);
21966
21967 relation_close(parentIdx, AccessExclusiveLock);
21968 relation_close(parentTbl, AccessExclusiveLock);
21969 }
21970 }
21971
21972 /*
21973 * When attaching an index as a partition of a partitioned index which is a
21974 * primary key, verify that all the columns in the partition are marked NOT
21975 * NULL.
21976 */
21977 static void
21978 verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition)
21979 {
21980 for (int i = 0; i < iinfo->ii_NumIndexKeyAttrs; i++)
21981 {
21982 Form_pg_attribute att = TupleDescAttr(RelationGetDescr(partition),
21983 iinfo->ii_IndexAttrNumbers[i] - 1);
21984
21985 if (!att->attnotnull)
21986 ereport(ERROR,
21987 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
21988 errmsg("invalid primary key definition"),
21989 errdetail("Column \"%s\" of relation \"%s\" is not marked NOT NULL.",
21990 NameStr(att->attname),
21991 RelationGetRelationName(partition)));
21992 }
21993 }
21994
21995 /*
21996 * Return an OID list of constraints that reference the given relation
21997 * that are marked as having a parent constraints.
21998 */
21999 static List *
22000 GetParentedForeignKeyRefs(Relation partition)
22001 {
22002 Relation pg_constraint;
22003 HeapTuple tuple;
22004 SysScanDesc scan;
22005 ScanKeyData key[2];
22006 List *constraints = NIL;
22007
22008 /*
22009 * If no indexes, or no columns are referenceable by FKs, we can avoid the
22010 * scan.
22011 */
22012 if (RelationGetIndexList(partition) == NIL ||
22013 bms_is_empty(RelationGetIndexAttrBitmap(partition,
22014 INDEX_ATTR_BITMAP_KEY)))
22015 return NIL;
22016
22017 /* Search for constraints referencing this table */
22018 pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
22019 ScanKeyInit(&key[0],
22020 Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
22021 F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(partition)));
22022 ScanKeyInit(&key[1],
22023 Anum_pg_constraint_contype, BTEqualStrategyNumber,
22024 F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
22025
22026 /* XXX This is a seqscan, as we don't have a usable index */
22027 scan = systable_beginscan(pg_constraint, InvalidOid, true, NULL, 2, key);
22028 while ((tuple = systable_getnext(scan)) != NULL)
22029 {
22030 Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22031
22032 /*
22033 * We only need to process constraints that are part of larger ones.
22034 */
22035 if (!OidIsValid(constrForm->conparentid))
22036 continue;
22037
22038 constraints = lappend_oid(constraints, constrForm->oid);
22039 }
22040
22041 systable_endscan(scan);
22042 table_close(pg_constraint, AccessShareLock);
22043
22044 return constraints;
22045 }
22046
22047 /*
22048 * During DETACH PARTITION, verify that any foreign keys pointing to the
22049 * partitioned table would not become invalid. An error is raised if any
22050 * referenced values exist.
22051 */
22052 static void
22053 ATDetachCheckNoForeignKeyRefs(Relation partition)
22054 {
22055 List *constraints;
22056 ListCell *cell;
22057
22058 constraints = GetParentedForeignKeyRefs(partition);
22059
22060 foreach(cell, constraints)
22061 {
22062 Oid constrOid = lfirst_oid(cell);
22063 HeapTuple tuple;
22064 Form_pg_constraint constrForm;
22065 Relation rel;
22066 Trigger trig = {0};
22067
22068 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
22069 if (!HeapTupleIsValid(tuple))
22070 elog(ERROR, "cache lookup failed for constraint %u", constrOid);
22071 constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22072
22073 Assert(OidIsValid(constrForm->conparentid));
22074 Assert(constrForm->confrelid == RelationGetRelid(partition));
22075
22076 /* prevent data changes into the referencing table until commit */
22077 rel = table_open(constrForm->conrelid, ShareLock);
22078
22079 trig.tgoid = InvalidOid;
22080 trig.tgname = NameStr(constrForm->conname);
22081 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
22082 trig.tgisinternal = true;
22083 trig.tgconstrrelid = RelationGetRelid(partition);
22084 trig.tgconstrindid = constrForm->conindid;
22085 trig.tgconstraint = constrForm->oid;
22086 trig.tgdeferrable = false;
22087 trig.tginitdeferred = false;
22088 /* we needn't fill in remaining fields */
22089
22090 RI_PartitionRemove_Check(&trig, rel, partition);
22091
22092 ReleaseSysCache(tuple);
22093
22094 table_close(rel, NoLock);
22095 }
22096 }
22097
22098 /*
22099 * resolve column compression specification to compression method.
22100 */
22101 static char
22102 GetAttributeCompression(Oid atttypid, const char *compression)
22103 {
22104 char cmethod;
22105
22106 if (compression == NULL || strcmp(compression, "default") == 0)
22107 return InvalidCompressionMethod;
22108
22109 /*
22110 * To specify a nondefault method, the column data type must be toastable.
22111 * Note this says nothing about whether the column's attstorage setting
22112 * permits compression; we intentionally allow attstorage and
22113 * attcompression to be independent. But with a non-toastable type,
22114 * attstorage could not be set to a value that would permit compression.
22115 *
22116 * We don't actually need to enforce this, since nothing bad would happen
22117 * if attcompression were non-default; it would never be consulted. But
22118 * it seems more user-friendly to complain about a certainly-useless
22119 * attempt to set the property.
22120 */
22121 if (!TypeIsToastable(atttypid))
22122 ereport(ERROR,
22123 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22124 errmsg("column data type %s does not support compression",
22125 format_type_be(atttypid))));
22126
22127 cmethod = CompressionNameToMethod(compression);
22128 if (!CompressionMethodIsValid(cmethod))
22129 ereport(ERROR,
22130 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22131 errmsg("invalid compression method \"%s\"", compression)));
22132
22133 return cmethod;
22134 }
22135
22136 /*
22137 * resolve column storage specification
22138 */
22139 static char
22140 GetAttributeStorage(Oid atttypid, const char *storagemode)
22141 {
22142 char cstorage = 0;
22143
22144 if (pg_strcasecmp(storagemode, "plain") == 0)
22145 cstorage = TYPSTORAGE_PLAIN;
22146 else if (pg_strcasecmp(storagemode, "external") == 0)
22147 cstorage = TYPSTORAGE_EXTERNAL;
22148 else if (pg_strcasecmp(storagemode, "extended") == 0)
22149 cstorage = TYPSTORAGE_EXTENDED;
22150 else if (pg_strcasecmp(storagemode, "main") == 0)
22151 cstorage = TYPSTORAGE_MAIN;
22152 else if (pg_strcasecmp(storagemode, "default") == 0)
22153 cstorage = get_typstorage(atttypid);
22154 else
22155 ereport(ERROR,
22156 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22157 errmsg("invalid storage type \"%s\"",
22158 storagemode)));
22159
22160 /*
22161 * safety check: do not allow toasted storage modes unless column datatype
22162 * is TOAST-aware.
22163 */
22164 if (!(cstorage == TYPSTORAGE_PLAIN || TypeIsToastable(atttypid)))
22165 ereport(ERROR,
22166 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22167 errmsg("column data type %s can only have storage PLAIN",
22168 format_type_be(atttypid))));
22169
22170 return cstorage;
22171 }