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