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