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