PostgreSQL Source Code  git master
tablecmds.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * tablecmds.c
4  * Commands for creating and altering table structures and settings
5  *
6  * Portions Copyright (c) 1996-2020, 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/heapam.h"
20 #include "access/heapam_xlog.h"
21 #include "access/multixact.h"
22 #include "access/reloptions.h"
23 #include "access/relscan.h"
24 #include "access/sysattr.h"
25 #include "access/tableam.h"
26 #include "access/xact.h"
27 #include "access/xlog.h"
28 #include "catalog/catalog.h"
29 #include "catalog/dependency.h"
30 #include "catalog/heap.h"
31 #include "catalog/index.h"
32 #include "catalog/namespace.h"
33 #include "catalog/objectaccess.h"
34 #include "catalog/partition.h"
35 #include "catalog/pg_am.h"
36 #include "catalog/pg_collation.h"
37 #include "catalog/pg_constraint.h"
38 #include "catalog/pg_depend.h"
40 #include "catalog/pg_inherits.h"
41 #include "catalog/pg_namespace.h"
42 #include "catalog/pg_opclass.h"
43 #include "catalog/pg_tablespace.h"
44 #include "catalog/pg_trigger.h"
45 #include "catalog/pg_type.h"
46 #include "catalog/storage.h"
47 #include "catalog/storage_xlog.h"
48 #include "catalog/toasting.h"
49 #include "commands/cluster.h"
50 #include "commands/comment.h"
51 #include "commands/defrem.h"
52 #include "commands/event_trigger.h"
53 #include "commands/policy.h"
54 #include "commands/sequence.h"
55 #include "commands/tablecmds.h"
56 #include "commands/tablespace.h"
57 #include "commands/trigger.h"
58 #include "commands/typecmds.h"
59 #include "commands/user.h"
60 #include "executor/executor.h"
61 #include "foreign/foreign.h"
62 #include "miscadmin.h"
63 #include "nodes/makefuncs.h"
64 #include "nodes/nodeFuncs.h"
65 #include "nodes/parsenodes.h"
66 #include "optimizer/optimizer.h"
67 #include "parser/parse_clause.h"
68 #include "parser/parse_coerce.h"
69 #include "parser/parse_collate.h"
70 #include "parser/parse_expr.h"
71 #include "parser/parse_oper.h"
72 #include "parser/parse_relation.h"
73 #include "parser/parse_type.h"
74 #include "parser/parse_utilcmd.h"
75 #include "parser/parser.h"
77 #include "partitioning/partdesc.h"
78 #include "pgstat.h"
79 #include "rewrite/rewriteDefine.h"
80 #include "rewrite/rewriteHandler.h"
81 #include "rewrite/rewriteManip.h"
82 #include "storage/bufmgr.h"
83 #include "storage/lmgr.h"
84 #include "storage/lock.h"
85 #include "storage/predicate.h"
86 #include "storage/smgr.h"
87 #include "tcop/utility.h"
88 #include "utils/acl.h"
89 #include "utils/builtins.h"
90 #include "utils/fmgroids.h"
91 #include "utils/inval.h"
92 #include "utils/lsyscache.h"
93 #include "utils/memutils.h"
94 #include "utils/partcache.h"
95 #include "utils/pg_locale.h"
96 #include "utils/relcache.h"
97 #include "utils/ruleutils.h"
98 #include "utils/snapmgr.h"
99 #include "utils/syscache.h"
100 #include "utils/timestamp.h"
101 #include "utils/typcache.h"
102 
103 /*
104  * ON COMMIT action list
105  */
106 typedef struct OnCommitItem
107 {
108  Oid relid; /* relid of relation */
109  OnCommitAction oncommit; /* what to do at end of xact */
110 
111  /*
112  * If this entry was created during the current transaction,
113  * creating_subid is the ID of the creating subxact; if created in a prior
114  * transaction, creating_subid is zero. If deleted during the current
115  * transaction, deleting_subid is the ID of the deleting subxact; if no
116  * deletion request is pending, deleting_subid is zero.
117  */
120 } OnCommitItem;
121 
122 static List *on_commits = NIL;
123 
124 
125 /*
126  * State information for ALTER TABLE
127  *
128  * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
129  * structs, one for each table modified by the operation (the named table
130  * plus any child tables that are affected). We save lists of subcommands
131  * to apply to this table (possibly modified by parse transformation steps);
132  * these lists will be executed in Phase 2. If a Phase 3 step is needed,
133  * necessary information is stored in the constraints and newvals lists.
134  *
135  * Phase 2 is divided into multiple passes; subcommands are executed in
136  * a pass determined by subcommand type.
137  */
138 
139 #define AT_PASS_UNSET -1 /* UNSET will cause ERROR */
140 #define AT_PASS_DROP 0 /* DROP (all flavors) */
141 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
142 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
143 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
144 /* We could support a RENAME COLUMN pass here, but not currently used */
145 #define AT_PASS_ADD_COL 4 /* ADD COLUMN */
146 #define AT_PASS_ADD_CONSTR 5 /* ADD constraints (initial examination) */
147 #define AT_PASS_COL_ATTRS 6 /* set column attributes, eg NOT NULL */
148 #define AT_PASS_ADD_INDEXCONSTR 7 /* ADD index-based constraints */
149 #define AT_PASS_ADD_INDEX 8 /* ADD indexes */
150 #define AT_PASS_ADD_OTHERCONSTR 9 /* ADD other constraints, defaults */
151 #define AT_PASS_MISC 10 /* other stuff */
152 #define AT_NUM_PASSES 11
153 
154 typedef struct AlteredTableInfo
155 {
156  /* Information saved before any work commences: */
157  Oid relid; /* Relation to work on */
158  char relkind; /* Its relkind */
159  TupleDesc oldDesc; /* Pre-modification tuple descriptor */
160  /* Information saved by Phase 1 for Phase 2: */
161  List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
162  /* Information saved by Phases 1/2 for Phase 3: */
163  List *constraints; /* List of NewConstraint */
164  List *newvals; /* List of NewColumnValue */
165  List *afterStmts; /* List of utility command parsetrees */
166  bool verify_new_notnull; /* T if we should recheck NOT NULL */
167  int rewrite; /* Reason for forced rewrite, if any */
168  Oid newTableSpace; /* new tablespace; 0 means no change */
169  bool chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
170  char newrelpersistence; /* if above is true */
171  Expr *partition_constraint; /* for attach partition validation */
172  /* true, if validating default due to some other attach/detach */
174  /* Objects to rebuild after completing ALTER TYPE operations */
175  List *changedConstraintOids; /* OIDs of constraints to rebuild */
176  List *changedConstraintDefs; /* string definitions of same */
177  List *changedIndexOids; /* OIDs of indexes to rebuild */
178  List *changedIndexDefs; /* string definitions of same */
179  char *replicaIdentityIndex; /* index to reset as REPLICA IDENTITY */
180  char *clusterOnIndex; /* index to use for CLUSTER */
182 
183 /* Struct describing one new constraint to check in Phase 3 scan */
184 /* Note: new NOT NULL constraints are handled elsewhere */
185 typedef struct NewConstraint
186 {
187  char *name; /* Constraint name, or NULL if none */
188  ConstrType contype; /* CHECK or FOREIGN */
189  Oid refrelid; /* PK rel, if FOREIGN */
190  Oid refindid; /* OID of PK's index, if FOREIGN */
191  Oid conid; /* OID of pg_constraint entry, if FOREIGN */
192  Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
193  ExprState *qualstate; /* Execution state for CHECK expr */
194 } NewConstraint;
195 
196 /*
197  * Struct describing one new column value that needs to be computed during
198  * Phase 3 copy (this could be either a new column with a non-null default, or
199  * a column that we're changing the type of). Columns without such an entry
200  * are just copied from the old table during ATRewriteTable. Note that the
201  * expr is an expression over *old* table values, except when is_generated
202  * is true; then it is an expression over columns of the *new* tuple.
203  */
204 typedef struct NewColumnValue
205 {
206  AttrNumber attnum; /* which column */
207  Expr *expr; /* expression to compute */
208  ExprState *exprstate; /* execution state */
209  bool is_generated; /* is it a GENERATED expression? */
211 
212 /*
213  * Error-reporting support for RemoveRelations
214  */
216 {
217  char kind;
219  const char *nonexistent_msg;
220  const char *skipping_msg;
221  const char *nota_msg;
222  const char *drophint_msg;
223 };
224 
225 static const struct dropmsgstrings dropmsgstringarray[] = {
226  {RELKIND_RELATION,
228  gettext_noop("table \"%s\" does not exist"),
229  gettext_noop("table \"%s\" does not exist, skipping"),
230  gettext_noop("\"%s\" is not a table"),
231  gettext_noop("Use DROP TABLE to remove a table.")},
232  {RELKIND_SEQUENCE,
234  gettext_noop("sequence \"%s\" does not exist"),
235  gettext_noop("sequence \"%s\" does not exist, skipping"),
236  gettext_noop("\"%s\" is not a sequence"),
237  gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
238  {RELKIND_VIEW,
240  gettext_noop("view \"%s\" does not exist"),
241  gettext_noop("view \"%s\" does not exist, skipping"),
242  gettext_noop("\"%s\" is not a view"),
243  gettext_noop("Use DROP VIEW to remove a view.")},
244  {RELKIND_MATVIEW,
246  gettext_noop("materialized view \"%s\" does not exist"),
247  gettext_noop("materialized view \"%s\" does not exist, skipping"),
248  gettext_noop("\"%s\" is not a materialized view"),
249  gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
250  {RELKIND_INDEX,
251  ERRCODE_UNDEFINED_OBJECT,
252  gettext_noop("index \"%s\" does not exist"),
253  gettext_noop("index \"%s\" does not exist, skipping"),
254  gettext_noop("\"%s\" is not an index"),
255  gettext_noop("Use DROP INDEX to remove an index.")},
256  {RELKIND_COMPOSITE_TYPE,
257  ERRCODE_UNDEFINED_OBJECT,
258  gettext_noop("type \"%s\" does not exist"),
259  gettext_noop("type \"%s\" does not exist, skipping"),
260  gettext_noop("\"%s\" is not a type"),
261  gettext_noop("Use DROP TYPE to remove a type.")},
262  {RELKIND_FOREIGN_TABLE,
263  ERRCODE_UNDEFINED_OBJECT,
264  gettext_noop("foreign table \"%s\" does not exist"),
265  gettext_noop("foreign table \"%s\" does not exist, skipping"),
266  gettext_noop("\"%s\" is not a foreign table"),
267  gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
268  {RELKIND_PARTITIONED_TABLE,
270  gettext_noop("table \"%s\" does not exist"),
271  gettext_noop("table \"%s\" does not exist, skipping"),
272  gettext_noop("\"%s\" is not a table"),
273  gettext_noop("Use DROP TABLE to remove a table.")},
274  {RELKIND_PARTITIONED_INDEX,
275  ERRCODE_UNDEFINED_OBJECT,
276  gettext_noop("index \"%s\" does not exist"),
277  gettext_noop("index \"%s\" does not exist, skipping"),
278  gettext_noop("\"%s\" is not an index"),
279  gettext_noop("Use DROP INDEX to remove an index.")},
280  {'\0', 0, NULL, NULL, NULL, NULL}
281 };
282 
284 {
285  char relkind;
289 };
290 
291 /* Alter table target-type flags for ATSimplePermissions */
292 #define ATT_TABLE 0x0001
293 #define ATT_VIEW 0x0002
294 #define ATT_MATVIEW 0x0004
295 #define ATT_INDEX 0x0008
296 #define ATT_COMPOSITE_TYPE 0x0010
297 #define ATT_FOREIGN_TABLE 0x0020
298 #define ATT_PARTITIONED_INDEX 0x0040
299 
300 /*
301  * Partition tables are expected to be dropped when the parent partitioned
302  * table gets dropped. Hence for partitioning we use AUTO dependency.
303  * Otherwise, for regular inheritance use NORMAL dependency.
304  */
305 #define child_dependency_type(child_is_partition) \
306  ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
307 
308 static void truncate_check_rel(Oid relid, Form_pg_class reltuple);
309 static void truncate_check_perms(Oid relid, Form_pg_class reltuple);
310 static void truncate_check_activity(Relation rel);
311 static void RangeVarCallbackForTruncate(const RangeVar *relation,
312  Oid relId, Oid oldRelId, void *arg);
313 static List *MergeAttributes(List *schema, List *supers, char relpersistence,
314  bool is_partition, List **supconstr);
315 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
316 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
317 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
318 static void StoreCatalogInheritance(Oid relationId, List *supers,
319  bool child_is_partition);
320 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
321  int32 seqNumber, Relation inhRelation,
322  bool child_is_partition);
323 static int findAttrByName(const char *attributeName, List *schema);
324 static void AlterIndexNamespaces(Relation classRel, Relation rel,
325  Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
326 static void AlterSeqNamespaces(Relation classRel, Relation rel,
327  Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
328  LOCKMODE lockmode);
330  bool recurse, bool recursing, LOCKMODE lockmode);
332  Relation rel, char *constrName,
333  bool recurse, bool recursing, LOCKMODE lockmode);
334 static int transformColumnNameList(Oid relId, List *colList,
335  int16 *attnums, Oid *atttypids);
336 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
337  List **attnamelist,
338  int16 *attnums, Oid *atttypids,
339  Oid *opclasses);
341  int numattrs, int16 *attnums,
342  Oid *opclasses);
343 static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
344 static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
345  Oid *funcid);
346 static void validateForeignKeyConstraint(char *conname,
347  Relation rel, Relation pkrel,
348  Oid pkindOid, Oid constraintOid);
349 static void ATController(AlterTableStmt *parsetree,
350  Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
351  AlterTableUtilityContext *context);
352 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
353  bool recurse, bool recursing, LOCKMODE lockmode,
354  AlterTableUtilityContext *context);
355 static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
356  AlterTableUtilityContext *context);
357 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
358  AlterTableCmd *cmd, LOCKMODE lockmode, int cur_pass,
359  AlterTableUtilityContext *context);
361  Relation rel, AlterTableCmd *cmd,
362  bool recurse, LOCKMODE lockmode,
363  int cur_pass,
364  AlterTableUtilityContext *context);
365 static void ATRewriteTables(AlterTableStmt *parsetree,
366  List **wqueue, LOCKMODE lockmode,
367  AlterTableUtilityContext *context);
368 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode);
369 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
370 static void ATSimplePermissions(Relation rel, int allowed_targets);
371 static void ATWrongRelkindError(Relation rel, int allowed_targets);
372 static void ATSimpleRecursion(List **wqueue, Relation rel,
373  AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
374  AlterTableUtilityContext *context);
375 static void ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode);
376 static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
377  LOCKMODE lockmode,
378  AlterTableUtilityContext *context);
379 static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
380  DropBehavior behavior);
381 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
382  bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
383  AlterTableUtilityContext *context);
384 static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab,
385  Relation rel, AlterTableCmd **cmd,
386  bool recurse, bool recursing,
387  LOCKMODE lockmode, int cur_pass,
388  AlterTableUtilityContext *context);
389 static bool check_for_column_name_collision(Relation rel, const char *colname,
390  bool if_not_exists);
393 static void ATPrepDropNotNull(Relation rel, bool recurse, bool recursing);
394 static ObjectAddress ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode);
395 static void ATPrepSetNotNull(List **wqueue, Relation rel,
396  AlterTableCmd *cmd, bool recurse, bool recursing,
397  LOCKMODE lockmode,
398  AlterTableUtilityContext *context);
400  const char *colName, LOCKMODE lockmode);
401 static void ATExecCheckNotNull(AlteredTableInfo *tab, Relation rel,
402  const char *colName, LOCKMODE lockmode);
404 static bool ConstraintImpliedByRelConstraint(Relation scanrel,
405  List *testConstraint, List *provenConstraint);
406 static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
407  Node *newDefault, LOCKMODE lockmode);
409  Node *newDefault);
410 static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName,
411  Node *def, LOCKMODE lockmode);
412 static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName,
413  Node *def, LOCKMODE lockmode);
414 static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
415 static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode);
416 static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
417 static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum,
418  Node *newValue, LOCKMODE lockmode);
419 static ObjectAddress ATExecSetOptions(Relation rel, const char *colName,
420  Node *options, bool isReset, LOCKMODE lockmode);
421 static ObjectAddress ATExecSetStorage(Relation rel, const char *colName,
422  Node *newValue, LOCKMODE lockmode);
423 static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
424  AlterTableCmd *cmd, LOCKMODE lockmode,
425  AlterTableUtilityContext *context);
426 static ObjectAddress ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
427  DropBehavior behavior,
428  bool recurse, bool recursing,
429  bool missing_ok, LOCKMODE lockmode,
430  ObjectAddresses *addrs);
432  IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
433 static ObjectAddress ATExecAddConstraint(List **wqueue,
434  AlteredTableInfo *tab, Relation rel,
435  Constraint *newConstraint, bool recurse, bool is_readd,
436  LOCKMODE lockmode);
437 static char *ChooseForeignKeyConstraintNameAddition(List *colnames);
439  IndexStmt *stmt, LOCKMODE lockmode);
440 static ObjectAddress ATAddCheckConstraint(List **wqueue,
441  AlteredTableInfo *tab, Relation rel,
442  Constraint *constr,
443  bool recurse, bool recursing, bool is_readd,
444  LOCKMODE lockmode);
446  Relation rel, Constraint *fkconstraint, Oid parentConstr,
447  bool recurse, bool recursing,
448  LOCKMODE lockmode);
449 static ObjectAddress addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint,
450  Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
451  int numfks, int16 *pkattnum, int16 *fkattnum,
452  Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
453  bool old_check_ok);
454 static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
455  Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
456  int numfks, int16 *pkattnum, int16 *fkattnum,
457  Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
458  bool old_check_ok, LOCKMODE lockmode);
459 static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
460  Relation partitionRel);
461 static void CloneFkReferenced(Relation parentRel, Relation partitionRel);
462 static void CloneFkReferencing(List **wqueue, Relation parentRel,
463  Relation partRel);
464 static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
465  Constraint *fkconstraint, Oid constraintOid,
466  Oid indexOid);
467 static void createForeignKeyActionTriggers(Relation rel, Oid refRelOid,
468  Constraint *fkconstraint, Oid constraintOid,
469  Oid indexOid);
471  Oid partRelid,
472  Oid parentConstrOid, int numfks,
473  AttrNumber *mapped_conkey, AttrNumber *confkey,
474  Oid *conpfeqop);
475 static void ATExecDropConstraint(Relation rel, const char *constrName,
476  DropBehavior behavior,
477  bool recurse, bool recursing,
478  bool missing_ok, LOCKMODE lockmode);
479 static void ATPrepAlterColumnType(List **wqueue,
480  AlteredTableInfo *tab, Relation rel,
481  bool recurse, bool recursing,
482  AlterTableCmd *cmd, LOCKMODE lockmode,
483  AlterTableUtilityContext *context);
484 static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
486  AlterTableCmd *cmd, LOCKMODE lockmode);
487 static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
488 static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
489 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
490  LOCKMODE lockmode);
491 static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId,
492  char *cmd, List **wqueue, LOCKMODE lockmode,
493  bool rewrite);
494 static void RebuildConstraintComment(AlteredTableInfo *tab, int pass,
495  Oid objid, Relation rel, List *domname,
496  const char *conname);
497 static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
498 static void TryReuseForeignKey(Oid oldId, Constraint *con);
499 static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
500  List *options, LOCKMODE lockmode);
501 static void change_owner_fix_column_acls(Oid relationOid,
502  Oid oldOwnerId, Oid newOwnerId);
503 static void change_owner_recurse_to_sequences(Oid relationOid,
504  Oid newOwnerId, LOCKMODE lockmode);
505 static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
506  LOCKMODE lockmode);
507 static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
508 static bool ATPrepChangePersistence(Relation rel, bool toLogged);
509 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
510  const char *tablespacename, LOCKMODE lockmode);
511 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
512 static void ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace);
513 static void ATExecSetRelOptions(Relation rel, List *defList,
514  AlterTableType operation,
515  LOCKMODE lockmode);
516 static void ATExecEnableDisableTrigger(Relation rel, const char *trigname,
517  char fires_when, bool skip_system, LOCKMODE lockmode);
518 static void ATExecEnableDisableRule(Relation rel, const char *rulename,
519  char fires_when, LOCKMODE lockmode);
520 static void ATPrepAddInherit(Relation child_rel);
521 static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
522 static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
523 static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
524  DependencyType deptype);
525 static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
526 static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
527 static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
528 static void ATExecGenericOptions(Relation rel, List *options);
529 static void ATExecEnableRowSecurity(Relation rel);
530 static void ATExecDisableRowSecurity(Relation rel);
531 static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
532 
533 static void index_copy_data(Relation rel, RelFileNode newrnode);
534 static const char *storage_name(char c);
535 
536 static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
537  Oid oldRelOid, void *arg);
538 static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
539  Oid oldrelid, void *arg);
540 static PartitionSpec *transformPartitionSpec(Relation rel, PartitionSpec *partspec, char *strategy);
541 static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
542  List **partexprs, Oid *partopclass, Oid *partcollation, char strategy);
543 static void CreateInheritance(Relation child_rel, Relation parent_rel);
544 static void RemoveInheritance(Relation child_rel, Relation parent_rel);
545 static ObjectAddress ATExecAttachPartition(List **wqueue, Relation rel,
546  PartitionCmd *cmd,
547  AlterTableUtilityContext *context);
548 static void AttachPartitionEnsureIndexes(Relation rel, Relation attachrel);
549 static void QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
550  List *partConstraint,
551  bool validate_default);
552 static void CloneRowTriggersToPartition(Relation parent, Relation partition);
553 static void DropClonedTriggersFromPartition(Oid partitionId);
556  RangeVar *name);
557 static void validatePartitionedIndex(Relation partedIdx, Relation partedTbl);
558 static void refuseDupeIndexAttach(Relation parentIdx, Relation partIdx,
559  Relation partitionTbl);
560 static List *GetParentedForeignKeyRefs(Relation partition);
561 static void ATDetachCheckNoForeignKeyRefs(Relation partition);
562 static void ATExecAlterCollationRefreshVersion(Relation rel, List *coll);
563 
564 
565 /* ----------------------------------------------------------------
566  * DefineRelation
567  * Creates a new relation.
568  *
569  * stmt carries parsetree information from an ordinary CREATE TABLE statement.
570  * The other arguments are used to extend the behavior for other cases:
571  * relkind: relkind to assign to the new relation
572  * ownerId: if not InvalidOid, use this as the new relation's owner.
573  * typaddress: if not null, it's set to the pg_type entry's address.
574  * queryString: for error reporting
575  *
576  * Note that permissions checks are done against current user regardless of
577  * ownerId. A nonzero ownerId is used when someone is creating a relation
578  * "on behalf of" someone else, so we still want to see that the current user
579  * has permissions to do it.
580  *
581  * If successful, returns the address of the new relation.
582  * ----------------------------------------------------------------
583  */
585 DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
586  ObjectAddress *typaddress, const char *queryString)
587 {
588  char relname[NAMEDATALEN];
589  Oid namespaceId;
590  Oid relationId;
591  Oid tablespaceId;
592  Relation rel;
594  List *inheritOids;
595  List *old_constraints;
596  List *rawDefaults;
597  List *cookedDefaults;
598  Datum reloptions;
599  ListCell *listptr;
601  bool partitioned;
602  static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
603  Oid ofTypeId;
604  ObjectAddress address;
605  LOCKMODE parentLockmode;
606  const char *accessMethod = NULL;
607  Oid accessMethodId = InvalidOid;
608 
609  /*
610  * Truncate relname to appropriate length (probably a waste of time, as
611  * parser should have done this already).
612  */
613  strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
614 
615  /*
616  * Check consistency of arguments
617  */
618  if (stmt->oncommit != ONCOMMIT_NOOP
619  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
620  ereport(ERROR,
621  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
622  errmsg("ON COMMIT can only be used on temporary tables")));
623 
624  if (stmt->partspec != NULL)
625  {
626  if (relkind != RELKIND_RELATION)
627  elog(ERROR, "unexpected relkind: %d", (int) relkind);
628 
629  relkind = RELKIND_PARTITIONED_TABLE;
630  partitioned = true;
631  }
632  else
633  partitioned = false;
634 
635  /*
636  * Look up the namespace in which we are supposed to create the relation,
637  * check we have permission to create there, lock it against concurrent
638  * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
639  * namespace is selected.
640  */
641  namespaceId =
643 
644  /*
645  * Security check: disallow creating temp tables from security-restricted
646  * code. This is needed because calling code might not expect untrusted
647  * tables to appear in pg_temp at the front of its search path.
648  */
649  if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
651  ereport(ERROR,
652  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
653  errmsg("cannot create temporary table within security-restricted operation")));
654 
655  /*
656  * Determine the lockmode to use when scanning parents. A self-exclusive
657  * lock is needed here.
658  *
659  * For regular inheritance, if two backends attempt to add children to the
660  * same parent simultaneously, and that parent has no pre-existing
661  * children, then both will attempt to update the parent's relhassubclass
662  * field, leading to a "tuple concurrently updated" error. Also, this
663  * interlocks against a concurrent ANALYZE on the parent table, which
664  * might otherwise be attempting to clear the parent's relhassubclass
665  * field, if its previous children were recently dropped.
666  *
667  * If the child table is a partition, then we instead grab an exclusive
668  * lock on the parent because its partition descriptor will be changed by
669  * addition of the new partition.
670  */
671  parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
673 
674  /* Determine the list of OIDs of the parents. */
675  inheritOids = NIL;
676  foreach(listptr, stmt->inhRelations)
677  {
678  RangeVar *rv = (RangeVar *) lfirst(listptr);
679  Oid parentOid;
680 
681  parentOid = RangeVarGetRelid(rv, parentLockmode, false);
682 
683  /*
684  * Reject duplications in the list of parents.
685  */
686  if (list_member_oid(inheritOids, parentOid))
687  ereport(ERROR,
688  (errcode(ERRCODE_DUPLICATE_TABLE),
689  errmsg("relation \"%s\" would be inherited from more than once",
690  get_rel_name(parentOid))));
691 
692  inheritOids = lappend_oid(inheritOids, parentOid);
693  }
694 
695  /*
696  * Select tablespace to use: an explicitly indicated one, or (in the case
697  * of a partitioned table) the parent's, if it has one.
698  */
699  if (stmt->tablespacename)
700  {
701  tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
702 
703  if (partitioned && tablespaceId == MyDatabaseTableSpace)
704  ereport(ERROR,
705  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
706  errmsg("cannot specify default tablespace for partitioned relations")));
707  }
708  else if (stmt->partbound)
709  {
710  /*
711  * For partitions, when no other tablespace is specified, we default
712  * the tablespace to the parent partitioned table's.
713  */
714  Assert(list_length(inheritOids) == 1);
715  tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
716  }
717  else
718  tablespaceId = InvalidOid;
719 
720  /* still nothing? use the default */
721  if (!OidIsValid(tablespaceId))
722  tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
723  partitioned);
724 
725  /* Check permissions except when using database's default */
726  if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
727  {
728  AclResult aclresult;
729 
730  aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
731  ACL_CREATE);
732  if (aclresult != ACLCHECK_OK)
734  get_tablespace_name(tablespaceId));
735  }
736 
737  /* In all cases disallow placing user relations in pg_global */
738  if (tablespaceId == GLOBALTABLESPACE_OID)
739  ereport(ERROR,
740  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
741  errmsg("only shared relations can be placed in pg_global tablespace")));
742 
743  /* Identify user ID that will own the table */
744  if (!OidIsValid(ownerId))
745  ownerId = GetUserId();
746 
747  /*
748  * Parse and validate reloptions, if any.
749  */
750  reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
751  true, false);
752 
753  switch (relkind)
754  {
755  case RELKIND_VIEW:
756  (void) view_reloptions(reloptions, true);
757  break;
758  case RELKIND_PARTITIONED_TABLE:
759  (void) partitioned_table_reloptions(reloptions, true);
760  break;
761  default:
762  (void) heap_reloptions(relkind, reloptions, true);
763  }
764 
765  if (stmt->ofTypename)
766  {
767  AclResult aclresult;
768 
769  ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
770 
771  aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
772  if (aclresult != ACLCHECK_OK)
773  aclcheck_error_type(aclresult, ofTypeId);
774  }
775  else
776  ofTypeId = InvalidOid;
777 
778  /*
779  * Look up inheritance ancestors and generate relation schema, including
780  * inherited attributes. (Note that stmt->tableElts is destructively
781  * modified by MergeAttributes.)
782  */
783  stmt->tableElts =
784  MergeAttributes(stmt->tableElts, inheritOids,
785  stmt->relation->relpersistence,
786  stmt->partbound != NULL,
787  &old_constraints);
788 
789  /*
790  * Create a tuple descriptor from the relation schema. Note that this
791  * deals with column names, types, and NOT NULL constraints, but not
792  * default values or CHECK constraints; we handle those below.
793  */
794  descriptor = BuildDescForRelation(stmt->tableElts);
795 
796  /*
797  * Find columns with default values and prepare for insertion of the
798  * defaults. Pre-cooked (that is, inherited) defaults go into a list of
799  * CookedConstraint structs that we'll pass to heap_create_with_catalog,
800  * while raw defaults go into a list of RawColumnDefault structs that will
801  * be processed by AddRelationNewConstraints. (We can't deal with raw
802  * expressions until we can do transformExpr.)
803  *
804  * We can set the atthasdef flags now in the tuple descriptor; this just
805  * saves StoreAttrDefault from having to do an immediate update of the
806  * pg_attribute rows.
807  */
808  rawDefaults = NIL;
809  cookedDefaults = NIL;
810  attnum = 0;
811 
812  foreach(listptr, stmt->tableElts)
813  {
814  ColumnDef *colDef = lfirst(listptr);
815  Form_pg_attribute attr;
816 
817  attnum++;
818  attr = TupleDescAttr(descriptor, attnum - 1);
819 
820  if (colDef->raw_default != NULL)
821  {
822  RawColumnDefault *rawEnt;
823 
824  Assert(colDef->cooked_default == NULL);
825 
826  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
827  rawEnt->attnum = attnum;
828  rawEnt->raw_default = colDef->raw_default;
829  rawEnt->missingMode = false;
830  rawEnt->generated = colDef->generated;
831  rawDefaults = lappend(rawDefaults, rawEnt);
832  attr->atthasdef = true;
833  }
834  else if (colDef->cooked_default != NULL)
835  {
836  CookedConstraint *cooked;
837 
838  cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
839  cooked->contype = CONSTR_DEFAULT;
840  cooked->conoid = InvalidOid; /* until created */
841  cooked->name = NULL;
842  cooked->attnum = attnum;
843  cooked->expr = colDef->cooked_default;
844  cooked->skip_validation = false;
845  cooked->is_local = true; /* not used for defaults */
846  cooked->inhcount = 0; /* ditto */
847  cooked->is_no_inherit = false;
848  cookedDefaults = lappend(cookedDefaults, cooked);
849  attr->atthasdef = true;
850  }
851 
852  if (colDef->identity)
853  attr->attidentity = colDef->identity;
854 
855  if (colDef->generated)
856  attr->attgenerated = colDef->generated;
857  }
858 
859  /*
860  * If the statement hasn't specified an access method, but we're defining
861  * a type of relation that needs one, use the default.
862  */
863  if (stmt->accessMethod != NULL)
864  {
865  accessMethod = stmt->accessMethod;
866 
867  if (partitioned)
868  ereport(ERROR,
869  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
870  errmsg("specifying a table access method is not supported on a partitioned table")));
871 
872  }
873  else if (relkind == RELKIND_RELATION ||
874  relkind == RELKIND_TOASTVALUE ||
875  relkind == RELKIND_MATVIEW)
876  accessMethod = default_table_access_method;
877 
878  /* look up the access method, verify it is for a table */
879  if (accessMethod != NULL)
880  accessMethodId = get_table_am_oid(accessMethod, false);
881 
882  /*
883  * Create the relation. Inherited defaults and constraints are passed in
884  * for immediate handling --- since they don't need parsing, they can be
885  * stored immediately.
886  */
887  relationId = heap_create_with_catalog(relname,
888  namespaceId,
889  tablespaceId,
890  InvalidOid,
891  InvalidOid,
892  ofTypeId,
893  ownerId,
894  accessMethodId,
895  descriptor,
896  list_concat(cookedDefaults,
897  old_constraints),
898  relkind,
899  stmt->relation->relpersistence,
900  false,
901  false,
902  stmt->oncommit,
903  reloptions,
904  true,
906  false,
907  InvalidOid,
908  typaddress);
909 
910  /*
911  * We must bump the command counter to make the newly-created relation
912  * tuple visible for opening.
913  */
915 
916  /*
917  * Open the new relation and acquire exclusive lock on it. This isn't
918  * really necessary for locking out other backends (since they can't see
919  * the new rel anyway until we commit), but it keeps the lock manager from
920  * complaining about deadlock risks.
921  */
922  rel = relation_open(relationId, AccessExclusiveLock);
923 
924  /*
925  * Now add any newly specified column default and generation expressions
926  * to the new relation. These are passed to us in the form of raw
927  * parsetrees; we need to transform them to executable expression trees
928  * before they can be added. The most convenient way to do that is to
929  * apply the parser's transformExpr routine, but transformExpr doesn't
930  * work unless we have a pre-existing relation. So, the transformation has
931  * to be postponed to this final step of CREATE TABLE.
932  *
933  * This needs to be before processing the partitioning clauses because
934  * those could refer to generated columns.
935  */
936  if (rawDefaults)
937  AddRelationNewConstraints(rel, rawDefaults, NIL,
938  true, true, false, queryString);
939 
940  /*
941  * Make column generation expressions visible for use by partitioning.
942  */
944 
945  /* Process and store partition bound, if any. */
946  if (stmt->partbound)
947  {
948  PartitionBoundSpec *bound;
949  ParseState *pstate;
950  Oid parentId = linitial_oid(inheritOids),
951  defaultPartOid;
952  Relation parent,
953  defaultRel = NULL;
954  ParseNamespaceItem *nsitem;
955 
956  /* Already have strong enough lock on the parent */
957  parent = table_open(parentId, NoLock);
958 
959  /*
960  * We are going to try to validate the partition bound specification
961  * against the partition key of parentRel, so it better have one.
962  */
963  if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
964  ereport(ERROR,
965  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
966  errmsg("\"%s\" is not partitioned",
967  RelationGetRelationName(parent))));
968 
969  /*
970  * The partition constraint of the default partition depends on the
971  * partition bounds of every other partition. It is possible that
972  * another backend might be about to execute a query on the default
973  * partition table, and that the query relies on previously cached
974  * default partition constraints. We must therefore take a table lock
975  * strong enough to prevent all queries on the default partition from
976  * proceeding until we commit and send out a shared-cache-inval notice
977  * that will make them update their index lists.
978  *
979  * Order of locking: The relation being added won't be visible to
980  * other backends until it is committed, hence here in
981  * DefineRelation() the order of locking the default partition and the
982  * relation being added does not matter. But at all other places we
983  * need to lock the default relation before we lock the relation being
984  * added or removed i.e. we should take the lock in same order at all
985  * the places such that lock parent, lock default partition and then
986  * lock the partition so as to avoid a deadlock.
987  */
988  defaultPartOid =
990  if (OidIsValid(defaultPartOid))
991  defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
992 
993  /* Transform the bound values */
994  pstate = make_parsestate(NULL);
995  pstate->p_sourcetext = queryString;
996 
997  /*
998  * Add an nsitem containing this relation, so that transformExpr
999  * called on partition bound expressions is able to report errors
1000  * using a proper context.
1001  */
1002  nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1003  NULL, false, false);
1004  addNSItemToQuery(pstate, nsitem, false, true, true);
1005 
1006  bound = transformPartitionBound(pstate, parent, stmt->partbound);
1007 
1008  /*
1009  * Check first that the new partition's bound is valid and does not
1010  * overlap with any of existing partitions of the parent.
1011  */
1012  check_new_partition_bound(relname, parent, bound, pstate);
1013 
1014  /*
1015  * If the default partition exists, its partition constraints will
1016  * change after the addition of this new partition such that it won't
1017  * allow any row that qualifies for this new partition. So, check that
1018  * the existing data in the default partition satisfies the constraint
1019  * as it will exist after adding this partition.
1020  */
1021  if (OidIsValid(defaultPartOid))
1022  {
1023  check_default_partition_contents(parent, defaultRel, bound);
1024  /* Keep the lock until commit. */
1025  table_close(defaultRel, NoLock);
1026  }
1027 
1028  /* Update the pg_class entry. */
1029  StorePartitionBound(rel, parent, bound);
1030 
1031  table_close(parent, NoLock);
1032  }
1033 
1034  /* Store inheritance information for new rel. */
1035  StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
1036 
1037  /*
1038  * Process the partitioning specification (if any) and store the partition
1039  * key information into the catalog.
1040  */
1041  if (partitioned)
1042  {
1043  ParseState *pstate;
1044  char strategy;
1045  int partnatts;
1046  AttrNumber partattrs[PARTITION_MAX_KEYS];
1047  Oid partopclass[PARTITION_MAX_KEYS];
1048  Oid partcollation[PARTITION_MAX_KEYS];
1049  List *partexprs = NIL;
1050 
1051  pstate = make_parsestate(NULL);
1052  pstate->p_sourcetext = queryString;
1053 
1054  partnatts = list_length(stmt->partspec->partParams);
1055 
1056  /* Protect fixed-size arrays here and in executor */
1057  if (partnatts > PARTITION_MAX_KEYS)
1058  ereport(ERROR,
1059  (errcode(ERRCODE_TOO_MANY_COLUMNS),
1060  errmsg("cannot partition using more than %d columns",
1061  PARTITION_MAX_KEYS)));
1062 
1063  /*
1064  * We need to transform the raw parsetrees corresponding to partition
1065  * expressions into executable expression trees. Like column defaults
1066  * and CHECK constraints, we could not have done the transformation
1067  * earlier.
1068  */
1069  stmt->partspec = transformPartitionSpec(rel, stmt->partspec,
1070  &strategy);
1071 
1072  ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1073  partattrs, &partexprs, partopclass,
1074  partcollation, strategy);
1075 
1076  StorePartitionKey(rel, strategy, partnatts, partattrs, partexprs,
1077  partopclass, partcollation);
1078 
1079  /* make it all visible */
1081  }
1082 
1083  /*
1084  * If we're creating a partition, create now all the indexes, triggers,
1085  * FKs defined in the parent.
1086  *
1087  * We can't do it earlier, because DefineIndex wants to know the partition
1088  * key which we just stored.
1089  */
1090  if (stmt->partbound)
1091  {
1092  Oid parentId = linitial_oid(inheritOids);
1093  Relation parent;
1094  List *idxlist;
1095  ListCell *cell;
1096 
1097  /* Already have strong enough lock on the parent */
1098  parent = table_open(parentId, NoLock);
1099  idxlist = RelationGetIndexList(parent);
1100 
1101  /*
1102  * For each index in the parent table, create one in the partition
1103  */
1104  foreach(cell, idxlist)
1105  {
1106  Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1107  AttrMap *attmap;
1108  IndexStmt *idxstmt;
1109  Oid constraintOid;
1110 
1111  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1112  {
1113  if (idxRel->rd_index->indisunique)
1114  ereport(ERROR,
1115  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1116  errmsg("cannot create foreign partition of partitioned table \"%s\"",
1117  RelationGetRelationName(parent)),
1118  errdetail("Table \"%s\" contains indexes that are unique.",
1119  RelationGetRelationName(parent))));
1120  else
1121  {
1122  index_close(idxRel, AccessShareLock);
1123  continue;
1124  }
1125  }
1126 
1128  RelationGetDescr(parent));
1129  idxstmt =
1130  generateClonedIndexStmt(NULL, idxRel,
1131  attmap, &constraintOid);
1133  idxstmt,
1134  InvalidOid,
1135  RelationGetRelid(idxRel),
1136  constraintOid,
1137  false, false, false, false, false);
1138 
1139  index_close(idxRel, AccessShareLock);
1140  }
1141 
1142  list_free(idxlist);
1143 
1144  /*
1145  * If there are any row-level triggers, clone them to the new
1146  * partition.
1147  */
1148  if (parent->trigdesc != NULL)
1149  CloneRowTriggersToPartition(parent, rel);
1150 
1151  /*
1152  * And foreign keys too. Note that because we're freshly creating the
1153  * table, there is no need to verify these new constraints.
1154  */
1155  CloneForeignKeyConstraints(NULL, parent, rel);
1156 
1157  table_close(parent, NoLock);
1158  }
1159 
1160  /*
1161  * Now add any newly specified CHECK constraints to the new relation. Same
1162  * as for defaults above, but these need to come after partitioning is set
1163  * up.
1164  */
1165  if (stmt->constraints)
1167  true, true, false, queryString);
1168 
1169  ObjectAddressSet(address, RelationRelationId, relationId);
1170 
1171  /*
1172  * Clean up. We keep lock on new relation (although it shouldn't be
1173  * visible to anyone else anyway, until commit).
1174  */
1175  relation_close(rel, NoLock);
1176 
1177  return address;
1178 }
1179 
1180 /*
1181  * Emit the right error or warning message for a "DROP" command issued on a
1182  * non-existent relation
1183  */
1184 static void
1185 DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
1186 {
1187  const struct dropmsgstrings *rentry;
1188 
1189  if (rel->schemaname != NULL &&
1191  {
1192  if (!missing_ok)
1193  {
1194  ereport(ERROR,
1195  (errcode(ERRCODE_UNDEFINED_SCHEMA),
1196  errmsg("schema \"%s\" does not exist", rel->schemaname)));
1197  }
1198  else
1199  {
1200  ereport(NOTICE,
1201  (errmsg("schema \"%s\" does not exist, skipping",
1202  rel->schemaname)));
1203  }
1204  return;
1205  }
1206 
1207  for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1208  {
1209  if (rentry->kind == rightkind)
1210  {
1211  if (!missing_ok)
1212  {
1213  ereport(ERROR,
1214  (errcode(rentry->nonexistent_code),
1215  errmsg(rentry->nonexistent_msg, rel->relname)));
1216  }
1217  else
1218  {
1219  ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
1220  break;
1221  }
1222  }
1223  }
1224 
1225  Assert(rentry->kind != '\0'); /* Should be impossible */
1226 }
1227 
1228 /*
1229  * Emit the right error message for a "DROP" command issued on a
1230  * relation of the wrong type
1231  */
1232 static void
1233 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
1234 {
1235  const struct dropmsgstrings *rentry;
1236  const struct dropmsgstrings *wentry;
1237 
1238  for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1239  if (rentry->kind == rightkind)
1240  break;
1241  Assert(rentry->kind != '\0');
1242 
1243  for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
1244  if (wentry->kind == wrongkind)
1245  break;
1246  /* wrongkind could be something we don't have in our table... */
1247 
1248  ereport(ERROR,
1249  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1250  errmsg(rentry->nota_msg, relname),
1251  (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
1252 }
1253 
1254 /*
1255  * RemoveRelations
1256  * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
1257  * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
1258  */
1259 void
1261 {
1262  ObjectAddresses *objects;
1263  char relkind;
1264  ListCell *cell;
1265  int flags = 0;
1266  LOCKMODE lockmode = AccessExclusiveLock;
1267 
1268  /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1269  if (drop->concurrent)
1270  {
1271  /*
1272  * Note that for temporary relations this lock may get upgraded later
1273  * on, but as no other session can access a temporary relation, this
1274  * is actually fine.
1275  */
1276  lockmode = ShareUpdateExclusiveLock;
1277  Assert(drop->removeType == OBJECT_INDEX);
1278  if (list_length(drop->objects) != 1)
1279  ereport(ERROR,
1280  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1281  errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1282  if (drop->behavior == DROP_CASCADE)
1283  ereport(ERROR,
1284  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1285  errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1286  }
1287 
1288  /*
1289  * First we identify all the relations, then we delete them in a single
1290  * performMultipleDeletions() call. This is to avoid unwanted DROP
1291  * RESTRICT errors if one of the relations depends on another.
1292  */
1293 
1294  /* Determine required relkind */
1295  switch (drop->removeType)
1296  {
1297  case OBJECT_TABLE:
1298  relkind = RELKIND_RELATION;
1299  break;
1300 
1301  case OBJECT_INDEX:
1302  relkind = RELKIND_INDEX;
1303  break;
1304 
1305  case OBJECT_SEQUENCE:
1306  relkind = RELKIND_SEQUENCE;
1307  break;
1308 
1309  case OBJECT_VIEW:
1310  relkind = RELKIND_VIEW;
1311  break;
1312 
1313  case OBJECT_MATVIEW:
1314  relkind = RELKIND_MATVIEW;
1315  break;
1316 
1317  case OBJECT_FOREIGN_TABLE:
1318  relkind = RELKIND_FOREIGN_TABLE;
1319  break;
1320 
1321  default:
1322  elog(ERROR, "unrecognized drop object type: %d",
1323  (int) drop->removeType);
1324  relkind = 0; /* keep compiler quiet */
1325  break;
1326  }
1327 
1328  /* Lock and validate each relation; build a list of object addresses */
1329  objects = new_object_addresses();
1330 
1331  foreach(cell, drop->objects)
1332  {
1333  RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1334  Oid relOid;
1335  ObjectAddress obj;
1336  struct DropRelationCallbackState state;
1337 
1338  /*
1339  * These next few steps are a great deal like relation_openrv, but we
1340  * don't bother building a relcache entry since we don't need it.
1341  *
1342  * Check for shared-cache-inval messages before trying to access the
1343  * relation. This is needed to cover the case where the name
1344  * identifies a rel that has been dropped and recreated since the
1345  * start of our transaction: if we don't flush the old syscache entry,
1346  * then we'll latch onto that entry and suffer an error later.
1347  */
1349 
1350  /* Look up the appropriate relation using namespace search. */
1351  state.relkind = relkind;
1352  state.heapOid = InvalidOid;
1353  state.partParentOid = InvalidOid;
1354  state.concurrent = drop->concurrent;
1355  relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1357  (void *) &state);
1358 
1359  /* Not there? */
1360  if (!OidIsValid(relOid))
1361  {
1362  DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1363  continue;
1364  }
1365 
1366  /*
1367  * Decide if concurrent mode needs to be used here or not. The
1368  * relation persistence cannot be known without its OID.
1369  */
1370  if (drop->concurrent &&
1371  get_rel_persistence(relOid) != RELPERSISTENCE_TEMP)
1372  {
1373  Assert(list_length(drop->objects) == 1 &&
1374  drop->removeType == OBJECT_INDEX);
1376  }
1377 
1378  /*
1379  * Concurrent index drop cannot be used with partitioned indexes,
1380  * either.
1381  */
1382  if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1383  get_rel_relkind(relOid) == RELKIND_PARTITIONED_INDEX)
1384  ereport(ERROR,
1385  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1386  errmsg("cannot drop partitioned index \"%s\" concurrently",
1387  rel->relname)));
1388 
1389  /* OK, we're ready to delete this one */
1390  obj.classId = RelationRelationId;
1391  obj.objectId = relOid;
1392  obj.objectSubId = 0;
1393 
1394  add_exact_object_address(&obj, objects);
1395  }
1396 
1397  performMultipleDeletions(objects, drop->behavior, flags);
1398 
1399  free_object_addresses(objects);
1400 }
1401 
1402 /*
1403  * Before acquiring a table lock, check whether we have sufficient rights.
1404  * In the case of DROP INDEX, also try to lock the table before the index.
1405  * Also, if the table to be dropped is a partition, we try to lock the parent
1406  * first.
1407  */
1408 static void
1409 RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
1410  void *arg)
1411 {
1412  HeapTuple tuple;
1414  char relkind;
1415  char expected_relkind;
1416  bool is_partition;
1417  Form_pg_class classform;
1418  LOCKMODE heap_lockmode;
1419  bool invalid_system_index = false;
1420 
1421  state = (struct DropRelationCallbackState *) arg;
1422  relkind = state->relkind;
1423  heap_lockmode = state->concurrent ?
1425 
1426  /*
1427  * If we previously locked some other index's heap, and the name we're
1428  * looking up no longer refers to that relation, release the now-useless
1429  * lock.
1430  */
1431  if (relOid != oldRelOid && OidIsValid(state->heapOid))
1432  {
1433  UnlockRelationOid(state->heapOid, heap_lockmode);
1434  state->heapOid = InvalidOid;
1435  }
1436 
1437  /*
1438  * Similarly, if we previously locked some other partition's heap, and the
1439  * name we're looking up no longer refers to that relation, release the
1440  * now-useless lock.
1441  */
1442  if (relOid != oldRelOid && OidIsValid(state->partParentOid))
1443  {
1445  state->partParentOid = InvalidOid;
1446  }
1447 
1448  /* Didn't find a relation, so no need for locking or permission checks. */
1449  if (!OidIsValid(relOid))
1450  return;
1451 
1452  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1453  if (!HeapTupleIsValid(tuple))
1454  return; /* concurrently dropped, so nothing to do */
1455  classform = (Form_pg_class) GETSTRUCT(tuple);
1456  is_partition = classform->relispartition;
1457 
1458  /*
1459  * Both RELKIND_RELATION and RELKIND_PARTITIONED_TABLE are OBJECT_TABLE,
1460  * but RemoveRelations() can only pass one relkind for a given relation.
1461  * It chooses RELKIND_RELATION for both regular and partitioned tables.
1462  * That means we must be careful before giving the wrong type error when
1463  * the relation is RELKIND_PARTITIONED_TABLE. An equivalent problem
1464  * exists with indexes.
1465  */
1466  if (classform->relkind == RELKIND_PARTITIONED_TABLE)
1467  expected_relkind = RELKIND_RELATION;
1468  else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
1469  expected_relkind = RELKIND_INDEX;
1470  else
1471  expected_relkind = classform->relkind;
1472 
1473  if (relkind != expected_relkind)
1474  DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
1475 
1476  /* Allow DROP to either table owner or schema owner */
1477  if (!pg_class_ownercheck(relOid, GetUserId()) &&
1478  !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
1480  rel->relname);
1481 
1482  /*
1483  * Check the case of a system index that might have been invalidated by a
1484  * failed concurrent process and allow its drop. For the time being, this
1485  * only concerns indexes of toast relations that became invalid during a
1486  * REINDEX CONCURRENTLY process.
1487  */
1488  if (IsSystemClass(relOid, classform) && relkind == RELKIND_INDEX)
1489  {
1490  HeapTuple locTuple;
1491  Form_pg_index indexform;
1492  bool indisvalid;
1493 
1494  locTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
1495  if (!HeapTupleIsValid(locTuple))
1496  {
1497  ReleaseSysCache(tuple);
1498  return;
1499  }
1500 
1501  indexform = (Form_pg_index) GETSTRUCT(locTuple);
1502  indisvalid = indexform->indisvalid;
1503  ReleaseSysCache(locTuple);
1504 
1505  /* Mark object as being an invalid index of system catalogs */
1506  if (!indisvalid)
1507  invalid_system_index = true;
1508  }
1509 
1510  /* In the case of an invalid index, it is fine to bypass this check */
1511  if (!invalid_system_index && !allowSystemTableMods && IsSystemClass(relOid, classform))
1512  ereport(ERROR,
1513  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1514  errmsg("permission denied: \"%s\" is a system catalog",
1515  rel->relname)));
1516 
1517  ReleaseSysCache(tuple);
1518 
1519  /*
1520  * In DROP INDEX, attempt to acquire lock on the parent table before
1521  * locking the index. index_drop() will need this anyway, and since
1522  * regular queries lock tables before their indexes, we risk deadlock if
1523  * we do it the other way around. No error if we don't find a pg_index
1524  * entry, though --- the relation may have been dropped.
1525  */
1526  if ((relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX) &&
1527  relOid != oldRelOid)
1528  {
1529  state->heapOid = IndexGetRelation(relOid, true);
1530  if (OidIsValid(state->heapOid))
1531  LockRelationOid(state->heapOid, heap_lockmode);
1532  }
1533 
1534  /*
1535  * Similarly, if the relation is a partition, we must acquire lock on its
1536  * parent before locking the partition. That's because queries lock the
1537  * parent before its partitions, so we risk deadlock it we do it the other
1538  * way around.
1539  */
1540  if (is_partition && relOid != oldRelOid)
1541  {
1542  state->partParentOid = get_partition_parent(relOid);
1543  if (OidIsValid(state->partParentOid))
1545  }
1546 }
1547 
1548 /*
1549  * ExecuteTruncate
1550  * Executes a TRUNCATE command.
1551  *
1552  * This is a multi-relation truncate. We first open and grab exclusive
1553  * lock on all relations involved, checking permissions and otherwise
1554  * verifying that the relation is OK for truncation. In CASCADE mode,
1555  * relations having FK references to the targeted relations are automatically
1556  * added to the group; in RESTRICT mode, we check that all FK references are
1557  * internal to the group that's being truncated. Finally all the relations
1558  * are truncated and reindexed.
1559  */
1560 void
1562 {
1563  List *rels = NIL;
1564  List *relids = NIL;
1565  List *relids_logged = NIL;
1566  ListCell *cell;
1567 
1568  /*
1569  * Open, exclusive-lock, and check all the explicitly-specified relations
1570  */
1571  foreach(cell, stmt->relations)
1572  {
1573  RangeVar *rv = lfirst(cell);
1574  Relation rel;
1575  bool recurse = rv->inh;
1576  Oid myrelid;
1577  LOCKMODE lockmode = AccessExclusiveLock;
1578 
1579  myrelid = RangeVarGetRelidExtended(rv, lockmode,
1581  NULL);
1582 
1583  /* open the relation, we already hold a lock on it */
1584  rel = table_open(myrelid, NoLock);
1585 
1586  /* don't throw error for "TRUNCATE foo, foo" */
1587  if (list_member_oid(relids, myrelid))
1588  {
1589  table_close(rel, lockmode);
1590  continue;
1591  }
1592 
1593  /*
1594  * RangeVarGetRelidExtended() has done most checks with its callback,
1595  * but other checks with the now-opened Relation remain.
1596  */
1598 
1599  rels = lappend(rels, rel);
1600  relids = lappend_oid(relids, myrelid);
1601  /* Log this relation only if needed for logical decoding */
1602  if (RelationIsLogicallyLogged(rel))
1603  relids_logged = lappend_oid(relids_logged, myrelid);
1604 
1605  if (recurse)
1606  {
1607  ListCell *child;
1608  List *children;
1609 
1610  children = find_all_inheritors(myrelid, lockmode, NULL);
1611 
1612  foreach(child, children)
1613  {
1614  Oid childrelid = lfirst_oid(child);
1615 
1616  if (list_member_oid(relids, childrelid))
1617  continue;
1618 
1619  /* find_all_inheritors already got lock */
1620  rel = table_open(childrelid, NoLock);
1621 
1622  /*
1623  * It is possible that the parent table has children that are
1624  * temp tables of other backends. We cannot safely access
1625  * such tables (because of buffering issues), and the best
1626  * thing to do is to silently ignore them. Note that this
1627  * check is the same as one of the checks done in
1628  * truncate_check_activity() called below, still it is kept
1629  * here for simplicity.
1630  */
1631  if (RELATION_IS_OTHER_TEMP(rel))
1632  {
1633  table_close(rel, lockmode);
1634  continue;
1635  }
1636 
1637  /*
1638  * Inherited TRUNCATE commands perform access permission
1639  * checks on the parent table only. So we skip checking the
1640  * children's permissions and don't call
1641  * truncate_check_perms() here.
1642  */
1645 
1646  rels = lappend(rels, rel);
1647  relids = lappend_oid(relids, childrelid);
1648  /* Log this relation only if needed for logical decoding */
1649  if (RelationIsLogicallyLogged(rel))
1650  relids_logged = lappend_oid(relids_logged, childrelid);
1651  }
1652  }
1653  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1654  ereport(ERROR,
1655  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1656  errmsg("cannot truncate only a partitioned table"),
1657  errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1658  }
1659 
1660  ExecuteTruncateGuts(rels, relids, relids_logged,
1661  stmt->behavior, stmt->restart_seqs);
1662 
1663  /* And close the rels */
1664  foreach(cell, rels)
1665  {
1666  Relation rel = (Relation) lfirst(cell);
1667 
1668  table_close(rel, NoLock);
1669  }
1670 }
1671 
1672 /*
1673  * ExecuteTruncateGuts
1674  *
1675  * Internal implementation of TRUNCATE. This is called by the actual TRUNCATE
1676  * command (see above) as well as replication subscribers that execute a
1677  * replicated TRUNCATE action.
1678  *
1679  * explicit_rels is the list of Relations to truncate that the command
1680  * specified. relids is the list of Oids corresponding to explicit_rels.
1681  * relids_logged is the list of Oids (a subset of relids) that require
1682  * WAL-logging. This is all a bit redundant, but the existing callers have
1683  * this information handy in this form.
1684  */
1685 void
1686 ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged,
1687  DropBehavior behavior, bool restart_seqs)
1688 {
1689  List *rels;
1690  List *seq_relids = NIL;
1691  EState *estate;
1692  ResultRelInfo *resultRelInfos;
1693  ResultRelInfo *resultRelInfo;
1694  SubTransactionId mySubid;
1695  ListCell *cell;
1696  Oid *logrelids;
1697 
1698  /*
1699  * Check the explicitly-specified relations.
1700  *
1701  * In CASCADE mode, suck in all referencing relations as well. This
1702  * requires multiple iterations to find indirectly-dependent relations. At
1703  * each phase, we need to exclusive-lock new rels before looking for their
1704  * dependencies, else we might miss something. Also, we check each rel as
1705  * soon as we open it, to avoid a faux pas such as holding lock for a long
1706  * time on a rel we have no permissions for.
1707  */
1708  rels = list_copy(explicit_rels);
1709  if (behavior == DROP_CASCADE)
1710  {
1711  for (;;)
1712  {
1713  List *newrelids;
1714 
1715  newrelids = heap_truncate_find_FKs(relids);
1716  if (newrelids == NIL)
1717  break; /* nothing else to add */
1718 
1719  foreach(cell, newrelids)
1720  {
1721  Oid relid = lfirst_oid(cell);
1722  Relation rel;
1723 
1724  rel = table_open(relid, AccessExclusiveLock);
1725  ereport(NOTICE,
1726  (errmsg("truncate cascades to table \"%s\"",
1727  RelationGetRelationName(rel))));
1728  truncate_check_rel(relid, rel->rd_rel);
1729  truncate_check_perms(relid, rel->rd_rel);
1731  rels = lappend(rels, rel);
1732  relids = lappend_oid(relids, relid);
1733  /* Log this relation only if needed for logical decoding */
1734  if (RelationIsLogicallyLogged(rel))
1735  relids_logged = lappend_oid(relids_logged, relid);
1736  }
1737  }
1738  }
1739 
1740  /*
1741  * Check foreign key references. In CASCADE mode, this should be
1742  * unnecessary since we just pulled in all the references; but as a
1743  * cross-check, do it anyway if in an Assert-enabled build.
1744  */
1745 #ifdef USE_ASSERT_CHECKING
1746  heap_truncate_check_FKs(rels, false);
1747 #else
1748  if (behavior == DROP_RESTRICT)
1749  heap_truncate_check_FKs(rels, false);
1750 #endif
1751 
1752  /*
1753  * If we are asked to restart sequences, find all the sequences, lock them
1754  * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1755  * We want to do this early since it's pointless to do all the truncation
1756  * work only to fail on sequence permissions.
1757  */
1758  if (restart_seqs)
1759  {
1760  foreach(cell, rels)
1761  {
1762  Relation rel = (Relation) lfirst(cell);
1763  List *seqlist = getOwnedSequences(RelationGetRelid(rel));
1764  ListCell *seqcell;
1765 
1766  foreach(seqcell, seqlist)
1767  {
1768  Oid seq_relid = lfirst_oid(seqcell);
1769  Relation seq_rel;
1770 
1771  seq_rel = relation_open(seq_relid, AccessExclusiveLock);
1772 
1773  /* This check must match AlterSequence! */
1774  if (!pg_class_ownercheck(seq_relid, GetUserId()))
1776  RelationGetRelationName(seq_rel));
1777 
1778  seq_relids = lappend_oid(seq_relids, seq_relid);
1779 
1780  relation_close(seq_rel, NoLock);
1781  }
1782  }
1783  }
1784 
1785  /* Prepare to catch AFTER triggers. */
1787 
1788  /*
1789  * To fire triggers, we'll need an EState as well as a ResultRelInfo for
1790  * each relation. We don't need to call ExecOpenIndices, though.
1791  *
1792  * We put the ResultRelInfos in the es_opened_result_relations list, even
1793  * though we don't have a range table and don't populate the
1794  * es_result_relations array. That's a bit bogus, but it's enough to make
1795  * ExecGetTriggerResultRel() find them.
1796  */
1797  estate = CreateExecutorState();
1798  resultRelInfos = (ResultRelInfo *)
1799  palloc(list_length(rels) * sizeof(ResultRelInfo));
1800  resultRelInfo = resultRelInfos;
1801  foreach(cell, rels)
1802  {
1803  Relation rel = (Relation) lfirst(cell);
1804 
1805  InitResultRelInfo(resultRelInfo,
1806  rel,
1807  0, /* dummy rangetable index */
1808  NULL,
1809  0);
1810  estate->es_opened_result_relations =
1811  lappend(estate->es_opened_result_relations, resultRelInfo);
1812  resultRelInfo++;
1813  }
1814 
1815  /*
1816  * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1817  * truncating (this is because one of them might throw an error). Also, if
1818  * we were to allow them to prevent statement execution, that would need
1819  * to be handled here.
1820  */
1821  resultRelInfo = resultRelInfos;
1822  foreach(cell, rels)
1823  {
1824  ExecBSTruncateTriggers(estate, resultRelInfo);
1825  resultRelInfo++;
1826  }
1827 
1828  /*
1829  * OK, truncate each table.
1830  */
1831  mySubid = GetCurrentSubTransactionId();
1832 
1833  foreach(cell, rels)
1834  {
1835  Relation rel = (Relation) lfirst(cell);
1836 
1837  /* Skip partitioned tables as there is nothing to do */
1838  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1839  continue;
1840 
1841  /*
1842  * Normally, we need a transaction-safe truncation here. However, if
1843  * the table was either created in the current (sub)transaction or has
1844  * a new relfilenode in the current (sub)transaction, then we can just
1845  * truncate it in-place, because a rollback would cause the whole
1846  * table or the current physical file to be thrown away anyway.
1847  */
1848  if (rel->rd_createSubid == mySubid ||
1849  rel->rd_newRelfilenodeSubid == mySubid)
1850  {
1851  /* Immediate, non-rollbackable truncation is OK */
1852  heap_truncate_one_rel(rel);
1853  }
1854  else
1855  {
1856  Oid heap_relid;
1857  Oid toast_relid;
1858 
1859  /*
1860  * This effectively deletes all rows in the table, and may be done
1861  * in a serializable transaction. In that case we must record a
1862  * rw-conflict in to this transaction from each transaction
1863  * holding a predicate lock on the table.
1864  */
1866 
1867  /*
1868  * Need the full transaction-safe pushups.
1869  *
1870  * Create a new empty storage file for the relation, and assign it
1871  * as the relfilenode value. The old storage file is scheduled for
1872  * deletion at commit.
1873  */
1874  RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence);
1875 
1876  heap_relid = RelationGetRelid(rel);
1877 
1878  /*
1879  * The same for the toast table, if any.
1880  */
1881  toast_relid = rel->rd_rel->reltoastrelid;
1882  if (OidIsValid(toast_relid))
1883  {
1884  Relation toastrel = relation_open(toast_relid,
1886 
1887  RelationSetNewRelfilenode(toastrel,
1888  toastrel->rd_rel->relpersistence);
1889  table_close(toastrel, NoLock);
1890  }
1891 
1892  /*
1893  * Reconstruct the indexes to match, and we're done.
1894  */
1896  }
1897 
1898  pgstat_count_truncate(rel);
1899  }
1900 
1901  /*
1902  * Restart owned sequences if we were asked to.
1903  */
1904  foreach(cell, seq_relids)
1905  {
1906  Oid seq_relid = lfirst_oid(cell);
1907 
1908  ResetSequence(seq_relid);
1909  }
1910 
1911  /*
1912  * Write a WAL record to allow this set of actions to be logically
1913  * decoded.
1914  *
1915  * Assemble an array of relids so we can write a single WAL record for the
1916  * whole action.
1917  */
1918  if (list_length(relids_logged) > 0)
1919  {
1920  xl_heap_truncate xlrec;
1921  int i = 0;
1922 
1923  /* should only get here if wal_level >= logical */
1925 
1926  logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
1927  foreach(cell, relids_logged)
1928  logrelids[i++] = lfirst_oid(cell);
1929 
1930  xlrec.dbId = MyDatabaseId;
1931  xlrec.nrelids = list_length(relids_logged);
1932  xlrec.flags = 0;
1933  if (behavior == DROP_CASCADE)
1934  xlrec.flags |= XLH_TRUNCATE_CASCADE;
1935  if (restart_seqs)
1937 
1938  XLogBeginInsert();
1939  XLogRegisterData((char *) &xlrec, SizeOfHeapTruncate);
1940  XLogRegisterData((char *) logrelids, list_length(relids_logged) * sizeof(Oid));
1941 
1943 
1944  (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
1945  }
1946 
1947  /*
1948  * Process all AFTER STATEMENT TRUNCATE triggers.
1949  */
1950  resultRelInfo = resultRelInfos;
1951  foreach(cell, rels)
1952  {
1953  ExecASTruncateTriggers(estate, resultRelInfo);
1954  resultRelInfo++;
1955  }
1956 
1957  /* Handle queued AFTER triggers */
1958  AfterTriggerEndQuery(estate);
1959 
1960  /* We can clean up the EState now */
1961  FreeExecutorState(estate);
1962 
1963  /*
1964  * Close any rels opened by CASCADE (can't do this while EState still
1965  * holds refs)
1966  */
1967  rels = list_difference_ptr(rels, explicit_rels);
1968  foreach(cell, rels)
1969  {
1970  Relation rel = (Relation) lfirst(cell);
1971 
1972  table_close(rel, NoLock);
1973  }
1974 }
1975 
1976 /*
1977  * Check that a given relation is safe to truncate. Subroutine for
1978  * ExecuteTruncate() and RangeVarCallbackForTruncate().
1979  */
1980 static void
1982 {
1983  char *relname = NameStr(reltuple->relname);
1984 
1985  /*
1986  * Only allow truncate on regular tables and partitioned tables (although,
1987  * the latter are only being included here for the following checks; no
1988  * physical truncation will occur in their case.)
1989  */
1990  if (reltuple->relkind != RELKIND_RELATION &&
1991  reltuple->relkind != RELKIND_PARTITIONED_TABLE)
1992  ereport(ERROR,
1993  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1994  errmsg("\"%s\" is not a table", relname)));
1995 
1996  if (!allowSystemTableMods && IsSystemClass(relid, reltuple))
1997  ereport(ERROR,
1998  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1999  errmsg("permission denied: \"%s\" is a system catalog",
2000  relname)));
2001 
2002  InvokeObjectTruncateHook(relid);
2003 }
2004 
2005 /*
2006  * Check that current user has the permission to truncate given relation.
2007  */
2008 static void
2010 {
2011  char *relname = NameStr(reltuple->relname);
2012  AclResult aclresult;
2013 
2014  /* Permissions checks */
2015  aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
2016  if (aclresult != ACLCHECK_OK)
2017  aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
2018  relname);
2019 }
2020 
2021 /*
2022  * Set of extra sanity checks to check if a given relation is safe to
2023  * truncate. This is split with truncate_check_rel() as
2024  * RangeVarCallbackForTruncate() cannot open a Relation yet.
2025  */
2026 static void
2028 {
2029  /*
2030  * Don't allow truncate on temp tables of other backends ... their local
2031  * buffer manager is not going to cope.
2032  */
2033  if (RELATION_IS_OTHER_TEMP(rel))
2034  ereport(ERROR,
2035  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2036  errmsg("cannot truncate temporary tables of other sessions")));
2037 
2038  /*
2039  * Also check for active uses of the relation in the current transaction,
2040  * including open scans and pending AFTER trigger events.
2041  */
2042  CheckTableNotInUse(rel, "TRUNCATE");
2043 }
2044 
2045 /*
2046  * storage_name
2047  * returns the name corresponding to a typstorage/attstorage enum value
2048  */
2049 static const char *
2051 {
2052  switch (c)
2053  {
2054  case TYPSTORAGE_PLAIN:
2055  return "PLAIN";
2056  case TYPSTORAGE_EXTERNAL:
2057  return "EXTERNAL";
2058  case TYPSTORAGE_EXTENDED:
2059  return "EXTENDED";
2060  case TYPSTORAGE_MAIN:
2061  return "MAIN";
2062  default:
2063  return "???";
2064  }
2065 }
2066 
2067 /*----------
2068  * MergeAttributes
2069  * Returns new schema given initial schema and superclasses.
2070  *
2071  * Input arguments:
2072  * 'schema' is the column/attribute definition for the table. (It's a list
2073  * of ColumnDef's.) It is destructively changed.
2074  * 'supers' is a list of OIDs of parent relations, already locked by caller.
2075  * 'relpersistence' is the persistence type of the table.
2076  * 'is_partition' tells if the table is a partition.
2077  *
2078  * Output arguments:
2079  * 'supconstr' receives a list of constraints belonging to the parents,
2080  * updated as necessary to be valid for the child.
2081  *
2082  * Return value:
2083  * Completed schema list.
2084  *
2085  * Notes:
2086  * The order in which the attributes are inherited is very important.
2087  * Intuitively, the inherited attributes should come first. If a table
2088  * inherits from multiple parents, the order of those attributes are
2089  * according to the order of the parents specified in CREATE TABLE.
2090  *
2091  * Here's an example:
2092  *
2093  * create table person (name text, age int4, location point);
2094  * create table emp (salary int4, manager text) inherits(person);
2095  * create table student (gpa float8) inherits (person);
2096  * create table stud_emp (percent int4) inherits (emp, student);
2097  *
2098  * The order of the attributes of stud_emp is:
2099  *
2100  * person {1:name, 2:age, 3:location}
2101  * / \
2102  * {6:gpa} student emp {4:salary, 5:manager}
2103  * \ /
2104  * stud_emp {7:percent}
2105  *
2106  * If the same attribute name appears multiple times, then it appears
2107  * in the result table in the proper location for its first appearance.
2108  *
2109  * Constraints (including NOT NULL constraints) for the child table
2110  * are the union of all relevant constraints, from both the child schema
2111  * and parent tables.
2112  *
2113  * The default value for a child column is defined as:
2114  * (1) If the child schema specifies a default, that value is used.
2115  * (2) If neither the child nor any parent specifies a default, then
2116  * the column will not have a default.
2117  * (3) If conflicting defaults are inherited from different parents
2118  * (and not overridden by the child), an error is raised.
2119  * (4) Otherwise the inherited default is used.
2120  * Rule (3) is new in Postgres 7.1; in earlier releases you got a
2121  * rather arbitrary choice of which parent default to use.
2122  *----------
2123  */
2124 static List *
2125 MergeAttributes(List *schema, List *supers, char relpersistence,
2126  bool is_partition, List **supconstr)
2127 {
2128  List *inhSchema = NIL;
2129  List *constraints = NIL;
2130  bool have_bogus_defaults = false;
2131  int child_attno;
2132  static Node bogus_marker = {0}; /* marks conflicting defaults */
2133  List *saved_schema = NIL;
2134  ListCell *entry;
2135 
2136  /*
2137  * Check for and reject tables with too many columns. We perform this
2138  * check relatively early for two reasons: (a) we don't run the risk of
2139  * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
2140  * okay if we're processing <= 1600 columns, but could take minutes to
2141  * execute if the user attempts to create a table with hundreds of
2142  * thousands of columns.
2143  *
2144  * Note that we also need to check that we do not exceed this figure after
2145  * including columns from inherited relations.
2146  */
2147  if (list_length(schema) > MaxHeapAttributeNumber)
2148  ereport(ERROR,
2149  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2150  errmsg("tables can have at most %d columns",
2152 
2153  /*
2154  * Check for duplicate names in the explicit list of attributes.
2155  *
2156  * Although we might consider merging such entries in the same way that we
2157  * handle name conflicts for inherited attributes, it seems to make more
2158  * sense to assume such conflicts are errors.
2159  *
2160  * We don't use foreach() here because we have two nested loops over the
2161  * schema list, with possible element deletions in the inner one. If we
2162  * used foreach_delete_current() it could only fix up the state of one of
2163  * the loops, so it seems cleaner to use looping over list indexes for
2164  * both loops. Note that any deletion will happen beyond where the outer
2165  * loop is, so its index never needs adjustment.
2166  */
2167  for (int coldefpos = 0; coldefpos < list_length(schema); coldefpos++)
2168  {
2169  ColumnDef *coldef = list_nth_node(ColumnDef, schema, coldefpos);
2170 
2171  if (!is_partition && coldef->typeName == NULL)
2172  {
2173  /*
2174  * Typed table column option that does not belong to a column from
2175  * the type. This works because the columns from the type come
2176  * first in the list. (We omit this check for partition column
2177  * lists; those are processed separately below.)
2178  */
2179  ereport(ERROR,
2180  (errcode(ERRCODE_UNDEFINED_COLUMN),
2181  errmsg("column \"%s\" does not exist",
2182  coldef->colname)));
2183  }
2184 
2185  /* restpos scans all entries beyond coldef; incr is in loop body */
2186  for (int restpos = coldefpos + 1; restpos < list_length(schema);)
2187  {
2188  ColumnDef *restdef = list_nth_node(ColumnDef, schema, restpos);
2189 
2190  if (strcmp(coldef->colname, restdef->colname) == 0)
2191  {
2192  if (coldef->is_from_type)
2193  {
2194  /*
2195  * merge the column options into the column from the type
2196  */
2197  coldef->is_not_null = restdef->is_not_null;
2198  coldef->raw_default = restdef->raw_default;
2199  coldef->cooked_default = restdef->cooked_default;
2200  coldef->constraints = restdef->constraints;
2201  coldef->is_from_type = false;
2202  schema = list_delete_nth_cell(schema, restpos);
2203  }
2204  else
2205  ereport(ERROR,
2206  (errcode(ERRCODE_DUPLICATE_COLUMN),
2207  errmsg("column \"%s\" specified more than once",
2208  coldef->colname)));
2209  }
2210  else
2211  restpos++;
2212  }
2213  }
2214 
2215  /*
2216  * In case of a partition, there are no new column definitions, only dummy
2217  * ColumnDefs created for column constraints. Set them aside for now and
2218  * process them at the end.
2219  */
2220  if (is_partition)
2221  {
2222  saved_schema = schema;
2223  schema = NIL;
2224  }
2225 
2226  /*
2227  * Scan the parents left-to-right, and merge their attributes to form a
2228  * list of inherited attributes (inhSchema). Also check to see if we need
2229  * to inherit an OID column.
2230  */
2231  child_attno = 0;
2232  foreach(entry, supers)
2233  {
2234  Oid parent = lfirst_oid(entry);
2235  Relation relation;
2236  TupleDesc tupleDesc;
2237  TupleConstr *constr;
2238  AttrMap *newattmap;
2239  List *inherited_defaults;
2240  List *cols_with_defaults;
2241  AttrNumber parent_attno;
2242  ListCell *lc1;
2243  ListCell *lc2;
2244 
2245  /* caller already got lock */
2246  relation = table_open(parent, NoLock);
2247 
2248  /*
2249  * Check for active uses of the parent partitioned table in the
2250  * current transaction, such as being used in some manner by an
2251  * enclosing command.
2252  */
2253  if (is_partition)
2254  CheckTableNotInUse(relation, "CREATE TABLE .. PARTITION OF");
2255 
2256  /*
2257  * We do not allow partitioned tables and partitions to participate in
2258  * regular inheritance.
2259  */
2260  if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
2261  !is_partition)
2262  ereport(ERROR,
2263  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2264  errmsg("cannot inherit from partitioned table \"%s\"",
2265  RelationGetRelationName(relation))));
2266  if (relation->rd_rel->relispartition && !is_partition)
2267  ereport(ERROR,
2268  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2269  errmsg("cannot inherit from partition \"%s\"",
2270  RelationGetRelationName(relation))));
2271 
2272  if (relation->rd_rel->relkind != RELKIND_RELATION &&
2273  relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2274  relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2275  ereport(ERROR,
2276  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2277  errmsg("inherited relation \"%s\" is not a table or foreign table",
2278  RelationGetRelationName(relation))));
2279 
2280  /*
2281  * If the parent is permanent, so must be all of its partitions. Note
2282  * that inheritance allows that case.
2283  */
2284  if (is_partition &&
2285  relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
2286  relpersistence == RELPERSISTENCE_TEMP)
2287  ereport(ERROR,
2288  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2289  errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
2290  RelationGetRelationName(relation))));
2291 
2292  /* Permanent rels cannot inherit from temporary ones */
2293  if (relpersistence != RELPERSISTENCE_TEMP &&
2294  relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
2295  ereport(ERROR,
2296  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2297  errmsg(!is_partition
2298  ? "cannot inherit from temporary relation \"%s\""
2299  : "cannot create a permanent relation as partition of temporary relation \"%s\"",
2300  RelationGetRelationName(relation))));
2301 
2302  /* If existing rel is temp, it must belong to this session */
2303  if (relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
2304  !relation->rd_islocaltemp)
2305  ereport(ERROR,
2306  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2307  errmsg(!is_partition
2308  ? "cannot inherit from temporary relation of another session"
2309  : "cannot create as partition of temporary relation of another session")));
2310 
2311  /*
2312  * We should have an UNDER permission flag for this, but for now,
2313  * demand that creator of a child table own the parent.
2314  */
2315  if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
2317  RelationGetRelationName(relation));
2318 
2319  tupleDesc = RelationGetDescr(relation);
2320  constr = tupleDesc->constr;
2321 
2322  /*
2323  * newattmap->attnums[] will contain the child-table attribute numbers
2324  * for the attributes of this parent table. (They are not the same
2325  * for parents after the first one, nor if we have dropped columns.)
2326  */
2327  newattmap = make_attrmap(tupleDesc->natts);
2328 
2329  /* We can't process inherited defaults until newattmap is complete. */
2330  inherited_defaults = cols_with_defaults = NIL;
2331 
2332  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
2333  parent_attno++)
2334  {
2335  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
2336  parent_attno - 1);
2337  char *attributeName = NameStr(attribute->attname);
2338  int exist_attno;
2339  ColumnDef *def;
2340 
2341  /*
2342  * Ignore dropped columns in the parent.
2343  */
2344  if (attribute->attisdropped)
2345  continue; /* leave newattmap->attnums entry as zero */
2346 
2347  /*
2348  * Does it conflict with some previously inherited column?
2349  */
2350  exist_attno = findAttrByName(attributeName, inhSchema);
2351  if (exist_attno > 0)
2352  {
2353  Oid defTypeId;
2354  int32 deftypmod;
2355  Oid defCollId;
2356 
2357  /*
2358  * Yes, try to merge the two column definitions. They must
2359  * have the same type, typmod, and collation.
2360  */
2361  ereport(NOTICE,
2362  (errmsg("merging multiple inherited definitions of column \"%s\"",
2363  attributeName)));
2364  def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
2365  typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
2366  if (defTypeId != attribute->atttypid ||
2367  deftypmod != attribute->atttypmod)
2368  ereport(ERROR,
2369  (errcode(ERRCODE_DATATYPE_MISMATCH),
2370  errmsg("inherited column \"%s\" has a type conflict",
2371  attributeName),
2372  errdetail("%s versus %s",
2373  format_type_with_typemod(defTypeId,
2374  deftypmod),
2375  format_type_with_typemod(attribute->atttypid,
2376  attribute->atttypmod))));
2377  defCollId = GetColumnDefCollation(NULL, def, defTypeId);
2378  if (defCollId != attribute->attcollation)
2379  ereport(ERROR,
2380  (errcode(ERRCODE_COLLATION_MISMATCH),
2381  errmsg("inherited column \"%s\" has a collation conflict",
2382  attributeName),
2383  errdetail("\"%s\" versus \"%s\"",
2384  get_collation_name(defCollId),
2385  get_collation_name(attribute->attcollation))));
2386 
2387  /* Copy/check storage parameter */
2388  if (def->storage == 0)
2389  def->storage = attribute->attstorage;
2390  else if (def->storage != attribute->attstorage)
2391  ereport(ERROR,
2392  (errcode(ERRCODE_DATATYPE_MISMATCH),
2393  errmsg("inherited column \"%s\" has a storage parameter conflict",
2394  attributeName),
2395  errdetail("%s versus %s",
2396  storage_name(def->storage),
2397  storage_name(attribute->attstorage))));
2398 
2399  def->inhcount++;
2400  /* Merge of NOT NULL constraints = OR 'em together */
2401  def->is_not_null |= attribute->attnotnull;
2402  /* Default and other constraints are handled below */
2403  newattmap->attnums[parent_attno - 1] = exist_attno;
2404 
2405  /* Check for GENERATED conflicts */
2406  if (def->generated != attribute->attgenerated)
2407  ereport(ERROR,
2408  (errcode(ERRCODE_DATATYPE_MISMATCH),
2409  errmsg("inherited column \"%s\" has a generation conflict",
2410  attributeName)));
2411  }
2412  else
2413  {
2414  /*
2415  * No, create a new inherited column
2416  */
2417  def = makeNode(ColumnDef);
2418  def->colname = pstrdup(attributeName);
2419  def->typeName = makeTypeNameFromOid(attribute->atttypid,
2420  attribute->atttypmod);
2421  def->inhcount = 1;
2422  def->is_local = false;
2423  def->is_not_null = attribute->attnotnull;
2424  def->is_from_type = false;
2425  def->storage = attribute->attstorage;
2426  def->raw_default = NULL;
2427  def->cooked_default = NULL;
2428  def->generated = attribute->attgenerated;
2429  def->collClause = NULL;
2430  def->collOid = attribute->attcollation;
2431  def->constraints = NIL;
2432  def->location = -1;
2433  inhSchema = lappend(inhSchema, def);
2434  newattmap->attnums[parent_attno - 1] = ++child_attno;
2435  }
2436 
2437  /*
2438  * Locate default if any
2439  */
2440  if (attribute->atthasdef)
2441  {
2442  Node *this_default = NULL;
2443  AttrDefault *attrdef;
2444  int i;
2445 
2446  /* Find default in constraint structure */
2447  Assert(constr != NULL);
2448  attrdef = constr->defval;
2449  for (i = 0; i < constr->num_defval; i++)
2450  {
2451  if (attrdef[i].adnum == parent_attno)
2452  {
2453  this_default = stringToNode(attrdef[i].adbin);
2454  break;
2455  }
2456  }
2457  Assert(this_default != NULL);
2458 
2459  /*
2460  * If it's a GENERATED default, it might contain Vars that
2461  * need to be mapped to the inherited column(s)' new numbers.
2462  * We can't do that till newattmap is ready, so just remember
2463  * all the inherited default expressions for the moment.
2464  */
2465  inherited_defaults = lappend(inherited_defaults, this_default);
2466  cols_with_defaults = lappend(cols_with_defaults, def);
2467  }
2468  }
2469 
2470  /*
2471  * Now process any inherited default expressions, adjusting attnos
2472  * using the completed newattmap map.
2473  */
2474  forboth(lc1, inherited_defaults, lc2, cols_with_defaults)
2475  {
2476  Node *this_default = (Node *) lfirst(lc1);
2477  ColumnDef *def = (ColumnDef *) lfirst(lc2);
2478  bool found_whole_row;
2479 
2480  /* Adjust Vars to match new table's column numbering */
2481  this_default = map_variable_attnos(this_default,
2482  1, 0,
2483  newattmap,
2484  InvalidOid, &found_whole_row);
2485 
2486  /*
2487  * For the moment we have to reject whole-row variables. We could
2488  * convert them, if we knew the new table's rowtype OID, but that
2489  * hasn't been assigned yet. (A variable could only appear in a
2490  * generation expression, so the error message is correct.)
2491  */
2492  if (found_whole_row)
2493  ereport(ERROR,
2494  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2495  errmsg("cannot convert whole-row table reference"),
2496  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
2497  def->colname,
2498  RelationGetRelationName(relation))));
2499 
2500  /*
2501  * If we already had a default from some prior parent, check to
2502  * see if they are the same. If so, no problem; if not, mark the
2503  * column as having a bogus default. Below, we will complain if
2504  * the bogus default isn't overridden by the child schema.
2505  */
2506  Assert(def->raw_default == NULL);
2507  if (def->cooked_default == NULL)
2508  def->cooked_default = this_default;
2509  else if (!equal(def->cooked_default, this_default))
2510  {
2511  def->cooked_default = &bogus_marker;
2512  have_bogus_defaults = true;
2513  }
2514  }
2515 
2516  /*
2517  * Now copy the CHECK constraints of this parent, adjusting attnos
2518  * using the completed newattmap map. Identically named constraints
2519  * are merged if possible, else we throw error.
2520  */
2521  if (constr && constr->num_check > 0)
2522  {
2523  ConstrCheck *check = constr->check;
2524  int i;
2525 
2526  for (i = 0; i < constr->num_check; i++)
2527  {
2528  char *name = check[i].ccname;
2529  Node *expr;
2530  bool found_whole_row;
2531 
2532  /* ignore if the constraint is non-inheritable */
2533  if (check[i].ccnoinherit)
2534  continue;
2535 
2536  /* Adjust Vars to match new table's column numbering */
2537  expr = map_variable_attnos(stringToNode(check[i].ccbin),
2538  1, 0,
2539  newattmap,
2540  InvalidOid, &found_whole_row);
2541 
2542  /*
2543  * For the moment we have to reject whole-row variables. We
2544  * could convert them, if we knew the new table's rowtype OID,
2545  * but that hasn't been assigned yet.
2546  */
2547  if (found_whole_row)
2548  ereport(ERROR,
2549  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2550  errmsg("cannot convert whole-row table reference"),
2551  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
2552  name,
2553  RelationGetRelationName(relation))));
2554 
2555  /* check for duplicate */
2556  if (!MergeCheckConstraint(constraints, name, expr))
2557  {
2558  /* nope, this is a new one */
2559  CookedConstraint *cooked;
2560 
2561  cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2562  cooked->contype = CONSTR_CHECK;
2563  cooked->conoid = InvalidOid; /* until created */
2564  cooked->name = pstrdup(name);
2565  cooked->attnum = 0; /* not used for constraints */
2566  cooked->expr = expr;
2567  cooked->skip_validation = false;
2568  cooked->is_local = false;
2569  cooked->inhcount = 1;
2570  cooked->is_no_inherit = false;
2571  constraints = lappend(constraints, cooked);
2572  }
2573  }
2574  }
2575 
2576  free_attrmap(newattmap);
2577 
2578  /*
2579  * Close the parent rel, but keep our lock on it until xact commit.
2580  * That will prevent someone else from deleting or ALTERing the parent
2581  * before the child is committed.
2582  */
2583  table_close(relation, NoLock);
2584  }
2585 
2586  /*
2587  * If we had no inherited attributes, the result schema is just the
2588  * explicitly declared columns. Otherwise, we need to merge the declared
2589  * columns into the inherited schema list. Although, we never have any
2590  * explicitly declared columns if the table is a partition.
2591  */
2592  if (inhSchema != NIL)
2593  {
2594  int schema_attno = 0;
2595 
2596  foreach(entry, schema)
2597  {
2598  ColumnDef *newdef = lfirst(entry);
2599  char *attributeName = newdef->colname;
2600  int exist_attno;
2601 
2602  schema_attno++;
2603 
2604  /*
2605  * Does it conflict with some previously inherited column?
2606  */
2607  exist_attno = findAttrByName(attributeName, inhSchema);
2608  if (exist_attno > 0)
2609  {
2610  ColumnDef *def;
2611  Oid defTypeId,
2612  newTypeId;
2613  int32 deftypmod,
2614  newtypmod;
2615  Oid defcollid,
2616  newcollid;
2617 
2618  /*
2619  * Partitions have only one parent and have no column
2620  * definitions of their own, so conflict should never occur.
2621  */
2622  Assert(!is_partition);
2623 
2624  /*
2625  * Yes, try to merge the two column definitions. They must
2626  * have the same type, typmod, and collation.
2627  */
2628  if (exist_attno == schema_attno)
2629  ereport(NOTICE,
2630  (errmsg("merging column \"%s\" with inherited definition",
2631  attributeName)));
2632  else
2633  ereport(NOTICE,
2634  (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
2635  errdetail("User-specified column moved to the position of the inherited column.")));
2636  def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
2637  typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
2638  typenameTypeIdAndMod(NULL, newdef->typeName, &newTypeId, &newtypmod);
2639  if (defTypeId != newTypeId || deftypmod != newtypmod)
2640  ereport(ERROR,
2641  (errcode(ERRCODE_DATATYPE_MISMATCH),
2642  errmsg("column \"%s\" has a type conflict",
2643  attributeName),
2644  errdetail("%s versus %s",
2645  format_type_with_typemod(defTypeId,
2646  deftypmod),
2647  format_type_with_typemod(newTypeId,
2648  newtypmod))));
2649  defcollid = GetColumnDefCollation(NULL, def, defTypeId);
2650  newcollid = GetColumnDefCollation(NULL, newdef, newTypeId);
2651  if (defcollid != newcollid)
2652  ereport(ERROR,
2653  (errcode(ERRCODE_COLLATION_MISMATCH),
2654  errmsg("column \"%s\" has a collation conflict",
2655  attributeName),
2656  errdetail("\"%s\" versus \"%s\"",
2657  get_collation_name(defcollid),
2658  get_collation_name(newcollid))));
2659 
2660  /*
2661  * Identity is never inherited. The new column can have an
2662  * identity definition, so we always just take that one.
2663  */
2664  def->identity = newdef->identity;
2665 
2666  /* Copy storage parameter */
2667  if (def->storage == 0)
2668  def->storage = newdef->storage;
2669  else if (newdef->storage != 0 && def->storage != newdef->storage)
2670  ereport(ERROR,
2671  (errcode(ERRCODE_DATATYPE_MISMATCH),
2672  errmsg("column \"%s\" has a storage parameter conflict",
2673  attributeName),
2674  errdetail("%s versus %s",
2675  storage_name(def->storage),
2676  storage_name(newdef->storage))));
2677 
2678  /* Mark the column as locally defined */
2679  def->is_local = true;
2680  /* Merge of NOT NULL constraints = OR 'em together */
2681  def->is_not_null |= newdef->is_not_null;
2682 
2683  /*
2684  * Check for conflicts related to generated columns.
2685  *
2686  * If the parent column is generated, the child column must be
2687  * unadorned and will be made a generated column. (We could
2688  * in theory allow the child column definition specifying the
2689  * exact same generation expression, but that's a bit
2690  * complicated to implement and doesn't seem very useful.) We
2691  * also check that the child column doesn't specify a default
2692  * value or identity, which matches the rules for a single
2693  * column in parse_util.c.
2694  */
2695  if (def->generated)
2696  {
2697  if (newdef->generated)
2698  ereport(ERROR,
2699  (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
2700  errmsg("child column \"%s\" specifies generation expression",
2701  def->colname),
2702  errhint("Omit the generation expression in the definition of the child table column to inherit the generation expression from the parent table.")));
2703  if (newdef->raw_default && !newdef->generated)
2704  ereport(ERROR,
2705  (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
2706  errmsg("column \"%s\" inherits from generated column but specifies default",
2707  def->colname)));
2708  if (newdef->identity)
2709  ereport(ERROR,
2710  (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
2711  errmsg("column \"%s\" inherits from generated column but specifies identity",
2712  def->colname)));
2713  }
2714 
2715  /*
2716  * If the parent column is not generated, then take whatever
2717  * the child column definition says.
2718  */
2719  else
2720  {
2721  if (newdef->generated)
2722  def->generated = newdef->generated;
2723  }
2724 
2725  /* If new def has a default, override previous default */
2726  if (newdef->raw_default != NULL)
2727  {
2728  def->raw_default = newdef->raw_default;
2729  def->cooked_default = newdef->cooked_default;
2730  }
2731  }
2732  else
2733  {
2734  /*
2735  * No, attach new column to result schema
2736  */
2737  inhSchema = lappend(inhSchema, newdef);
2738  }
2739  }
2740 
2741  schema = inhSchema;
2742 
2743  /*
2744  * Check that we haven't exceeded the legal # of columns after merging
2745  * in inherited columns.
2746  */
2747  if (list_length(schema) > MaxHeapAttributeNumber)
2748  ereport(ERROR,
2749  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2750  errmsg("tables can have at most %d columns",
2752  }
2753 
2754  /*
2755  * Now that we have the column definition list for a partition, we can
2756  * check whether the columns referenced in the column constraint specs
2757  * actually exist. Also, we merge NOT NULL and defaults into each
2758  * corresponding column definition.
2759  */
2760  if (is_partition)
2761  {
2762  foreach(entry, saved_schema)
2763  {
2764  ColumnDef *restdef = lfirst(entry);
2765  bool found = false;
2766  ListCell *l;
2767 
2768  foreach(l, schema)
2769  {
2770  ColumnDef *coldef = lfirst(l);
2771 
2772  if (strcmp(coldef->colname, restdef->colname) == 0)
2773  {
2774  found = true;
2775  coldef->is_not_null |= restdef->is_not_null;
2776 
2777  /*
2778  * Override the parent's default value for this column
2779  * (coldef->cooked_default) with the partition's local
2780  * definition (restdef->raw_default), if there's one. It
2781  * should be physically impossible to get a cooked default
2782  * in the local definition or a raw default in the
2783  * inherited definition, but make sure they're nulls, for
2784  * future-proofing.
2785  */
2786  Assert(restdef->cooked_default == NULL);
2787  Assert(coldef->raw_default == NULL);
2788  if (restdef->raw_default)
2789  {
2790  coldef->raw_default = restdef->raw_default;
2791  coldef->cooked_default = NULL;
2792  }
2793  }
2794  }
2795 
2796  /* complain for constraints on columns not in parent */
2797  if (!found)
2798  ereport(ERROR,
2799  (errcode(ERRCODE_UNDEFINED_COLUMN),
2800  errmsg("column \"%s\" does not exist",
2801  restdef->colname)));
2802  }
2803  }
2804 
2805  /*
2806  * If we found any conflicting parent default values, check to make sure
2807  * they were overridden by the child.
2808  */
2809  if (have_bogus_defaults)
2810  {
2811  foreach(entry, schema)
2812  {
2813  ColumnDef *def = lfirst(entry);
2814 
2815  if (def->cooked_default == &bogus_marker)
2816  {
2817  if (def->generated)
2818  ereport(ERROR,
2819  (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
2820  errmsg("column \"%s\" inherits conflicting generation expressions",
2821  def->colname)));
2822  else
2823  ereport(ERROR,
2824  (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
2825  errmsg("column \"%s\" inherits conflicting default values",
2826  def->colname),
2827  errhint("To resolve the conflict, specify a default explicitly.")));
2828  }
2829  }
2830  }
2831 
2832  *supconstr = constraints;
2833  return schema;
2834 }
2835 
2836 
2837 /*
2838  * MergeCheckConstraint
2839  * Try to merge an inherited CHECK constraint with previous ones
2840  *
2841  * If we inherit identically-named constraints from multiple parents, we must
2842  * merge them, or throw an error if they don't have identical definitions.
2843  *
2844  * constraints is a list of CookedConstraint structs for previous constraints.
2845  *
2846  * Returns true if merged (constraint is a duplicate), or false if it's
2847  * got a so-far-unique name, or throws error if conflict.
2848  */
2849 static bool
2850 MergeCheckConstraint(List *constraints, char *name, Node *expr)
2851 {
2852  ListCell *lc;
2853 
2854  foreach(lc, constraints)
2855  {
2856  CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
2857 
2858  Assert(ccon->contype == CONSTR_CHECK);
2859 
2860  /* Non-matching names never conflict */
2861  if (strcmp(ccon->name, name) != 0)
2862  continue;
2863 
2864  if (equal(expr, ccon->expr))
2865  {
2866  /* OK to merge */
2867  ccon->inhcount++;
2868  return true;
2869  }
2870 
2871  ereport(ERROR,
2873  errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
2874  name)));
2875  }
2876 
2877  return false;
2878 }
2879 
2880 
2881 /*
2882  * StoreCatalogInheritance
2883  * Updates the system catalogs with proper inheritance information.
2884  *
2885  * supers is a list of the OIDs of the new relation's direct ancestors.
2886  */
2887 static void
2888 StoreCatalogInheritance(Oid relationId, List *supers,
2889  bool child_is_partition)
2890 {
2891  Relation relation;
2892  int32 seqNumber;
2893  ListCell *entry;
2894 
2895  /*
2896  * sanity checks
2897  */
2898  AssertArg(OidIsValid(relationId));
2899 
2900  if (supers == NIL)
2901  return;
2902 
2903  /*
2904  * Store INHERITS information in pg_inherits using direct ancestors only.
2905  * Also enter dependencies on the direct ancestors, and make sure they are
2906  * marked with relhassubclass = true.
2907  *
2908  * (Once upon a time, both direct and indirect ancestors were found here
2909  * and then entered into pg_ipl. Since that catalog doesn't exist
2910  * anymore, there's no need to look for indirect ancestors.)
2911  */
2912  relation = table_open(InheritsRelationId, RowExclusiveLock);
2913 
2914  seqNumber = 1;
2915  foreach(entry, supers)
2916  {
2917  Oid parentOid = lfirst_oid(entry);
2918 
2919  StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
2920  child_is_partition);
2921  seqNumber++;
2922  }
2923 
2924  table_close(relation, RowExclusiveLock);
2925 }
2926 
2927 /*
2928  * Make catalog entries showing relationId as being an inheritance child
2929  * of parentOid. inhRelation is the already-opened pg_inherits catalog.
2930  */
2931 static void
2932 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
2933  int32 seqNumber, Relation inhRelation,
2934  bool child_is_partition)
2935 {
2936  ObjectAddress childobject,
2937  parentobject;
2938 
2939  /* store the pg_inherits row */
2940  StoreSingleInheritance(relationId, parentOid, seqNumber);
2941 
2942  /*
2943  * Store a dependency too
2944  */
2945  parentobject.classId = RelationRelationId;
2946  parentobject.objectId = parentOid;
2947  parentobject.objectSubId = 0;
2948  childobject.classId = RelationRelationId;
2949  childobject.objectId = relationId;
2950  childobject.objectSubId = 0;
2951 
2952  recordDependencyOn(&childobject, &parentobject,
2953  child_dependency_type(child_is_partition));
2954 
2955  /*
2956  * Post creation hook of this inheritance. Since object_access_hook
2957  * doesn't take multiple object identifiers, we relay oid of parent
2958  * relation using auxiliary_id argument.
2959  */
2960  InvokeObjectPostAlterHookArg(InheritsRelationId,
2961  relationId, 0,
2962  parentOid, false);
2963 
2964  /*
2965  * Mark the parent as having subclasses.
2966  */
2967  SetRelationHasSubclass(parentOid, true);
2968 }
2969 
2970 /*
2971  * Look for an existing schema entry with the given name.
2972  *
2973  * Returns the index (starting with 1) if attribute already exists in schema,
2974  * 0 if it doesn't.
2975  */
2976 static int
2977 findAttrByName(const char *attributeName, List *schema)
2978 {
2979  ListCell *s;
2980  int i = 1;
2981 
2982  foreach(s, schema)
2983  {
2984  ColumnDef *def = lfirst(s);
2985 
2986  if (strcmp(attributeName, def->colname) == 0)
2987  return i;
2988 
2989  i++;
2990  }
2991  return 0;
2992 }
2993 
2994 
2995 /*
2996  * SetRelationHasSubclass
2997  * Set the value of the relation's relhassubclass field in pg_class.
2998  *
2999  * NOTE: caller must be holding an appropriate lock on the relation.
3000  * ShareUpdateExclusiveLock is sufficient.
3001  *
3002  * NOTE: an important side-effect of this operation is that an SI invalidation
3003  * message is sent out to all backends --- including me --- causing plans
3004  * referencing the relation to be rebuilt with the new list of children.
3005  * This must happen even if we find that no change is needed in the pg_class
3006  * row.
3007  */
3008 void
3009 SetRelationHasSubclass(Oid relationId, bool relhassubclass)
3010 {
3011  Relation relationRelation;
3012  HeapTuple tuple;
3013  Form_pg_class classtuple;
3014 
3015  /*
3016  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3017  */
3018  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3019  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3020  if (!HeapTupleIsValid(tuple))
3021  elog(ERROR, "cache lookup failed for relation %u", relationId);
3022  classtuple = (Form_pg_class) GETSTRUCT(tuple);
3023 
3024  if (classtuple->relhassubclass != relhassubclass)
3025  {
3026  classtuple->relhassubclass = relhassubclass;
3027  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3028  }
3029  else
3030  {
3031  /* no need to change tuple, but force relcache rebuild anyway */
3033  }
3034 
3035  heap_freetuple(tuple);
3036  table_close(relationRelation, RowExclusiveLock);
3037 }
3038 
3039 /*
3040  * renameatt_check - basic sanity checks before attribute rename
3041  */
3042 static void
3043 renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
3044 {
3045  char relkind = classform->relkind;
3046 
3047  if (classform->reloftype && !recursing)
3048  ereport(ERROR,
3049  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3050  errmsg("cannot rename column of typed table")));
3051 
3052  /*
3053  * Renaming the columns of sequences or toast tables doesn't actually
3054  * break anything from the system's point of view, since internal
3055  * references are by attnum. But it doesn't seem right to allow users to
3056  * change names that are hardcoded into the system, hence the following
3057  * restriction.
3058  */
3059  if (relkind != RELKIND_RELATION &&
3060  relkind != RELKIND_VIEW &&
3061  relkind != RELKIND_MATVIEW &&
3062  relkind != RELKIND_COMPOSITE_TYPE &&
3063  relkind != RELKIND_INDEX &&
3064  relkind != RELKIND_PARTITIONED_INDEX &&
3065  relkind != RELKIND_FOREIGN_TABLE &&
3066  relkind != RELKIND_PARTITIONED_TABLE)
3067  ereport(ERROR,
3068  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3069  errmsg("\"%s\" is not a table, view, materialized view, composite type, index, or foreign table",
3070  NameStr(classform->relname))));
3071 
3072  /*
3073  * permissions checking. only the owner of a class can change its schema.
3074  */
3075  if (!pg_class_ownercheck(myrelid, GetUserId()))
3077  NameStr(classform->relname));
3078  if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
3079  ereport(ERROR,
3080  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3081  errmsg("permission denied: \"%s\" is a system catalog",
3082  NameStr(classform->relname))));
3083 }
3084 
3085 /*
3086  * renameatt_internal - workhorse for renameatt
3087  *
3088  * Return value is the attribute number in the 'myrelid' relation.
3089  */
3090 static AttrNumber
3092  const char *oldattname,
3093  const char *newattname,
3094  bool recurse,
3095  bool recursing,
3096  int expected_parents,
3097  DropBehavior behavior)
3098 {
3099  Relation targetrelation;
3100  Relation attrelation;
3101  HeapTuple atttup;
3102  Form_pg_attribute attform;
3104 
3105  /*
3106  * Grab an exclusive lock on the target table, which we will NOT release
3107  * until end of transaction.
3108  */
3109  targetrelation = relation_open(myrelid, AccessExclusiveLock);
3110  renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
3111 
3112  /*
3113  * if the 'recurse' flag is set then we are supposed to rename this
3114  * attribute in all classes that inherit from 'relname' (as well as in
3115  * 'relname').
3116  *
3117  * any permissions or problems with duplicate attributes will cause the
3118  * whole transaction to abort, which is what we want -- all or nothing.
3119  */
3120  if (recurse)
3121  {
3122  List *child_oids,
3123  *child_numparents;
3124  ListCell *lo,
3125  *li;
3126 
3127  /*
3128  * we need the number of parents for each child so that the recursive
3129  * calls to renameatt() can determine whether there are any parents
3130  * outside the inheritance hierarchy being processed.
3131  */
3132  child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
3133  &child_numparents);
3134 
3135  /*
3136  * find_all_inheritors does the recursive search of the inheritance
3137  * hierarchy, so all we have to do is process all of the relids in the
3138  * list that it returns.
3139  */
3140  forboth(lo, child_oids, li, child_numparents)
3141  {
3142  Oid childrelid = lfirst_oid(lo);
3143  int numparents = lfirst_int(li);
3144 
3145  if (childrelid == myrelid)
3146  continue;
3147  /* note we need not recurse again */
3148  renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
3149  }
3150  }
3151  else
3152  {
3153  /*
3154  * If we are told not to recurse, there had better not be any child
3155  * tables; else the rename would put them out of step.
3156  *
3157  * expected_parents will only be 0 if we are not already recursing.
3158  */
3159  if (expected_parents == 0 &&
3160  find_inheritance_children(myrelid, NoLock) != NIL)
3161  ereport(ERROR,
3162  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3163  errmsg("inherited column \"%s\" must be renamed in child tables too",
3164  oldattname)));
3165  }
3166 
3167  /* rename attributes in typed tables of composite type */
3168  if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
3169  {
3170  List *child_oids;
3171  ListCell *lo;
3172 
3173  child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
3174  RelationGetRelationName(targetrelation),
3175  behavior);
3176 
3177  foreach(lo, child_oids)
3178  renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
3179  }
3180 
3181  attrelation = table_open(AttributeRelationId, RowExclusiveLock);
3182 
3183  atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
3184  if (!HeapTupleIsValid(atttup))
3185  ereport(ERROR,
3186  (errcode(ERRCODE_UNDEFINED_COLUMN),
3187  errmsg("column \"%s\" does not exist",
3188  oldattname)));
3189  attform = (Form_pg_attribute) GETSTRUCT(atttup);
3190 
3191  attnum = attform->attnum;
3192  if (attnum <= 0)
3193  ereport(ERROR,
3194  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3195  errmsg("cannot rename system column \"%s\"",
3196  oldattname)));
3197 
3198  /*
3199  * if the attribute is inherited, forbid the renaming. if this is a
3200  * top-level call to renameatt(), then expected_parents will be 0, so the
3201  * effect of this code will be to prohibit the renaming if the attribute
3202  * is inherited at all. if this is a recursive call to renameatt(),
3203  * expected_parents will be the number of parents the current relation has
3204  * within the inheritance hierarchy being processed, so we'll prohibit the
3205  * renaming only if there are additional parents from elsewhere.
3206  */
3207  if (attform->attinhcount > expected_parents)
3208  ereport(ERROR,
3209  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3210  errmsg("cannot rename inherited column \"%s\"",
3211  oldattname)));
3212 
3213  /* new name should not already exist */
3214  (void) check_for_column_name_collision(targetrelation, newattname, false);
3215 
3216  /* apply the update */
3217  namestrcpy(&(attform->attname), newattname);
3218 
3219  CatalogTupleUpdate(attrelation, &atttup->t_self, atttup);
3220 
3221  InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
3222 
3223  heap_freetuple(atttup);
3224 
3225  table_close(attrelation, RowExclusiveLock);
3226 
3227  relation_close(targetrelation, NoLock); /* close rel but keep lock */
3228 
3229  return attnum;
3230 }
3231 
3232 /*
3233  * Perform permissions and integrity checks before acquiring a relation lock.
3234  */
3235 static void
3237  void *arg)
3238 {
3239  HeapTuple tuple;
3240  Form_pg_class form;
3241 
3242  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
3243  if (!HeapTupleIsValid(tuple))
3244  return; /* concurrently dropped */
3245  form = (Form_pg_class) GETSTRUCT(tuple);
3246  renameatt_check(relid, form, false);
3247  ReleaseSysCache(tuple);
3248 }
3249 
3250 /*
3251  * renameatt - changes the name of an attribute in a relation
3252  *
3253  * The returned ObjectAddress is that of the renamed column.
3254  */
3257 {
3258  Oid relid;
3260  ObjectAddress address;
3261 
3262  /* lock level taken here should match renameatt_internal */
3264  stmt->missing_ok ? RVR_MISSING_OK : 0,
3266  NULL);
3267 
3268  if (!OidIsValid(relid))
3269  {
3270  ereport(NOTICE,
3271  (errmsg("relation \"%s\" does not exist, skipping",
3272  stmt->relation->relname)));
3273  return InvalidObjectAddress;
3274  }
3275 
3276  attnum =
3277  renameatt_internal(relid,
3278  stmt->subname, /* old att name */
3279  stmt->newname, /* new att name */
3280  stmt->relation->inh, /* recursive? */
3281  false, /* recursing? */
3282  0, /* expected inhcount */
3283  stmt->behavior);
3284 
3285  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
3286 
3287  return address;
3288 }
3289 
3290 /*
3291  * same logic as renameatt_internal
3292  */
3293 static ObjectAddress
3295  Oid mytypid,
3296  const char *oldconname,
3297  const char *newconname,
3298  bool recurse,
3299  bool recursing,
3300  int expected_parents)
3301 {
3302  Relation targetrelation = NULL;
3303  Oid constraintOid;
3304  HeapTuple tuple;
3305  Form_pg_constraint con;
3306  ObjectAddress address;
3307 
3308  AssertArg(!myrelid || !mytypid);
3309 
3310  if (mytypid)
3311  {
3312  constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
3313  }
3314  else
3315  {
3316  targetrelation = relation_open(myrelid, AccessExclusiveLock);
3317 
3318  /*
3319  * don't tell it whether we're recursing; we allow changing typed
3320  * tables here
3321  */
3322  renameatt_check(myrelid, RelationGetForm(targetrelation), false);
3323 
3324  constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
3325  }
3326 
3327  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
3328  if (!HeapTupleIsValid(tuple))
3329  elog(ERROR, "cache lookup failed for constraint %u",
3330  constraintOid);
3331  con = (Form_pg_constraint) GETSTRUCT(tuple);
3332 
3333  if (myrelid && con->contype == CONSTRAINT_CHECK && !con->connoinherit)
3334  {
3335  if (recurse)
3336  {
3337  List *child_oids,
3338  *child_numparents;
3339  ListCell *lo,
3340  *li;
3341 
3342  child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
3343  &child_numparents);
3344 
3345  forboth(lo, child_oids, li, child_numparents)
3346  {
3347  Oid childrelid = lfirst_oid(lo);
3348  int numparents = lfirst_int(li);
3349 
3350  if (childrelid == myrelid)
3351  continue;
3352 
3353  rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
3354  }
3355  }
3356  else
3357  {
3358  if (expected_parents == 0 &&
3359  find_inheritance_children(myrelid, NoLock) != NIL)
3360  ereport(ERROR,
3361  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3362  errmsg("inherited constraint \"%s\" must be renamed in child tables too",
3363  oldconname)));
3364  }
3365 
3366  if (con->coninhcount > expected_parents)
3367  ereport(ERROR,
3368  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3369  errmsg("cannot rename inherited constraint \"%s\"",
3370  oldconname)));
3371  }
3372 
3373  if (con->conindid
3374  && (con->contype == CONSTRAINT_PRIMARY
3375  || con->contype == CONSTRAINT_UNIQUE
3376  || con->contype == CONSTRAINT_EXCLUSION))
3377  /* rename the index; this renames the constraint as well */
3378  RenameRelationInternal(con->conindid, newconname, false, true);
3379  else
3380  RenameConstraintById(constraintOid, newconname);
3381 
3382  ObjectAddressSet(address, ConstraintRelationId, constraintOid);
3383 
3384  ReleaseSysCache(tuple);
3385 
3386  if (targetrelation)
3387  {
3388  /*
3389  * Invalidate relcache so as others can see the new constraint name.
3390  */
3391  CacheInvalidateRelcache(targetrelation);
3392 
3393  relation_close(targetrelation, NoLock); /* close rel but keep lock */
3394  }
3395 
3396  return address;
3397 }
3398 
3401 {
3402  Oid relid = InvalidOid;
3403  Oid typid = InvalidOid;
3404 
3405  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
3406  {
3407  Relation rel;
3408  HeapTuple tup;
3409 
3411  rel = table_open(TypeRelationId, RowExclusiveLock);
3412  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3413  if (!HeapTupleIsValid(tup))
3414  elog(ERROR, "cache lookup failed for type %u", typid);
3415  checkDomainOwner(tup);
3416  ReleaseSysCache(tup);
3417  table_close(rel, NoLock);
3418  }
3419  else
3420  {
3421  /* lock level taken here should match rename_constraint_internal */
3423  stmt->missing_ok ? RVR_MISSING_OK : 0,
3425  NULL);
3426  if (!OidIsValid(relid))
3427  {
3428  ereport(NOTICE,
3429  (errmsg("relation \"%s\" does not exist, skipping",
3430  stmt->relation->relname)));
3431  return InvalidObjectAddress;
3432  }
3433  }
3434 
3435  return
3436  rename_constraint_internal(relid, typid,
3437  stmt->subname,
3438  stmt->newname,
3439  (stmt->relation &&
3440  stmt->relation->inh), /* recursive? */
3441  false, /* recursing? */
3442  0 /* expected inhcount */ );
3443 
3444 }
3445 
3446 /*
3447  * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
3448  * RENAME
3449  */
3452 {
3453  bool is_index = stmt->renameType == OBJECT_INDEX;
3454  Oid relid;
3455  ObjectAddress address;
3456 
3457  /*
3458  * Grab an exclusive lock on the target table, index, sequence, view,
3459  * materialized view, or foreign table, which we will NOT release until
3460  * end of transaction.
3461  *
3462  * Lock level used here should match RenameRelationInternal, to avoid lock
3463  * escalation.
3464  */
3465  relid = RangeVarGetRelidExtended(stmt->relation,
3467  stmt->missing_ok ? RVR_MISSING_OK : 0,
3469  (void *) stmt);
3470 
3471  if (!OidIsValid(relid))
3472  {
3473  ereport(NOTICE,
3474  (errmsg("relation \"%s\" does not exist, skipping",
3475  stmt->relation->relname)));
3476  return InvalidObjectAddress;
3477  }
3478 
3479  /* Do the work */
3480  RenameRelationInternal(relid, stmt->newname, false, is_index);
3481 
3482  ObjectAddressSet(address, RelationRelationId, relid);
3483 
3484  return address;
3485 }
3486 
3487 /*
3488  * RenameRelationInternal - change the name of a relation
3489  */
3490 void
3491 RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
3492 {
3493  Relation targetrelation;
3494  Relation relrelation; /* for RELATION relation */
3495  HeapTuple reltup;
3496  Form_pg_class relform;
3497  Oid namespaceId;
3498 
3499  /*
3500  * Grab a lock on the target relation, which we will NOT release until end
3501  * of transaction. We need at least a self-exclusive lock so that
3502  * concurrent DDL doesn't overwrite the rename if they start updating
3503  * while still seeing the old version. The lock also guards against
3504  * triggering relcache reloads in concurrent sessions, which might not
3505  * handle this information changing under them. For indexes, we can use a
3506  * reduced lock level because RelationReloadIndexInfo() handles indexes
3507  * specially.
3508  */
3509  targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
3510  namespaceId = RelationGetNamespace(targetrelation);
3511 
3512  /*
3513  * Find relation's pg_class tuple, and make sure newrelname isn't in use.
3514  */
3515  relrelation = table_open(RelationRelationId, RowExclusiveLock);
3516 
3517  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
3518  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
3519  elog(ERROR, "cache lookup failed for relation %u", myrelid);
3520  relform = (Form_pg_class) GETSTRUCT(reltup);
3521 
3522  if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
3523  ereport(ERROR,
3524  (errcode(ERRCODE_DUPLICATE_TABLE),
3525  errmsg("relation \"%s\" already exists",
3526  newrelname)));
3527 
3528  /*
3529  * Update pg_class tuple with new relname. (Scribbling on reltup is OK
3530  * because it's a copy...)
3531  */
3532  namestrcpy(&(relform->relname), newrelname);
3533 
3534  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
3535 
3536  InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
3537  InvalidOid, is_internal);
3538 
3539  heap_freetuple(reltup);
3540  table_close(relrelation, RowExclusiveLock);
3541 
3542  /*
3543  * Also rename the associated type, if any.
3544  */
3545  if (OidIsValid(targetrelation->rd_rel->reltype))
3546  RenameTypeInternal(targetrelation->rd_rel->reltype,
3547  newrelname, namespaceId);
3548 
3549  /*
3550  * Also rename the associated constraint, if any.
3551  */
3552  if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
3553  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3554  {
3555  Oid constraintId = get_index_constraint(myrelid);
3556 
3557  if (OidIsValid(constraintId))
3558  RenameConstraintById(constraintId, newrelname);
3559  }
3560 
3561  /*
3562  * Close rel, but keep lock!
3563  */
3564  relation_close(targetrelation, NoLock);
3565 }
3566 
3567 /*
3568  * Disallow ALTER TABLE (and similar commands) when the current backend has
3569  * any open reference to the target table besides the one just acquired by
3570  * the calling command; this implies there's an open cursor or active plan.
3571  * We need this check because our lock doesn't protect us against stomping
3572  * on our own foot, only other people's feet!
3573  *
3574  * For ALTER TABLE, the only case known to cause serious trouble is ALTER
3575  * COLUMN TYPE, and some changes are obviously pretty benign, so this could
3576  * possibly be relaxed to only error out for certain types of alterations.
3577  * But the use-case for allowing any of these things is not obvious, so we
3578  * won't work hard at it for now.
3579  *
3580  * We also reject these commands if there are any pending AFTER trigger events
3581  * for the rel. This is certainly necessary for the rewriting variants of
3582  * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
3583  * events would try to fetch the wrong tuples. It might be overly cautious
3584  * in other cases, but again it seems better to err on the side of paranoia.
3585  *
3586  * REINDEX calls this with "rel" referencing the index to be rebuilt; here
3587  * we are worried about active indexscans on the index. The trigger-event
3588  * check can be skipped, since we are doing no damage to the parent table.
3589  *
3590  * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
3591  */
3592 void
3593 CheckTableNotInUse(Relation rel, const char *stmt)
3594 {
3595  int expected_refcnt;
3596 
3597  expected_refcnt = rel->rd_isnailed ? 2 : 1;
3598  if (rel->rd_refcnt != expected_refcnt)
3599  ereport(ERROR,
3600  (errcode(ERRCODE_OBJECT_IN_USE),
3601  /* translator: first %s is a SQL command, eg ALTER TABLE */
3602  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
3603  stmt, RelationGetRelationName(rel))));
3604 
3605  if (rel->rd_rel->relkind != RELKIND_INDEX &&
3606  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
3608  ereport(ERROR,
3609  (errcode(ERRCODE_OBJECT_IN_USE),
3610  /* translator: first %s is a SQL command, eg ALTER TABLE */
3611  errmsg("cannot %s \"%s\" because it has pending trigger events",
3612  stmt, RelationGetRelationName(rel))));
3613 }
3614 
3615 /*
3616  * AlterTableLookupRelation
3617  * Look up, and lock, the OID for the relation named by an alter table
3618  * statement.
3619  */
3620 Oid
3622 {
3623  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3624  stmt->missing_ok ? RVR_MISSING_OK : 0,
3626  (void *) stmt);
3627 }
3628 
3629 /*
3630  * AlterTable
3631  * Execute ALTER TABLE, which can be a list of subcommands
3632  *
3633  * ALTER TABLE is performed in three phases:
3634  * 1. Examine subcommands and perform pre-transformation checking.
3635  * 2. Validate and transform subcommands, and update system catalogs.
3636  * 3. Scan table(s) to check new constraints, and optionally recopy
3637  * the data into new table(s).
3638  * Phase 3 is not performed unless one or more of the subcommands requires
3639  * it. The intention of this design is to allow multiple independent
3640  * updates of the table schema to be performed with only one pass over the
3641  * data.
3642  *
3643  * ATPrepCmd performs phase 1. A "work queue" entry is created for
3644  * each table to be affected (there may be multiple affected tables if the
3645  * commands traverse a table inheritance hierarchy). Also we do preliminary
3646  * validation of the subcommands. Because earlier subcommands may change
3647  * the catalog state seen by later commands, there are limits to what can
3648  * be done in this phase. Generally, this phase acquires table locks,
3649  * checks permissions and relkind, and recurses to find child tables.
3650  *
3651  * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
3652  * phases 2 and 3 normally do no explicit recursion, since phase 1 already
3653  * did it --- although some subcommands have to recurse in phase 2 instead.)
3654  * Certain subcommands need to be performed before others to avoid
3655  * unnecessary conflicts; for example, DROP COLUMN should come before
3656  * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
3657  * lists, one for each logical "pass" of phase 2.
3658  *
3659  * ATRewriteTables performs phase 3 for those tables that need it.
3660  *
3661  * Thanks to the magic of MVCC, an error anywhere along the way rolls back
3662  * the whole operation; we don't have to do anything special to clean up.
3663  *
3664  * The caller must lock the relation, with an appropriate lock level
3665  * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
3666  * or higher. We pass the lock level down
3667  * so that we can apply it recursively to inherited tables. Note that the
3668  * lock level we want as we recurse might well be higher than required for
3669  * that specific subcommand. So we pass down the overall lock requirement,
3670  * rather than reassess it at lower levels.
3671  *
3672  * The caller also provides a "context" which is to be passed back to
3673  * utility.c when we need to execute a subcommand such as CREATE INDEX.
3674  * Some of the fields therein, such as the relid, are used here as well.
3675  */
3676 void
3678  AlterTableUtilityContext *context)
3679 {
3680  Relation rel;
3681 
3682  /* Caller is required to provide an adequate lock. */
3683  rel = relation_open(context->relid, NoLock);
3684 
3685  CheckTableNotInUse(rel, "ALTER TABLE");
3686 
3687  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
3688 }
3689 
3690 /*
3691  * AlterTableInternal
3692  *
3693  * ALTER TABLE with target specified by OID
3694  *
3695  * We do not reject if the relation is already open, because it's quite
3696  * likely that one or more layers of caller have it open. That means it
3697  * is unsafe to use this entry point for alterations that could break
3698  * existing query plans. On the assumption it's not used for such, we
3699  * don't have to reject pending AFTER triggers, either.
3700  *
3701  * Also, since we don't have an AlterTableUtilityContext, this cannot be
3702  * used for any subcommand types that require parse transformation or
3703  * could generate subcommands that have to be passed to ProcessUtility.
3704  */
3705 void
3706 AlterTableInternal(Oid relid, List *cmds, bool recurse)
3707 {
3708  Relation rel;
3709  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3710 
3711  rel = relation_open(relid, lockmode);
3712 
3714 
3715  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
3716 }
3717 
3718 /*
3719  * AlterTableGetLockLevel
3720  *
3721  * Sets the overall lock level required for the supplied list of subcommands.
3722  * Policy for doing this set according to needs of AlterTable(), see
3723  * comments there for overall explanation.
3724  *
3725  * Function is called before and after parsing, so it must give same
3726  * answer each time it is called. Some subcommands are transformed
3727  * into other subcommand types, so the transform must never be made to a
3728  * lower lock level than previously assigned. All transforms are noted below.
3729  *
3730  * Since this is called before we lock the table we cannot use table metadata
3731  * to influence the type of lock we acquire.
3732  *
3733  * There should be no lockmodes hardcoded into the subcommand functions. All
3734  * lockmode decisions for ALTER TABLE are made here only. The one exception is
3735  * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
3736  * and does not travel through this section of code and cannot be combined with
3737  * any of the subcommands given here.
3738  *
3739  * Note that Hot Standby only knows about AccessExclusiveLocks on the primary
3740  * so any changes that might affect SELECTs running on standbys need to use
3741  * AccessExclusiveLocks even if you think a lesser lock would do, unless you
3742  * have a solution for that also.
3743  *
3744  * Also note that pg_dump uses only an AccessShareLock, meaning that anything
3745  * that takes a lock less than AccessExclusiveLock can change object definitions
3746  * while pg_dump is running. Be careful to check that the appropriate data is
3747  * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
3748  * otherwise we might end up with an inconsistent dump that can't restore.
3749  */
3750 LOCKMODE
3752 {
3753  /*
3754  * This only works if we read catalog tables using MVCC snapshots.
3755  */
3756  ListCell *lcmd;
3758 
3759  foreach(lcmd, cmds)
3760  {
3761  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3762  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
3763 
3764  switch (cmd->subtype)
3765  {
3766  /*
3767  * These subcommands rewrite the heap, so require full locks.
3768  */
3769  case AT_AddColumn: /* may rewrite heap, in some cases and visible
3770  * to SELECT */
3771  case AT_SetTableSpace: /* must rewrite heap */
3772  case AT_AlterColumnType: /* must rewrite heap */
3773  cmd_lockmode = AccessExclusiveLock;
3774  break;
3775 
3776  /*
3777  * These subcommands may require addition of toast tables. If
3778  * we add a toast table to a table currently being scanned, we
3779  * might miss data added to the new toast table by concurrent
3780  * insert transactions.
3781  */
3782  case AT_SetStorage: /* may add toast tables, see
3783  * ATRewriteCatalogs() */
3784  cmd_lockmode = AccessExclusiveLock;
3785  break;
3786 
3787  /*
3788  * Removing constraints can affect SELECTs that have been
3789  * optimized assuming the constraint holds true. See also
3790  * CloneFkReferenced.
3791  */
3792  case AT_DropConstraint: /* as DROP INDEX */
3793  case AT_DropNotNull: /* may change some SQL plans */
3794  cmd_lockmode = AccessExclusiveLock;
3795  break;
3796 
3797  /*
3798  * Subcommands that may be visible to concurrent SELECTs
3799  */
3800  case AT_DropColumn: /* change visible to SELECT */
3801  case AT_AddColumnToView: /* CREATE VIEW */
3802  case AT_DropOids: /* used to equiv to DropColumn */
3803  case AT_EnableAlwaysRule: /* may change SELECT rules */
3804  case AT_EnableReplicaRule: /* may change SELECT rules */
3805  case AT_EnableRule: /* may change SELECT rules */
3806  case AT_DisableRule: /* may change SELECT rules */
3807  cmd_lockmode = AccessExclusiveLock;
3808  break;
3809 
3810  /*
3811  * Changing owner may remove implicit SELECT privileges
3812  */
3813  case AT_ChangeOwner: /* change visible to SELECT */
3814  cmd_lockmode = AccessExclusiveLock;
3815  break;
3816 
3817  /*
3818  * Changing foreign table options may affect optimization.
3819  */
3820  case AT_GenericOptions:
3822  cmd_lockmode = AccessExclusiveLock;
3823  break;
3824 
3825  /*
3826  * These subcommands affect write operations only.
3827  */
3828  case AT_EnableTrig:
3829  case AT_EnableAlwaysTrig:
3830  case AT_EnableReplicaTrig:
3831  case AT_EnableTrigAll:
3832  case AT_EnableTrigUser:
3833  case AT_DisableTrig:
3834  case AT_DisableTrigAll:
3835  case AT_DisableTrigUser:
3836  cmd_lockmode = ShareRowExclusiveLock;
3837  break;
3838 
3839  /*
3840  * These subcommands affect write operations only. XXX
3841  * Theoretically, these could be ShareRowExclusiveLock.
3842  */
3843  case AT_ColumnDefault:
3845  case AT_AlterConstraint:
3846  case AT_AddIndex: /* from ADD CONSTRAINT */
3847  case AT_AddIndexConstraint:
3848  case AT_ReplicaIdentity:
3849  case AT_SetNotNull:
3850  case AT_EnableRowSecurity:
3851  case AT_DisableRowSecurity:
3852  case AT_ForceRowSecurity:
3853  case AT_NoForceRowSecurity:
3854  case AT_AddIdentity:
3855  case AT_DropIdentity:
3856  case AT_SetIdentity:
3857  case AT_DropExpression:
3858  cmd_lockmode = AccessExclusiveLock;
3859  break;
3860 
3861  case AT_AddConstraint:
3862  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
3863  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
3864  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
3865  if (IsA(cmd->def, Constraint))
3866  {
3867  Constraint *con = (Constraint *) cmd->def;
3868 
3869  switch (con->contype)
3870  {
3871  case CONSTR_EXCLUSION:
3872  case CONSTR_PRIMARY:
3873  case CONSTR_UNIQUE:
3874 
3875  /*
3876  * Cases essentially the same as CREATE INDEX. We
3877  * could reduce the lock strength to ShareLock if
3878  * we can work out how to allow concurrent catalog
3879  * updates. XXX Might be set down to
3880  * ShareRowExclusiveLock but requires further
3881  * analysis.
3882  */
3883  cmd_lockmode = AccessExclusiveLock;
3884  break;
3885  case CONSTR_FOREIGN:
3886 
3887  /*
3888  * We add triggers to both tables when we add a
3889  * Foreign Key, so the lock level must be at least
3890  * as strong as CREATE TRIGGER.
3891  */
3892  cmd_lockmode = ShareRowExclusiveLock;
3893  break;
3894 
3895  default:
3896  cmd_lockmode = AccessExclusiveLock;
3897  }
3898  }
3899  break;
3900 
3901  /*
3902  * These subcommands affect inheritance behaviour. Queries
3903  * started before us will continue to see the old inheritance
3904  * behaviour, while queries started after we commit will see
3905  * new behaviour. No need to prevent reads or writes to the
3906  * subtable while we hook it up though. Changing the TupDesc
3907  * may be a problem, so keep highest lock.
3908  */
3909  case AT_AddInherit:
3910  case AT_DropInherit:
3911  cmd_lockmode = AccessExclusiveLock;
3912  break;
3913 
3914  /*
3915  * These subcommands affect implicit row type conversion. They
3916  * have affects similar to CREATE/DROP CAST on queries. don't
3917  * provide for invalidating parse trees as a result of such
3918  * changes, so we keep these at AccessExclusiveLock.
3919  */
3920  case AT_AddOf:
3921  case AT_DropOf:
3922  cmd_lockmode = AccessExclusiveLock;
3923  break;
3924 
3925  /*
3926  * Only used by CREATE OR REPLACE VIEW which must conflict
3927  * with an SELECTs currently using the view.
3928  */
3929  case AT_ReplaceRelOptions:
3930  cmd_lockmode = AccessExclusiveLock;
3931  break;
3932 
3933  /*
3934  * These subcommands affect general strategies for performance
3935  * and maintenance, though don't change the semantic results
3936  * from normal data reads and writes. Delaying an ALTER TABLE
3937  * behind currently active writes only delays the point where
3938  * the new strategy begins to take effect, so there is no
3939  * benefit in waiting. In this case the minimum restriction
3940  * applies: we don't currently allow concurrent catalog
3941  * updates.
3942  */
3943  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
3944  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
3945  case AT_DropCluster: /* Uses MVCC in getIndexes() */
3946  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
3947  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
3948  cmd_lockmode = ShareUpdateExclusiveLock;
3949  break;
3950 
3951  case AT_SetLogged:
3952  case AT_SetUnLogged:
3953  cmd_lockmode = AccessExclusiveLock;
3954  break;
3955 
3956  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
3957  cmd_lockmode = ShareUpdateExclusiveLock;
3958  break;
3959 
3960  /*
3961  * Rel options are more complex than first appears. Options
3962  * are set here for tables, views and indexes; for historical
3963  * reasons these can all be used with ALTER TABLE, so we can't
3964  * decide between them using the basic grammar.
3965  */
3966  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3967  * getTables() */
3968  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3969  * getTables() */
3970  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
3971  break;
3972 
3973  case AT_AttachPartition:
3974  cmd_lockmode = ShareUpdateExclusiveLock;
3975  break;
3976 
3977  case AT_DetachPartition:
3978  cmd_lockmode = AccessExclusiveLock;
3979  break;
3980 
3981  case AT_CheckNotNull:
3982 
3983  /*
3984  * This only examines the table's schema; but lock must be
3985  * strong enough to prevent concurrent DROP NOT NULL.
3986  */
3987  cmd_lockmode = AccessShareLock;
3988  break;
3989 
3991  cmd_lockmode = AccessExclusiveLock;
3992  break;
3993 
3994  default: /* oops */
3995  elog(ERROR, "unrecognized alter table type: %d",
3996  (int) cmd->subtype);
3997  break;
3998  }
3999 
4000  /*
4001  * Take the greatest lockmode from any subcommand
4002  */
4003  if (cmd_lockmode > lockmode)
4004  lockmode = cmd_lockmode;
4005  }
4006 
4007  return lockmode;
4008 }
4009 
4010 /*
4011  * ATController provides top level control over the phases.
4012  *
4013  * parsetree is passed in to allow it to be passed to event triggers
4014  * when requested.
4015  */
4016 static void
4018  Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
4019  AlterTableUtilityContext *context)
4020 {
4021  List *wqueue = NIL;
4022  ListCell *lcmd;
4023 
4024  /* Phase 1: preliminary examination of commands, create work queue */
4025  foreach(lcmd, cmds)
4026  {
4027  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4028 
4029  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
4030  }
4031 
4032  /* Close the relation, but keep lock until commit */
4033  relation_close(rel, NoLock);
4034 
4035  /* Phase 2: update system catalogs */
4036  ATRewriteCatalogs(&wqueue, lockmode, context);
4037 
4038  /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
4039  ATRewriteTables(parsetree, &wqueue, lockmode, context);
4040 }
4041 
4042 /*
4043  * ATPrepCmd
4044  *
4045  * Traffic cop for ALTER TABLE Phase 1 operations, including simple
4046  * recursion and permission checks.
4047  *
4048  * Caller must have acquired appropriate lock type on relation already.
4049  * This lock should be held until commit.
4050  */
4051 static void
4052 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
4053  bool recurse, bool recursing, LOCKMODE lockmode,
4054  AlterTableUtilityContext *context)
4055 {
4056  AlteredTableInfo *tab;
4057  int pass = AT_PASS_UNSET;
4058 
4059  /* Find or create work queue entry for this table */
4060  tab = ATGetQueueEntry(wqueue, rel);
4061 
4062  /*
4063  * Copy the original subcommand for each table. This avoids conflicts
4064  * when different child tables need to make different parse
4065  * transformations (for example, the same column may have different column
4066  * numbers in different children). It also ensures that we don't corrupt
4067  * the original parse tree, in case it is saved in plancache.
4068  */
4069  cmd = copyObject(cmd);
4070 
4071  /*
4072  * Do permissions and relkind checking, recursion to child tables if
4073  * needed, and any additional phase-1 processing needed. (But beware of
4074  * adding any processing that looks at table details that another
4075  * subcommand could change. In some cases we reject multiple subcommands
4076  * that could try to change the same state in contrary ways.)
4077  */
4078  switch (cmd->subtype)
4079  {
4080  case AT_AddColumn: /* ADD COLUMN */
4081  ATSimplePermissions(rel,
4083  ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
4084  lockmode, context);
4085  /* Recursion occurs during execution phase */
4086  pass = AT_PASS_ADD_COL;
4087  break;
4088  case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
4090  ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
4091  lockmode, context);
4092  /* Recursion occurs during execution phase */
4093  pass = AT_PASS_ADD_COL;
4094  break;
4095  case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
4096 
4097  /*
4098  * We allow defaults on views so that INSERT into a view can have
4099  * default-ish behavior. This works because the rewriter
4100  * substitutes default values into INSERTs before it expands
4101  * rules.
4102  */
4104  ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
4105  /* No command-specific prep needed */
4106  pass = cmd->def ? AT_PASS_ADD_OTHERCONSTR : AT_PASS_DROP;
4107  break;
4108  case AT_CookedColumnDefault: /* add a pre-cooked default */
4109  /* This is currently used only in CREATE TABLE */
4110  /* (so the permission check really isn't necessary) */
4112  /* This command never recurses */
4113  pass = AT_PASS_ADD_OTHERCONSTR;
4114  break;
4115  case AT_AddIdentity:
4117  /* This command never recurses */
4118  pass = AT_PASS_ADD_OTHERCONSTR;
4119  break;
4120  case AT_SetIdentity:
4122  /* This command never recurses */
4123  /* This should run after AddIdentity, so do it in MISC pass */
4124  pass = AT_PASS_MISC;
4125  break;
4126  case AT_DropIdentity:
4128  /* This command never recurses */
4129  pass = AT_PASS_DROP;
4130  break;
4131  case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
4133  ATPrepDropNotNull(rel, recurse, recursing);
4134  ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
4135  pass = AT_PASS_DROP;
4136  break;
4137  case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
4139  /* Need command-specific recursion decision */
4140  ATPrepSetNotNull(wqueue, rel, cmd, recurse, recursing,
4141  lockmode, context);
4142  pass = AT_PASS_COL_ATTRS;
4143  break;
4144  case AT_CheckNotNull: /* check column is already marked NOT NULL */
4146  ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
4147  /* No command-specific prep needed */
4148  pass = AT_PASS_COL_ATTRS;
4149  break;
4150  case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */
4152  ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
4153  ATPrepDropExpression(rel, cmd, recurse, recursing, lockmode);
4154  pass = AT_PASS_DROP;
4155  break;
4156  case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
4158  ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
4159  /* No command-specific prep needed */
4160  pass = AT_PASS_MISC;
4161  break;
4162  case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
4163  case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
4165  /* This command never recurses */
4166  pass = AT_PASS_MISC;
4167  break;
4168  case AT_AlterCollationRefreshVersion: /* ALTER COLLATION ... REFRESH
4169  * VERSION */
4171  /* This command never recurses */
4172  pass = AT_PASS_MISC;
4173  break;
4174  case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
4176  ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
4177  /* No command-specific prep needed */
4178  pass = AT_PASS_MISC;
4179  break;
4180  case AT_DropColumn: /* DROP COLUMN */
4181  ATSimplePermissions(rel,
4183  ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd,
4184  lockmode, context);
4185  /* Recursion occurs during execution phase */
4186  pass = AT_PASS_DROP;
4187  break;
4188  case AT_AddIndex: /* ADD INDEX */
4190  /* This command never recurses */
4191  /* No command-specific prep needed */
4192  pass = AT_PASS_ADD_INDEX;
4193  break;
4194  case AT_AddConstraint: /* ADD CONSTRAINT */
4196  /* Recursion occurs during execution phase */
4197  /* No command-specific prep needed except saving recurse flag */
4198  if (recurse)
4200  pass = AT_PASS_ADD_CONSTR;
4201  break;
4202  case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
4204  /* This command never recurses */
4205  /* No command-specific prep needed */
4206  pass = AT_PASS_ADD_INDEXCONSTR;
4207  break;
4208  case AT_DropConstraint: /* DROP CONSTRAINT */
4210  ATCheckPartitionsNotInUse(rel, lockmode);
4211  /* Other recursion occurs during execution phase */
4212  /* No command-specific prep needed except saving recurse flag */
4213  if (recurse)
4215  pass = AT_PASS_DROP;
4216  break;
4217  case AT_AlterColumnType: /* ALTER COLUMN TYPE */
4218  ATSimplePermissions(rel,
4220  /* See comments for ATPrepAlterColumnType */
4221  cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
4222  AT_PASS_UNSET, context);
4223  Assert(cmd != NULL);
4224  /* Performs own recursion */
4225  ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
4226  lockmode, context);
4227  pass = AT_PASS_ALTER_TYPE;
4228  break;
4231  /* This command never recurses */
4232  /* No command-specific prep needed */
4233  pass = AT_PASS_MISC;
4234  break;
4235  case AT_ChangeOwner: /* ALTER OWNER */
4236  /* This command never recurses */
4237  /* No command-specific prep needed */
4238  pass = AT_PASS_MISC;
4239  break;
4240  case AT_ClusterOn: /* CLUSTER ON */
4241  case AT_DropCluster: /* SET WITHOUT CLUSTER */
4243  /* These commands never recurse */
4244  /* No command-specific prep needed */
4245  pass = AT_PASS_MISC;
4246  break;
4247  case AT_SetLogged: /* SET LOGGED */
4249  if (tab->chgPersistence)
4250  ereport(ERROR,
4251  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4252  errmsg("cannot change persistence setting twice")));
4253  tab->chgPersistence = ATPrepChangePersistence(rel, true);
4254  /* force rewrite if necessary; see comment in ATRewriteTables */
4255  if (tab->chgPersistence)
4256  {
4258  tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
4259  }
4260  pass = AT_PASS_MISC;
4261  break;
4262  case AT_SetUnLogged: /* SET UNLOGGED */
4264  if (tab->chgPersistence)
4265  ereport(ERROR,
4266  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4267  errmsg("cannot change persistence setting twice")));
4268  tab->chgPersistence = ATPrepChangePersistence(rel, false);
4269  /* force rewrite if necessary; see comment in ATRewriteTables */
4270  if (tab->chgPersistence)
4271  {
4273  tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
4274  }
4275  pass = AT_PASS_MISC;
4276  break;
4277  case AT_DropOids: /* SET WITHOUT OIDS */
4279  pass = AT_PASS_DROP;
4280  break;
4281  case AT_SetTableSpace: /* SET TABLESPACE */
4284  /* This command never recurses */
4285  ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
4286  pass = AT_PASS_MISC; /* doesn't actually matter */
4287  break;
4288  case AT_SetRelOptions: /* SET (...) */
4289  case AT_ResetRelOptions: /* RESET (...) */
4290  case AT_ReplaceRelOptions: /* reset them all, then set just these */
4292  /* This command never recurses */
4293  /* No command-specific prep needed */
4294  pass = AT_PASS_MISC;
4295  break;
4296  case AT_AddInherit: /* INHERIT */
4298  /* This command never recurses */
4299  ATPrepAddInherit(rel);
4300  pass = AT_PASS_MISC;
4301  break;
4302  case AT_DropInherit: /* NO INHERIT */
4304  /* This command never recurses */
4305  /* No command-specific prep needed */
4306  pass = AT_PASS_MISC;
4307  break;
4308  case AT_AlterConstraint: /* ALTER CONSTRAINT */
4310  pass = AT_PASS_MISC;
4311  break;
4312  case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
4314  /* Recursion occurs during execution phase */
4315  /* No command-specific prep needed except saving recurse flag */
4316  if (recurse)
4318  pass = AT_PASS_MISC;
4319  break;
4320  case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
4322  pass = AT_PASS_MISC;
4323  /* This command never recurses */
4324  /* No command-specific prep needed */
4325  break;
4326  case AT_EnableTrig: /* ENABLE TRIGGER variants */
4327  case AT_EnableAlwaysTrig:
4328  case AT_EnableReplicaTrig:
4329  case AT_EnableTrigAll:
4330  case AT_EnableTrigUser:
4331  case AT_DisableTrig: /* DISABLE TRIGGER variants */
4332  case AT_DisableTrigAll:
4333  case AT_DisableTrigUser:
4335  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
4336  ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
4337  pass = AT_PASS_MISC;
4338  break;
4339  case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
4340  case AT_EnableAlwaysRule:
4341  case AT_EnableReplicaRule:
4342  case AT_DisableRule:
4343  case AT_AddOf: /* OF */
4344  case AT_DropOf: /* NOT OF */
4345  case AT_EnableRowSecurity:
4346  case AT_DisableRowSecurity:
4347  case AT_ForceRowSecurity:
4348  case AT_NoForceRowSecurity:
4350  /* These commands never recurse */
4351  /* No command-specific prep needed */
4352  pass = AT_PASS_MISC;
4353  break;
4354  case AT_GenericOptions:
4356  /* No command-specific prep needed */
4357  pass = AT_PASS_MISC;
4358  break;
4359  case AT_AttachPartition:
4361  /* No command-specific prep needed */
4362  pass = AT_PASS_MISC;
4363  break;
4364  case AT_DetachPartition:
4366  /* No command-specific prep needed */
4367  pass = AT_PASS_MISC;
4368  break;
4369  default: /* oops */
4370  elog(ERROR, "unrecognized alter table type: %d",
4371  (int) cmd->subtype);
4372  pass = AT_PASS_UNSET; /* keep compiler quiet */
4373  break;
4374  }
4375  Assert(pass > AT_PASS_UNSET);
4376 
4377  /* Add the subcommand to the appropriate list for phase 2 */
4378  tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
4379 }
4380 
4381 /*
4382  * ATRewriteCatalogs
4383  *
4384  * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
4385  * dispatched in a "safe" execution order (designed to avoid unnecessary
4386  * conflicts).
4387  */
4388 static void
4389 ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
4390  AlterTableUtilityContext *context)
4391 {
4392  int pass;
4393  ListCell *ltab;
4394 
4395  /*
4396  * We process all the tables "in parallel", one pass at a time. This is
4397  * needed because we may have to propagate work from one table to another
4398  * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
4399  * re-adding of the foreign key constraint to the other table). Work can
4400  * only be propagated into later passes, however.
4401  */
4402  for (pass = 0; pass < AT_NUM_PASSES; pass++)
4403  {
4404  /* Go through each table that needs to be processed */
4405  foreach(ltab, *wqueue)
4406  {
4407  AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
4408  List *subcmds = tab->subcmds[pass];
4409  Relation rel;
4410  ListCell *lcmd;
4411 
4412  if (subcmds == NIL)
4413  continue;
4414 
4415  /*
4416  * Appropriate lock was obtained by phase 1, needn't get it again
4417  */
4418  rel = relation_open(tab->relid, NoLock);
4419 
4420  foreach(lcmd, subcmds)
4421  ATExecCmd(wqueue, tab, rel,
4422  castNode(AlterTableCmd, lfirst(lcmd)),
4423  lockmode, pass, context);
4424 
4425  /*
4426  * After the ALTER TYPE pass, do cleanup work (this is not done in
4427  * ATExecAlterColumnType since it should be done only once if
4428  * multiple columns of a table are altered).
4429  */
4430  if (pass == AT_PASS_ALTER_TYPE)
4431  ATPostAlterTypeCleanup(wqueue, tab, lockmode);
4432 
4433  relation_close(rel, NoLock);
4434  }
4435  }
4436 
4437  /* Check to see if a toast table must be added. */
4438  foreach(ltab, *wqueue)
4439  {
4440  AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
4441 
4442  /*
4443  * If the table is source table of ATTACH PARTITION command, we did
4444  * not modify anything about it that will change its toasting
4445  * requirement, so no need to check.
4446  */
4447  if (((tab->relkind == RELKIND_RELATION ||
4448  tab->relkind == RELKIND_PARTITIONED_TABLE) &&
4449  tab->partition_constraint == NULL) ||
4450  tab->relkind == RELKIND_MATVIEW)
4451  AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
4452  }
4453 }
4454 
4455 /*
4456  * ATExecCmd: dispatch a subcommand to appropriate execution routine
4457  */
4458 static void
4460  AlterTableCmd *cmd, LOCKMODE lockmode, int cur_pass,
4461  AlterTableUtilityContext *context)
4462 {
4464 
4465  switch (cmd->subtype)
4466  {
4467  case AT_AddColumn: /* ADD COLUMN */
4468  case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
4469  address = ATExecAddColumn(wqueue, tab, rel, &cmd,
4470  false, false,
4471  lockmode, cur_pass, context);
4472  break;
4473  case AT_AddColumnRecurse:
4474  address = ATExecAddColumn(wqueue, tab, rel, &cmd,
4475  true, false,
4476  lockmode, cur_pass, context);
4477  break;
4478  case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
4479  address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
4480  break;
4481  case AT_CookedColumnDefault: /* add a pre-cooked default */
4482  address = ATExecCookedColumnDefault(rel, cmd->num, cmd->def);
4483  break;
4484  case AT_AddIdentity:
4485  cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
4486  cur_pass, context);
4487  Assert(cmd != NULL);
4488  address = ATExecAddIdentity(rel, cmd->name, cmd->def, lockmode);
4489  break;
4490  case AT_SetIdentity:
4491  cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
4492  cur_pass, context);
4493  Assert(cmd != NULL);
4494  address = ATExecSetIdentity(rel, cmd->name, cmd->def, lockmode);
4495  break;
4496  case AT_DropIdentity:
4497  address = ATExecDropIdentity(rel, cmd->name, cmd->missing_ok, lockmode);
4498  break;
4499  case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
4500  address = ATExecDropNotNull(rel, cmd->name, lockmode);
4501  break;
4502  case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
4503  address = ATExecSetNotNull(tab, rel, cmd->name, lockmode);
4504  break;
4505  case AT_CheckNotNull: /* check column is already marked NOT NULL */
4506  ATExecCheckNotNull(tab, rel, cmd->name, lockmode);
4507  break;
4508  case AT_DropExpression:
4509  address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode);
4510  break;
4511  case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
4512  address = ATExecSetStatistics(rel, cmd->name, cmd->num, cmd->def, lockmode);
4513  break;
4514  case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
4515  address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
4516  break;
4517  case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
4518  address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
4519  break;
4520  case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
4521  address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
4522  break;
4523  case AT_DropColumn: /* DROP COLUMN */
4524  address = ATExecDropColumn(wqueue, rel, cmd->name,
4525  cmd->behavior, false, false,
4526  cmd->missing_ok, lockmode,
4527  NULL);
4528  break;
4529  case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
4530  address = ATExecDropColumn(wqueue, rel, cmd->name,
4531  cmd->behavior, true, false,
4532  cmd->missing_ok, lockmode,
4533  NULL);
4534  break;
4535  case AT_AddIndex: /* ADD INDEX */
4536  address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
4537  lockmode);
4538  break;
4539  case AT_ReAddIndex: /* ADD INDEX */
4540  address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
4541  lockmode);
4542  break;
4543  case AT_AddConstraint: /* ADD CONSTRAINT */
4544  /* Transform the command only during initial examination */
4545  if (cur_pass == AT_PASS_ADD_CONSTR)
4546  cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
4547  false, lockmode,
4548  cur_pass, context);
4549  /* Depending on constraint type, might be no more work to do now */
4550  if (cmd != NULL)
4551  address =
4552  ATExecAddConstraint(wqueue, tab, rel,
4553  (Constraint *) cmd->def,
4554  false, false, lockmode);
4555  break;
4556  case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
4557  /* Transform the command only during initial examination */
4558  if (cur_pass == AT_PASS_ADD_CONSTR)
4559  cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
4560  true, lockmode,
4561  cur_pass, context);
4562  /* Depending on constraint type, might be no more work to do now */
4563  if (cmd != NULL)
4564  address =
4565  ATExecAddConstraint(wqueue, tab, rel,
4566  (Constraint *) cmd->def,
4567  true, false, lockmode);
4568  break;
4569  case AT_ReAddConstraint: /* Re-add pre-existing check constraint */
4570  address =
4571  ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
4572  true, true, lockmode);
4573  break;
4574  case AT_ReAddDomainConstraint: /* Re-add pre-existing domain check
4575  * constraint */
4576  address =
4577  AlterDomainAddConstraint(((AlterDomainStmt *) cmd->def)->typeName,
4578  ((AlterDomainStmt *) cmd->def)->def,
4579  NULL);
4580  break;
4581  case AT_ReAddComment: /* Re-add existing comment */
4582  address = CommentObject((CommentStmt *) cmd->def);
4583  break;
4584  case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
4585  address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
4586  lockmode);
4587  break;
4588  case AT_AlterConstraint: /* ALTER CONSTRAINT */
4589  address = ATExecAlterConstraint(rel, cmd, false, false, lockmode);
4590  break;
4591  case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
4592  address = ATExecValidateConstraint(wqueue, rel, cmd->name, false,
4593  false, lockmode);
4594  break;
4595  case AT_ValidateConstraintRecurse: /* VALIDATE CONSTRAINT with
4596  * recursion */
4597  address = ATExecValidateConstraint(wqueue, rel, cmd->name, true,
4598  false, lockmode);
4599  break;
4600  case AT_DropConstraint: /* DROP CONSTRAINT */
4601  ATExecDropConstraint(rel, cmd->name, cmd->behavior,
4602  false, false,
4603  cmd->missing_ok, lockmode);
4604  break;
4605  case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
4606  ATExecDropConstraint(rel, cmd->name, cmd->behavior,
4607  true, false,
4608  cmd->missing_ok, lockmode);
4609  break;
4610  case AT_AlterColumnType: /* ALTER COLUMN TYPE */
4611  /* parse transformation was done earlier */
4612  address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
4613  break;
4614  case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
4615  address =
4617  (List *) cmd->def, lockmode);
4618  break;
4619  case AT_ChangeOwner: /* ALTER OWNER */
4621  get_rolespec_oid(cmd->newowner, false),
4622  false, lockmode);
4623  break;
4624  case AT_ClusterOn: /* CLUSTER ON */
4625  address = ATExecClusterOn(rel, cmd->name, lockmode);
4626  break;
4627  case AT_DropCluster: /* SET WITHOUT CLUSTER */
4628  ATExecDropCluster(rel, lockmode);
4629  break;
4630  case AT_SetLogged: /* SET LOGGED */
4631  case AT_SetUnLogged: /* SET UNLOGGED */
4632  break;
4633  case AT_DropOids: /* SET WITHOUT OIDS */
4634  /* nothing to do here, oid columns don't exist anymore */
4635  break;
4636  case AT_SetTableSpace: /* SET TABLESPACE */
4637 
4638  /*
4639  * Only do this for partitioned tables and indexes, for which this
4640  * is just a catalog change. Other relation types which have
4641  * storage are handled by Phase 3.
4642  */
4643  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
4644  rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4646 
4647  break;
4648  case AT_SetRelOptions: /* SET (...) */
4649  case AT_ResetRelOptions: /* RESET (...) */
4650  case AT_ReplaceRelOptions: /* replace entire option list */
4651  ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
4652  break;
4653  case AT_EnableTrig: /* ENABLE TRIGGER name */
4654  ATExecEnableDisableTrigger(rel, cmd->name,
4655  TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
4656  break;
4657  case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
4658  ATExecEnableDisableTrigger(rel, cmd->name,
4659  TRIGGER_FIRES_ALWAYS, false, lockmode);
4660  break;
4661  case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
4662  ATExecEnableDisableTrigger(rel, cmd->name,
4663  TRIGGER_FIRES_ON_REPLICA, false, lockmode);
4664  break;
4665  case AT_DisableTrig: /* DISABLE TRIGGER name */
4666  ATExecEnableDisableTrigger(rel, cmd->name,
4667  TRIGGER_DISABLED, false, lockmode);
4668  break;
4669  case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
4670  ATExecEnableDisableTrigger(rel, NULL,
4671  TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
4672  break;
4673  case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
4674  ATExecEnableDisableTrigger(rel, NULL,
4675  TRIGGER_DISABLED, false, lockmode);
4676  break;
4677  case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
4678  ATExecEnableDisableTrigger(rel, NULL,
4679  TRIGGER_FIRES_ON_ORIGIN, true, lockmode);
4680  break;
4681  case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
4682  ATExecEnableDisableTrigger(rel, NULL,
4683  TRIGGER_DISABLED, true, lockmode);
4684  break;
4685 
4686  case AT_EnableRule: /* ENABLE RULE name */
4687  ATExecEnableDisableRule(rel, cmd->name,
4688  RULE_FIRES_ON_ORIGIN, lockmode);
4689  break;
4690  case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
4691  ATExecEnableDisableRule(rel, cmd->name,
4692  RULE_FIRES_ALWAYS, lockmode);
4693  break;
4694  case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
4695  ATExecEnableDisableRule(rel, cmd->name,
4696  RULE_FIRES_ON_REPLICA, lockmode);
4697  break;
4698  case AT_DisableRule: /* DISABLE RULE name */
4699  ATExecEnableDisableRule(rel, cmd->name,
4700  RULE_DISABLED, lockmode);
4701  break;
4702 
4703  case AT_AddInherit:
4704  address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
4705  break;
4706  case AT_DropInherit:
4707  address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
4708  break;
4709  case AT_AddOf:
4710  address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
4711  break;
4712  case AT_DropOf:
4713  ATExecDropOf(rel, lockmode);
4714  break;
4715  case AT_ReplicaIdentity:
4716  ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
4717  break;
4718  case AT_EnableRowSecurity:
4720  break;
4721  case AT_DisableRowSecurity:
4723  break;
4724  case AT_ForceRowSecurity:
4725  ATExecForceNoForceRowSecurity(rel, true);
4726  break;
4727  case AT_NoForceRowSecurity:
4728  ATExecForceNoForceRowSecurity(rel, false);
4729  break;
4730  case AT_GenericOptions:
4731  ATExecGenericOptions(rel, (List *) cmd->def);
4732  break;
4733  case AT_AttachPartition:
4734  cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
4735  cur_pass, context);
4736  Assert(cmd != NULL);
4737  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
4738  ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
4739  context);
4740  else
4741  ATExecAttachPartitionIdx(wqueue, rel,
4742  ((PartitionCmd *) cmd->def)->name);
4743  break;
4744  case AT_DetachPartition:
4745  cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
4746  cur_pass, context);
4747  Assert(cmd != NULL);
4748  /* ATPrepCmd ensures it must be a table */
4749  Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
4750  ATExecDetachPartition(rel, ((PartitionCmd *) cmd->def)->name);
4751  break;
4753  /* ATPrepCmd ensured it must be an index */
4754  Assert(rel->rd_rel->relkind == RELKIND_INDEX);
4756  break;
4757  default: /* oops */
4758  elog(ERROR, "unrecognized alter table type: %d",
4759  (int) cmd->subtype);
4760  break;
4761  }
4762 
4763  /*
4764  * Report the subcommand to interested event triggers.
4765  */
4766  if (cmd)
4767  EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
4768 
4769  /*
4770  * Bump the command counter to ensure the next subcommand in the sequence
4771  * can see the changes so far
4772  */
4774 }
4775 
4776 /*
4777  * ATParseTransformCmd: perform parse transformation for one subcommand
4778  *
4779  * Returns the transformed subcommand tree, if there is one, else NULL.
4780  *
4781  * The parser may hand back additional AlterTableCmd(s) and/or other
4782  * utility statements, either before or after the original subcommand.
4783  * Other AlterTableCmds are scheduled into the appropriate slot of the
4784  * AlteredTableInfo (they had better be for later passes than the current one).
4785  * Utility statements that are supposed to happen before the AlterTableCmd
4786  * are executed immediately. Those that are supposed to happen afterwards
4787  * are added to the tab->afterStmts list to be done at the very end.
4788  */
4789 static AlterTableCmd *
4791  AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
4792  int cur_pass, AlterTableUtilityContext *context)
4793 {
4794  AlterTableCmd *newcmd = NULL;
4796  List *beforeStmts;
4797  List *afterStmts;
4798  ListCell *lc;
4799 
4800  /* Gin up an AlterTableStmt with just this subcommand and this table */
4801  atstmt->relation =
4804  -1);
4805  atstmt->relation->inh = recurse;
4806  atstmt->cmds = list_make1(cmd);
4807  atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
4808  atstmt->missing_ok = false;
4809 
4810  /* Transform the AlterTableStmt */
4812  atstmt,
4813  context->queryString,
4814  &beforeStmts,
4815  &afterStmts);
4816 
4817  /* Execute any statements that should happen before these subcommand(s) */
4818  foreach(lc, beforeStmts)
4819  {
4820  Node *stmt = (Node *) lfirst(lc);
4821 
4822  ProcessUtilityForAlterTable(stmt, context);
4824  }
4825 
4826  /* Examine the transformed subcommands and schedule them appropriately */
4827  foreach(lc, atstmt->cmds)
4828  {
4830  int pass;
4831 
4832  /*
4833  * This switch need only cover the subcommand types that can be added
4834  * by parse_utilcmd.c; otherwise, we'll use the default strategy of
4835  * executing the subcommand immediately, as a substitute for the
4836  * original subcommand. (Note, however, that this does cause
4837  * AT_AddConstraint subcommands to be rescheduled into later passes,
4838  * which is important for index and foreign key constraints.)
4839  *
4840  * We assume we needn't do any phase-1 checks for added subcommands.
4841  */
4842  switch (cmd2->subtype)
4843  {
4844  case AT_SetNotNull:
4845  /* Need command-specific recursion decision */
4846  ATPrepSetNotNull(wqueue, rel, cmd2,
4847  recurse, false,
4848  lockmode, context);
4849  pass = AT_PASS_COL_ATTRS;
4850  break;
4851  case AT_AddIndex:
4852  /* This command never recurses */
4853  /* No command-specific prep needed */
4854  pass = AT_PASS_ADD_INDEX;
4855  break;
4856  case AT_AddIndexConstraint:
4857  /* This command never recurses */
4858  /* No command-specific prep needed */
4859  pass = AT_PASS_ADD_INDEXCONSTR;
4860  break;
4861  case AT_AddConstraint:
4862  /* Recursion occurs during execution phase */
4863  if (recurse)
4865  switch (castNode(Constraint, cmd2->def)->contype)
4866  {
4867  case CONSTR_PRIMARY:
4868  case CONSTR_UNIQUE:
4869  case CONSTR_EXCLUSION:
4870  pass = AT_PASS_ADD_INDEXCONSTR;
4871  break;
4872  default:
4873  pass = AT_PASS_ADD_OTHERCONSTR;
4874  break;
4875  }
4876  break;
4878  /* This command never recurses */
4879  /* No command-specific prep needed */
4880  pass = AT_PASS_MISC;
4881  break;
4882  default:
4883  pass = cur_pass;
4884  break;
4885  }
4886 
4887  if (pass < cur_pass)
4888  {
4889  /* Cannot schedule into a pass we already finished */
4890  elog(ERROR, "ALTER TABLE scheduling failure: too late for pass %d",
4891  pass);
4892  }
4893  else if (pass > cur_pass)
4894  {
4895  /* OK, queue it up for later */
4896  tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd2);
4897  }
4898  else
4899  {
4900  /*
4901  * We should see at most one subcommand for the current pass,
4902  * which is the transformed version of the original subcommand.
4903  */
4904  if (newcmd == NULL && cmd->subtype == cmd2->subtype)
4905  {
4906  /* Found the transformed version of our subcommand */
4907  newcmd = cmd2;
4908  }
4909  else
4910  elog(ERROR, "ALTER TABLE scheduling failure: bogus item for pass %d",
4911  pass);
4912  }
4913  }
4914 
4915  /* Queue up any after-statements to happen at the end */
4916  tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
4917 
4918  return newcmd;
4919 }
4920 
4921 /*
4922  * ATRewriteTables: ALTER TABLE phase 3
4923  */
4924 static void
4925 ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
4926  AlterTableUtilityContext *context)
4927 {
4928  ListCell *ltab;
4929 
4930  /* Go through each table that needs to be checked or rewritten */
4931  foreach(ltab, *wqueue)
4932  {
4933  AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
4934 
4935  /* Relations without storage may be ignored here */
4936  if (!RELKIND_HAS_STORAGE(tab->relkind))
4937  continue;
4938 
4939  /*
4940  * If we change column data types, the operation has to be propagated
4941  * to tables that use this table's rowtype as a column type.
4942  * tab->newvals will also be non-NULL in the case where we're adding a
4943  * column with a default. We choose to forbid that case as well,
4944  * since composite types might eventually support defaults.
4945  *
4946  * (Eventually we'll probably need to check for composite type
4947  * dependencies even when we're just scanning the table without a
4948  * rewrite, but at the moment a composite type does not enforce any
4949  * constraints, so it's not necessary/appropriate to enforce them just
4950  * during ALTER.)
4951  */
4952  if (tab->newvals != NIL || tab->rewrite > 0)
4953  {
4954  Relation rel;
4955 
4956  rel = table_open(tab->relid, NoLock);
4957  find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
4958  table_close(rel, NoLock);
4959  }
4960 
4961  /*
4962  * We only need to rewrite the table if at least one column needs to
4963  * be recomputed, or we are changing its persistence.
4964  *
4965  * There are two reasons for requiring a rewrite when changing
4966  * persistence: on one hand, we need to ensure that the buffers
4967  * belonging to each of the two relations are marked with or without
4968  * BM_PERMANENT properly. On the other hand, since rewriting creates
4969  * and assigns a new relfilenode, we automatically create or drop an
4970  * init fork for the relation as appropriate.
4971  */
4972  if (tab->rewrite > 0)
4973  {
4974  /* Build a temporary relation and copy data */
4975  Relation OldHeap;
4976  Oid OIDNewHeap;
4977  Oid NewTableSpace;
4978  char persistence;
4979 
4980  OldHeap = table_open(tab->relid, NoLock);
4981 
4982  /*
4983  * We don't support rewriting of system catalogs; there are too
4984  * many corner cases and too little benefit. In particular this
4985  * is certainly not going to work for mapped catalogs.
4986  */
4987  if (IsSystemRelation(OldHeap))
4988  ereport(ERROR,
4989  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4990  errmsg("cannot rewrite system relation \"%s\"",
4991  RelationGetRelationName(OldHeap))));
4992 
4993  if (RelationIsUsedAsCatalogTable(OldHeap))
4994  ereport(ERROR,
4995  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4996  errmsg("cannot rewrite table \"%s\" used as a catalog table",
4997  RelationGetRelationName(OldHeap))));
4998 
4999  /*
5000  * Don't allow rewrite on temp tables of other backends ... their
5001  * local buffer manager is not going to cope.
5002  */
5003  if (RELATION_IS_OTHER_TEMP(OldHeap))
5004  ereport(ERROR,
5005  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5006  errmsg("cannot rewrite temporary tables of other sessions")));
5007 
5008  /*
5009  * Select destination tablespace (same as original unless user
5010  * requested a change)
5011  */
5012  if (tab->newTableSpace)
5013  NewTableSpace = tab->newTableSpace;
5014  else
5015  NewTableSpace = OldHeap->rd_rel->reltablespace;
5016 
5017  /*
5018  * Select persistence of transient table (same as original unless
5019  * user requested a change)
5020  */
5021  persistence = tab->chgPersistence ?
5022  tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
5023 
5024  table_close(OldHeap, NoLock);
5025 
5026  /*
5027  * Fire off an Event Trigger now, before actually rewriting the
5028  * table.
5029  *
5030  * We don't support Event Trigger for nested commands anywhere,
5031  * here included, and parsetree is given NULL when coming from
5032  * AlterTableInternal.
5033  *
5034  * And fire it only once.
5035  */
5036  if (parsetree)
5037  EventTriggerTableRewrite((Node *) parsetree,
5038  tab->relid,
5039  tab->rewrite);
5040 
5041  /*
5042  * Create transient table that will receive the modified data.
5043  *
5044  * Ensure it is marked correctly as logged or unlogged. We have
5045  * to do this here so that buffers for the new relfilenode will
5046  * have the right persistence set, and at the same time ensure
5047  * that the original filenode's buffers will get read in with the
5048  * correct setting (i.e. the original one). Otherwise a rollback
5049  * after the rewrite would possibly result with buffers for the
5050  * original filenode having the wrong persistence setting.
5051  *
5052  * NB: This relies on swap_relation_files() also swapping the
5053  * persistence. That wouldn't work for pg_class, but that can't be
5054  * unlogged anyway.
5055  */
5056  OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, persistence,
5057  lockmode);
5058 
5059  /*
5060  * Copy the heap data into the new table with the desired
5061  * modifications, and test the current data within the table
5062  * against new constraints generated by ALTER TABLE commands.
5063  */
5064  ATRewriteTable(tab, OIDNewHeap, lockmode);
5065 
5066  /*
5067  * Swap the physical files of the old and new heaps, then rebuild
5068  * indexes and discard the old heap. We can use RecentXmin for
5069  * the table's new relfrozenxid because we rewrote all the tuples
5070  * in ATRewriteTable, so no older Xid remains in the table. Also,
5071  * we never try to swap toast tables by content, since we have no
5072  * interest in letting this code work on system catalogs.
5073  */
5074  finish_heap_swap(tab->relid, OIDNewHeap,
5075  false, false, true,
5076  !OidIsValid(tab->newTableSpace),
5077  RecentXmin,
5079  persistence);
5080  }
5081  else
5082  {
5083  /*
5084  * If required, test the current data within the table against new
5085  * constraints generated by ALTER TABLE commands, but don't
5086  * rebuild data.
5087  */
5088  if (tab->constraints != NIL || tab->verify_new_notnull ||
5089  tab->partition_constraint != NULL)
5090  ATRewriteTable(tab, InvalidOid, lockmode);
5091 
5092  /*
5093  * If we had SET TABLESPACE but no reason to reconstruct tuples,
5094  * just do a block-by-block copy.
5095  */
5096  if (tab->newTableSpace)
5097  ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
5098  }
5099  }
5100 
5101  /*
5102  * Foreign key constraints are checked in a final pass, since (a) it's
5103  * generally best to examine each one separately, and (b) it's at least
5104  * theoretically possible that we have changed both relations of the
5105  * foreign key, and we'd better have finished both rewrites before we try
5106  * to read the tables.
5107  */
5108  foreach(ltab, *wqueue)
5109  {
5110  AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5111  Relation rel = NULL;
5112  ListCell *lcon;
5113 
5114  /* Relations without storage may be ignored here too */
5115  if (!RELKIND_HAS_STORAGE(tab->relkind))
5116  continue;
5117 
5118  foreach(lcon, tab->constraints)
5119  {
5120  NewConstraint *con = lfirst(lcon);
5121 
5122  if (con->contype == CONSTR_FOREIGN)
5123  {
5124  Constraint *fkconstraint = (Constraint *) con->qual;
5125  Relation refrel;
5126 
5127  if (rel == NULL)
5128  {
5129  /* Long since locked, no need for another */
5130  rel = table_open(tab->relid, NoLock);
5131  }
5132 
5133  refrel = table_open(con->refrelid, RowShareLock);
5134 
5135  validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
5136  con->refindid,
5137  con->conid);
5138 
5139  /*
5140  * No need to mark the constraint row as validated, we did
5141  * that when we inserted the row earlier.
5142  */
5143 
5144  table_close(refrel, NoLock);
5145  }
5146  }
5147 
5148  if (rel)
5149  table_close(rel, NoLock);
5150  }
5151 
5152  /* Finally, run any afterStmts that were queued up */
5153  foreach(ltab, *wqueue)
5154  {
5155  AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5156  ListCell *lc;
5157 
5158  foreach(lc, tab->afterStmts)
5159  {
5160  Node *stmt = (Node *) lfirst(lc);
5161 
5162  ProcessUtilityForAlterTable(stmt, context);
5164  }
5165  }
5166 }
5167 
5168 /*
5169  * ATRewriteTable: scan or rewrite one table
5170  *
5171  * OIDNewHeap is InvalidOid if we don't need to rewrite
5172  */
5173 static void
5174 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
5175 {
5176  Relation oldrel;
5177  Relation newrel;
5178  TupleDesc oldTupDesc;
5179  TupleDesc newTupDesc;
5180  bool needscan = false;
5181  List *notnull_attrs;
5182  int i;
5183  ListCell *l;
5184  EState *estate;
5185  CommandId mycid;
5186  BulkInsertState bistate;
5187  int ti_options;
5188  ExprState *partqualstate = NULL;
5189 
5190  /*
5191  * Open the relation(s). We have surely already locked the existing
5192  * table.
5193  */
5194  oldrel = table_open(tab->relid, NoLock);
5195  oldTupDesc = tab->oldDesc;
5196  newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
5197 
5198  if (OidIsValid(OIDNewHeap))
5199  newrel = table_open(OIDNewHeap, lockmode);
5200  else
5201  newrel = NULL;
5202 
5203  /*
5204  * Prepare a BulkInsertState and options for table_tuple_insert. The FSM
5205  * is empty, so don't bother using it.
5206  */
5207  if (newrel)
5208  {
5209  mycid = GetCurrentCommandId(true);
5210  bistate = GetBulkInsertState();
5211  ti_options = TABLE_INSERT_SKIP_FSM;
5212  }
5213  else
5214  {
5215  /* keep compiler quiet about using these uninitialized */
5216  mycid = 0;
5217  bistate = NULL;
5218  ti_options = 0;
5219  }
5220 
5221  /*
5222  * Generate the constraint and default execution states
5223  */
5224 
5225  estate = CreateExecutorState();
5226 
5227  /* Build the needed expression execution states */
5228  foreach(l, tab->constraints)
5229  {
5230  NewConstraint *con = lfirst(l);
5231 
5232  switch (con->contype)
5233  {
5234  case CONSTR_CHECK:
5235  needscan = true;
5236  con->qualstate = ExecPrepareExpr((Expr *) con->qual, estate);
5237  break;
5238  case CONSTR_FOREIGN:
5239  /* Nothing to do here */
5240  break;
5241  default:
5242  elog(ERROR, "unrecognized constraint type: %d",
5243  (int) con->contype);
5244  }
5245  }
5246 
5247  /* Build expression execution states for partition check quals */
5248  if (tab->partition_constraint)
5249  {
5250  needscan = true;
5251  partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
5252  }
5253 
5254  foreach(l, tab->newvals)
5255  {
5256  NewColumnValue *ex = lfirst(l);
5257 
5258  /* expr already planned */
5259  ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
5260  }
5261 
5262  notnull_attrs = NIL;
5263  if (newrel || tab->verify_new_notnull)
5264  {
5265  /*
5266  * If we are rebuilding the tuples OR if we added any new but not
5267  * verified NOT NULL constraints, check all not-null constraints. This
5268  * is a bit of overkill but it minimizes risk of bugs, and
5269  * heap_attisnull is a pretty cheap test anyway.
5270  */
5271  for (i = 0; i < newTupDesc->natts; i++)
5272  {
5273  Form_pg_attribute attr = TupleDescAttr(newTupDesc, i);
5274 
5275  if (attr->attnotnull && !attr->attisdropped)
5276  notnull_attrs = lappend_int(notnull_attrs, i);
5277  }
5278  if (notnull_attrs)
5279  needscan = true;
5280  }
5281 
5282  if (newrel || needscan)
5283  {
5284  ExprContext *econtext;
5285  TupleTableSlot *oldslot;
5286  TupleTableSlot *newslot;
5287  TableScanDesc scan;
5288  MemoryContext oldCxt;
5289  List *dropped_attrs = NIL;
5290  ListCell *lc;
5291  Snapshot snapshot;
5292 
5293  if (newrel)
5294  ereport(DEBUG1,
5295  (errmsg("rewriting table \"%s\"",
5296  RelationGetRelationName(oldrel))));
5297  else
5298  ereport(DEBUG1,
5299  (errmsg("verifying table \"%s\"",
5300  RelationGetRelationName(oldrel))));
5301 
5302  if (newrel)
5303  {
5304  /*
5305  * All predicate locks on the tuples or pages are about to be made
5306  * invalid, because we move tuples around. Promote them to
5307  * relation locks.
5308  */
5310  }
5311 
5312  econtext = GetPerTupleExprContext(estate);
5313 
5314  /*
5315  * Create necessary tuple slots. When rewriting, two slots are needed,
5316  * otherwise one suffices. In the case where one slot suffices, we
5317  * need to use the new tuple descriptor, otherwise some constraints
5318  * can't be evaluated. Note that even when the tuple layout is the
5319  * same and no rewrite is required, the tupDescs might not be
5320  * (consider ADD COLUMN without a default).
5321  */
5322  if (tab->rewrite)
5323  {
5324  Assert(newrel != NULL);
5325  oldslot = MakeSingleTupleTableSlot(oldTupDesc,
5326  table_slot_callbacks(oldrel));
5327  newslot = MakeSingleTupleTableSlot(newTupDesc,
5328  table_slot_callbacks(newrel));
5329 
5330  /*
5331  * Set all columns in the new slot to NULL initially, to ensure
5332  * columns added as part of the rewrite are initialized to NULL.
5333  * That is necessary as tab->newvals will not contain an
5334  * expression for columns with a NULL default, e.g. when adding a
5335  * column without a default together with a column with a default
5336  * requiring an actual rewrite.
5337  */
5338  ExecStoreAllNullTuple(newslot);
5339  }
5340  else
5341  {
5342  oldslot = MakeSingleTupleTableSlot(newTupDesc,
5343  table_slot_callbacks(oldrel));
5344  newslot = NULL;
5345  }
5346 
5347  /*
5348  * Any attributes that are dropped according to the new tuple
5349  * descriptor can be set to NULL. We precompute the list of dropped
5350  * attributes to avoid needing to do so in the per-tuple loop.
5351  */
5352  for (i = 0; i < newTupDesc->natts; i++)
5353  {
5354  if (TupleDescAttr(newTupDesc, i)->attisdropped)
5355  dropped_attrs = lappend_int(dropped_attrs, i);
5356  }
5357 
5358  /*
5359  * Scan through the rows, generating a new row if needed and then
5360  * checking all the constraints.
5361  */
5362  snapshot = RegisterSnapshot(GetLatestSnapshot());
5363  scan = table_beginscan(oldrel, snapshot, 0, NULL);
5364 
5365  /*
5366  * Switch to per-tuple memory context and reset it for each tuple
5367  * produced, so we don't leak memory.
5368  */
5370 
5371  while (table_scan_getnextslot(scan, ForwardScanDirection, oldslot))
5372  {
5373  TupleTableSlot *insertslot;
5374 
5375  if (tab->rewrite > 0)
5376  {
5377  /* Extract data from old tuple */
5378  slot_getallattrs(oldslot);
5379  ExecClearTuple(newslot);
5380 
5381  /* copy attributes */
5382  memcpy(newslot->tts_values, oldslot->tts_values,
5383  sizeof(Datum) * oldslot->tts_nvalid);
5384  memcpy(newslot->tts_isnull, oldslot->tts_isnull,
5385  sizeof(bool) * oldslot->tts_nvalid);
5386