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