]> granicus.if.org Git - postgresql/blob - src/backend/commands/tablecmds.c
Allow CURRENT/SESSION_USER to be used in certain commands
[postgresql] / src / backend / commands / tablecmds.c
1 /*-------------------------------------------------------------------------
2  *
3  * tablecmds.c
4  *        Commands for creating and altering table structures and settings
5  *
6  * Portions Copyright (c) 1996-2015, 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/xact.h"
24 #include "access/xlog.h"
25 #include "catalog/catalog.h"
26 #include "catalog/dependency.h"
27 #include "catalog/heap.h"
28 #include "catalog/index.h"
29 #include "catalog/indexing.h"
30 #include "catalog/namespace.h"
31 #include "catalog/objectaccess.h"
32 #include "catalog/pg_collation.h"
33 #include "catalog/pg_constraint.h"
34 #include "catalog/pg_depend.h"
35 #include "catalog/pg_foreign_table.h"
36 #include "catalog/pg_inherits.h"
37 #include "catalog/pg_inherits_fn.h"
38 #include "catalog/pg_namespace.h"
39 #include "catalog/pg_opclass.h"
40 #include "catalog/pg_tablespace.h"
41 #include "catalog/pg_trigger.h"
42 #include "catalog/pg_type.h"
43 #include "catalog/pg_type_fn.h"
44 #include "catalog/storage.h"
45 #include "catalog/toasting.h"
46 #include "commands/cluster.h"
47 #include "commands/comment.h"
48 #include "commands/defrem.h"
49 #include "commands/event_trigger.h"
50 #include "commands/policy.h"
51 #include "commands/sequence.h"
52 #include "commands/tablecmds.h"
53 #include "commands/tablespace.h"
54 #include "commands/trigger.h"
55 #include "commands/typecmds.h"
56 #include "commands/user.h"
57 #include "executor/executor.h"
58 #include "foreign/foreign.h"
59 #include "miscadmin.h"
60 #include "nodes/makefuncs.h"
61 #include "nodes/nodeFuncs.h"
62 #include "nodes/parsenodes.h"
63 #include "optimizer/clauses.h"
64 #include "optimizer/planner.h"
65 #include "parser/parse_clause.h"
66 #include "parser/parse_coerce.h"
67 #include "parser/parse_collate.h"
68 #include "parser/parse_expr.h"
69 #include "parser/parse_oper.h"
70 #include "parser/parse_relation.h"
71 #include "parser/parse_type.h"
72 #include "parser/parse_utilcmd.h"
73 #include "parser/parser.h"
74 #include "pgstat.h"
75 #include "rewrite/rewriteDefine.h"
76 #include "rewrite/rewriteHandler.h"
77 #include "rewrite/rewriteManip.h"
78 #include "storage/bufmgr.h"
79 #include "storage/lmgr.h"
80 #include "storage/lock.h"
81 #include "storage/predicate.h"
82 #include "storage/smgr.h"
83 #include "utils/acl.h"
84 #include "utils/builtins.h"
85 #include "utils/fmgroids.h"
86 #include "utils/inval.h"
87 #include "utils/lsyscache.h"
88 #include "utils/memutils.h"
89 #include "utils/relcache.h"
90 #include "utils/ruleutils.h"
91 #include "utils/snapmgr.h"
92 #include "utils/syscache.h"
93 #include "utils/tqual.h"
94 #include "utils/typcache.h"
95
96
97 /*
98  * ON COMMIT action list
99  */
100 typedef struct OnCommitItem
101 {
102         Oid                     relid;                  /* relid of relation */
103         OnCommitAction oncommit;        /* what to do at end of xact */
104
105         /*
106          * If this entry was created during the current transaction,
107          * creating_subid is the ID of the creating subxact; if created in a prior
108          * transaction, creating_subid is zero.  If deleted during the current
109          * transaction, deleting_subid is the ID of the deleting subxact; if no
110          * deletion request is pending, deleting_subid is zero.
111          */
112         SubTransactionId creating_subid;
113         SubTransactionId deleting_subid;
114 } OnCommitItem;
115
116 static List *on_commits = NIL;
117
118
119 /*
120  * State information for ALTER TABLE
121  *
122  * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
123  * structs, one for each table modified by the operation (the named table
124  * plus any child tables that are affected).  We save lists of subcommands
125  * to apply to this table (possibly modified by parse transformation steps);
126  * these lists will be executed in Phase 2.  If a Phase 3 step is needed,
127  * necessary information is stored in the constraints and newvals lists.
128  *
129  * Phase 2 is divided into multiple passes; subcommands are executed in
130  * a pass determined by subcommand type.
131  */
132
133 #define AT_PASS_UNSET                   -1              /* UNSET will cause ERROR */
134 #define AT_PASS_DROP                    0               /* DROP (all flavors) */
135 #define AT_PASS_ALTER_TYPE              1               /* ALTER COLUMN TYPE */
136 #define AT_PASS_OLD_INDEX               2               /* re-add existing indexes */
137 #define AT_PASS_OLD_CONSTR              3               /* re-add existing constraints */
138 #define AT_PASS_COL_ATTRS               4               /* set other column attributes */
139 /* We could support a RENAME COLUMN pass here, but not currently used */
140 #define AT_PASS_ADD_COL                 5               /* ADD COLUMN */
141 #define AT_PASS_ADD_INDEX               6               /* ADD indexes */
142 #define AT_PASS_ADD_CONSTR              7               /* ADD constraints, defaults */
143 #define AT_PASS_MISC                    8               /* other stuff */
144 #define AT_NUM_PASSES                   9
145
146 typedef struct AlteredTableInfo
147 {
148         /* Information saved before any work commences: */
149         Oid                     relid;                  /* Relation to work on */
150         char            relkind;                /* Its relkind */
151         TupleDesc       oldDesc;                /* Pre-modification tuple descriptor */
152         /* Information saved by Phase 1 for Phase 2: */
153         List       *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
154         /* Information saved by Phases 1/2 for Phase 3: */
155         List       *constraints;        /* List of NewConstraint */
156         List       *newvals;            /* List of NewColumnValue */
157         bool            new_notnull;    /* T if we added new NOT NULL constraints */
158         int                     rewrite;                /* Reason for forced rewrite, if any */
159         Oid                     newTableSpace;  /* new tablespace; 0 means no change */
160         bool            chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
161         char            newrelpersistence;              /* if above is true */
162         /* Objects to rebuild after completing ALTER TYPE operations */
163         List       *changedConstraintOids;      /* OIDs of constraints to rebuild */
164         List       *changedConstraintDefs;      /* string definitions of same */
165         List       *changedIndexOids;           /* OIDs of indexes to rebuild */
166         List       *changedIndexDefs;           /* string definitions of same */
167 } AlteredTableInfo;
168
169 /* Struct describing one new constraint to check in Phase 3 scan */
170 /* Note: new NOT NULL constraints are handled elsewhere */
171 typedef struct NewConstraint
172 {
173         char       *name;                       /* Constraint name, or NULL if none */
174         ConstrType      contype;                /* CHECK or FOREIGN */
175         Oid                     refrelid;               /* PK rel, if FOREIGN */
176         Oid                     refindid;               /* OID of PK's index, if FOREIGN */
177         Oid                     conid;                  /* OID of pg_constraint entry, if FOREIGN */
178         Node       *qual;                       /* Check expr or CONSTR_FOREIGN Constraint */
179         List       *qualstate;          /* Execution state for CHECK */
180 } NewConstraint;
181
182 /*
183  * Struct describing one new column value that needs to be computed during
184  * Phase 3 copy (this could be either a new column with a non-null default, or
185  * a column that we're changing the type of).  Columns without such an entry
186  * are just copied from the old table during ATRewriteTable.  Note that the
187  * expr is an expression over *old* table values.
188  */
189 typedef struct NewColumnValue
190 {
191         AttrNumber      attnum;                 /* which column */
192         Expr       *expr;                       /* expression to compute */
193         ExprState  *exprstate;          /* execution state */
194 } NewColumnValue;
195
196 /*
197  * Error-reporting support for RemoveRelations
198  */
199 struct dropmsgstrings
200 {
201         char            kind;
202         int                     nonexistent_code;
203         const char *nonexistent_msg;
204         const char *skipping_msg;
205         const char *nota_msg;
206         const char *drophint_msg;
207 };
208
209 static const struct dropmsgstrings dropmsgstringarray[] = {
210         {RELKIND_RELATION,
211                 ERRCODE_UNDEFINED_TABLE,
212                 gettext_noop("table \"%s\" does not exist"),
213                 gettext_noop("table \"%s\" does not exist, skipping"),
214                 gettext_noop("\"%s\" is not a table"),
215         gettext_noop("Use DROP TABLE to remove a table.")},
216         {RELKIND_SEQUENCE,
217                 ERRCODE_UNDEFINED_TABLE,
218                 gettext_noop("sequence \"%s\" does not exist"),
219                 gettext_noop("sequence \"%s\" does not exist, skipping"),
220                 gettext_noop("\"%s\" is not a sequence"),
221         gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
222         {RELKIND_VIEW,
223                 ERRCODE_UNDEFINED_TABLE,
224                 gettext_noop("view \"%s\" does not exist"),
225                 gettext_noop("view \"%s\" does not exist, skipping"),
226                 gettext_noop("\"%s\" is not a view"),
227         gettext_noop("Use DROP VIEW to remove a view.")},
228         {RELKIND_MATVIEW,
229                 ERRCODE_UNDEFINED_TABLE,
230                 gettext_noop("materialized view \"%s\" does not exist"),
231                 gettext_noop("materialized view \"%s\" does not exist, skipping"),
232                 gettext_noop("\"%s\" is not a materialized view"),
233         gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
234         {RELKIND_INDEX,
235                 ERRCODE_UNDEFINED_OBJECT,
236                 gettext_noop("index \"%s\" does not exist"),
237                 gettext_noop("index \"%s\" does not exist, skipping"),
238                 gettext_noop("\"%s\" is not an index"),
239         gettext_noop("Use DROP INDEX to remove an index.")},
240         {RELKIND_COMPOSITE_TYPE,
241                 ERRCODE_UNDEFINED_OBJECT,
242                 gettext_noop("type \"%s\" does not exist"),
243                 gettext_noop("type \"%s\" does not exist, skipping"),
244                 gettext_noop("\"%s\" is not a type"),
245         gettext_noop("Use DROP TYPE to remove a type.")},
246         {RELKIND_FOREIGN_TABLE,
247                 ERRCODE_UNDEFINED_OBJECT,
248                 gettext_noop("foreign table \"%s\" does not exist"),
249                 gettext_noop("foreign table \"%s\" does not exist, skipping"),
250                 gettext_noop("\"%s\" is not a foreign table"),
251         gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
252         {'\0', 0, NULL, NULL, NULL, NULL}
253 };
254
255 struct DropRelationCallbackState
256 {
257         char            relkind;
258         Oid                     heapOid;
259         bool            concurrent;
260 };
261
262 /* Alter table target-type flags for ATSimplePermissions */
263 #define         ATT_TABLE                               0x0001
264 #define         ATT_VIEW                                0x0002
265 #define         ATT_MATVIEW                             0x0004
266 #define         ATT_INDEX                               0x0008
267 #define         ATT_COMPOSITE_TYPE              0x0010
268 #define         ATT_FOREIGN_TABLE               0x0020
269
270 static void truncate_check_rel(Relation rel);
271 static List *MergeAttributes(List *schema, List *supers, char relpersistence,
272                                 List **supOids, List **supconstr, int *supOidCount);
273 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
274 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
275 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
276 static void StoreCatalogInheritance(Oid relationId, List *supers);
277 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
278                                                  int16 seqNumber, Relation inhRelation);
279 static int      findAttrByName(const char *attributeName, List *schema);
280 static void AlterIndexNamespaces(Relation classRel, Relation rel,
281                                    Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
282 static void AlterSeqNamespaces(Relation classRel, Relation rel,
283                                    Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
284                                    LOCKMODE lockmode);
285 static void ATExecAlterConstraint(Relation rel, AlterTableCmd *cmd,
286                                           bool recurse, bool recursing, LOCKMODE lockmode);
287 static void ATExecValidateConstraint(Relation rel, char *constrName,
288                                                  bool recurse, bool recursing, LOCKMODE lockmode);
289 static int transformColumnNameList(Oid relId, List *colList,
290                                                 int16 *attnums, Oid *atttypids);
291 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
292                                                    List **attnamelist,
293                                                    int16 *attnums, Oid *atttypids,
294                                                    Oid *opclasses);
295 static Oid transformFkeyCheckAttrs(Relation pkrel,
296                                                 int numattrs, int16 *attnums,
297                                                 Oid *opclasses);
298 static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
299 static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
300                          Oid *funcid);
301 static void validateCheckConstraint(Relation rel, HeapTuple constrtup);
302 static void validateForeignKeyConstraint(char *conname,
303                                                          Relation rel, Relation pkrel,
304                                                          Oid pkindOid, Oid constraintOid);
305 static void createForeignKeyTriggers(Relation rel, Oid refRelOid,
306                                                  Constraint *fkconstraint,
307                                                  Oid constraintOid, Oid indexOid);
308 static void ATController(AlterTableStmt *parsetree,
309                                                  Relation rel, List *cmds, bool recurse, LOCKMODE lockmode);
310 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
311                   bool recurse, bool recursing, LOCKMODE lockmode);
312 static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode);
313 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
314                   AlterTableCmd *cmd, LOCKMODE lockmode);
315 static void ATRewriteTables(AlterTableStmt *parsetree,
316                                                         List **wqueue, LOCKMODE lockmode);
317 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode);
318 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
319 static void ATSimplePermissions(Relation rel, int allowed_targets);
320 static void ATWrongRelkindError(Relation rel, int allowed_targets);
321 static void ATSimpleRecursion(List **wqueue, Relation rel,
322                                   AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode);
323 static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
324                                           LOCKMODE lockmode);
325 static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
326                                                           DropBehavior behavior);
327 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
328                                 bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode);
329 static void ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
330                                 ColumnDef *colDef, bool isOid,
331                                 bool recurse, bool recursing, LOCKMODE lockmode);
332 static void check_for_column_name_collision(Relation rel, const char *colname);
333 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
334 static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
335 static void ATPrepAddOids(List **wqueue, Relation rel, bool recurse,
336                           AlterTableCmd *cmd, LOCKMODE lockmode);
337 static void ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode);
338 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
339                                  const char *colName, LOCKMODE lockmode);
340 static void ATExecColumnDefault(Relation rel, const char *colName,
341                                         Node *newDefault, LOCKMODE lockmode);
342 static void ATPrepSetStatistics(Relation rel, const char *colName,
343                                         Node *newValue, LOCKMODE lockmode);
344 static void ATExecSetStatistics(Relation rel, const char *colName,
345                                         Node *newValue, LOCKMODE lockmode);
346 static void ATExecSetOptions(Relation rel, const char *colName,
347                                  Node *options, bool isReset, LOCKMODE lockmode);
348 static void ATExecSetStorage(Relation rel, const char *colName,
349                                  Node *newValue, LOCKMODE lockmode);
350 static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
351                                  AlterTableCmd *cmd, LOCKMODE lockmode);
352 static void ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
353                                  DropBehavior behavior,
354                                  bool recurse, bool recursing,
355                                  bool missing_ok, LOCKMODE lockmode);
356 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
357                            IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
358 static void ATExecAddConstraint(List **wqueue,
359                                         AlteredTableInfo *tab, Relation rel,
360                                         Constraint *newConstraint, bool recurse, bool is_readd,
361                                         LOCKMODE lockmode);
362 static void ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
363                                                  IndexStmt *stmt, LOCKMODE lockmode);
364 static void ATAddCheckConstraint(List **wqueue,
365                                          AlteredTableInfo *tab, Relation rel,
366                                          Constraint *constr,
367                                          bool recurse, bool recursing, bool is_readd,
368                                          LOCKMODE lockmode);
369 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
370                                                   Constraint *fkconstraint, LOCKMODE lockmode);
371 static void ATExecDropConstraint(Relation rel, const char *constrName,
372                                          DropBehavior behavior,
373                                          bool recurse, bool recursing,
374                                          bool missing_ok, LOCKMODE lockmode);
375 static void ATPrepAlterColumnType(List **wqueue,
376                                           AlteredTableInfo *tab, Relation rel,
377                                           bool recurse, bool recursing,
378                                           AlterTableCmd *cmd, LOCKMODE lockmode);
379 static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
380 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
381                                           AlterTableCmd *cmd, LOCKMODE lockmode);
382 static void ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
383                                                                 List *options, LOCKMODE lockmode);
384 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
385                                            LOCKMODE lockmode);
386 static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId,
387                                          char *cmd, List **wqueue, LOCKMODE lockmode,
388                                          bool rewrite);
389 static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
390 static void TryReuseForeignKey(Oid oldId, Constraint *con);
391 static void change_owner_fix_column_acls(Oid relationOid,
392                                                          Oid oldOwnerId, Oid newOwnerId);
393 static void change_owner_recurse_to_sequences(Oid relationOid,
394                                                                   Oid newOwnerId, LOCKMODE lockmode);
395 static void ATExecClusterOn(Relation rel, const char *indexName,
396                                 LOCKMODE lockmode);
397 static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
398 static bool ATPrepChangePersistence(Relation rel, bool toLogged);
399 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
400                                         char *tablespacename, LOCKMODE lockmode);
401 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
402 static void ATExecSetRelOptions(Relation rel, List *defList,
403                                         AlterTableType operation,
404                                         LOCKMODE lockmode);
405 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
406                                            char fires_when, bool skip_system, LOCKMODE lockmode);
407 static void ATExecEnableDisableRule(Relation rel, char *rulename,
408                                                 char fires_when, LOCKMODE lockmode);
409 static void ATPrepAddInherit(Relation child_rel);
410 static void ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
411 static void ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
412 static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid);
413 static void ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
414 static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
415 static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
416 static void ATExecGenericOptions(Relation rel, List *options);
417 static void ATExecEnableRowSecurity(Relation rel);
418 static void ATExecDisableRowSecurity(Relation rel);
419
420 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
421                                    ForkNumber forkNum, char relpersistence);
422 static const char *storage_name(char c);
423
424 static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
425                                                                 Oid oldRelOid, void *arg);
426 static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
427                                                                  Oid oldrelid, void *arg);
428
429
430 /* ----------------------------------------------------------------
431  *              DefineRelation
432  *                              Creates a new relation.
433  *
434  * stmt carries parsetree information from an ordinary CREATE TABLE statement.
435  * The other arguments are used to extend the behavior for other cases:
436  * relkind: relkind to assign to the new relation
437  * ownerId: if not InvalidOid, use this as the new relation's owner.
438  * typaddress: if not null, it's set to the pg_type entry's address.
439  *
440  * Note that permissions checks are done against current user regardless of
441  * ownerId.  A nonzero ownerId is used when someone is creating a relation
442  * "on behalf of" someone else, so we still want to see that the current user
443  * has permissions to do it.
444  *
445  * If successful, returns the address of the new relation.
446  * ----------------------------------------------------------------
447  */
448 ObjectAddress
449 DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
450                            ObjectAddress *typaddress)
451 {
452         char            relname[NAMEDATALEN];
453         Oid                     namespaceId;
454         List       *schema = stmt->tableElts;
455         Oid                     relationId;
456         Oid                     tablespaceId;
457         Relation        rel;
458         TupleDesc       descriptor;
459         List       *inheritOids;
460         List       *old_constraints;
461         bool            localHasOids;
462         int                     parentOidCount;
463         List       *rawDefaults;
464         List       *cookedDefaults;
465         Datum           reloptions;
466         ListCell   *listptr;
467         AttrNumber      attnum;
468         static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
469         Oid                     ofTypeId;
470         ObjectAddress address;
471
472         /*
473          * Truncate relname to appropriate length (probably a waste of time, as
474          * parser should have done this already).
475          */
476         StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
477
478         /*
479          * Check consistency of arguments
480          */
481         if (stmt->oncommit != ONCOMMIT_NOOP
482                 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
483                 ereport(ERROR,
484                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
485                                  errmsg("ON COMMIT can only be used on temporary tables")));
486
487         /*
488          * Look up the namespace in which we are supposed to create the relation,
489          * check we have permission to create there, lock it against concurrent
490          * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
491          * namespace is selected.
492          */
493         namespaceId =
494                 RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
495
496         /*
497          * Security check: disallow creating temp tables from security-restricted
498          * code.  This is needed because calling code might not expect untrusted
499          * tables to appear in pg_temp at the front of its search path.
500          */
501         if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
502                 && InSecurityRestrictedOperation())
503                 ereport(ERROR,
504                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
505                                  errmsg("cannot create temporary table within security-restricted operation")));
506
507         /*
508          * Select tablespace to use.  If not specified, use default tablespace
509          * (which may in turn default to database's default).
510          */
511         if (stmt->tablespacename)
512         {
513                 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
514         }
515         else
516         {
517                 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence);
518                 /* note InvalidOid is OK in this case */
519         }
520
521         /* Check permissions except when using database's default */
522         if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
523         {
524                 AclResult       aclresult;
525
526                 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
527                                                                                    ACL_CREATE);
528                 if (aclresult != ACLCHECK_OK)
529                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
530                                                    get_tablespace_name(tablespaceId));
531         }
532
533         /* In all cases disallow placing user relations in pg_global */
534         if (tablespaceId == GLOBALTABLESPACE_OID)
535                 ereport(ERROR,
536                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
537                                  errmsg("only shared relations can be placed in pg_global tablespace")));
538
539         /* Identify user ID that will own the table */
540         if (!OidIsValid(ownerId))
541                 ownerId = GetUserId();
542
543         /*
544          * Parse and validate reloptions, if any.
545          */
546         reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
547                                                                          true, false);
548
549         if (relkind == RELKIND_VIEW)
550                 (void) view_reloptions(reloptions, true);
551         else
552                 (void) heap_reloptions(relkind, reloptions, true);
553
554         if (stmt->ofTypename)
555         {
556                 AclResult       aclresult;
557
558                 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
559
560                 aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
561                 if (aclresult != ACLCHECK_OK)
562                         aclcheck_error_type(aclresult, ofTypeId);
563         }
564         else
565                 ofTypeId = InvalidOid;
566
567         /*
568          * Look up inheritance ancestors and generate relation schema, including
569          * inherited attributes.
570          */
571         schema = MergeAttributes(schema, stmt->inhRelations,
572                                                          stmt->relation->relpersistence,
573                                                          &inheritOids, &old_constraints, &parentOidCount);
574
575         /*
576          * Create a tuple descriptor from the relation schema.  Note that this
577          * deals with column names, types, and NOT NULL constraints, but not
578          * default values or CHECK constraints; we handle those below.
579          */
580         descriptor = BuildDescForRelation(schema);
581
582         localHasOids = interpretOidsOption(stmt->options,
583                                                                            (relkind == RELKIND_RELATION));
584         descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
585
586         /*
587          * Find columns with default values and prepare for insertion of the
588          * defaults.  Pre-cooked (that is, inherited) defaults go into a list of
589          * CookedConstraint structs that we'll pass to heap_create_with_catalog,
590          * while raw defaults go into a list of RawColumnDefault structs that will
591          * be processed by AddRelationNewConstraints.  (We can't deal with raw
592          * expressions until we can do transformExpr.)
593          *
594          * We can set the atthasdef flags now in the tuple descriptor; this just
595          * saves StoreAttrDefault from having to do an immediate update of the
596          * pg_attribute rows.
597          */
598         rawDefaults = NIL;
599         cookedDefaults = NIL;
600         attnum = 0;
601
602         foreach(listptr, schema)
603         {
604                 ColumnDef  *colDef = lfirst(listptr);
605
606                 attnum++;
607
608                 if (colDef->raw_default != NULL)
609                 {
610                         RawColumnDefault *rawEnt;
611
612                         Assert(colDef->cooked_default == NULL);
613
614                         rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
615                         rawEnt->attnum = attnum;
616                         rawEnt->raw_default = colDef->raw_default;
617                         rawDefaults = lappend(rawDefaults, rawEnt);
618                         descriptor->attrs[attnum - 1]->atthasdef = true;
619                 }
620                 else if (colDef->cooked_default != NULL)
621                 {
622                         CookedConstraint *cooked;
623
624                         cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
625                         cooked->contype = CONSTR_DEFAULT;
626                         cooked->name = NULL;
627                         cooked->attnum = attnum;
628                         cooked->expr = colDef->cooked_default;
629                         cooked->skip_validation = false;
630                         cooked->is_local = true;        /* not used for defaults */
631                         cooked->inhcount = 0;           /* ditto */
632                         cooked->is_no_inherit = false;
633                         cookedDefaults = lappend(cookedDefaults, cooked);
634                         descriptor->attrs[attnum - 1]->atthasdef = true;
635                 }
636         }
637
638         /*
639          * Create the relation.  Inherited defaults and constraints are passed in
640          * for immediate handling --- since they don't need parsing, they can be
641          * stored immediately.
642          */
643         relationId = heap_create_with_catalog(relname,
644                                                                                   namespaceId,
645                                                                                   tablespaceId,
646                                                                                   InvalidOid,
647                                                                                   InvalidOid,
648                                                                                   ofTypeId,
649                                                                                   ownerId,
650                                                                                   descriptor,
651                                                                                   list_concat(cookedDefaults,
652                                                                                                           old_constraints),
653                                                                                   relkind,
654                                                                                   stmt->relation->relpersistence,
655                                                                                   false,
656                                                                                   false,
657                                                                                   localHasOids,
658                                                                                   parentOidCount,
659                                                                                   stmt->oncommit,
660                                                                                   reloptions,
661                                                                                   true,
662                                                                                   allowSystemTableMods,
663                                                                                   false,
664                                                                                   typaddress);
665
666         /* Store inheritance information for new rel. */
667         StoreCatalogInheritance(relationId, inheritOids);
668
669         /*
670          * We must bump the command counter to make the newly-created relation
671          * tuple visible for opening.
672          */
673         CommandCounterIncrement();
674
675         /*
676          * Open the new relation and acquire exclusive lock on it.  This isn't
677          * really necessary for locking out other backends (since they can't see
678          * the new rel anyway until we commit), but it keeps the lock manager from
679          * complaining about deadlock risks.
680          */
681         rel = relation_open(relationId, AccessExclusiveLock);
682
683         /*
684          * Now add any newly specified column default values and CHECK constraints
685          * to the new relation.  These are passed to us in the form of raw
686          * parsetrees; we need to transform them to executable expression trees
687          * before they can be added. The most convenient way to do that is to
688          * apply the parser's transformExpr routine, but transformExpr doesn't
689          * work unless we have a pre-existing relation. So, the transformation has
690          * to be postponed to this final step of CREATE TABLE.
691          */
692         if (rawDefaults || stmt->constraints)
693                 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
694                                                                   true, true, false);
695
696         ObjectAddressSet(address, RelationRelationId, relationId);
697
698         /*
699          * Clean up.  We keep lock on new relation (although it shouldn't be
700          * visible to anyone else anyway, until commit).
701          */
702         relation_close(rel, NoLock);
703
704         return address;
705 }
706
707 /*
708  * Emit the right error or warning message for a "DROP" command issued on a
709  * non-existent relation
710  */
711 static void
712 DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
713 {
714         const struct dropmsgstrings *rentry;
715
716         if (rel->schemaname != NULL &&
717                 !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
718         {
719                 if (!missing_ok)
720                 {
721                         ereport(ERROR,
722                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
723                                    errmsg("schema \"%s\" does not exist", rel->schemaname)));
724                 }
725                 else
726                 {
727                         ereport(NOTICE,
728                                         (errmsg("schema \"%s\" does not exist, skipping",
729                                                         rel->schemaname)));
730                 }
731                 return;
732         }
733
734         for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
735         {
736                 if (rentry->kind == rightkind)
737                 {
738                         if (!missing_ok)
739                         {
740                                 ereport(ERROR,
741                                                 (errcode(rentry->nonexistent_code),
742                                                  errmsg(rentry->nonexistent_msg, rel->relname)));
743                         }
744                         else
745                         {
746                                 ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
747                                 break;
748                         }
749                 }
750         }
751
752         Assert(rentry->kind != '\0');           /* Should be impossible */
753 }
754
755 /*
756  * Emit the right error message for a "DROP" command issued on a
757  * relation of the wrong type
758  */
759 static void
760 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
761 {
762         const struct dropmsgstrings *rentry;
763         const struct dropmsgstrings *wentry;
764
765         for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
766                 if (rentry->kind == rightkind)
767                         break;
768         Assert(rentry->kind != '\0');
769
770         for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
771                 if (wentry->kind == wrongkind)
772                         break;
773         /* wrongkind could be something we don't have in our table... */
774
775         ereport(ERROR,
776                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
777                          errmsg(rentry->nota_msg, relname),
778            (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
779 }
780
781 /*
782  * RemoveRelations
783  *              Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
784  *              DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
785  */
786 void
787 RemoveRelations(DropStmt *drop)
788 {
789         ObjectAddresses *objects;
790         char            relkind;
791         ListCell   *cell;
792         int                     flags = 0;
793         LOCKMODE        lockmode = AccessExclusiveLock;
794
795         /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
796         if (drop->concurrent)
797         {
798                 flags |= PERFORM_DELETION_CONCURRENTLY;
799                 lockmode = ShareUpdateExclusiveLock;
800                 Assert(drop->removeType == OBJECT_INDEX);
801                 if (list_length(drop->objects) != 1)
802                         ereport(ERROR,
803                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
804                                          errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
805                 if (drop->behavior == DROP_CASCADE)
806                         ereport(ERROR,
807                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
808                                 errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
809         }
810
811         /*
812          * First we identify all the relations, then we delete them in a single
813          * performMultipleDeletions() call.  This is to avoid unwanted DROP
814          * RESTRICT errors if one of the relations depends on another.
815          */
816
817         /* Determine required relkind */
818         switch (drop->removeType)
819         {
820                 case OBJECT_TABLE:
821                         relkind = RELKIND_RELATION;
822                         break;
823
824                 case OBJECT_INDEX:
825                         relkind = RELKIND_INDEX;
826                         break;
827
828                 case OBJECT_SEQUENCE:
829                         relkind = RELKIND_SEQUENCE;
830                         break;
831
832                 case OBJECT_VIEW:
833                         relkind = RELKIND_VIEW;
834                         break;
835
836                 case OBJECT_MATVIEW:
837                         relkind = RELKIND_MATVIEW;
838                         break;
839
840                 case OBJECT_FOREIGN_TABLE:
841                         relkind = RELKIND_FOREIGN_TABLE;
842                         break;
843
844                 default:
845                         elog(ERROR, "unrecognized drop object type: %d",
846                                  (int) drop->removeType);
847                         relkind = 0;            /* keep compiler quiet */
848                         break;
849         }
850
851         /* Lock and validate each relation; build a list of object addresses */
852         objects = new_object_addresses();
853
854         foreach(cell, drop->objects)
855         {
856                 RangeVar   *rel = makeRangeVarFromNameList((List *) lfirst(cell));
857                 Oid                     relOid;
858                 ObjectAddress obj;
859                 struct DropRelationCallbackState state;
860
861                 /*
862                  * These next few steps are a great deal like relation_openrv, but we
863                  * don't bother building a relcache entry since we don't need it.
864                  *
865                  * Check for shared-cache-inval messages before trying to access the
866                  * relation.  This is needed to cover the case where the name
867                  * identifies a rel that has been dropped and recreated since the
868                  * start of our transaction: if we don't flush the old syscache entry,
869                  * then we'll latch onto that entry and suffer an error later.
870                  */
871                 AcceptInvalidationMessages();
872
873                 /* Look up the appropriate relation using namespace search. */
874                 state.relkind = relkind;
875                 state.heapOid = InvalidOid;
876                 state.concurrent = drop->concurrent;
877                 relOid = RangeVarGetRelidExtended(rel, lockmode, true,
878                                                                                   false,
879                                                                                   RangeVarCallbackForDropRelation,
880                                                                                   (void *) &state);
881
882                 /* Not there? */
883                 if (!OidIsValid(relOid))
884                 {
885                         DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
886                         continue;
887                 }
888
889                 /* OK, we're ready to delete this one */
890                 obj.classId = RelationRelationId;
891                 obj.objectId = relOid;
892                 obj.objectSubId = 0;
893
894                 add_exact_object_address(&obj, objects);
895         }
896
897         performMultipleDeletions(objects, drop->behavior, flags);
898
899         free_object_addresses(objects);
900 }
901
902 /*
903  * Before acquiring a table lock, check whether we have sufficient rights.
904  * In the case of DROP INDEX, also try to lock the table before the index.
905  */
906 static void
907 RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
908                                                                 void *arg)
909 {
910         HeapTuple       tuple;
911         struct DropRelationCallbackState *state;
912         char            relkind;
913         Form_pg_class classform;
914         LOCKMODE        heap_lockmode;
915
916         state = (struct DropRelationCallbackState *) arg;
917         relkind = state->relkind;
918         heap_lockmode = state->concurrent ?
919                 ShareUpdateExclusiveLock : AccessExclusiveLock;
920
921         /*
922          * If we previously locked some other index's heap, and the name we're
923          * looking up no longer refers to that relation, release the now-useless
924          * lock.
925          */
926         if (relOid != oldRelOid && OidIsValid(state->heapOid))
927         {
928                 UnlockRelationOid(state->heapOid, heap_lockmode);
929                 state->heapOid = InvalidOid;
930         }
931
932         /* Didn't find a relation, so no need for locking or permission checks. */
933         if (!OidIsValid(relOid))
934                 return;
935
936         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
937         if (!HeapTupleIsValid(tuple))
938                 return;                                 /* concurrently dropped, so nothing to do */
939         classform = (Form_pg_class) GETSTRUCT(tuple);
940
941         if (classform->relkind != relkind)
942                 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
943
944         /* Allow DROP to either table owner or schema owner */
945         if (!pg_class_ownercheck(relOid, GetUserId()) &&
946                 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
947                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
948                                            rel->relname);
949
950         if (!allowSystemTableMods && IsSystemClass(relOid, classform))
951                 ereport(ERROR,
952                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
953                                  errmsg("permission denied: \"%s\" is a system catalog",
954                                                 rel->relname)));
955
956         ReleaseSysCache(tuple);
957
958         /*
959          * In DROP INDEX, attempt to acquire lock on the parent table before
960          * locking the index.  index_drop() will need this anyway, and since
961          * regular queries lock tables before their indexes, we risk deadlock if
962          * we do it the other way around.  No error if we don't find a pg_index
963          * entry, though --- the relation may have been dropped.
964          */
965         if (relkind == RELKIND_INDEX && relOid != oldRelOid)
966         {
967                 state->heapOid = IndexGetRelation(relOid, true);
968                 if (OidIsValid(state->heapOid))
969                         LockRelationOid(state->heapOid, heap_lockmode);
970         }
971 }
972
973 /*
974  * ExecuteTruncate
975  *              Executes a TRUNCATE command.
976  *
977  * This is a multi-relation truncate.  We first open and grab exclusive
978  * lock on all relations involved, checking permissions and otherwise
979  * verifying that the relation is OK for truncation.  In CASCADE mode,
980  * relations having FK references to the targeted relations are automatically
981  * added to the group; in RESTRICT mode, we check that all FK references are
982  * internal to the group that's being truncated.  Finally all the relations
983  * are truncated and reindexed.
984  */
985 void
986 ExecuteTruncate(TruncateStmt *stmt)
987 {
988         List       *rels = NIL;
989         List       *relids = NIL;
990         List       *seq_relids = NIL;
991         EState     *estate;
992         ResultRelInfo *resultRelInfos;
993         ResultRelInfo *resultRelInfo;
994         SubTransactionId mySubid;
995         ListCell   *cell;
996
997         /*
998          * Open, exclusive-lock, and check all the explicitly-specified relations
999          */
1000         foreach(cell, stmt->relations)
1001         {
1002                 RangeVar   *rv = lfirst(cell);
1003                 Relation        rel;
1004                 bool            recurse = interpretInhOption(rv->inhOpt);
1005                 Oid                     myrelid;
1006
1007                 rel = heap_openrv(rv, AccessExclusiveLock);
1008                 myrelid = RelationGetRelid(rel);
1009                 /* don't throw error for "TRUNCATE foo, foo" */
1010                 if (list_member_oid(relids, myrelid))
1011                 {
1012                         heap_close(rel, AccessExclusiveLock);
1013                         continue;
1014                 }
1015                 truncate_check_rel(rel);
1016                 rels = lappend(rels, rel);
1017                 relids = lappend_oid(relids, myrelid);
1018
1019                 if (recurse)
1020                 {
1021                         ListCell   *child;
1022                         List       *children;
1023
1024                         children = find_all_inheritors(myrelid, AccessExclusiveLock, NULL);
1025
1026                         foreach(child, children)
1027                         {
1028                                 Oid                     childrelid = lfirst_oid(child);
1029
1030                                 if (list_member_oid(relids, childrelid))
1031                                         continue;
1032
1033                                 /* find_all_inheritors already got lock */
1034                                 rel = heap_open(childrelid, NoLock);
1035                                 truncate_check_rel(rel);
1036                                 rels = lappend(rels, rel);
1037                                 relids = lappend_oid(relids, childrelid);
1038                         }
1039                 }
1040         }
1041
1042         /*
1043          * In CASCADE mode, suck in all referencing relations as well.  This
1044          * requires multiple iterations to find indirectly-dependent relations. At
1045          * each phase, we need to exclusive-lock new rels before looking for their
1046          * dependencies, else we might miss something.  Also, we check each rel as
1047          * soon as we open it, to avoid a faux pas such as holding lock for a long
1048          * time on a rel we have no permissions for.
1049          */
1050         if (stmt->behavior == DROP_CASCADE)
1051         {
1052                 for (;;)
1053                 {
1054                         List       *newrelids;
1055
1056                         newrelids = heap_truncate_find_FKs(relids);
1057                         if (newrelids == NIL)
1058                                 break;                  /* nothing else to add */
1059
1060                         foreach(cell, newrelids)
1061                         {
1062                                 Oid                     relid = lfirst_oid(cell);
1063                                 Relation        rel;
1064
1065                                 rel = heap_open(relid, AccessExclusiveLock);
1066                                 ereport(NOTICE,
1067                                                 (errmsg("truncate cascades to table \"%s\"",
1068                                                                 RelationGetRelationName(rel))));
1069                                 truncate_check_rel(rel);
1070                                 rels = lappend(rels, rel);
1071                                 relids = lappend_oid(relids, relid);
1072                         }
1073                 }
1074         }
1075
1076         /*
1077          * Check foreign key references.  In CASCADE mode, this should be
1078          * unnecessary since we just pulled in all the references; but as a
1079          * cross-check, do it anyway if in an Assert-enabled build.
1080          */
1081 #ifdef USE_ASSERT_CHECKING
1082         heap_truncate_check_FKs(rels, false);
1083 #else
1084         if (stmt->behavior == DROP_RESTRICT)
1085                 heap_truncate_check_FKs(rels, false);
1086 #endif
1087
1088         /*
1089          * If we are asked to restart sequences, find all the sequences, lock them
1090          * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1091          * We want to do this early since it's pointless to do all the truncation
1092          * work only to fail on sequence permissions.
1093          */
1094         if (stmt->restart_seqs)
1095         {
1096                 foreach(cell, rels)
1097                 {
1098                         Relation        rel = (Relation) lfirst(cell);
1099                         List       *seqlist = getOwnedSequences(RelationGetRelid(rel));
1100                         ListCell   *seqcell;
1101
1102                         foreach(seqcell, seqlist)
1103                         {
1104                                 Oid                     seq_relid = lfirst_oid(seqcell);
1105                                 Relation        seq_rel;
1106
1107                                 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
1108
1109                                 /* This check must match AlterSequence! */
1110                                 if (!pg_class_ownercheck(seq_relid, GetUserId()))
1111                                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1112                                                                    RelationGetRelationName(seq_rel));
1113
1114                                 seq_relids = lappend_oid(seq_relids, seq_relid);
1115
1116                                 relation_close(seq_rel, NoLock);
1117                         }
1118                 }
1119         }
1120
1121         /* Prepare to catch AFTER triggers. */
1122         AfterTriggerBeginQuery();
1123
1124         /*
1125          * To fire triggers, we'll need an EState as well as a ResultRelInfo for
1126          * each relation.  We don't need to call ExecOpenIndices, though.
1127          */
1128         estate = CreateExecutorState();
1129         resultRelInfos = (ResultRelInfo *)
1130                 palloc(list_length(rels) * sizeof(ResultRelInfo));
1131         resultRelInfo = resultRelInfos;
1132         foreach(cell, rels)
1133         {
1134                 Relation        rel = (Relation) lfirst(cell);
1135
1136                 InitResultRelInfo(resultRelInfo,
1137                                                   rel,
1138                                                   0,    /* dummy rangetable index */
1139                                                   0);
1140                 resultRelInfo++;
1141         }
1142         estate->es_result_relations = resultRelInfos;
1143         estate->es_num_result_relations = list_length(rels);
1144
1145         /*
1146          * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1147          * truncating (this is because one of them might throw an error). Also, if
1148          * we were to allow them to prevent statement execution, that would need
1149          * to be handled here.
1150          */
1151         resultRelInfo = resultRelInfos;
1152         foreach(cell, rels)
1153         {
1154                 estate->es_result_relation_info = resultRelInfo;
1155                 ExecBSTruncateTriggers(estate, resultRelInfo);
1156                 resultRelInfo++;
1157         }
1158
1159         /*
1160          * OK, truncate each table.
1161          */
1162         mySubid = GetCurrentSubTransactionId();
1163
1164         foreach(cell, rels)
1165         {
1166                 Relation        rel = (Relation) lfirst(cell);
1167
1168                 /*
1169                  * Normally, we need a transaction-safe truncation here.  However, if
1170                  * the table was either created in the current (sub)transaction or has
1171                  * a new relfilenode in the current (sub)transaction, then we can just
1172                  * truncate it in-place, because a rollback would cause the whole
1173                  * table or the current physical file to be thrown away anyway.
1174                  */
1175                 if (rel->rd_createSubid == mySubid ||
1176                         rel->rd_newRelfilenodeSubid == mySubid)
1177                 {
1178                         /* Immediate, non-rollbackable truncation is OK */
1179                         heap_truncate_one_rel(rel);
1180                 }
1181                 else
1182                 {
1183                         Oid                     heap_relid;
1184                         Oid                     toast_relid;
1185                         MultiXactId minmulti;
1186
1187                         /*
1188                          * This effectively deletes all rows in the table, and may be done
1189                          * in a serializable transaction.  In that case we must record a
1190                          * rw-conflict in to this transaction from each transaction
1191                          * holding a predicate lock on the table.
1192                          */
1193                         CheckTableForSerializableConflictIn(rel);
1194
1195                         minmulti = GetOldestMultiXactId();
1196
1197                         /*
1198                          * Need the full transaction-safe pushups.
1199                          *
1200                          * Create a new empty storage file for the relation, and assign it
1201                          * as the relfilenode value. The old storage file is scheduled for
1202                          * deletion at commit.
1203                          */
1204                         RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1205                                                                           RecentXmin, minmulti);
1206                         if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1207                                 heap_create_init_fork(rel);
1208
1209                         heap_relid = RelationGetRelid(rel);
1210                         toast_relid = rel->rd_rel->reltoastrelid;
1211
1212                         /*
1213                          * The same for the toast table, if any.
1214                          */
1215                         if (OidIsValid(toast_relid))
1216                         {
1217                                 rel = relation_open(toast_relid, AccessExclusiveLock);
1218                                 RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1219                                                                                   RecentXmin, minmulti);
1220                                 if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1221                                         heap_create_init_fork(rel);
1222                                 heap_close(rel, NoLock);
1223                         }
1224
1225                         /*
1226                          * Reconstruct the indexes to match, and we're done.
1227                          */
1228                         reindex_relation(heap_relid, REINDEX_REL_PROCESS_TOAST);
1229                 }
1230
1231                 pgstat_count_truncate(rel);
1232         }
1233
1234         /*
1235          * Restart owned sequences if we were asked to.
1236          */
1237         foreach(cell, seq_relids)
1238         {
1239                 Oid                     seq_relid = lfirst_oid(cell);
1240
1241                 ResetSequence(seq_relid);
1242         }
1243
1244         /*
1245          * Process all AFTER STATEMENT TRUNCATE triggers.
1246          */
1247         resultRelInfo = resultRelInfos;
1248         foreach(cell, rels)
1249         {
1250                 estate->es_result_relation_info = resultRelInfo;
1251                 ExecASTruncateTriggers(estate, resultRelInfo);
1252                 resultRelInfo++;
1253         }
1254
1255         /* Handle queued AFTER triggers */
1256         AfterTriggerEndQuery(estate);
1257
1258         /* We can clean up the EState now */
1259         FreeExecutorState(estate);
1260
1261         /* And close the rels (can't do this while EState still holds refs) */
1262         foreach(cell, rels)
1263         {
1264                 Relation        rel = (Relation) lfirst(cell);
1265
1266                 heap_close(rel, NoLock);
1267         }
1268 }
1269
1270 /*
1271  * Check that a given rel is safe to truncate.  Subroutine for ExecuteTruncate
1272  */
1273 static void
1274 truncate_check_rel(Relation rel)
1275 {
1276         AclResult       aclresult;
1277
1278         /* Only allow truncate on regular tables */
1279         if (rel->rd_rel->relkind != RELKIND_RELATION)
1280                 ereport(ERROR,
1281                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1282                                  errmsg("\"%s\" is not a table",
1283                                                 RelationGetRelationName(rel))));
1284
1285         /* Permissions checks */
1286         aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1287                                                                   ACL_TRUNCATE);
1288         if (aclresult != ACLCHECK_OK)
1289                 aclcheck_error(aclresult, ACL_KIND_CLASS,
1290                                            RelationGetRelationName(rel));
1291
1292         if (!allowSystemTableMods && IsSystemRelation(rel))
1293                 ereport(ERROR,
1294                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1295                                  errmsg("permission denied: \"%s\" is a system catalog",
1296                                                 RelationGetRelationName(rel))));
1297
1298         /*
1299          * Don't allow truncate on temp tables of other backends ... their local
1300          * buffer manager is not going to cope.
1301          */
1302         if (RELATION_IS_OTHER_TEMP(rel))
1303                 ereport(ERROR,
1304                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1305                           errmsg("cannot truncate temporary tables of other sessions")));
1306
1307         /*
1308          * Also check for active uses of the relation in the current transaction,
1309          * including open scans and pending AFTER trigger events.
1310          */
1311         CheckTableNotInUse(rel, "TRUNCATE");
1312 }
1313
1314 /*
1315  * storage_name
1316  *        returns the name corresponding to a typstorage/attstorage enum value
1317  */
1318 static const char *
1319 storage_name(char c)
1320 {
1321         switch (c)
1322         {
1323                 case 'p':
1324                         return "PLAIN";
1325                 case 'm':
1326                         return "MAIN";
1327                 case 'x':
1328                         return "EXTENDED";
1329                 case 'e':
1330                         return "EXTERNAL";
1331                 default:
1332                         return "???";
1333         }
1334 }
1335
1336 /*----------
1337  * MergeAttributes
1338  *              Returns new schema given initial schema and superclasses.
1339  *
1340  * Input arguments:
1341  * 'schema' is the column/attribute definition for the table. (It's a list
1342  *              of ColumnDef's.) It is destructively changed.
1343  * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1344  * 'relpersistence' is a persistence type of the table.
1345  *
1346  * Output arguments:
1347  * 'supOids' receives a list of the OIDs of the parent relations.
1348  * 'supconstr' receives a list of constraints belonging to the parents,
1349  *              updated as necessary to be valid for the child.
1350  * 'supOidCount' is set to the number of parents that have OID columns.
1351  *
1352  * Return value:
1353  * Completed schema list.
1354  *
1355  * Notes:
1356  *        The order in which the attributes are inherited is very important.
1357  *        Intuitively, the inherited attributes should come first. If a table
1358  *        inherits from multiple parents, the order of those attributes are
1359  *        according to the order of the parents specified in CREATE TABLE.
1360  *
1361  *        Here's an example:
1362  *
1363  *              create table person (name text, age int4, location point);
1364  *              create table emp (salary int4, manager text) inherits(person);
1365  *              create table student (gpa float8) inherits (person);
1366  *              create table stud_emp (percent int4) inherits (emp, student);
1367  *
1368  *        The order of the attributes of stud_emp is:
1369  *
1370  *                                                      person {1:name, 2:age, 3:location}
1371  *                                                      /        \
1372  *                         {6:gpa}      student   emp {4:salary, 5:manager}
1373  *                                                      \        /
1374  *                                                 stud_emp {7:percent}
1375  *
1376  *         If the same attribute name appears multiple times, then it appears
1377  *         in the result table in the proper location for its first appearance.
1378  *
1379  *         Constraints (including NOT NULL constraints) for the child table
1380  *         are the union of all relevant constraints, from both the child schema
1381  *         and parent tables.
1382  *
1383  *         The default value for a child column is defined as:
1384  *              (1) If the child schema specifies a default, that value is used.
1385  *              (2) If neither the child nor any parent specifies a default, then
1386  *                      the column will not have a default.
1387  *              (3) If conflicting defaults are inherited from different parents
1388  *                      (and not overridden by the child), an error is raised.
1389  *              (4) Otherwise the inherited default is used.
1390  *              Rule (3) is new in Postgres 7.1; in earlier releases you got a
1391  *              rather arbitrary choice of which parent default to use.
1392  *----------
1393  */
1394 static List *
1395 MergeAttributes(List *schema, List *supers, char relpersistence,
1396                                 List **supOids, List **supconstr, int *supOidCount)
1397 {
1398         ListCell   *entry;
1399         List       *inhSchema = NIL;
1400         List       *parentOids = NIL;
1401         List       *constraints = NIL;
1402         int                     parentsWithOids = 0;
1403         bool            have_bogus_defaults = false;
1404         int                     child_attno;
1405         static Node bogus_marker = {0};         /* marks conflicting defaults */
1406
1407         /*
1408          * Check for and reject tables with too many columns. We perform this
1409          * check relatively early for two reasons: (a) we don't run the risk of
1410          * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1411          * okay if we're processing <= 1600 columns, but could take minutes to
1412          * execute if the user attempts to create a table with hundreds of
1413          * thousands of columns.
1414          *
1415          * Note that we also need to check that any we do not exceed this figure
1416          * after including columns from inherited relations.
1417          */
1418         if (list_length(schema) > MaxHeapAttributeNumber)
1419                 ereport(ERROR,
1420                                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1421                                  errmsg("tables can have at most %d columns",
1422                                                 MaxHeapAttributeNumber)));
1423
1424         /*
1425          * Check for duplicate names in the explicit list of attributes.
1426          *
1427          * Although we might consider merging such entries in the same way that we
1428          * handle name conflicts for inherited attributes, it seems to make more
1429          * sense to assume such conflicts are errors.
1430          */
1431         foreach(entry, schema)
1432         {
1433                 ColumnDef  *coldef = lfirst(entry);
1434                 ListCell   *rest = lnext(entry);
1435                 ListCell   *prev = entry;
1436
1437                 if (coldef->typeName == NULL)
1438
1439                         /*
1440                          * Typed table column option that does not belong to a column from
1441                          * the type.  This works because the columns from the type come
1442                          * first in the list.
1443                          */
1444                         ereport(ERROR,
1445                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1446                                          errmsg("column \"%s\" does not exist",
1447                                                         coldef->colname)));
1448
1449                 while (rest != NULL)
1450                 {
1451                         ColumnDef  *restdef = lfirst(rest);
1452                         ListCell   *next = lnext(rest);         /* need to save it in case we
1453                                                                                                  * delete it */
1454
1455                         if (strcmp(coldef->colname, restdef->colname) == 0)
1456                         {
1457                                 if (coldef->is_from_type)
1458                                 {
1459                                         /*
1460                                          * merge the column options into the column from the type
1461                                          */
1462                                         coldef->is_not_null = restdef->is_not_null;
1463                                         coldef->raw_default = restdef->raw_default;
1464                                         coldef->cooked_default = restdef->cooked_default;
1465                                         coldef->constraints = restdef->constraints;
1466                                         coldef->is_from_type = false;
1467                                         list_delete_cell(schema, rest, prev);
1468                                 }
1469                                 else
1470                                         ereport(ERROR,
1471                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
1472                                                          errmsg("column \"%s\" specified more than once",
1473                                                                         coldef->colname)));
1474                         }
1475                         prev = rest;
1476                         rest = next;
1477                 }
1478         }
1479
1480         /*
1481          * Scan the parents left-to-right, and merge their attributes to form a
1482          * list of inherited attributes (inhSchema).  Also check to see if we need
1483          * to inherit an OID column.
1484          */
1485         child_attno = 0;
1486         foreach(entry, supers)
1487         {
1488                 RangeVar   *parent = (RangeVar *) lfirst(entry);
1489                 Relation        relation;
1490                 TupleDesc       tupleDesc;
1491                 TupleConstr *constr;
1492                 AttrNumber *newattno;
1493                 AttrNumber      parent_attno;
1494
1495                 /*
1496                  * A self-exclusive lock is needed here.  If two backends attempt to
1497                  * add children to the same parent simultaneously, and that parent has
1498                  * no pre-existing children, then both will attempt to update the
1499                  * parent's relhassubclass field, leading to a "tuple concurrently
1500                  * updated" error.  Also, this interlocks against a concurrent ANALYZE
1501                  * on the parent table, which might otherwise be attempting to clear
1502                  * the parent's relhassubclass field, if its previous children were
1503                  * recently dropped.
1504                  */
1505                 relation = heap_openrv(parent, ShareUpdateExclusiveLock);
1506
1507                 if (relation->rd_rel->relkind != RELKIND_RELATION)
1508                         ereport(ERROR,
1509                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1510                                          errmsg("inherited relation \"%s\" is not a table",
1511                                                         parent->relname)));
1512                 /* Permanent rels cannot inherit from temporary ones */
1513                 if (relpersistence != RELPERSISTENCE_TEMP &&
1514                         relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
1515                         ereport(ERROR,
1516                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1517                                          errmsg("cannot inherit from temporary relation \"%s\"",
1518                                                         parent->relname)));
1519
1520                 /* If existing rel is temp, it must belong to this session */
1521                 if (relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
1522                         !relation->rd_islocaltemp)
1523                         ereport(ERROR,
1524                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1525                                          errmsg("cannot inherit from temporary relation of another session")));
1526
1527                 /*
1528                  * We should have an UNDER permission flag for this, but for now,
1529                  * demand that creator of a child table own the parent.
1530                  */
1531                 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1532                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1533                                                    RelationGetRelationName(relation));
1534
1535                 /*
1536                  * Reject duplications in the list of parents.
1537                  */
1538                 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1539                         ereport(ERROR,
1540                                         (errcode(ERRCODE_DUPLICATE_TABLE),
1541                          errmsg("relation \"%s\" would be inherited from more than once",
1542                                         parent->relname)));
1543
1544                 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1545
1546                 if (relation->rd_rel->relhasoids)
1547                         parentsWithOids++;
1548
1549                 tupleDesc = RelationGetDescr(relation);
1550                 constr = tupleDesc->constr;
1551
1552                 /*
1553                  * newattno[] will contain the child-table attribute numbers for the
1554                  * attributes of this parent table.  (They are not the same for
1555                  * parents after the first one, nor if we have dropped columns.)
1556                  */
1557                 newattno = (AttrNumber *)
1558                         palloc0(tupleDesc->natts * sizeof(AttrNumber));
1559
1560                 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1561                          parent_attno++)
1562                 {
1563                         Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1564                         char       *attributeName = NameStr(attribute->attname);
1565                         int                     exist_attno;
1566                         ColumnDef  *def;
1567
1568                         /*
1569                          * Ignore dropped columns in the parent.
1570                          */
1571                         if (attribute->attisdropped)
1572                                 continue;               /* leave newattno entry as zero */
1573
1574                         /*
1575                          * Does it conflict with some previously inherited column?
1576                          */
1577                         exist_attno = findAttrByName(attributeName, inhSchema);
1578                         if (exist_attno > 0)
1579                         {
1580                                 Oid                     defTypeId;
1581                                 int32           deftypmod;
1582                                 Oid                     defCollId;
1583
1584                                 /*
1585                                  * Yes, try to merge the two column definitions. They must
1586                                  * have the same type, typmod, and collation.
1587                                  */
1588                                 ereport(NOTICE,
1589                                                 (errmsg("merging multiple inherited definitions of column \"%s\"",
1590                                                                 attributeName)));
1591                                 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1592                                 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1593                                 if (defTypeId != attribute->atttypid ||
1594                                         deftypmod != attribute->atttypmod)
1595                                         ereport(ERROR,
1596                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1597                                                 errmsg("inherited column \"%s\" has a type conflict",
1598                                                            attributeName),
1599                                                          errdetail("%s versus %s",
1600                                                                            TypeNameToString(def->typeName),
1601                                                                            format_type_be(attribute->atttypid))));
1602                                 defCollId = GetColumnDefCollation(NULL, def, defTypeId);
1603                                 if (defCollId != attribute->attcollation)
1604                                         ereport(ERROR,
1605                                                         (errcode(ERRCODE_COLLATION_MISMATCH),
1606                                         errmsg("inherited column \"%s\" has a collation conflict",
1607                                                    attributeName),
1608                                                          errdetail("\"%s\" versus \"%s\"",
1609                                                                            get_collation_name(defCollId),
1610                                                           get_collation_name(attribute->attcollation))));
1611
1612                                 /* Copy storage parameter */
1613                                 if (def->storage == 0)
1614                                         def->storage = attribute->attstorage;
1615                                 else if (def->storage != attribute->attstorage)
1616                                         ereport(ERROR,
1617                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1618                                                          errmsg("inherited column \"%s\" has a storage parameter conflict",
1619                                                                         attributeName),
1620                                                          errdetail("%s versus %s",
1621                                                                            storage_name(def->storage),
1622                                                                            storage_name(attribute->attstorage))));
1623
1624                                 def->inhcount++;
1625                                 /* Merge of NOT NULL constraints = OR 'em together */
1626                                 def->is_not_null |= attribute->attnotnull;
1627                                 /* Default and other constraints are handled below */
1628                                 newattno[parent_attno - 1] = exist_attno;
1629                         }
1630                         else
1631                         {
1632                                 /*
1633                                  * No, create a new inherited column
1634                                  */
1635                                 def = makeNode(ColumnDef);
1636                                 def->colname = pstrdup(attributeName);
1637                                 def->typeName = makeTypeNameFromOid(attribute->atttypid,
1638                                                                                                         attribute->atttypmod);
1639                                 def->inhcount = 1;
1640                                 def->is_local = false;
1641                                 def->is_not_null = attribute->attnotnull;
1642                                 def->is_from_type = false;
1643                                 def->storage = attribute->attstorage;
1644                                 def->raw_default = NULL;
1645                                 def->cooked_default = NULL;
1646                                 def->collClause = NULL;
1647                                 def->collOid = attribute->attcollation;
1648                                 def->constraints = NIL;
1649                                 def->location = -1;
1650                                 inhSchema = lappend(inhSchema, def);
1651                                 newattno[parent_attno - 1] = ++child_attno;
1652                         }
1653
1654                         /*
1655                          * Copy default if any
1656                          */
1657                         if (attribute->atthasdef)
1658                         {
1659                                 Node       *this_default = NULL;
1660                                 AttrDefault *attrdef;
1661                                 int                     i;
1662
1663                                 /* Find default in constraint structure */
1664                                 Assert(constr != NULL);
1665                                 attrdef = constr->defval;
1666                                 for (i = 0; i < constr->num_defval; i++)
1667                                 {
1668                                         if (attrdef[i].adnum == parent_attno)
1669                                         {
1670                                                 this_default = stringToNode(attrdef[i].adbin);
1671                                                 break;
1672                                         }
1673                                 }
1674                                 Assert(this_default != NULL);
1675
1676                                 /*
1677                                  * If default expr could contain any vars, we'd need to fix
1678                                  * 'em, but it can't; so default is ready to apply to child.
1679                                  *
1680                                  * If we already had a default from some prior parent, check
1681                                  * to see if they are the same.  If so, no problem; if not,
1682                                  * mark the column as having a bogus default. Below, we will
1683                                  * complain if the bogus default isn't overridden by the child
1684                                  * schema.
1685                                  */
1686                                 Assert(def->raw_default == NULL);
1687                                 if (def->cooked_default == NULL)
1688                                         def->cooked_default = this_default;
1689                                 else if (!equal(def->cooked_default, this_default))
1690                                 {
1691                                         def->cooked_default = &bogus_marker;
1692                                         have_bogus_defaults = true;
1693                                 }
1694                         }
1695                 }
1696
1697                 /*
1698                  * Now copy the CHECK constraints of this parent, adjusting attnos
1699                  * using the completed newattno[] map.  Identically named constraints
1700                  * are merged if possible, else we throw error.
1701                  */
1702                 if (constr && constr->num_check > 0)
1703                 {
1704                         ConstrCheck *check = constr->check;
1705                         int                     i;
1706
1707                         for (i = 0; i < constr->num_check; i++)
1708                         {
1709                                 char       *name = check[i].ccname;
1710                                 Node       *expr;
1711                                 bool            found_whole_row;
1712
1713                                 /* ignore if the constraint is non-inheritable */
1714                                 if (check[i].ccnoinherit)
1715                                         continue;
1716
1717                                 /* Adjust Vars to match new table's column numbering */
1718                                 expr = map_variable_attnos(stringToNode(check[i].ccbin),
1719                                                                                    1, 0,
1720                                                                                    newattno, tupleDesc->natts,
1721                                                                                    &found_whole_row);
1722
1723                                 /*
1724                                  * For the moment we have to reject whole-row variables. We
1725                                  * could convert them, if we knew the new table's rowtype OID,
1726                                  * but that hasn't been assigned yet.
1727                                  */
1728                                 if (found_whole_row)
1729                                         ereport(ERROR,
1730                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1731                                                   errmsg("cannot convert whole-row table reference"),
1732                                                          errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1733                                                                            name,
1734                                                                            RelationGetRelationName(relation))));
1735
1736                                 /* check for duplicate */
1737                                 if (!MergeCheckConstraint(constraints, name, expr))
1738                                 {
1739                                         /* nope, this is a new one */
1740                                         CookedConstraint *cooked;
1741
1742                                         cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1743                                         cooked->contype = CONSTR_CHECK;
1744                                         cooked->name = pstrdup(name);
1745                                         cooked->attnum = 0; /* not used for constraints */
1746                                         cooked->expr = expr;
1747                                         cooked->skip_validation = false;
1748                                         cooked->is_local = false;
1749                                         cooked->inhcount = 1;
1750                                         cooked->is_no_inherit = false;
1751                                         constraints = lappend(constraints, cooked);
1752                                 }
1753                         }
1754                 }
1755
1756                 pfree(newattno);
1757
1758                 /*
1759                  * Close the parent rel, but keep our AccessShareLock on it until xact
1760                  * commit.  That will prevent someone else from deleting or ALTERing
1761                  * the parent before the child is committed.
1762                  */
1763                 heap_close(relation, NoLock);
1764         }
1765
1766         /*
1767          * If we had no inherited attributes, the result schema is just the
1768          * explicitly declared columns.  Otherwise, we need to merge the declared
1769          * columns into the inherited schema list.
1770          */
1771         if (inhSchema != NIL)
1772         {
1773                 int             schema_attno = 0;
1774
1775                 foreach(entry, schema)
1776                 {
1777                         ColumnDef  *newdef = lfirst(entry);
1778                         char       *attributeName = newdef->colname;
1779                         int                     exist_attno;
1780
1781                         schema_attno++;
1782
1783                         /*
1784                          * Does it conflict with some previously inherited column?
1785                          */
1786                         exist_attno = findAttrByName(attributeName, inhSchema);
1787                         if (exist_attno > 0)
1788                         {
1789                                 ColumnDef  *def;
1790                                 Oid                     defTypeId,
1791                                                         newTypeId;
1792                                 int32           deftypmod,
1793                                                         newtypmod;
1794                                 Oid                     defcollid,
1795                                                         newcollid;
1796
1797                                 /*
1798                                  * Yes, try to merge the two column definitions. They must
1799                                  * have the same type, typmod, and collation.
1800                                  */
1801                                  if (exist_attno == schema_attno)
1802                                         ereport(NOTICE,
1803                                            (errmsg("merging column \"%s\" with inherited definition",
1804                                                            attributeName)));
1805                                 else
1806                                         ereport(NOTICE,
1807                                            (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
1808                                                 errdetail("User-specified column moved to the position of the inherited column.")));
1809                                 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1810                                 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1811                                 typenameTypeIdAndMod(NULL, newdef->typeName, &newTypeId, &newtypmod);
1812                                 if (defTypeId != newTypeId || deftypmod != newtypmod)
1813                                         ereport(ERROR,
1814                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1815                                                          errmsg("column \"%s\" has a type conflict",
1816                                                                         attributeName),
1817                                                          errdetail("%s versus %s",
1818                                                                            TypeNameToString(def->typeName),
1819                                                                            TypeNameToString(newdef->typeName))));
1820                                 defcollid = GetColumnDefCollation(NULL, def, defTypeId);
1821                                 newcollid = GetColumnDefCollation(NULL, newdef, newTypeId);
1822                                 if (defcollid != newcollid)
1823                                         ereport(ERROR,
1824                                                         (errcode(ERRCODE_COLLATION_MISMATCH),
1825                                                          errmsg("column \"%s\" has a collation conflict",
1826                                                                         attributeName),
1827                                                          errdetail("\"%s\" versus \"%s\"",
1828                                                                            get_collation_name(defcollid),
1829                                                                            get_collation_name(newcollid))));
1830
1831                                 /* Copy storage parameter */
1832                                 if (def->storage == 0)
1833                                         def->storage = newdef->storage;
1834                                 else if (newdef->storage != 0 && def->storage != newdef->storage)
1835                                         ereport(ERROR,
1836                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1837                                          errmsg("column \"%s\" has a storage parameter conflict",
1838                                                         attributeName),
1839                                                          errdetail("%s versus %s",
1840                                                                            storage_name(def->storage),
1841                                                                            storage_name(newdef->storage))));
1842
1843                                 /* Mark the column as locally defined */
1844                                 def->is_local = true;
1845                                 /* Merge of NOT NULL constraints = OR 'em together */
1846                                 def->is_not_null |= newdef->is_not_null;
1847                                 /* If new def has a default, override previous default */
1848                                 if (newdef->raw_default != NULL)
1849                                 {
1850                                         def->raw_default = newdef->raw_default;
1851                                         def->cooked_default = newdef->cooked_default;
1852                                 }
1853                         }
1854                         else
1855                         {
1856                                 /*
1857                                  * No, attach new column to result schema
1858                                  */
1859                                 inhSchema = lappend(inhSchema, newdef);
1860                         }
1861                 }
1862
1863                 schema = inhSchema;
1864
1865                 /*
1866                  * Check that we haven't exceeded the legal # of columns after merging
1867                  * in inherited columns.
1868                  */
1869                 if (list_length(schema) > MaxHeapAttributeNumber)
1870                         ereport(ERROR,
1871                                         (errcode(ERRCODE_TOO_MANY_COLUMNS),
1872                                          errmsg("tables can have at most %d columns",
1873                                                         MaxHeapAttributeNumber)));
1874         }
1875
1876         /*
1877          * If we found any conflicting parent default values, check to make sure
1878          * they were overridden by the child.
1879          */
1880         if (have_bogus_defaults)
1881         {
1882                 foreach(entry, schema)
1883                 {
1884                         ColumnDef  *def = lfirst(entry);
1885
1886                         if (def->cooked_default == &bogus_marker)
1887                                 ereport(ERROR,
1888                                                 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1889                                   errmsg("column \"%s\" inherits conflicting default values",
1890                                                  def->colname),
1891                                                  errhint("To resolve the conflict, specify a default explicitly.")));
1892                 }
1893         }
1894
1895         *supOids = parentOids;
1896         *supconstr = constraints;
1897         *supOidCount = parentsWithOids;
1898         return schema;
1899 }
1900
1901
1902 /*
1903  * MergeCheckConstraint
1904  *              Try to merge an inherited CHECK constraint with previous ones
1905  *
1906  * If we inherit identically-named constraints from multiple parents, we must
1907  * merge them, or throw an error if they don't have identical definitions.
1908  *
1909  * constraints is a list of CookedConstraint structs for previous constraints.
1910  *
1911  * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1912  * got a so-far-unique name, or throws error if conflict.
1913  */
1914 static bool
1915 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1916 {
1917         ListCell   *lc;
1918
1919         foreach(lc, constraints)
1920         {
1921                 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1922
1923                 Assert(ccon->contype == CONSTR_CHECK);
1924
1925                 /* Non-matching names never conflict */
1926                 if (strcmp(ccon->name, name) != 0)
1927                         continue;
1928
1929                 if (equal(expr, ccon->expr))
1930                 {
1931                         /* OK to merge */
1932                         ccon->inhcount++;
1933                         return true;
1934                 }
1935
1936                 ereport(ERROR,
1937                                 (errcode(ERRCODE_DUPLICATE_OBJECT),
1938                                  errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1939                                                 name)));
1940         }
1941
1942         return false;
1943 }
1944
1945
1946 /*
1947  * StoreCatalogInheritance
1948  *              Updates the system catalogs with proper inheritance information.
1949  *
1950  * supers is a list of the OIDs of the new relation's direct ancestors.
1951  */
1952 static void
1953 StoreCatalogInheritance(Oid relationId, List *supers)
1954 {
1955         Relation        relation;
1956         int16           seqNumber;
1957         ListCell   *entry;
1958
1959         /*
1960          * sanity checks
1961          */
1962         AssertArg(OidIsValid(relationId));
1963
1964         if (supers == NIL)
1965                 return;
1966
1967         /*
1968          * Store INHERITS information in pg_inherits using direct ancestors only.
1969          * Also enter dependencies on the direct ancestors, and make sure they are
1970          * marked with relhassubclass = true.
1971          *
1972          * (Once upon a time, both direct and indirect ancestors were found here
1973          * and then entered into pg_ipl.  Since that catalog doesn't exist
1974          * anymore, there's no need to look for indirect ancestors.)
1975          */
1976         relation = heap_open(InheritsRelationId, RowExclusiveLock);
1977
1978         seqNumber = 1;
1979         foreach(entry, supers)
1980         {
1981                 Oid                     parentOid = lfirst_oid(entry);
1982
1983                 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1984                 seqNumber++;
1985         }
1986
1987         heap_close(relation, RowExclusiveLock);
1988 }
1989
1990 /*
1991  * Make catalog entries showing relationId as being an inheritance child
1992  * of parentOid.  inhRelation is the already-opened pg_inherits catalog.
1993  */
1994 static void
1995 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1996                                                  int16 seqNumber, Relation inhRelation)
1997 {
1998         TupleDesc       desc = RelationGetDescr(inhRelation);
1999         Datum           values[Natts_pg_inherits];
2000         bool            nulls[Natts_pg_inherits];
2001         ObjectAddress childobject,
2002                                 parentobject;
2003         HeapTuple       tuple;
2004
2005         /*
2006          * Make the pg_inherits entry
2007          */
2008         values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(relationId);
2009         values[Anum_pg_inherits_inhparent - 1] = ObjectIdGetDatum(parentOid);
2010         values[Anum_pg_inherits_inhseqno - 1] = Int16GetDatum(seqNumber);
2011
2012         memset(nulls, 0, sizeof(nulls));
2013
2014         tuple = heap_form_tuple(desc, values, nulls);
2015
2016         simple_heap_insert(inhRelation, tuple);
2017
2018         CatalogUpdateIndexes(inhRelation, tuple);
2019
2020         heap_freetuple(tuple);
2021
2022         /*
2023          * Store a dependency too
2024          */
2025         parentobject.classId = RelationRelationId;
2026         parentobject.objectId = parentOid;
2027         parentobject.objectSubId = 0;
2028         childobject.classId = RelationRelationId;
2029         childobject.objectId = relationId;
2030         childobject.objectSubId = 0;
2031
2032         recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
2033
2034         /*
2035          * Post creation hook of this inheritance. Since object_access_hook
2036          * doesn't take multiple object identifiers, we relay oid of parent
2037          * relation using auxiliary_id argument.
2038          */
2039         InvokeObjectPostAlterHookArg(InheritsRelationId,
2040                                                                  relationId, 0,
2041                                                                  parentOid, false);
2042
2043         /*
2044          * Mark the parent as having subclasses.
2045          */
2046         SetRelationHasSubclass(parentOid, true);
2047 }
2048
2049 /*
2050  * Look for an existing schema entry with the given name.
2051  *
2052  * Returns the index (starting with 1) if attribute already exists in schema,
2053  * 0 if it doesn't.
2054  */
2055 static int
2056 findAttrByName(const char *attributeName, List *schema)
2057 {
2058         ListCell   *s;
2059         int                     i = 1;
2060
2061         foreach(s, schema)
2062         {
2063                 ColumnDef  *def = lfirst(s);
2064
2065                 if (strcmp(attributeName, def->colname) == 0)
2066                         return i;
2067
2068                 i++;
2069         }
2070         return 0;
2071 }
2072
2073
2074 /*
2075  * SetRelationHasSubclass
2076  *              Set the value of the relation's relhassubclass field in pg_class.
2077  *
2078  * NOTE: caller must be holding an appropriate lock on the relation.
2079  * ShareUpdateExclusiveLock is sufficient.
2080  *
2081  * NOTE: an important side-effect of this operation is that an SI invalidation
2082  * message is sent out to all backends --- including me --- causing plans
2083  * referencing the relation to be rebuilt with the new list of children.
2084  * This must happen even if we find that no change is needed in the pg_class
2085  * row.
2086  */
2087 void
2088 SetRelationHasSubclass(Oid relationId, bool relhassubclass)
2089 {
2090         Relation        relationRelation;
2091         HeapTuple       tuple;
2092         Form_pg_class classtuple;
2093
2094         /*
2095          * Fetch a modifiable copy of the tuple, modify it, update pg_class.
2096          */
2097         relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
2098         tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
2099         if (!HeapTupleIsValid(tuple))
2100                 elog(ERROR, "cache lookup failed for relation %u", relationId);
2101         classtuple = (Form_pg_class) GETSTRUCT(tuple);
2102
2103         if (classtuple->relhassubclass != relhassubclass)
2104         {
2105                 classtuple->relhassubclass = relhassubclass;
2106                 simple_heap_update(relationRelation, &tuple->t_self, tuple);
2107
2108                 /* keep the catalog indexes up to date */
2109                 CatalogUpdateIndexes(relationRelation, tuple);
2110         }
2111         else
2112         {
2113                 /* no need to change tuple, but force relcache rebuild anyway */
2114                 CacheInvalidateRelcacheByTuple(tuple);
2115         }
2116
2117         heap_freetuple(tuple);
2118         heap_close(relationRelation, RowExclusiveLock);
2119 }
2120
2121 /*
2122  *              renameatt_check                 - basic sanity checks before attribute rename
2123  */
2124 static void
2125 renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
2126 {
2127         char            relkind = classform->relkind;
2128
2129         if (classform->reloftype && !recursing)
2130                 ereport(ERROR,
2131                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2132                                  errmsg("cannot rename column of typed table")));
2133
2134         /*
2135          * Renaming the columns of sequences or toast tables doesn't actually
2136          * break anything from the system's point of view, since internal
2137          * references are by attnum.  But it doesn't seem right to allow users to
2138          * change names that are hardcoded into the system, hence the following
2139          * restriction.
2140          */
2141         if (relkind != RELKIND_RELATION &&
2142                 relkind != RELKIND_VIEW &&
2143                 relkind != RELKIND_MATVIEW &&
2144                 relkind != RELKIND_COMPOSITE_TYPE &&
2145                 relkind != RELKIND_INDEX &&
2146                 relkind != RELKIND_FOREIGN_TABLE)
2147                 ereport(ERROR,
2148                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2149                                  errmsg("\"%s\" is not a table, view, materialized view, composite type, index, or foreign table",
2150                                                 NameStr(classform->relname))));
2151
2152         /*
2153          * permissions checking.  only the owner of a class can change its schema.
2154          */
2155         if (!pg_class_ownercheck(myrelid, GetUserId()))
2156                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2157                                            NameStr(classform->relname));
2158         if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
2159                 ereport(ERROR,
2160                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2161                                  errmsg("permission denied: \"%s\" is a system catalog",
2162                                                 NameStr(classform->relname))));
2163 }
2164
2165 /*
2166  *              renameatt_internal              - workhorse for renameatt
2167  *
2168  * Return value is the attribute number in the 'myrelid' relation.
2169  */
2170 static AttrNumber
2171 renameatt_internal(Oid myrelid,
2172                                    const char *oldattname,
2173                                    const char *newattname,
2174                                    bool recurse,
2175                                    bool recursing,
2176                                    int expected_parents,
2177                                    DropBehavior behavior)
2178 {
2179         Relation        targetrelation;
2180         Relation        attrelation;
2181         HeapTuple       atttup;
2182         Form_pg_attribute attform;
2183         AttrNumber      attnum;
2184
2185         /*
2186          * Grab an exclusive lock on the target table, which we will NOT release
2187          * until end of transaction.
2188          */
2189         targetrelation = relation_open(myrelid, AccessExclusiveLock);
2190         renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
2191
2192         /*
2193          * if the 'recurse' flag is set then we are supposed to rename this
2194          * attribute in all classes that inherit from 'relname' (as well as in
2195          * 'relname').
2196          *
2197          * any permissions or problems with duplicate attributes will cause the
2198          * whole transaction to abort, which is what we want -- all or nothing.
2199          */
2200         if (recurse)
2201         {
2202                 List       *child_oids,
2203                                    *child_numparents;
2204                 ListCell   *lo,
2205                                    *li;
2206
2207                 /*
2208                  * we need the number of parents for each child so that the recursive
2209                  * calls to renameatt() can determine whether there are any parents
2210                  * outside the inheritance hierarchy being processed.
2211                  */
2212                 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2213                                                                                  &child_numparents);
2214
2215                 /*
2216                  * find_all_inheritors does the recursive search of the inheritance
2217                  * hierarchy, so all we have to do is process all of the relids in the
2218                  * list that it returns.
2219                  */
2220                 forboth(lo, child_oids, li, child_numparents)
2221                 {
2222                         Oid                     childrelid = lfirst_oid(lo);
2223                         int                     numparents = lfirst_int(li);
2224
2225                         if (childrelid == myrelid)
2226                                 continue;
2227                         /* note we need not recurse again */
2228                         renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
2229                 }
2230         }
2231         else
2232         {
2233                 /*
2234                  * If we are told not to recurse, there had better not be any child
2235                  * tables; else the rename would put them out of step.
2236                  *
2237                  * expected_parents will only be 0 if we are not already recursing.
2238                  */
2239                 if (expected_parents == 0 &&
2240                         find_inheritance_children(myrelid, NoLock) != NIL)
2241                         ereport(ERROR,
2242                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2243                                          errmsg("inherited column \"%s\" must be renamed in child tables too",
2244                                                         oldattname)));
2245         }
2246
2247         /* rename attributes in typed tables of composite type */
2248         if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
2249         {
2250                 List       *child_oids;
2251                 ListCell   *lo;
2252
2253                 child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
2254                                                                          RelationGetRelationName(targetrelation),
2255                                                                                                    behavior);
2256
2257                 foreach(lo, child_oids)
2258                         renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
2259         }
2260
2261         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
2262
2263         atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
2264         if (!HeapTupleIsValid(atttup))
2265                 ereport(ERROR,
2266                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
2267                                  errmsg("column \"%s\" does not exist",
2268                                                 oldattname)));
2269         attform = (Form_pg_attribute) GETSTRUCT(atttup);
2270
2271         attnum = attform->attnum;
2272         if (attnum <= 0)
2273                 ereport(ERROR,
2274                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2275                                  errmsg("cannot rename system column \"%s\"",
2276                                                 oldattname)));
2277
2278         /*
2279          * if the attribute is inherited, forbid the renaming.  if this is a
2280          * top-level call to renameatt(), then expected_parents will be 0, so the
2281          * effect of this code will be to prohibit the renaming if the attribute
2282          * is inherited at all.  if this is a recursive call to renameatt(),
2283          * expected_parents will be the number of parents the current relation has
2284          * within the inheritance hierarchy being processed, so we'll prohibit the
2285          * renaming only if there are additional parents from elsewhere.
2286          */
2287         if (attform->attinhcount > expected_parents)
2288                 ereport(ERROR,
2289                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2290                                  errmsg("cannot rename inherited column \"%s\"",
2291                                                 oldattname)));
2292
2293         /* new name should not already exist */
2294         check_for_column_name_collision(targetrelation, newattname);
2295
2296         /* apply the update */
2297         namestrcpy(&(attform->attname), newattname);
2298
2299         simple_heap_update(attrelation, &atttup->t_self, atttup);
2300
2301         /* keep system catalog indexes current */
2302         CatalogUpdateIndexes(attrelation, atttup);
2303
2304         InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
2305
2306         heap_freetuple(atttup);
2307
2308         heap_close(attrelation, RowExclusiveLock);
2309
2310         relation_close(targetrelation, NoLock);         /* close rel but keep lock */
2311
2312         return attnum;
2313 }
2314
2315 /*
2316  * Perform permissions and integrity checks before acquiring a relation lock.
2317  */
2318 static void
2319 RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
2320                                                                    void *arg)
2321 {
2322         HeapTuple       tuple;
2323         Form_pg_class form;
2324
2325         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2326         if (!HeapTupleIsValid(tuple))
2327                 return;                                 /* concurrently dropped */
2328         form = (Form_pg_class) GETSTRUCT(tuple);
2329         renameatt_check(relid, form, false);
2330         ReleaseSysCache(tuple);
2331 }
2332
2333 /*
2334  *              renameatt               - changes the name of a attribute in a relation
2335  *
2336  * The returned ObjectAddress is that of the renamed column.
2337  */
2338 ObjectAddress
2339 renameatt(RenameStmt *stmt)
2340 {
2341         Oid                     relid;
2342         AttrNumber      attnum;
2343         ObjectAddress address;
2344
2345         /* lock level taken here should match renameatt_internal */
2346         relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2347                                                                          stmt->missing_ok, false,
2348                                                                          RangeVarCallbackForRenameAttribute,
2349                                                                          NULL);
2350
2351         if (!OidIsValid(relid))
2352         {
2353                 ereport(NOTICE,
2354                                 (errmsg("relation \"%s\" does not exist, skipping",
2355                                                 stmt->relation->relname)));
2356                 return InvalidObjectAddress;
2357         }
2358
2359         attnum =
2360                 renameatt_internal(relid,
2361                                                    stmt->subname,               /* old att name */
2362                                                    stmt->newname,               /* new att name */
2363                                                    interpretInhOption(stmt->relation->inhOpt),  /* recursive? */
2364                                                    false,               /* recursing? */
2365                                                    0,   /* expected inhcount */
2366                                                    stmt->behavior);
2367
2368         ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
2369
2370         return address;
2371 }
2372
2373 /*
2374  * same logic as renameatt_internal
2375  */
2376 static ObjectAddress
2377 rename_constraint_internal(Oid myrelid,
2378                                                    Oid mytypid,
2379                                                    const char *oldconname,
2380                                                    const char *newconname,
2381                                                    bool recurse,
2382                                                    bool recursing,
2383                                                    int expected_parents)
2384 {
2385         Relation        targetrelation = NULL;
2386         Oid                     constraintOid;
2387         HeapTuple       tuple;
2388         Form_pg_constraint con;
2389         ObjectAddress address;
2390
2391         AssertArg(!myrelid || !mytypid);
2392
2393         if (mytypid)
2394         {
2395                 constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
2396         }
2397         else
2398         {
2399                 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2400
2401                 /*
2402                  * don't tell it whether we're recursing; we allow changing typed
2403                  * tables here
2404                  */
2405                 renameatt_check(myrelid, RelationGetForm(targetrelation), false);
2406
2407                 constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
2408         }
2409
2410         tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2411         if (!HeapTupleIsValid(tuple))
2412                 elog(ERROR, "cache lookup failed for constraint %u",
2413                          constraintOid);
2414         con = (Form_pg_constraint) GETSTRUCT(tuple);
2415
2416         if (myrelid && con->contype == CONSTRAINT_CHECK && !con->connoinherit)
2417         {
2418                 if (recurse)
2419                 {
2420                         List       *child_oids,
2421                                            *child_numparents;
2422                         ListCell   *lo,
2423                                            *li;
2424
2425                         child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2426                                                                                          &child_numparents);
2427
2428                         forboth(lo, child_oids, li, child_numparents)
2429                         {
2430                                 Oid                     childrelid = lfirst_oid(lo);
2431                                 int                     numparents = lfirst_int(li);
2432
2433                                 if (childrelid == myrelid)
2434                                         continue;
2435
2436                                 rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
2437                         }
2438                 }
2439                 else
2440                 {
2441                         if (expected_parents == 0 &&
2442                                 find_inheritance_children(myrelid, NoLock) != NIL)
2443                                 ereport(ERROR,
2444                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2445                                                  errmsg("inherited constraint \"%s\" must be renamed in child tables too",
2446                                                                 oldconname)));
2447                 }
2448
2449                 if (con->coninhcount > expected_parents)
2450                         ereport(ERROR,
2451                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2452                                          errmsg("cannot rename inherited constraint \"%s\"",
2453                                                         oldconname)));
2454         }
2455
2456         if (con->conindid
2457                 && (con->contype == CONSTRAINT_PRIMARY
2458                         || con->contype == CONSTRAINT_UNIQUE
2459                         || con->contype == CONSTRAINT_EXCLUSION))
2460                 /* rename the index; this renames the constraint as well */
2461                 RenameRelationInternal(con->conindid, newconname, false);
2462         else
2463                 RenameConstraintById(constraintOid, newconname);
2464
2465         ObjectAddressSet(address, ConstraintRelationId, constraintOid);
2466
2467         ReleaseSysCache(tuple);
2468
2469         if (targetrelation)
2470                 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2471
2472         return address;
2473 }
2474
2475 ObjectAddress
2476 RenameConstraint(RenameStmt *stmt)
2477 {
2478         Oid                     relid = InvalidOid;
2479         Oid                     typid = InvalidOid;
2480
2481         if (stmt->renameType == OBJECT_DOMCONSTRAINT)
2482         {
2483                 Relation        rel;
2484                 HeapTuple       tup;
2485
2486                 typid = typenameTypeId(NULL, makeTypeNameFromNameList(stmt->object));
2487                 rel = heap_open(TypeRelationId, RowExclusiveLock);
2488                 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2489                 if (!HeapTupleIsValid(tup))
2490                         elog(ERROR, "cache lookup failed for type %u", typid);
2491                 checkDomainOwner(tup);
2492                 ReleaseSysCache(tup);
2493                 heap_close(rel, NoLock);
2494         }
2495         else
2496         {
2497                 /* lock level taken here should match rename_constraint_internal */
2498                 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2499                                                                                  false, false,
2500                                                                                  RangeVarCallbackForRenameAttribute,
2501                                                                                  NULL);
2502         }
2503
2504         return
2505                 rename_constraint_internal(relid, typid,
2506                                                                    stmt->subname,
2507                                                                    stmt->newname,
2508                  stmt->relation ? interpretInhOption(stmt->relation->inhOpt) : false,   /* recursive? */
2509                                                                    false,               /* recursing? */
2510                                                                    0 /* expected inhcount */ );
2511
2512 }
2513
2514 /*
2515  * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
2516  * RENAME
2517  */
2518 ObjectAddress
2519 RenameRelation(RenameStmt *stmt)
2520 {
2521         Oid                     relid;
2522         ObjectAddress address;
2523
2524         /*
2525          * Grab an exclusive lock on the target table, index, sequence, view,
2526          * materialized view, or foreign table, which we will NOT release until
2527          * end of transaction.
2528          *
2529          * Lock level used here should match RenameRelationInternal, to avoid lock
2530          * escalation.
2531          */
2532         relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2533                                                                          stmt->missing_ok, false,
2534                                                                          RangeVarCallbackForAlterRelation,
2535                                                                          (void *) stmt);
2536
2537         if (!OidIsValid(relid))
2538         {
2539                 ereport(NOTICE,
2540                                 (errmsg("relation \"%s\" does not exist, skipping",
2541                                                 stmt->relation->relname)));
2542                 return InvalidObjectAddress;
2543         }
2544
2545         /* Do the work */
2546         RenameRelationInternal(relid, stmt->newname, false);
2547
2548         ObjectAddressSet(address, RelationRelationId, relid);
2549
2550         return address;
2551 }
2552
2553 /*
2554  *              RenameRelationInternal - change the name of a relation
2555  *
2556  *              XXX - When renaming sequences, we don't bother to modify the
2557  *                        sequence name that is stored within the sequence itself
2558  *                        (this would cause problems with MVCC). In the future,
2559  *                        the sequence name should probably be removed from the
2560  *                        sequence, AFAIK there's no need for it to be there.
2561  */
2562 void
2563 RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
2564 {
2565         Relation        targetrelation;
2566         Relation        relrelation;    /* for RELATION relation */
2567         HeapTuple       reltup;
2568         Form_pg_class relform;
2569         Oid                     namespaceId;
2570
2571         /*
2572          * Grab an exclusive lock on the target table, index, sequence, view,
2573          * materialized view, or foreign table, which we will NOT release until
2574          * end of transaction.
2575          */
2576         targetrelation = relation_open(myrelid, AccessExclusiveLock);
2577         namespaceId = RelationGetNamespace(targetrelation);
2578
2579         /*
2580          * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2581          */
2582         relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2583
2584         reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
2585         if (!HeapTupleIsValid(reltup))          /* shouldn't happen */
2586                 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2587         relform = (Form_pg_class) GETSTRUCT(reltup);
2588
2589         if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2590                 ereport(ERROR,
2591                                 (errcode(ERRCODE_DUPLICATE_TABLE),
2592                                  errmsg("relation \"%s\" already exists",
2593                                                 newrelname)));
2594
2595         /*
2596          * Update pg_class tuple with new relname.  (Scribbling on reltup is OK
2597          * because it's a copy...)
2598          */
2599         namestrcpy(&(relform->relname), newrelname);
2600
2601         simple_heap_update(relrelation, &reltup->t_self, reltup);
2602
2603         /* keep the system catalog indexes current */
2604         CatalogUpdateIndexes(relrelation, reltup);
2605
2606         InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
2607                                                                  InvalidOid, is_internal);
2608
2609         heap_freetuple(reltup);
2610         heap_close(relrelation, RowExclusiveLock);
2611
2612         /*
2613          * Also rename the associated type, if any.
2614          */
2615         if (OidIsValid(targetrelation->rd_rel->reltype))
2616                 RenameTypeInternal(targetrelation->rd_rel->reltype,
2617                                                    newrelname, namespaceId);
2618
2619         /*
2620          * Also rename the associated constraint, if any.
2621          */
2622         if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2623         {
2624                 Oid                     constraintId = get_index_constraint(myrelid);
2625
2626                 if (OidIsValid(constraintId))
2627                         RenameConstraintById(constraintId, newrelname);
2628         }
2629
2630         /*
2631          * Close rel, but keep exclusive lock!
2632          */
2633         relation_close(targetrelation, NoLock);
2634 }
2635
2636 /*
2637  * Disallow ALTER TABLE (and similar commands) when the current backend has
2638  * any open reference to the target table besides the one just acquired by
2639  * the calling command; this implies there's an open cursor or active plan.
2640  * We need this check because our lock doesn't protect us against stomping
2641  * on our own foot, only other people's feet!
2642  *
2643  * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2644  * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2645  * possibly be relaxed to only error out for certain types of alterations.
2646  * But the use-case for allowing any of these things is not obvious, so we
2647  * won't work hard at it for now.
2648  *
2649  * We also reject these commands if there are any pending AFTER trigger events
2650  * for the rel.  This is certainly necessary for the rewriting variants of
2651  * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2652  * events would try to fetch the wrong tuples.  It might be overly cautious
2653  * in other cases, but again it seems better to err on the side of paranoia.
2654  *
2655  * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2656  * we are worried about active indexscans on the index.  The trigger-event
2657  * check can be skipped, since we are doing no damage to the parent table.
2658  *
2659  * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2660  */
2661 void
2662 CheckTableNotInUse(Relation rel, const char *stmt)
2663 {
2664         int                     expected_refcnt;
2665
2666         expected_refcnt = rel->rd_isnailed ? 2 : 1;
2667         if (rel->rd_refcnt != expected_refcnt)
2668                 ereport(ERROR,
2669                                 (errcode(ERRCODE_OBJECT_IN_USE),
2670                 /* translator: first %s is a SQL command, eg ALTER TABLE */
2671                                  errmsg("cannot %s \"%s\" because "
2672                                                 "it is being used by active queries in this session",
2673                                                 stmt, RelationGetRelationName(rel))));
2674
2675         if (rel->rd_rel->relkind != RELKIND_INDEX &&
2676                 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2677                 ereport(ERROR,
2678                                 (errcode(ERRCODE_OBJECT_IN_USE),
2679                 /* translator: first %s is a SQL command, eg ALTER TABLE */
2680                                  errmsg("cannot %s \"%s\" because "
2681                                                 "it has pending trigger events",
2682                                                 stmt, RelationGetRelationName(rel))));
2683 }
2684
2685 /*
2686  * AlterTableLookupRelation
2687  *              Look up, and lock, the OID for the relation named by an alter table
2688  *              statement.
2689  */
2690 Oid
2691 AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
2692 {
2693         return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
2694                                                                         RangeVarCallbackForAlterRelation,
2695                                                                         (void *) stmt);
2696 }
2697
2698 /*
2699  * AlterTable
2700  *              Execute ALTER TABLE, which can be a list of subcommands
2701  *
2702  * ALTER TABLE is performed in three phases:
2703  *              1. Examine subcommands and perform pre-transformation checking.
2704  *              2. Update system catalogs.
2705  *              3. Scan table(s) to check new constraints, and optionally recopy
2706  *                 the data into new table(s).
2707  * Phase 3 is not performed unless one or more of the subcommands requires
2708  * it.  The intention of this design is to allow multiple independent
2709  * updates of the table schema to be performed with only one pass over the
2710  * data.
2711  *
2712  * ATPrepCmd performs phase 1.  A "work queue" entry is created for
2713  * each table to be affected (there may be multiple affected tables if the
2714  * commands traverse a table inheritance hierarchy).  Also we do preliminary
2715  * validation of the subcommands, including parse transformation of those
2716  * expressions that need to be evaluated with respect to the old table
2717  * schema.
2718  *
2719  * ATRewriteCatalogs performs phase 2 for each affected table.  (Note that
2720  * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2721  * did it --- although some subcommands have to recurse in phase 2 instead.)
2722  * Certain subcommands need to be performed before others to avoid
2723  * unnecessary conflicts; for example, DROP COLUMN should come before
2724  * ADD COLUMN.  Therefore phase 1 divides the subcommands into multiple
2725  * lists, one for each logical "pass" of phase 2.
2726  *
2727  * ATRewriteTables performs phase 3 for those tables that need it.
2728  *
2729  * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2730  * the whole operation; we don't have to do anything special to clean up.
2731  *
2732  * The caller must lock the relation, with an appropriate lock level
2733  * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
2734  * or higher. We pass the lock level down
2735  * so that we can apply it recursively to inherited tables. Note that the
2736  * lock level we want as we recurse might well be higher than required for
2737  * that specific subcommand. So we pass down the overall lock requirement,
2738  * rather than reassess it at lower levels.
2739  */
2740 void
2741 AlterTable(Oid relid, LOCKMODE lockmode, AlterTableStmt *stmt)
2742 {
2743         Relation        rel;
2744
2745         /* Caller is required to provide an adequate lock. */
2746         rel = relation_open(relid, NoLock);
2747
2748         CheckTableNotInUse(rel, "ALTER TABLE");
2749
2750         ATController(stmt,
2751                                  rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt),
2752                                  lockmode);
2753 }
2754
2755 /*
2756  * AlterTableInternal
2757  *
2758  * ALTER TABLE with target specified by OID
2759  *
2760  * We do not reject if the relation is already open, because it's quite
2761  * likely that one or more layers of caller have it open.  That means it
2762  * is unsafe to use this entry point for alterations that could break
2763  * existing query plans.  On the assumption it's not used for such, we
2764  * don't have to reject pending AFTER triggers, either.
2765  */
2766 void
2767 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2768 {
2769         Relation        rel;
2770         LOCKMODE        lockmode = AlterTableGetLockLevel(cmds);
2771
2772         rel = relation_open(relid, lockmode);
2773
2774         ATController(NULL, rel, cmds, recurse, lockmode);
2775 }
2776
2777 /*
2778  * AlterTableGetLockLevel
2779  *
2780  * Sets the overall lock level required for the supplied list of subcommands.
2781  * Policy for doing this set according to needs of AlterTable(), see
2782  * comments there for overall explanation.
2783  *
2784  * Function is called before and after parsing, so it must give same
2785  * answer each time it is called. Some subcommands are transformed
2786  * into other subcommand types, so the transform must never be made to a
2787  * lower lock level than previously assigned. All transforms are noted below.
2788  *
2789  * Since this is called before we lock the table we cannot use table metadata
2790  * to influence the type of lock we acquire.
2791  *
2792  * There should be no lockmodes hardcoded into the subcommand functions. All
2793  * lockmode decisions for ALTER TABLE are made here only. The one exception is
2794  * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
2795  * and does not travel through this section of code and cannot be combined with
2796  * any of the subcommands given here.
2797  *
2798  * Note that Hot Standby only knows about AccessExclusiveLocks on the master
2799  * so any changes that might affect SELECTs running on standbys need to use
2800  * AccessExclusiveLocks even if you think a lesser lock would do, unless you
2801  * have a solution for that also.
2802  *
2803  * Also note that pg_dump uses only an AccessShareLock, meaning that anything
2804  * that takes a lock less than AccessExclusiveLock can change object definitions
2805  * while pg_dump is running. Be careful to check that the appropriate data is
2806  * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
2807  * otherwise we might end up with an inconsistent dump that can't restore.
2808  */
2809 LOCKMODE
2810 AlterTableGetLockLevel(List *cmds)
2811 {
2812         /*
2813          * This only works if we read catalog tables using MVCC snapshots.
2814          */
2815         ListCell   *lcmd;
2816         LOCKMODE        lockmode = ShareUpdateExclusiveLock;
2817
2818         foreach(lcmd, cmds)
2819         {
2820                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2821                 LOCKMODE        cmd_lockmode = AccessExclusiveLock; /* default for compiler */
2822
2823                 switch (cmd->subtype)
2824                 {
2825                                 /*
2826                                  * These subcommands rewrite the heap, so require full locks.
2827                                  */
2828                         case AT_AddColumn:      /* may rewrite heap, in some cases and visible
2829                                                                  * to SELECT */
2830                         case AT_SetTableSpace:          /* must rewrite heap */
2831                         case AT_AlterColumnType:        /* must rewrite heap */
2832                         case AT_AddOids:        /* must rewrite heap */
2833                                 cmd_lockmode = AccessExclusiveLock;
2834                                 break;
2835
2836                                 /*
2837                                  * These subcommands may require addition of toast tables. If
2838                                  * we add a toast table to a table currently being scanned, we
2839                                  * might miss data added to the new toast table by concurrent
2840                                  * insert transactions.
2841                                  */
2842                         case AT_SetStorage:/* may add toast tables, see
2843                                                                  * ATRewriteCatalogs() */
2844                                 cmd_lockmode = AccessExclusiveLock;
2845                                 break;
2846
2847                                 /*
2848                                  * Removing constraints can affect SELECTs that have been
2849                                  * optimised assuming the constraint holds true.
2850                                  */
2851                         case AT_DropConstraint:         /* as DROP INDEX */
2852                         case AT_DropNotNull:            /* may change some SQL plans */
2853                                 cmd_lockmode = AccessExclusiveLock;
2854                                 break;
2855
2856                                 /*
2857                                  * Subcommands that may be visible to concurrent SELECTs
2858                                  */
2859                         case AT_DropColumn:     /* change visible to SELECT */
2860                         case AT_AddColumnToView:        /* CREATE VIEW */
2861                         case AT_DropOids:       /* calls AT_DropColumn */
2862                         case AT_EnableAlwaysRule:       /* may change SELECT rules */
2863                         case AT_EnableReplicaRule:      /* may change SELECT rules */
2864                         case AT_EnableRule:     /* may change SELECT rules */
2865                         case AT_DisableRule:            /* may change SELECT rules */
2866                                 cmd_lockmode = AccessExclusiveLock;
2867                                 break;
2868
2869                                 /*
2870                                  * Changing owner may remove implicit SELECT privileges
2871                                  */
2872                         case AT_ChangeOwner:            /* change visible to SELECT */
2873                                 cmd_lockmode = AccessExclusiveLock;
2874                                 break;
2875
2876                                 /*
2877                                  * Changing foreign table options may affect optimisation.
2878                                  */
2879                         case AT_GenericOptions:
2880                         case AT_AlterColumnGenericOptions:
2881                                 cmd_lockmode = AccessExclusiveLock;
2882                                 break;
2883
2884                                 /*
2885                                  * These subcommands affect write operations only. XXX
2886                                  * Theoretically, these could be ShareRowExclusiveLock.
2887                                  */
2888                         case AT_ColumnDefault:
2889                         case AT_ProcessedConstraint:            /* becomes AT_AddConstraint */
2890                         case AT_AddConstraintRecurse:           /* becomes AT_AddConstraint */
2891                         case AT_ReAddConstraint:        /* becomes AT_AddConstraint */
2892                         case AT_EnableTrig:
2893                         case AT_EnableAlwaysTrig:
2894                         case AT_EnableReplicaTrig:
2895                         case AT_EnableTrigAll:
2896                         case AT_EnableTrigUser:
2897                         case AT_DisableTrig:
2898                         case AT_DisableTrigAll:
2899                         case AT_DisableTrigUser:
2900                         case AT_AlterConstraint:
2901                         case AT_AddIndex:       /* from ADD CONSTRAINT */
2902                         case AT_AddIndexConstraint:
2903                         case AT_ReplicaIdentity:
2904                         case AT_SetNotNull:
2905                         case AT_EnableRowSecurity:
2906                         case AT_DisableRowSecurity:
2907                                 cmd_lockmode = AccessExclusiveLock;
2908                                 break;
2909
2910                         case AT_AddConstraint:
2911                                 if (IsA(cmd->def, Constraint))
2912                                 {
2913                                         Constraint *con = (Constraint *) cmd->def;
2914
2915                                         switch (con->contype)
2916                                         {
2917                                                 case CONSTR_EXCLUSION:
2918                                                 case CONSTR_PRIMARY:
2919                                                 case CONSTR_UNIQUE:
2920
2921                                                         /*
2922                                                          * Cases essentially the same as CREATE INDEX. We
2923                                                          * could reduce the lock strength to ShareLock if
2924                                                          * we can work out how to allow concurrent catalog
2925                                                          * updates. XXX Might be set down to
2926                                                          * ShareRowExclusiveLock but requires further
2927                                                          * analysis.
2928                                                          */
2929                                                         cmd_lockmode = AccessExclusiveLock;
2930                                                         break;
2931                                                 case CONSTR_FOREIGN:
2932
2933                                                         /*
2934                                                          * We add triggers to both tables when we add a
2935                                                          * Foreign Key, so the lock level must be at least
2936                                                          * as strong as CREATE TRIGGER. XXX Might be set
2937                                                          * down to ShareRowExclusiveLock though trigger
2938                                                          * info is accessed by pg_get_triggerdef
2939                                                          */
2940                                                         cmd_lockmode = AccessExclusiveLock;
2941                                                         break;
2942
2943                                                 default:
2944                                                         cmd_lockmode = AccessExclusiveLock;
2945                                         }
2946                                 }
2947                                 break;
2948
2949                                 /*
2950                                  * These subcommands affect inheritance behaviour. Queries
2951                                  * started before us will continue to see the old inheritance
2952                                  * behaviour, while queries started after we commit will see
2953                                  * new behaviour. No need to prevent reads or writes to the
2954                                  * subtable while we hook it up though. Changing the TupDesc
2955                                  * may be a problem, so keep highest lock.
2956                                  */
2957                         case AT_AddInherit:
2958                         case AT_DropInherit:
2959                                 cmd_lockmode = AccessExclusiveLock;
2960                                 break;
2961
2962                                 /*
2963                                  * These subcommands affect implicit row type conversion. They
2964                                  * have affects similar to CREATE/DROP CAST on queries. don't
2965                                  * provide for invalidating parse trees as a result of such
2966                                  * changes, so we keep these at AccessExclusiveLock.
2967                                  */
2968                         case AT_AddOf:
2969                         case AT_DropOf:
2970                                 cmd_lockmode = AccessExclusiveLock;
2971                                 break;
2972
2973                                 /*
2974                                  * Only used by CREATE OR REPLACE VIEW which must conflict
2975                                  * with an SELECTs currently using the view.
2976                                  */
2977                         case AT_ReplaceRelOptions:
2978                                 cmd_lockmode = AccessExclusiveLock;
2979                                 break;
2980
2981                                 /*
2982                                  * These subcommands affect general strategies for performance
2983                                  * and maintenance, though don't change the semantic results
2984                                  * from normal data reads and writes. Delaying an ALTER TABLE
2985                                  * behind currently active writes only delays the point where
2986                                  * the new strategy begins to take effect, so there is no
2987                                  * benefit in waiting. In this case the minimum restriction
2988                                  * applies: we don't currently allow concurrent catalog
2989                                  * updates.
2990                                  */
2991                         case AT_SetStatistics:          /* Uses MVCC in getTableAttrs() */
2992                         case AT_ClusterOn:      /* Uses MVCC in getIndexes() */
2993                         case AT_DropCluster:            /* Uses MVCC in getIndexes() */
2994                         case AT_SetOptions:     /* Uses MVCC in getTableAttrs() */
2995                         case AT_ResetOptions:           /* Uses MVCC in getTableAttrs() */
2996                                 cmd_lockmode = ShareUpdateExclusiveLock;
2997                                 break;
2998
2999                         case AT_SetLogged:
3000                         case AT_SetUnLogged:
3001                                 cmd_lockmode = AccessExclusiveLock;
3002                                 break;
3003
3004                         case AT_ValidateConstraint: /* Uses MVCC in
3005                                                                                                  * getConstraints() */
3006                                 cmd_lockmode = ShareUpdateExclusiveLock;
3007                                 break;
3008
3009                                 /*
3010                                  * Rel options are more complex than first appears. Options
3011                                  * are set here for tables, views and indexes; for historical
3012                                  * reasons these can all be used with ALTER TABLE, so we can't
3013                                  * decide between them using the basic grammar.
3014                                  *
3015                                  * XXX Look in detail at each option to determine lock level,
3016                                  * e.g. cmd_lockmode = GetRelOptionsLockLevel((List *)
3017                                  * cmd->def);
3018                                  */
3019                         case AT_SetRelOptions:          /* Uses MVCC in getIndexes() and
3020                                                                                  * getTables() */
3021                         case AT_ResetRelOptions:        /* Uses MVCC in getIndexes() and
3022                                                                                  * getTables() */
3023                                 cmd_lockmode = AccessExclusiveLock;
3024                                 break;
3025
3026                         default:                        /* oops */
3027                                 elog(ERROR, "unrecognized alter table type: %d",
3028                                          (int) cmd->subtype);
3029                                 break;
3030                 }
3031
3032                 /*
3033                  * Take the greatest lockmode from any subcommand
3034                  */
3035                 if (cmd_lockmode > lockmode)
3036                         lockmode = cmd_lockmode;
3037         }
3038
3039         return lockmode;
3040 }
3041
3042 /*
3043  * ATController provides top level control over the phases.
3044  *
3045  * parsetree is passed in to allow it to be passed to event triggers
3046  * when requested.
3047  */
3048 static void
3049 ATController(AlterTableStmt *parsetree,
3050                          Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
3051 {
3052         List       *wqueue = NIL;
3053         ListCell   *lcmd;
3054
3055         /* Phase 1: preliminary examination of commands, create work queue */
3056         foreach(lcmd, cmds)
3057         {
3058                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3059
3060                 ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
3061         }
3062
3063         /* Close the relation, but keep lock until commit */
3064         relation_close(rel, NoLock);
3065
3066         /* Phase 2: update system catalogs */
3067         ATRewriteCatalogs(&wqueue, lockmode);
3068
3069         /* Phase 3: scan/rewrite tables as needed */
3070         ATRewriteTables(parsetree, &wqueue, lockmode);
3071 }
3072
3073 /*
3074  * ATPrepCmd
3075  *
3076  * Traffic cop for ALTER TABLE Phase 1 operations, including simple
3077  * recursion and permission checks.
3078  *
3079  * Caller must have acquired appropriate lock type on relation already.
3080  * This lock should be held until commit.
3081  */
3082 static void
3083 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
3084                   bool recurse, bool recursing, LOCKMODE lockmode)
3085 {
3086         AlteredTableInfo *tab;
3087         int                     pass = AT_PASS_UNSET;
3088
3089         /* Find or create work queue entry for this table */
3090         tab = ATGetQueueEntry(wqueue, rel);
3091
3092         /*
3093          * Copy the original subcommand for each table.  This avoids conflicts
3094          * when different child tables need to make different parse
3095          * transformations (for example, the same column may have different column
3096          * numbers in different children).
3097          */
3098         cmd = copyObject(cmd);
3099
3100         /*
3101          * Do permissions checking, recursion to child tables if needed, and any
3102          * additional phase-1 processing needed.
3103          */
3104         switch (cmd->subtype)
3105         {
3106                 case AT_AddColumn:              /* ADD COLUMN */
3107                         ATSimplePermissions(rel,
3108                                                  ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3109                         ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
3110                                                         lockmode);
3111                         /* Recursion occurs during execution phase */
3112                         pass = AT_PASS_ADD_COL;
3113                         break;
3114                 case AT_AddColumnToView:                /* add column via CREATE OR REPLACE
3115                                                                                  * VIEW */
3116                         ATSimplePermissions(rel, ATT_VIEW);
3117                         ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
3118                                                         lockmode);
3119                         /* Recursion occurs during execution phase */
3120                         pass = AT_PASS_ADD_COL;
3121                         break;
3122                 case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
3123
3124                         /*
3125                          * We allow defaults on views so that INSERT into a view can have
3126                          * default-ish behavior.  This works because the rewriter
3127                          * substitutes default values into INSERTs before it expands
3128                          * rules.
3129                          */
3130                         ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_FOREIGN_TABLE);
3131                         ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3132                         /* No command-specific prep needed */
3133                         pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
3134                         break;
3135                 case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
3136                         ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3137                         ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3138                         /* No command-specific prep needed */
3139                         pass = AT_PASS_DROP;
3140                         break;
3141                 case AT_SetNotNull:             /* ALTER COLUMN SET NOT NULL */
3142                         ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3143                         ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3144                         /* No command-specific prep needed */
3145                         pass = AT_PASS_ADD_CONSTR;
3146                         break;
3147                 case AT_SetStatistics:  /* ALTER COLUMN SET STATISTICS */
3148                         ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3149                         /* Performs own permission checks */
3150                         ATPrepSetStatistics(rel, cmd->name, cmd->def, lockmode);
3151                         pass = AT_PASS_MISC;
3152                         break;
3153                 case AT_SetOptions:             /* ALTER COLUMN SET ( options ) */
3154                 case AT_ResetOptions:   /* ALTER COLUMN RESET ( options ) */
3155                         ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE);
3156                         /* This command never recurses */
3157                         pass = AT_PASS_MISC;
3158                         break;
3159                 case AT_SetStorage:             /* ALTER COLUMN SET STORAGE */
3160                         ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3161                         ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3162                         /* No command-specific prep needed */
3163                         pass = AT_PASS_MISC;
3164                         break;
3165                 case AT_DropColumn:             /* DROP COLUMN */
3166                         ATSimplePermissions(rel,
3167                                                  ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3168                         ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
3169                         /* Recursion occurs during execution phase */
3170                         pass = AT_PASS_DROP;
3171                         break;
3172                 case AT_AddIndex:               /* ADD INDEX */
3173                         ATSimplePermissions(rel, ATT_TABLE);
3174                         /* This command never recurses */
3175                         /* No command-specific prep needed */
3176                         pass = AT_PASS_ADD_INDEX;
3177                         break;
3178                 case AT_AddConstraint:  /* ADD CONSTRAINT */
3179                         ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3180                         /* Recursion occurs during execution phase */
3181                         /* No command-specific prep needed except saving recurse flag */
3182                         if (recurse)
3183                                 cmd->subtype = AT_AddConstraintRecurse;
3184                         pass = AT_PASS_ADD_CONSTR;
3185                         break;
3186                 case AT_AddIndexConstraint:             /* ADD CONSTRAINT USING INDEX */
3187                         ATSimplePermissions(rel, ATT_TABLE);
3188                         /* This command never recurses */
3189                         /* No command-specific prep needed */
3190                         pass = AT_PASS_ADD_CONSTR;
3191                         break;
3192                 case AT_DropConstraint: /* DROP CONSTRAINT */
3193                         ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3194                         /* Recursion occurs during execution phase */
3195                         /* No command-specific prep needed except saving recurse flag */
3196                         if (recurse)
3197                                 cmd->subtype = AT_DropConstraintRecurse;
3198                         pass = AT_PASS_DROP;
3199                         break;
3200                 case AT_AlterColumnType:                /* ALTER COLUMN TYPE */
3201                         ATSimplePermissions(rel,
3202                                                  ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3203                         /* Performs own recursion */
3204                         ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd, lockmode);
3205                         pass = AT_PASS_ALTER_TYPE;
3206                         break;
3207                 case AT_AlterColumnGenericOptions:
3208                         ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
3209                         /* This command never recurses */
3210                         /* No command-specific prep needed */
3211                         pass = AT_PASS_MISC;
3212                         break;
3213                 case AT_ChangeOwner:    /* ALTER OWNER */
3214                         /* This command never recurses */
3215                         /* No command-specific prep needed */
3216                         pass = AT_PASS_MISC;
3217                         break;
3218                 case AT_ClusterOn:              /* CLUSTER ON */
3219                 case AT_DropCluster:    /* SET WITHOUT CLUSTER */
3220                         ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3221                         /* These commands never recurse */
3222                         /* No command-specific prep needed */
3223                         pass = AT_PASS_MISC;
3224                         break;
3225                 case AT_SetLogged:              /* SET LOGGED */
3226                         ATSimplePermissions(rel, ATT_TABLE);
3227                         tab->chgPersistence = ATPrepChangePersistence(rel, true);
3228                         /* force rewrite if necessary; see comment in ATRewriteTables */
3229                         if (tab->chgPersistence)
3230                         {
3231                                 tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
3232                                 tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
3233                         }
3234                         pass = AT_PASS_MISC;
3235                         break;
3236                 case AT_SetUnLogged:    /* SET UNLOGGED */
3237                         ATSimplePermissions(rel, ATT_TABLE);
3238                         tab->chgPersistence = ATPrepChangePersistence(rel, false);
3239                         /* force rewrite if necessary; see comment in ATRewriteTables */
3240                         if (tab->chgPersistence)
3241                         {
3242                                 tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
3243                                 tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
3244                         }
3245                         pass = AT_PASS_MISC;
3246                         break;
3247                 case AT_AddOids:                /* SET WITH OIDS */
3248                         ATSimplePermissions(rel, ATT_TABLE);
3249                         if (!rel->rd_rel->relhasoids || recursing)
3250                                 ATPrepAddOids(wqueue, rel, recurse, cmd, lockmode);
3251                         /* Recursion occurs during execution phase */
3252                         pass = AT_PASS_ADD_COL;
3253                         break;
3254                 case AT_DropOids:               /* SET WITHOUT OIDS */
3255                         ATSimplePermissions(rel, ATT_TABLE);
3256                         /* Performs own recursion */
3257                         if (rel->rd_rel->relhasoids)
3258                         {
3259                                 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
3260
3261                                 dropCmd->subtype = AT_DropColumn;
3262                                 dropCmd->name = pstrdup("oid");
3263                                 dropCmd->behavior = cmd->behavior;
3264                                 ATPrepCmd(wqueue, rel, dropCmd, recurse, false, lockmode);
3265                         }
3266                         pass = AT_PASS_DROP;
3267                         break;
3268                 case AT_SetTableSpace:  /* SET TABLESPACE */
3269                         ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX);
3270                         /* This command never recurses */
3271                         ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
3272                         pass = AT_PASS_MISC;    /* doesn't actually matter */
3273                         break;
3274                 case AT_SetRelOptions:  /* SET (...) */
3275                 case AT_ResetRelOptions:                /* RESET (...) */
3276                 case AT_ReplaceRelOptions:              /* reset them all, then set just these */
3277                         ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX);
3278                         /* This command never recurses */
3279                         /* No command-specific prep needed */
3280                         pass = AT_PASS_MISC;
3281                         break;
3282                 case AT_AddInherit:             /* INHERIT */
3283                         ATSimplePermissions(rel, ATT_TABLE);
3284                         /* This command never recurses */
3285                         ATPrepAddInherit(rel);
3286                         pass = AT_PASS_MISC;
3287                         break;
3288                 case AT_AlterConstraint:                /* ALTER CONSTRAINT */
3289                         ATSimplePermissions(rel, ATT_TABLE);
3290                         pass = AT_PASS_MISC;
3291                         break;
3292                 case AT_ValidateConstraint:             /* VALIDATE CONSTRAINT */
3293                         ATSimplePermissions(rel, ATT_TABLE);
3294                         /* Recursion occurs during execution phase */
3295                         /* No command-specific prep needed except saving recurse flag */
3296                         if (recurse)
3297                                 cmd->subtype = AT_ValidateConstraintRecurse;
3298                         pass = AT_PASS_MISC;
3299                         break;
3300                 case AT_ReplicaIdentity:                /* REPLICA IDENTITY ... */
3301                         ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3302                         pass = AT_PASS_MISC;
3303                         /* This command never recurses */
3304                         /* No command-specific prep needed */
3305                         break;
3306                 case AT_EnableTrig:             /* ENABLE TRIGGER variants */
3307                 case AT_EnableAlwaysTrig:
3308                 case AT_EnableReplicaTrig:
3309                 case AT_EnableTrigAll:
3310                 case AT_EnableTrigUser:
3311                 case AT_DisableTrig:    /* DISABLE TRIGGER variants */
3312                 case AT_DisableTrigAll:
3313                 case AT_DisableTrigUser:
3314                         ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3315                         pass = AT_PASS_MISC;
3316                         break;
3317                 case AT_EnableRule:             /* ENABLE/DISABLE RULE variants */
3318                 case AT_EnableAlwaysRule:
3319                 case AT_EnableReplicaRule:
3320                 case AT_DisableRule:
3321                 case AT_DropInherit:    /* NO INHERIT */
3322                 case AT_AddOf:                  /* OF */
3323                 case AT_DropOf: /* NOT OF */
3324                 case AT_EnableRowSecurity:
3325                 case AT_DisableRowSecurity:
3326                         ATSimplePermissions(rel, ATT_TABLE);
3327                         /* These commands never recurse */
3328                         /* No command-specific prep needed */
3329                         pass = AT_PASS_MISC;
3330                         break;
3331                 case AT_GenericOptions:
3332                         ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
3333                         /* No command-specific prep needed */
3334                         pass = AT_PASS_MISC;
3335                         break;
3336                 default:                                /* oops */
3337                         elog(ERROR, "unrecognized alter table type: %d",
3338                                  (int) cmd->subtype);
3339                         pass = AT_PASS_UNSET;           /* keep compiler quiet */
3340                         break;
3341         }
3342         Assert(pass > AT_PASS_UNSET);
3343
3344         /* Add the subcommand to the appropriate list for phase 2 */
3345         tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
3346 }
3347
3348 /*
3349  * ATRewriteCatalogs
3350  *
3351  * Traffic cop for ALTER TABLE Phase 2 operations.  Subcommands are
3352  * dispatched in a "safe" execution order (designed to avoid unnecessary
3353  * conflicts).
3354  */
3355 static void
3356 ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
3357 {
3358         int                     pass;
3359         ListCell   *ltab;
3360
3361         /*
3362          * We process all the tables "in parallel", one pass at a time.  This is
3363          * needed because we may have to propagate work from one table to another
3364          * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
3365          * re-adding of the foreign key constraint to the other table).  Work can
3366          * only be propagated into later passes, however.
3367          */
3368         for (pass = 0; pass < AT_NUM_PASSES; pass++)
3369         {
3370                 /* Go through each table that needs to be processed */
3371                 foreach(ltab, *wqueue)
3372                 {
3373                         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3374                         List       *subcmds = tab->subcmds[pass];
3375                         Relation        rel;
3376                         ListCell   *lcmd;
3377
3378                         if (subcmds == NIL)
3379                                 continue;
3380
3381                         /*
3382                          * Appropriate lock was obtained by phase 1, needn't get it again
3383                          */
3384                         rel = relation_open(tab->relid, NoLock);
3385
3386                         foreach(lcmd, subcmds)
3387                                 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd), lockmode);
3388
3389                         /*
3390                          * After the ALTER TYPE pass, do cleanup work (this is not done in
3391                          * ATExecAlterColumnType since it should be done only once if
3392                          * multiple columns of a table are altered).
3393                          */
3394                         if (pass == AT_PASS_ALTER_TYPE)
3395                                 ATPostAlterTypeCleanup(wqueue, tab, lockmode);
3396
3397                         relation_close(rel, NoLock);
3398                 }
3399         }
3400
3401         /* Check to see if a toast table must be added. */
3402         foreach(ltab, *wqueue)
3403         {
3404                 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3405
3406                 if (tab->relkind == RELKIND_RELATION ||
3407                         tab->relkind == RELKIND_MATVIEW)
3408                         AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
3409         }
3410 }
3411
3412 /*
3413  * ATExecCmd: dispatch a subcommand to appropriate execution routine
3414  */
3415 static void
3416 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
3417                   AlterTableCmd *cmd, LOCKMODE lockmode)
3418 {
3419         switch (cmd->subtype)
3420         {
3421                 case AT_AddColumn:              /* ADD COLUMN */
3422                 case AT_AddColumnToView:                /* add column via CREATE OR REPLACE
3423                                                                                  * VIEW */
3424                         ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3425                                                         false, false, false, lockmode);
3426                         break;
3427                 case AT_AddColumnRecurse:
3428                         ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3429                                                         false, true, false, lockmode);
3430                         break;
3431                 case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
3432                         ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
3433                         break;
3434                 case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
3435                         ATExecDropNotNull(rel, cmd->name, lockmode);
3436                         break;
3437                 case AT_SetNotNull:             /* ALTER COLUMN SET NOT NULL */
3438                         ATExecSetNotNull(tab, rel, cmd->name, lockmode);
3439                         break;
3440                 case AT_SetStatistics:  /* ALTER COLUMN SET STATISTICS */
3441                         ATExecSetStatistics(rel, cmd->name, cmd->def, lockmode);
3442                         break;
3443                 case AT_SetOptions:             /* ALTER COLUMN SET ( options ) */
3444                         ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
3445                         break;
3446                 case AT_ResetOptions:   /* ALTER COLUMN RESET ( options ) */
3447                         ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
3448                         break;
3449                 case AT_SetStorage:             /* ALTER COLUMN SET STORAGE */
3450                         ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
3451                         break;
3452                 case AT_DropColumn:             /* DROP COLUMN */
3453                         ATExecDropColumn(wqueue, rel, cmd->name,
3454                                          cmd->behavior, false, false, cmd->missing_ok, lockmode);
3455                         break;
3456                 case AT_DropColumnRecurse:              /* DROP COLUMN with recursion */
3457                         ATExecDropColumn(wqueue, rel, cmd->name,
3458                                           cmd->behavior, true, false, cmd->missing_ok, lockmode);
3459                         break;
3460                 case AT_AddIndex:               /* ADD INDEX */
3461                         ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false, lockmode);
3462                         break;
3463                 case AT_ReAddIndex:             /* ADD INDEX */
3464                         ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true, lockmode);
3465                         break;
3466                 case AT_AddConstraint:  /* ADD CONSTRAINT */
3467                         ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3468                                                                 false, false, lockmode);
3469                         break;
3470                 case AT_AddConstraintRecurse:   /* ADD CONSTRAINT with recursion */
3471                         ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3472                                                                 true, false, lockmode);
3473                         break;
3474                 case AT_ReAddConstraint:                /* Re-add pre-existing check
3475                                                                                  * constraint */
3476                         ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3477                                                                 false, true, lockmode);
3478                         break;
3479                 case AT_AddIndexConstraint:             /* ADD CONSTRAINT USING INDEX */
3480                         ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def, lockmode);
3481                         break;
3482                 case AT_AlterConstraint:                /* ALTER CONSTRAINT */
3483                         ATExecAlterConstraint(rel, cmd, false, false, lockmode);
3484                         break;
3485                 case AT_ValidateConstraint:             /* VALIDATE CONSTRAINT */
3486                         ATExecValidateConstraint(rel, cmd->name, false, false, lockmode);
3487                         break;
3488                 case AT_ValidateConstraintRecurse:              /* VALIDATE CONSTRAINT with
3489                                                                                                  * recursion */
3490                         ATExecValidateConstraint(rel, cmd->name, true, false, lockmode);
3491                         break;
3492                 case AT_DropConstraint: /* DROP CONSTRAINT */
3493                         ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3494                                                                  false, false,
3495                                                                  cmd->missing_ok, lockmode);
3496                         break;
3497                 case AT_DropConstraintRecurse:  /* DROP CONSTRAINT with recursion */
3498                         ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3499                                                                  true, false,
3500                                                                  cmd->missing_ok, lockmode);
3501                         break;
3502                 case AT_AlterColumnType:                /* ALTER COLUMN TYPE */
3503                         ATExecAlterColumnType(tab, rel, cmd, lockmode);
3504                         break;
3505                 case AT_AlterColumnGenericOptions:              /* ALTER COLUMN OPTIONS */
3506                         ATExecAlterColumnGenericOptions(rel, cmd->name, (List *) cmd->def, lockmode);
3507                         break;
3508                 case AT_ChangeOwner:    /* ALTER OWNER */
3509                         ATExecChangeOwner(RelationGetRelid(rel),
3510                                                           get_rolespec_oid(cmd->newowner, false),
3511                                                           false, lockmode);
3512                         break;
3513                 case AT_ClusterOn:              /* CLUSTER ON */
3514                         ATExecClusterOn(rel, cmd->name, lockmode);
3515                         break;
3516                 case AT_DropCluster:    /* SET WITHOUT CLUSTER */
3517                         ATExecDropCluster(rel, lockmode);
3518                         break;
3519                 case AT_SetLogged:              /* SET LOGGED */
3520                 case AT_SetUnLogged:    /* SET UNLOGGED */
3521                         break;
3522                 case AT_AddOids:                /* SET WITH OIDS */
3523                         /* Use the ADD COLUMN code, unless prep decided to do nothing */
3524                         if (cmd->def != NULL)
3525                                 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3526                                                                 true, false, false, lockmode);
3527                         break;
3528                 case AT_AddOidsRecurse: /* SET WITH OIDS */
3529                         /* Use the ADD COLUMN code, unless prep decided to do nothing */
3530                         if (cmd->def != NULL)
3531                                 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3532                                                                 true, true, false, lockmode);
3533                         break;
3534                 case AT_DropOids:               /* SET WITHOUT OIDS */
3535
3536                         /*
3537                          * Nothing to do here; we'll have generated a DropColumn
3538                          * subcommand to do the real work
3539                          */
3540                         break;
3541                 case AT_SetTableSpace:  /* SET TABLESPACE */
3542
3543                         /*
3544                          * Nothing to do here; Phase 3 does the work
3545                          */
3546                         break;
3547                 case AT_SetRelOptions:  /* SET (...) */
3548                 case AT_ResetRelOptions:                /* RESET (...) */
3549                 case AT_ReplaceRelOptions:              /* replace entire option list */
3550                         ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
3551                         break;
3552                 case AT_EnableTrig:             /* ENABLE TRIGGER name */
3553                         ATExecEnableDisableTrigger(rel, cmd->name,
3554                                                                    TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3555                         break;
3556                 case AT_EnableAlwaysTrig:               /* ENABLE ALWAYS TRIGGER name */
3557                         ATExecEnableDisableTrigger(rel, cmd->name,
3558                                                                            TRIGGER_FIRES_ALWAYS, false, lockmode);
3559                         break;
3560                 case AT_EnableReplicaTrig:              /* ENABLE REPLICA TRIGGER name */
3561                         ATExecEnableDisableTrigger(rel, cmd->name,
3562                                                                   TRIGGER_FIRES_ON_REPLICA, false, lockmode);
3563                         break;
3564                 case AT_DisableTrig:    /* DISABLE TRIGGER name */
3565                         ATExecEnableDisableTrigger(rel, cmd->name,
3566                                                                            TRIGGER_DISABLED, false, lockmode);
3567                         break;
3568                 case AT_EnableTrigAll:  /* ENABLE TRIGGER ALL */
3569                         ATExecEnableDisableTrigger(rel, NULL,
3570                                                                    TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3571                         break;
3572                 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
3573                         ATExecEnableDisableTrigger(rel, NULL,
3574                                                                            TRIGGER_DISABLED, false, lockmode);
3575                         break;
3576                 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
3577                         ATExecEnableDisableTrigger(rel, NULL,
3578                                                                         TRIGGER_FIRES_ON_ORIGIN, true, lockmode);
3579                         break;
3580                 case AT_DisableTrigUser:                /* DISABLE TRIGGER USER */
3581                         ATExecEnableDisableTrigger(rel, NULL,
3582                                                                            TRIGGER_DISABLED, true, lockmode);
3583                         break;
3584
3585                 case AT_EnableRule:             /* ENABLE RULE name */
3586                         ATExecEnableDisableRule(rel, cmd->name,
3587                                                                         RULE_FIRES_ON_ORIGIN, lockmode);
3588                         break;
3589                 case AT_EnableAlwaysRule:               /* ENABLE ALWAYS RULE name */
3590                         ATExecEnableDisableRule(rel, cmd->name,
3591                                                                         RULE_FIRES_ALWAYS, lockmode);
3592                         break;
3593                 case AT_EnableReplicaRule:              /* ENABLE REPLICA RULE name */
3594                         ATExecEnableDisableRule(rel, cmd->name,
3595                                                                         RULE_FIRES_ON_REPLICA, lockmode);
3596                         break;
3597                 case AT_DisableRule:    /* DISABLE RULE name */
3598                         ATExecEnableDisableRule(rel, cmd->name,
3599                                                                         RULE_DISABLED, lockmode);
3600                         break;
3601
3602                 case AT_AddInherit:
3603                         ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
3604                         break;
3605                 case AT_DropInherit:
3606                         ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
3607                         break;
3608                 case AT_AddOf:
3609                         ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
3610                         break;
3611                 case AT_DropOf:
3612                         ATExecDropOf(rel, lockmode);
3613                         break;
3614                 case AT_ReplicaIdentity:
3615                         ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
3616                         break;
3617                 case AT_EnableRowSecurity:
3618                         ATExecEnableRowSecurity(rel);
3619                         break;
3620                 case AT_DisableRowSecurity:
3621                         ATExecDisableRowSecurity(rel);
3622                         break;
3623                 case AT_GenericOptions:
3624                         ATExecGenericOptions(rel, (List *) cmd->def);
3625                         break;
3626                 default:                                /* oops */
3627                         elog(ERROR, "unrecognized alter table type: %d",
3628                                  (int) cmd->subtype);
3629                         break;
3630         }
3631
3632         /*
3633          * Bump the command counter to ensure the next subcommand in the sequence
3634          * can see the changes so far
3635          */
3636         CommandCounterIncrement();
3637 }
3638
3639 /*
3640  * ATRewriteTables: ALTER TABLE phase 3
3641  */
3642 static void
3643 ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
3644 {
3645         ListCell   *ltab;
3646
3647         /* Go through each table that needs to be checked or rewritten */
3648         foreach(ltab, *wqueue)
3649         {
3650                 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3651
3652                 /* Foreign tables have no storage. */
3653                 if (tab->relkind == RELKIND_FOREIGN_TABLE)
3654                         continue;
3655
3656                 /*
3657                  * If we change column data types or add/remove OIDs, the operation
3658                  * has to be propagated to tables that use this table's rowtype as a
3659                  * column type.  tab->newvals will also be non-NULL in the case where
3660                  * we're adding a column with a default.  We choose to forbid that
3661                  * case as well, since composite types might eventually support
3662                  * defaults.
3663                  *
3664                  * (Eventually we'll probably need to check for composite type
3665                  * dependencies even when we're just scanning the table without a
3666                  * rewrite, but at the moment a composite type does not enforce any
3667                  * constraints, so it's not necessary/appropriate to enforce them just
3668                  * during ALTER.)
3669                  */
3670                 if (tab->newvals != NIL || tab->rewrite > 0)
3671                 {
3672                         Relation        rel;
3673
3674                         rel = heap_open(tab->relid, NoLock);
3675                         find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
3676                         heap_close(rel, NoLock);
3677                 }
3678
3679                 /*
3680                  * We only need to rewrite the table if at least one column needs to
3681                  * be recomputed, we are adding/removing the OID column, or we are
3682                  * changing its persistence.
3683                  *
3684                  * There are two reasons for requiring a rewrite when changing
3685                  * persistence: on one hand, we need to ensure that the buffers
3686                  * belonging to each of the two relations are marked with or without
3687                  * BM_PERMANENT properly.  On the other hand, since rewriting creates
3688                  * and assigns a new relfilenode, we automatically create or drop an
3689                  * init fork for the relation as appropriate.
3690                  */
3691                 if (tab->rewrite > 0)
3692                 {
3693                         /* Build a temporary relation and copy data */
3694                         Relation        OldHeap;
3695                         Oid                     OIDNewHeap;
3696                         Oid                     NewTableSpace;
3697                         char            persistence;
3698
3699                         OldHeap = heap_open(tab->relid, NoLock);
3700
3701                         /*
3702                          * We don't support rewriting of system catalogs; there are too
3703                          * many corner cases and too little benefit.  In particular this
3704                          * is certainly not going to work for mapped catalogs.
3705                          */
3706                         if (IsSystemRelation(OldHeap))
3707                                 ereport(ERROR,
3708                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3709                                                  errmsg("cannot rewrite system relation \"%s\"",
3710                                                                 RelationGetRelationName(OldHeap))));
3711
3712                         if (RelationIsUsedAsCatalogTable(OldHeap))
3713                                 ereport(ERROR,
3714                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3715                                 errmsg("cannot rewrite table \"%s\" used as a catalog table",
3716                                            RelationGetRelationName(OldHeap))));
3717
3718                         /*
3719                          * Don't allow rewrite on temp tables of other backends ... their
3720                          * local buffer manager is not going to cope.
3721                          */
3722                         if (RELATION_IS_OTHER_TEMP(OldHeap))
3723                                 ereport(ERROR,
3724                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3725                                 errmsg("cannot rewrite temporary tables of other sessions")));
3726
3727                         /*
3728                          * Select destination tablespace (same as original unless user
3729                          * requested a change)
3730                          */
3731                         if (tab->newTableSpace)
3732                                 NewTableSpace = tab->newTableSpace;
3733                         else
3734                                 NewTableSpace = OldHeap->rd_rel->reltablespace;
3735
3736                         /*
3737                          * Select persistence of transient table (same as original unless
3738                          * user requested a change)
3739                          */
3740                         persistence = tab->chgPersistence ?
3741                                 tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
3742
3743                         heap_close(OldHeap, NoLock);
3744
3745                         /*
3746                          * Fire off an Event Trigger now, before actually rewriting the
3747                          * table.
3748                          *
3749                          * We don't support Event Trigger for nested commands anywhere,
3750                          * here included, and parsetree is given NULL when coming from
3751                          * AlterTableInternal.
3752                          *
3753                          * And fire it only once.
3754                          */
3755                         if (parsetree)
3756                                 EventTriggerTableRewrite((Node *)parsetree,
3757                                                                                  tab->relid,
3758                                                                                  tab->rewrite);
3759
3760                         /*
3761                          * Create transient table that will receive the modified data.
3762                          *
3763                          * Ensure it is marked correctly as logged or unlogged.  We have
3764                          * to do this here so that buffers for the new relfilenode will
3765                          * have the right persistence set, and at the same time ensure
3766                          * that the original filenode's buffers will get read in with the
3767                          * correct setting (i.e. the original one).  Otherwise a rollback
3768                          * after the rewrite would possibly result with buffers for the
3769                          * original filenode having the wrong persistence setting.
3770                          *
3771                          * NB: This relies on swap_relation_files() also swapping the
3772                          * persistence. That wouldn't work for pg_class, but that can't be
3773                          * unlogged anyway.
3774                          */
3775                         OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, persistence,
3776                                                                            lockmode);
3777
3778                         /*
3779                          * Copy the heap data into the new table with the desired
3780                          * modifications, and test the current data within the table
3781                          * against new constraints generated by ALTER TABLE commands.
3782                          */
3783                         ATRewriteTable(tab, OIDNewHeap, lockmode);
3784
3785                         /*
3786                          * Swap the physical files of the old and new heaps, then rebuild
3787                          * indexes and discard the old heap.  We can use RecentXmin for
3788                          * the table's new relfrozenxid because we rewrote all the tuples
3789                          * in ATRewriteTable, so no older Xid remains in the table.  Also,
3790                          * we never try to swap toast tables by content, since we have no
3791                          * interest in letting this code work on system catalogs.
3792                          */
3793                         finish_heap_swap(tab->relid, OIDNewHeap,
3794                                                          false, false, true,
3795                                                          !OidIsValid(tab->newTableSpace),
3796                                                          RecentXmin,
3797                                                          ReadNextMultiXactId(),
3798                                                          persistence);
3799                 }
3800                 else
3801                 {
3802                         /*
3803                          * Test the current data within the table against new constraints
3804                          * generated by ALTER TABLE commands, but don't rebuild data.
3805                          */
3806                         if (tab->constraints != NIL || tab->new_notnull)
3807                                 ATRewriteTable(tab, InvalidOid, lockmode);
3808
3809                         /*
3810                          * If we had SET TABLESPACE but no reason to reconstruct tuples,
3811                          * just do a block-by-block copy.
3812                          */
3813                         if (tab->newTableSpace)
3814                                 ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
3815                 }
3816         }
3817
3818         /*
3819          * Foreign key constraints are checked in a final pass, since (a) it's
3820          * generally best to examine each one separately, and (b) it's at least
3821          * theoretically possible that we have changed both relations of the
3822          * foreign key, and we'd better have finished both rewrites before we try
3823          * to read the tables.
3824          */
3825         foreach(ltab, *wqueue)
3826         {
3827                 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3828                 Relation        rel = NULL;
3829                 ListCell   *lcon;
3830
3831                 foreach(lcon, tab->constraints)
3832                 {
3833                         NewConstraint *con = lfirst(lcon);
3834
3835                         if (con->contype == CONSTR_FOREIGN)
3836                         {
3837                                 Constraint *fkconstraint = (Constraint *) con->qual;
3838                                 Relation        refrel;
3839
3840                                 if (rel == NULL)
3841                                 {
3842                                         /* Long since locked, no need for another */
3843                                         rel = heap_open(tab->relid, NoLock);
3844                                 }
3845
3846                                 refrel = heap_open(con->refrelid, RowShareLock);
3847
3848                                 validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
3849                                                                                          con->refindid,
3850                                                                                          con->conid);
3851
3852                                 /*
3853                                  * No need to mark the constraint row as validated, we did
3854                                  * that when we inserted the row earlier.
3855                                  */
3856
3857                                 heap_close(refrel, NoLock);
3858                         }
3859                 }
3860
3861                 if (rel)
3862                         heap_close(rel, NoLock);
3863         }
3864 }
3865
3866 /*
3867  * ATRewriteTable: scan or rewrite one table
3868  *
3869  * OIDNewHeap is InvalidOid if we don't need to rewrite
3870  */
3871 static void
3872 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
3873 {
3874         Relation        oldrel;
3875         Relation        newrel;
3876         TupleDesc       oldTupDesc;
3877         TupleDesc       newTupDesc;
3878         bool            needscan = false;
3879         List       *notnull_attrs;
3880         int                     i;
3881         ListCell   *l;
3882         EState     *estate;
3883         CommandId       mycid;
3884         BulkInsertState bistate;
3885         int                     hi_options;
3886
3887         /*
3888          * Open the relation(s).  We have surely already locked the existing
3889          * table.
3890          */
3891         oldrel = heap_open(tab->relid, NoLock);
3892         oldTupDesc = tab->oldDesc;
3893         newTupDesc = RelationGetDescr(oldrel);          /* includes all mods */
3894
3895         if (OidIsValid(OIDNewHeap))
3896                 newrel = heap_open(OIDNewHeap, lockmode);
3897         else
3898                 newrel = NULL;
3899
3900         /*
3901          * Prepare a BulkInsertState and options for heap_insert. Because we're
3902          * building a new heap, we can skip WAL-logging and fsync it to disk at
3903          * the end instead (unless WAL-logging is required for archiving or
3904          * streaming replication). The FSM is empty too, so don't bother using it.
3905          */
3906         if (newrel)
3907         {
3908                 mycid = GetCurrentCommandId(true);
3909                 bistate = GetBulkInsertState();
3910
3911                 hi_options = HEAP_INSERT_SKIP_FSM;
3912                 if (!XLogIsNeeded())
3913                         hi_options |= HEAP_INSERT_SKIP_WAL;
3914         }
3915         else
3916         {
3917                 /* keep compiler quiet about using these uninitialized */
3918                 mycid = 0;
3919                 bistate = NULL;
3920                 hi_options = 0;
3921         }
3922
3923         /*
3924          * Generate the constraint and default execution states
3925          */
3926
3927         estate = CreateExecutorState();
3928
3929         /* Build the needed expression execution states */
3930         foreach(l, tab->constraints)
3931         {
3932                 NewConstraint *con = lfirst(l);
3933
3934                 switch (con->contype)
3935                 {
3936                         case CONSTR_CHECK:
3937                                 needscan = true;
3938                                 con->qualstate = (List *)
3939                                         ExecPrepareExpr((Expr *) con->qual, estate);
3940                                 break;
3941                         case CONSTR_FOREIGN:
3942                                 /* Nothing to do here */
3943                                 break;
3944                         default:
3945                                 elog(ERROR, "unrecognized constraint type: %d",
3946                                          (int) con->contype);
3947                 }
3948         }
3949
3950         foreach(l, tab->newvals)
3951         {
3952                 NewColumnValue *ex = lfirst(l);
3953
3954                 /* expr already planned */
3955                 ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
3956         }
3957
3958         notnull_attrs = NIL;
3959         if (newrel || tab->new_notnull)
3960         {
3961                 /*
3962                  * If we are rebuilding the tuples OR if we added any new NOT NULL
3963                  * constraints, check all not-null constraints.  This is a bit of
3964                  * overkill but it minimizes risk of bugs, and heap_attisnull is a
3965                  * pretty cheap test anyway.
3966                  */
3967                 for (i = 0; i < newTupDesc->natts; i++)
3968                 {
3969                         if (newTupDesc->attrs[i]->attnotnull &&
3970                                 !newTupDesc->attrs[i]->attisdropped)
3971                                 notnull_attrs = lappend_int(notnull_attrs, i);
3972                 }
3973                 if (notnull_attrs)
3974                         needscan = true;
3975         }
3976
3977         if (newrel || needscan)
3978         {
3979                 ExprContext *econtext;
3980                 Datum      *values;
3981                 bool       *isnull;
3982                 TupleTableSlot *oldslot;
3983                 TupleTableSlot *newslot;
3984                 HeapScanDesc scan;
3985                 HeapTuple       tuple;
3986                 MemoryContext oldCxt;
3987                 List       *dropped_attrs = NIL;
3988                 ListCell   *lc;
3989                 Snapshot        snapshot;
3990
3991                 if (newrel)
3992                         ereport(DEBUG1,
3993                                         (errmsg("rewriting table \"%s\"",
3994                                                         RelationGetRelationName(oldrel))));
3995                 else
3996                         ereport(DEBUG1,
3997                                         (errmsg("verifying table \"%s\"",
3998                                                         RelationGetRelationName(oldrel))));
3999
4000                 if (newrel)
4001                 {
4002                         /*
4003                          * All predicate locks on the tuples or pages are about to be made
4004                          * invalid, because we move tuples around.  Promote them to
4005                          * relation locks.
4006                          */
4007                         TransferPredicateLocksToHeapRelation(oldrel);
4008                 }
4009
4010                 econtext = GetPerTupleExprContext(estate);
4011
4012                 /*
4013                  * Make tuple slots for old and new tuples.  Note that even when the
4014                  * tuples are the same, the tupDescs might not be (consider ADD COLUMN
4015                  * without a default).
4016                  */
4017                 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
4018                 newslot = MakeSingleTupleTableSlot(newTupDesc);
4019
4020                 /* Preallocate values/isnull arrays */
4021                 i = Max(newTupDesc->natts, oldTupDesc->natts);
4022                 values = (Datum *) palloc(i * sizeof(Datum));
4023                 isnull = (bool *) palloc(i * sizeof(bool));
4024                 memset(values, 0, i * sizeof(Datum));
4025                 memset(isnull, true, i * sizeof(bool));
4026
4027                 /*
4028                  * Any attributes that are dropped according to the new tuple
4029                  * descriptor can be set to NULL. We precompute the list of dropped
4030                  * attributes to avoid needing to do so in the per-tuple loop.
4031                  */
4032                 for (i = 0; i < newTupDesc->natts; i++)
4033                 {
4034                         if (newTupDesc->attrs[i]->attisdropped)
4035                                 dropped_attrs = lappend_int(dropped_attrs, i);
4036                 }
4037
4038                 /*
4039                  * Scan through the rows, generating a new row if needed and then
4040                  * checking all the constraints.
4041                  */
4042                 snapshot = RegisterSnapshot(GetLatestSnapshot());
4043                 scan = heap_beginscan(oldrel, snapshot, 0, NULL);
4044
4045                 /*
4046                  * Switch to per-tuple memory context and reset it for each tuple
4047                  * produced, so we don't leak memory.
4048                  */
4049                 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
4050
4051                 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4052                 {
4053                         if (tab->rewrite > 0)
4054                         {
4055                                 Oid                     tupOid = InvalidOid;
4056
4057                                 /* Extract data from old tuple */
4058                                 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
4059                                 if (oldTupDesc->tdhasoid)
4060                                         tupOid = HeapTupleGetOid(tuple);
4061
4062                                 /* Set dropped attributes to null in new tuple */
4063                                 foreach(lc, dropped_attrs)
4064                                         isnull[lfirst_int(lc)] = true;
4065
4066                                 /*
4067                                  * Process supplied expressions to replace selected columns.
4068                                  * Expression inputs come from the old tuple.
4069                                  */
4070                                 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
4071                                 econtext->ecxt_scantuple = oldslot;
4072
4073                                 foreach(l, tab->newvals)
4074                                 {
4075                                         NewColumnValue *ex = lfirst(l);
4076
4077                                         values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
4078                                                                                                                   econtext,
4079                                                                                                          &isnull[ex->attnum - 1],
4080                                                                                                                   NULL);
4081                                 }
4082
4083                                 /*
4084                                  * Form the new tuple. Note that we don't explicitly pfree it,
4085                                  * since the per-tuple memory context will be reset shortly.
4086                                  */
4087                                 tuple = heap_form_tuple(newTupDesc, values, isnull);
4088
4089                                 /* Preserve OID, if any */
4090                                 if (newTupDesc->tdhasoid)
4091                                         HeapTupleSetOid(tuple, tupOid);
4092
4093                                 /*
4094                                  * Constraints might reference the tableoid column, so
4095                                  * initialize t_tableOid before evaluating them.
4096                                  */
4097                                 tuple->t_tableOid = RelationGetRelid(oldrel);
4098                         }
4099
4100                         /* Now check any constraints on the possibly-changed tuple */
4101                         ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
4102                         econtext->ecxt_scantuple = newslot;
4103
4104                         foreach(l, notnull_attrs)
4105                         {
4106                                 int                     attn = lfirst_int(l);
4107
4108                                 if (heap_attisnull(tuple, attn + 1))
4109                                         ereport(ERROR,
4110                                                         (errcode(ERRCODE_NOT_NULL_VIOLATION),
4111                                                          errmsg("column \"%s\" contains null values",
4112                                                                   NameStr(newTupDesc->attrs[attn]->attname)),
4113                                                          errtablecol(oldrel, attn + 1)));
4114                         }
4115
4116                         foreach(l, tab->constraints)
4117                         {
4118                                 NewConstraint *con = lfirst(l);
4119
4120                                 switch (con->contype)
4121                                 {
4122                                         case CONSTR_CHECK:
4123                                                 if (!ExecQual(con->qualstate, econtext, true))
4124                                                         ereport(ERROR,
4125                                                                         (errcode(ERRCODE_CHECK_VIOLATION),
4126                                                                          errmsg("check constraint \"%s\" is violated by some row",
4127                                                                                         con->name),
4128                                                                          errtableconstraint(oldrel, con->name)));
4129                                                 break;
4130                                         case CONSTR_FOREIGN:
4131                                                 /* Nothing to do here */
4132                                                 break;
4133                                         default:
4134                                                 elog(ERROR, "unrecognized constraint type: %d",
4135                                                          (int) con->contype);
4136                                 }
4137                         }
4138
4139                         /* Write the tuple out to the new relation */
4140                         if (newrel)
4141                                 heap_insert(newrel, tuple, mycid, hi_options, bistate);
4142
4143                         ResetExprContext(econtext);
4144
4145                         CHECK_FOR_INTERRUPTS();
4146                 }
4147
4148                 MemoryContextSwitchTo(oldCxt);
4149                 heap_endscan(scan);
4150                 UnregisterSnapshot(snapshot);
4151
4152                 ExecDropSingleTupleTableSlot(oldslot);
4153                 ExecDropSingleTupleTableSlot(newslot);
4154         }
4155
4156         FreeExecutorState(estate);
4157
4158         heap_close(oldrel, NoLock);
4159         if (newrel)
4160         {
4161                 FreeBulkInsertState(bistate);
4162
4163                 /* If we skipped writing WAL, then we need to sync the heap. */
4164                 if (hi_options & HEAP_INSERT_SKIP_WAL)
4165                         heap_sync(newrel);
4166
4167                 heap_close(newrel, NoLock);
4168         }
4169 }
4170
4171 /*
4172  * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
4173  */
4174 static AlteredTableInfo *
4175 ATGetQueueEntry(List **wqueue, Relation rel)
4176 {
4177         Oid                     relid = RelationGetRelid(rel);
4178         AlteredTableInfo *tab;
4179         ListCell   *ltab;
4180
4181         foreach(ltab, *wqueue)
4182         {
4183                 tab = (AlteredTableInfo *) lfirst(ltab);
4184                 if (tab->relid == relid)
4185                         return tab;
4186         }
4187
4188         /*
4189          * Not there, so add it.  Note that we make a copy of the relation's
4190          * existing descriptor before anything interesting can happen to it.
4191          */
4192         tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
4193         tab->relid = relid;
4194         tab->relkind = rel->rd_rel->relkind;
4195         tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
4196         tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
4197         tab->chgPersistence = false;
4198
4199         *wqueue = lappend(*wqueue, tab);
4200
4201         return tab;
4202 }
4203
4204 /*
4205  * ATSimplePermissions
4206  *
4207  * - Ensure that it is a relation (or possibly a view)
4208  * - Ensure this user is the owner
4209  * - Ensure that it is not a system table
4210  */
4211 static void
4212 ATSimplePermissions(Relation rel, int allowed_targets)
4213 {
4214         int                     actual_target;
4215
4216         switch (rel->rd_rel->relkind)
4217         {
4218                 case RELKIND_RELATION:
4219                         actual_target = ATT_TABLE;
4220                         break;
4221                 case RELKIND_VIEW:
4222                         actual_target = ATT_VIEW;
4223                         break;
4224                 case RELKIND_MATVIEW:
4225                         actual_target = ATT_MATVIEW;
4226                         break;
4227                 case RELKIND_INDEX:
4228                         actual_target = ATT_INDEX;
4229                         break;
4230                 case RELKIND_COMPOSITE_TYPE:
4231                         actual_target = ATT_COMPOSITE_TYPE;
4232                         break;
4233                 case RELKIND_FOREIGN_TABLE:
4234                         actual_target = ATT_FOREIGN_TABLE;
4235                         break;
4236                 default:
4237                         actual_target = 0;
4238                         break;
4239         }
4240
4241         /* Wrong target type? */
4242         if ((actual_target & allowed_targets) == 0)
4243                 ATWrongRelkindError(rel, allowed_targets);
4244
4245         /* Permissions checks */
4246         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4247                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4248                                            RelationGetRelationName(rel));
4249
4250         if (!allowSystemTableMods && IsSystemRelation(rel))
4251                 ereport(ERROR,
4252                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4253                                  errmsg("permission denied: \"%s\" is a system catalog",
4254                                                 RelationGetRelationName(rel))));
4255 }
4256
4257 /*
4258  * ATWrongRelkindError
4259  *
4260  * Throw an error when a relation has been determined to be of the wrong
4261  * type.
4262  */
4263 static void
4264 ATWrongRelkindError(Relation rel, int allowed_targets)
4265 {
4266         char       *msg;
4267
4268         switch (allowed_targets)
4269         {
4270                 case ATT_TABLE:
4271                         msg = _("\"%s\" is not a table");
4272                         break;
4273                 case ATT_TABLE | ATT_VIEW:
4274                         msg = _("\"%s\" is not a table or view");
4275                         break;
4276                 case ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX:
4277                         msg = _("\"%s\" is not a table, view, materialized view, or index");
4278                         break;
4279                 case ATT_TABLE | ATT_MATVIEW:
4280                         msg = _("\"%s\" is not a table or materialized view");
4281                         break;
4282                 case ATT_TABLE | ATT_MATVIEW | ATT_INDEX:
4283                         msg = _("\"%s\" is not a table, materialized view, or index");
4284                         break;
4285                 case ATT_TABLE | ATT_FOREIGN_TABLE:
4286                         msg = _("\"%s\" is not a table or foreign table");
4287                         break;
4288                 case ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE:
4289                         msg = _("\"%s\" is not a table, composite type, or foreign table");
4290                         break;
4291                 case ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE:
4292                         msg = _("\"%s\" is not a table, materialized view, composite type, or foreign table");
4293                         break;
4294                 case ATT_VIEW:
4295                         msg = _("\"%s\" is not a view");
4296                         break;
4297                 case ATT_FOREIGN_TABLE:
4298                         msg = _("\"%s\" is not a foreign table");
4299                         break;
4300                 default:
4301                         /* shouldn't get here, add all necessary cases above */
4302                         msg = _("\"%s\" is of the wrong type");
4303                         break;
4304         }
4305
4306         ereport(ERROR,
4307                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4308                          errmsg(msg, RelationGetRelationName(rel))));
4309 }
4310
4311 /*
4312  * ATSimpleRecursion
4313  *
4314  * Simple table recursion sufficient for most ALTER TABLE operations.
4315  * All direct and indirect children are processed in an unspecified order.
4316  * Note that if a child inherits from the original table via multiple
4317  * inheritance paths, it will be visited just once.
4318  */
4319 static void
4320 ATSimpleRecursion(List **wqueue, Relation rel,
4321                                   AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
4322 {
4323         /*
4324          * Propagate to children if desired.  Non-table relations never have
4325          * children, so no need to search in that case.
4326          */
4327         if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
4328         {
4329                 Oid                     relid = RelationGetRelid(rel);
4330                 ListCell   *child;
4331                 List       *children;
4332
4333                 children = find_all_inheritors(relid, lockmode, NULL);
4334
4335                 /*
4336                  * find_all_inheritors does the recursive search of the inheritance
4337                  * hierarchy, so all we have to do is process all of the relids in the
4338                  * list that it returns.
4339                  */
4340                 foreach(child, children)
4341                 {
4342                         Oid                     childrelid = lfirst_oid(child);
4343                         Relation        childrel;
4344
4345                         if (childrelid == relid)
4346                                 continue;
4347                         /* find_all_inheritors already got lock */
4348                         childrel = relation_open(childrelid, NoLock);
4349                         CheckTableNotInUse(childrel, "ALTER TABLE");
4350                         ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode);
4351                         relation_close(childrel, NoLock);
4352                 }
4353         }
4354 }
4355
4356 /*
4357  * ATTypedTableRecursion
4358  *
4359  * Propagate ALTER TYPE operations to the typed tables of that type.
4360  * Also check the RESTRICT/CASCADE behavior.  Given CASCADE, also permit
4361  * recursion to inheritance children of the typed tables.
4362  */
4363 static void
4364 ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
4365                                           LOCKMODE lockmode)
4366 {
4367         ListCell   *child;
4368         List       *children;
4369
4370         Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
4371
4372         children = find_typed_table_dependencies(rel->rd_rel->reltype,
4373                                                                                          RelationGetRelationName(rel),
4374                                                                                          cmd->behavior);
4375
4376         foreach(child, children)
4377         {
4378                 Oid                     childrelid = lfirst_oid(child);
4379                 Relation        childrel;
4380
4381                 childrel = relation_open(childrelid, lockmode);
4382                 CheckTableNotInUse(childrel, "ALTER TABLE");
4383                 ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode);
4384                 relation_close(childrel, NoLock);
4385         }
4386 }
4387
4388
4389 /*
4390  * find_composite_type_dependencies
4391  *
4392  * Check to see if a composite type is being used as a column in some
4393  * other table (possibly nested several levels deep in composite types!).
4394  * Eventually, we'd like to propagate the check or rewrite operation
4395  * into other such tables, but for now, just error out if we find any.
4396  *
4397  * Caller should provide either a table name or a type name (not both) to
4398  * report in the error message, if any.
4399  *
4400  * We assume that functions and views depending on the type are not reasons
4401  * to reject the ALTER.  (How safe is this really?)
4402  */
4403 void
4404 find_composite_type_dependencies(Oid typeOid, Relation origRelation,
4405                                                                  const char *origTypeName)
4406 {
4407         Relation        depRel;
4408         ScanKeyData key[2];
4409         SysScanDesc depScan;
4410         HeapTuple       depTup;
4411         Oid                     arrayOid;
4412
4413         /*
4414          * We scan pg_depend to find those things that depend on the rowtype. (We
4415          * assume we can ignore refobjsubid for a rowtype.)
4416          */
4417         depRel = heap_open(DependRelationId, AccessShareLock);
4418
4419         ScanKeyInit(&key[0],
4420                                 Anum_pg_depend_refclassid,
4421                                 BTEqualStrategyNumber, F_OIDEQ,
4422                                 ObjectIdGetDatum(TypeRelationId));
4423         ScanKeyInit(&key[1],
4424                                 Anum_pg_depend_refobjid,
4425                                 BTEqualStrategyNumber, F_OIDEQ,
4426                                 ObjectIdGetDatum(typeOid));
4427
4428         depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
4429                                                                  NULL, 2, key);
4430
4431         while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
4432         {
4433                 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
4434                 Relation        rel;
4435                 Form_pg_attribute att;
4436
4437                 /* Ignore dependees that aren't user columns of relations */
4438                 /* (we assume system columns are never of rowtypes) */
4439                 if (pg_depend->classid != RelationRelationId ||
4440                         pg_depend->objsubid <= 0)
4441                         continue;
4442
4443                 rel = relation_open(pg_depend->objid, AccessShareLock);
4444                 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
4445
4446                 if (rel->rd_rel->relkind == RELKIND_RELATION ||
4447                         rel->rd_rel->relkind == RELKIND_MATVIEW)
4448                 {
4449                         if (origTypeName)
4450                                 ereport(ERROR,
4451                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4452                                                  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4453                                                                 origTypeName,
4454                                                                 RelationGetRelationName(rel),
4455                                                                 NameStr(att->attname))));
4456                         else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4457                                 ereport(ERROR,
4458                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4459                                                  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4460                                                                 RelationGetRelationName(origRelation),
4461                                                                 RelationGetRelationName(rel),
4462                                                                 NameStr(att->attname))));
4463                         else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
4464                                 ereport(ERROR,
4465                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4466                                                  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
4467                                                                 RelationGetRelationName(origRelation),
4468                                                                 RelationGetRelationName(rel),
4469                                                                 NameStr(att->attname))));
4470                         else
4471                                 ereport(ERROR,
4472                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4473                                                  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
4474                                                                 RelationGetRelationName(origRelation),
4475                                                                 RelationGetRelationName(rel),
4476                                                                 NameStr(att->attname))));
4477                 }
4478                 else if (OidIsValid(rel->rd_rel->reltype))
4479                 {
4480                         /*
4481                          * A view or composite type itself isn't a problem, but we must
4482                          * recursively check for indirect dependencies via its rowtype.
4483                          */
4484                         find_composite_type_dependencies(rel->rd_rel->reltype,
4485                                                                                          origRelation, origTypeName);
4486                 }
4487
4488                 relation_close(rel, AccessShareLock);
4489         }
4490
4491         systable_endscan(depScan);
4492
4493         relation_close(depRel, AccessShareLock);
4494
4495         /*
4496          * If there's an array type for the rowtype, must check for uses of it,
4497          * too.
4498          */
4499         arrayOid = get_array_type(typeOid);
4500         if (OidIsValid(arrayOid))
4501                 find_composite_type_dependencies(arrayOid, origRelation, origTypeName);
4502 }
4503
4504
4505 /*
4506  * find_typed_table_dependencies
4507  *
4508  * Check to see if a composite type is being used as the type of a
4509  * typed table.  Abort if any are found and behavior is RESTRICT.
4510  * Else return the list of tables.
4511  */
4512 static List *
4513 find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
4514 {
4515         Relation        classRel;
4516         ScanKeyData key[1];
4517         HeapScanDesc scan;
4518         HeapTuple       tuple;
4519         List       *result = NIL;
4520
4521         classRel = heap_open(RelationRelationId, AccessShareLock);
4522
4523         ScanKeyInit(&key[0],
4524                                 Anum_pg_class_reloftype,
4525                                 BTEqualStrategyNumber, F_OIDEQ,
4526                                 ObjectIdGetDatum(typeOid));
4527
4528         scan = heap_beginscan_catalog(classRel, 1, key);
4529
4530         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4531         {
4532                 if (behavior == DROP_RESTRICT)
4533                         ereport(ERROR,
4534                                         (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
4535                                          errmsg("cannot alter type \"%s\" because it is the type of a typed table",
4536                                                         typeName),
4537                         errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
4538                 else
4539                         result = lappend_oid(result, HeapTupleGetOid(tuple));
4540         }
4541
4542         heap_endscan(scan);
4543         heap_close(classRel, AccessShareLock);
4544
4545         return result;
4546 }
4547
4548
4549 /*
4550  * check_of_type
4551  *
4552  * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF.  If it
4553  * isn't suitable, throw an error.  Currently, we require that the type
4554  * originated with CREATE TYPE AS.  We could support any row type, but doing so
4555  * would require handling a number of extra corner cases in the DDL commands.
4556  */
4557 void
4558 check_of_type(HeapTuple typetuple)
4559 {
4560         Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
4561         bool            typeOk = false;
4562
4563         if (typ->typtype == TYPTYPE_COMPOSITE)
4564         {
4565                 Relation        typeRelation;
4566
4567                 Assert(OidIsValid(typ->typrelid));
4568                 typeRelation = relation_open(typ->typrelid, AccessShareLock);
4569                 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
4570
4571                 /*
4572                  * Close the parent rel, but keep our AccessShareLock on it until xact
4573                  * commit.  That will prevent someone else from deleting or ALTERing
4574                  * the type before the typed table creation/conversion commits.
4575                  */
4576                 relation_close(typeRelation, NoLock);
4577         }
4578         if (!typeOk)
4579                 ereport(ERROR,
4580                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4581                                  errmsg("type %s is not a composite type",
4582                                                 format_type_be(HeapTupleGetOid(typetuple)))));
4583 }
4584
4585
4586 /*
4587  * ALTER TABLE ADD COLUMN
4588  *
4589  * Adds an additional attribute to a relation making the assumption that
4590  * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
4591  * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
4592  * AlterTableCmd's.
4593  *
4594  * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
4595  * have to decide at runtime whether to recurse or not depending on whether we
4596  * actually add a column or merely merge with an existing column.  (We can't
4597  * check this in a static pre-pass because it won't handle multiple inheritance
4598  * situations correctly.)
4599  */
4600 static void
4601 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
4602                                 bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode)
4603 {
4604         if (rel->rd_rel->reloftype && !recursing)
4605                 ereport(ERROR,
4606                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4607                                  errmsg("cannot add column to typed table")));
4608
4609         if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4610                 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
4611
4612         if (recurse && !is_view)
4613                 cmd->subtype = AT_AddColumnRecurse;
4614 }
4615
4616 static void
4617 ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
4618                                 ColumnDef *colDef, bool isOid,
4619                                 bool recurse, bool recursing, LOCKMODE lockmode)
4620 {
4621         Oid                     myrelid = RelationGetRelid(rel);
4622         Relation        pgclass,
4623                                 attrdesc;
4624         HeapTuple       reltup;
4625         FormData_pg_attribute attribute;
4626         int                     newattnum;
4627         char            relkind;
4628         HeapTuple       typeTuple;
4629         Oid                     typeOid;
4630         int32           typmod;
4631         Oid                     collOid;
4632         Form_pg_type tform;
4633         Expr       *defval;
4634         List       *children;
4635         ListCell   *child;
4636         AclResult       aclresult;
4637
4638         /* At top level, permission check was done in ATPrepCmd, else do it */
4639         if (recursing)
4640                 ATSimplePermissions(rel, ATT_TABLE);
4641
4642         attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
4643
4644         /*
4645          * Are we adding the column to a recursion child?  If so, check whether to
4646          * merge with an existing definition for the column.  If we do merge, we
4647          * must not recurse.  Children will already have the column, and recursing
4648          * into them would mess up attinhcount.
4649          */
4650         if (colDef->inhcount > 0)
4651         {
4652                 HeapTuple       tuple;
4653
4654                 /* Does child already have a column by this name? */
4655                 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
4656                 if (HeapTupleIsValid(tuple))
4657                 {
4658                         Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4659                         Oid                     ctypeId;
4660                         int32           ctypmod;
4661                         Oid                     ccollid;
4662
4663                         /* Child column must match on type, typmod, and collation */
4664                         typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
4665                         if (ctypeId != childatt->atttypid ||
4666                                 ctypmod != childatt->atttypmod)
4667                                 ereport(ERROR,
4668                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
4669                                                  errmsg("child table \"%s\" has different type for column \"%s\"",
4670                                                         RelationGetRelationName(rel), colDef->colname)));
4671                         ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
4672                         if (ccollid != childatt->attcollation)
4673                                 ereport(ERROR,
4674                                                 (errcode(ERRCODE_COLLATION_MISMATCH),
4675                                                  errmsg("child table \"%s\" has different collation for column \"%s\"",
4676                                                           RelationGetRelationName(rel), colDef->colname),
4677                                                  errdetail("\"%s\" versus \"%s\"",
4678                                                                    get_collation_name(ccollid),
4679                                                            get_collation_name(childatt->attcollation))));
4680
4681                         /* If it's OID, child column must actually be OID */
4682                         if (isOid && childatt->attnum != ObjectIdAttributeNumber)
4683                                 ereport(ERROR,
4684                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
4685                                  errmsg("child table \"%s\" has a conflicting \"%s\" column",
4686                                                 RelationGetRelationName(rel), colDef->colname)));
4687
4688                         /* Bump the existing child att's inhcount */
4689                         childatt->attinhcount++;
4690                         simple_heap_update(attrdesc, &tuple->t_self, tuple);
4691                         CatalogUpdateIndexes(attrdesc, tuple);
4692
4693                         heap_freetuple(tuple);
4694
4695                         /* Inform the user about the merge */
4696                         ereport(NOTICE,
4697                           (errmsg("merging definition of column \"%s\" for child \"%s\"",
4698                                           colDef->colname, RelationGetRelationName(rel))));
4699
4700                         heap_close(attrdesc, RowExclusiveLock);
4701                         return;
4702                 }
4703         }
4704
4705         pgclass = heap_open(RelationRelationId, RowExclusiveLock);
4706
4707         reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4708         if (!HeapTupleIsValid(reltup))
4709                 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4710         relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
4711
4712         /* new name should not already exist */
4713         check_for_column_name_collision(rel, colDef->colname);
4714
4715         /* Determine the new attribute's number */
4716         if (isOid)
4717                 newattnum = ObjectIdAttributeNumber;
4718         else
4719         {
4720                 newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
4721                 if (newattnum > MaxHeapAttributeNumber)
4722                         ereport(ERROR,
4723                                         (errcode(ERRCODE_TOO_MANY_COLUMNS),
4724                                          errmsg("tables can have at most %d columns",
4725                                                         MaxHeapAttributeNumber)));
4726         }
4727
4728         typeTuple = typenameType(NULL, colDef->typeName, &typmod);
4729         tform = (Form_pg_type) GETSTRUCT(typeTuple);
4730         typeOid = HeapTupleGetOid(typeTuple);
4731
4732         aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
4733         if (aclresult != ACLCHECK_OK)
4734                 aclcheck_error_type(aclresult, typeOid);
4735
4736         collOid = GetColumnDefCollation(NULL, colDef, typeOid);
4737
4738         /* make sure datatype is legal for a column */
4739         CheckAttributeType(colDef->colname, typeOid, collOid,
4740                                            list_make1_oid(rel->rd_rel->reltype),
4741                                            false);
4742
4743         /* construct new attribute's pg_attribute entry */
4744         attribute.attrelid = myrelid;
4745         namestrcpy(&(attribute.attname), colDef->colname);
4746         attribute.atttypid = typeOid;
4747         attribute.attstattarget = (newattnum > 0) ? -1 : 0;
4748         attribute.attlen = tform->typlen;
4749         attribute.attcacheoff = -1;
4750         attribute.atttypmod = typmod;
4751         attribute.attnum = newattnum;
4752         attribute.attbyval = tform->typbyval;
4753         attribute.attndims = list_length(colDef->typeName->arrayBounds);
4754         attribute.attstorage = tform->typstorage;
4755         attribute.attalign = tform->typalign;
4756         attribute.attnotnull = colDef->is_not_null;
4757         attribute.atthasdef = false;
4758         attribute.attisdropped = false;
4759         attribute.attislocal = colDef->is_local;
4760         attribute.attinhcount = colDef->inhcount;
4761         attribute.attcollation = collOid;
4762         /* attribute.attacl is handled by InsertPgAttributeTuple */
4763
4764         ReleaseSysCache(typeTuple);
4765
4766         InsertPgAttributeTuple(attrdesc, &attribute, NULL);
4767
4768         heap_close(attrdesc, RowExclusiveLock);
4769
4770         /*
4771          * Update pg_class tuple as appropriate
4772          */
4773         if (isOid)
4774                 ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
4775         else
4776                 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
4777
4778         simple_heap_update(pgclass, &reltup->t_self, reltup);
4779
4780         /* keep catalog indexes current */
4781         CatalogUpdateIndexes(pgclass, reltup);
4782
4783         heap_freetuple(reltup);
4784
4785         /* Post creation hook for new attribute */
4786         InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
4787
4788         heap_close(pgclass, RowExclusiveLock);
4789
4790         /* Make the attribute's catalog entry visible */
4791         CommandCounterIncrement();
4792
4793         /*
4794          * Store the DEFAULT, if any, in the catalogs
4795          */
4796         if (colDef->raw_default)
4797         {
4798                 RawColumnDefault *rawEnt;
4799
4800                 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4801                 rawEnt->attnum = attribute.attnum;
4802                 rawEnt->raw_default = copyObject(colDef->raw_default);
4803
4804                 /*
4805                  * This function is intended for CREATE TABLE, so it processes a
4806                  * _list_ of defaults, but we just do one.
4807                  */
4808                 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
4809                                                                   false, true, false);
4810
4811                 /* Make the additional catalog changes visible */
4812                 CommandCounterIncrement();
4813         }
4814
4815         /*
4816          * Tell Phase 3 to fill in the default expression, if there is one.
4817          *
4818          * If there is no default, Phase 3 doesn't have to do anything, because
4819          * that effectively means that the default is NULL.  The heap tuple access
4820          * routines always check for attnum > # of attributes in tuple, and return
4821          * NULL if so, so without any modification of the tuple data we will get
4822          * the effect of NULL values in the new column.
4823          *
4824          * An exception occurs when the new column is of a domain type: the domain
4825          * might have a NOT NULL constraint, or a check constraint that indirectly
4826          * rejects nulls.  If there are any domain constraints then we construct
4827          * an explicit NULL default value that will be passed through
4828          * CoerceToDomain processing.  (This is a tad inefficient, since it causes
4829          * rewriting the table which we really don't have to do, but the present
4830          * design of domain processing doesn't offer any simple way of checking
4831          * the constraints more directly.)
4832          *
4833          * Note: we use build_column_default, and not just the cooked default
4834          * returned by AddRelationNewConstraints, so that the right thing happens
4835          * when a datatype's default applies.
4836          *
4837          * We skip this step completely for views and foreign tables.  For a view,
4838          * we can only get here from CREATE OR REPLACE VIEW, which historically
4839          * doesn't set up defaults, not even for domain-typed columns.  And in any
4840          * case we mustn't invoke Phase 3 on a view or foreign table, since they
4841          * have no storage.
4842          */
4843         if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
4844                 && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
4845         {
4846                 defval = (Expr *) build_column_default(rel, attribute.attnum);
4847
4848                 if (!defval && DomainHasConstraints(typeOid))
4849                 {
4850                         Oid                     baseTypeId;
4851                         int32           baseTypeMod;
4852                         Oid                     baseTypeColl;
4853
4854                         baseTypeMod = typmod;
4855                         baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
4856                         baseTypeColl = get_typcollation(baseTypeId);
4857                         defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
4858                         defval = (Expr *) coerce_to_target_type(NULL,
4859                                                                                                         (Node *) defval,
4860                                                                                                         baseTypeId,
4861                                                                                                         typeOid,
4862                                                                                                         typmod,
4863                                                                                                         COERCION_ASSIGNMENT,
4864                                                                                                         COERCE_IMPLICIT_CAST,
4865                                                                                                         -1);
4866                         if (defval == NULL) /* should not happen */
4867                                 elog(ERROR, "failed to coerce base type to domain");
4868                 }
4869
4870                 if (defval)
4871                 {
4872                         NewColumnValue *newval;
4873
4874                         newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4875                         newval->attnum = attribute.attnum;
4876                         newval->expr = expression_planner(defval);
4877
4878                         tab->newvals = lappend(tab->newvals, newval);
4879                         tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
4880                 }
4881
4882                 /*
4883                  * If the new column is NOT NULL, tell Phase 3 it needs to test that.
4884                  * (Note we don't do this for an OID column.  OID will be marked not
4885                  * null, but since it's filled specially, there's no need to test
4886                  * anything.)
4887                  */
4888                 tab->new_notnull |= colDef->is_not_null;
4889         }
4890
4891         /*
4892          * If we are adding an OID column, we have to tell Phase 3 to rewrite the
4893          * table to fix that.
4894          */
4895         if (isOid)
4896                 tab->rewrite |= AT_REWRITE_ALTER_OID;
4897
4898         /*
4899          * Add needed dependency entries for the new column.
4900          */
4901         add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
4902         add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
4903
4904         /*
4905          * Propagate to children as appropriate.  Unlike most other ALTER
4906          * routines, we have to do this one level of recursion at a time; we can't
4907          * use find_all_inheritors to do it in one pass.
4908          */
4909         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
4910
4911         /*
4912          * If we are told not to recurse, there had better not be any child
4913          * tables; else the addition would put them out of step.
4914          */
4915         if (children && !recurse)
4916                 ereport(ERROR,
4917                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4918                                  errmsg("column must be added to child tables too")));
4919
4920         /* Children should see column as singly inherited */
4921         if (!recursing)
4922         {
4923                 colDef = copyObject(colDef);
4924                 colDef->inhcount = 1;
4925                 colDef->is_local = false;
4926         }
4927
4928         foreach(child, children)
4929         {
4930                 Oid                     childrelid = lfirst_oid(child);
4931                 Relation        childrel;
4932                 AlteredTableInfo *childtab;
4933
4934                 /* find_inheritance_children already got lock */
4935                 childrel = heap_open(childrelid, NoLock);
4936                 CheckTableNotInUse(childrel, "ALTER TABLE");
4937
4938                 /* Find or create work queue entry for this table */
4939                 childtab = ATGetQueueEntry(wqueue, childrel);
4940
4941                 /* Recurse to child */
4942                 ATExecAddColumn(wqueue, childtab, childrel,
4943                                                 colDef, isOid, recurse, true, lockmode);
4944
4945                 heap_close(childrel, NoLock);
4946         }
4947 }
4948
4949 /*
4950  * If a new or renamed column will collide with the name of an existing
4951  * column, error out.
4952  */
4953 static void
4954 check_for_column_name_collision(Relation rel, const char *colname)
4955 {
4956         HeapTuple       attTuple;
4957         int                     attnum;
4958
4959         /*
4960          * this test is deliberately not attisdropped-aware, since if one tries to
4961          * add a column matching a dropped column name, it's gonna fail anyway.
4962          */
4963         attTuple = SearchSysCache2(ATTNAME,
4964                                                            ObjectIdGetDatum(RelationGetRelid(rel)),
4965                                                            PointerGetDatum(colname));
4966         if (!HeapTupleIsValid(attTuple))
4967                 return;
4968
4969         attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
4970         ReleaseSysCache(attTuple);
4971
4972         /*
4973          * We throw a different error message for conflicts with system column
4974          * names, since they are normally not shown and the user might otherwise
4975          * be confused about the reason for the conflict.
4976          */
4977         if (attnum <= 0)
4978                 ereport(ERROR,
4979                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
4980                          errmsg("column name \"%s\" conflicts with a system column name",
4981                                         colname)));
4982         else
4983                 ereport(ERROR,
4984                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
4985                                  errmsg("column \"%s\" of relation \"%s\" already exists",
4986                                                 colname, RelationGetRelationName(rel))));
4987 }
4988
4989 /*
4990  * Install a column's dependency on its datatype.
4991  */
4992 static void
4993 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
4994 {
4995         ObjectAddress myself,
4996                                 referenced;
4997
4998         myself.classId = RelationRelationId;
4999         myself.objectId = relid;
5000         myself.objectSubId = attnum;
5001         referenced.classId = TypeRelationId;
5002         referenced.objectId = typid;
5003         referenced.objectSubId = 0;
5004         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5005 }
5006
5007 /*
5008  * Install a column's dependency on its collation.
5009  */
5010 static void
5011 add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
5012 {
5013         ObjectAddress myself,
5014                                 referenced;
5015
5016         /* We know the default collation is pinned, so don't bother recording it */
5017         if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
5018         {
5019                 myself.classId = RelationRelationId;
5020                 myself.objectId = relid;
5021                 myself.objectSubId = attnum;
5022                 referenced.classId = CollationRelationId;
5023                 referenced.objectId = collid;
5024                 referenced.objectSubId = 0;
5025                 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5026         }
5027 }
5028
5029 /*
5030  * ALTER TABLE SET WITH OIDS
5031  *
5032  * Basically this is an ADD COLUMN for the special OID column.  We have
5033  * to cons up a ColumnDef node because the ADD COLUMN code needs one.
5034  */
5035 static void
5036 ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
5037 {
5038         /* If we're recursing to a child table, the ColumnDef is already set up */
5039         if (cmd->def == NULL)
5040         {
5041                 ColumnDef  *cdef = makeNode(ColumnDef);
5042
5043                 cdef->colname = pstrdup("oid");
5044                 cdef->typeName = makeTypeNameFromOid(OIDOID, -1);
5045                 cdef->inhcount = 0;
5046                 cdef->is_local = true;
5047                 cdef->is_not_null = true;
5048                 cdef->storage = 0;
5049                 cdef->location = -1;
5050                 cmd->def = (Node *) cdef;
5051         }
5052         ATPrepAddColumn(wqueue, rel, recurse, false, false, cmd, lockmode);
5053
5054         if (recurse)
5055                 cmd->subtype = AT_AddOidsRecurse;
5056 }
5057
5058 /*
5059  * ALTER TABLE ALTER COLUMN DROP NOT NULL
5060  */
5061 static void
5062 ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode)
5063 {
5064         HeapTuple       tuple;
5065         AttrNumber      attnum;
5066         Relation        attr_rel;
5067         List       *indexoidlist;
5068         ListCell   *indexoidscan;
5069
5070         /*
5071          * lookup the attribute
5072          */
5073         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5074
5075         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5076
5077         if (!HeapTupleIsValid(tuple))
5078                 ereport(ERROR,
5079                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5080                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5081                                                 colName, RelationGetRelationName(rel))));
5082
5083         attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
5084
5085         /* Prevent them from altering a system attribute */
5086         if (attnum <= 0)
5087                 ereport(ERROR,
5088                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5089                                  errmsg("cannot alter system column \"%s\"",
5090                                                 colName)));
5091
5092         /*
5093          * Check that the attribute is not in a primary key
5094          *
5095          * Note: we'll throw error even if the pkey index is not valid.
5096          */
5097
5098         /* Loop over all indexes on the relation */
5099         indexoidlist = RelationGetIndexList(rel);
5100
5101         foreach(indexoidscan, indexoidlist)
5102         {
5103                 Oid                     indexoid = lfirst_oid(indexoidscan);
5104                 HeapTuple       indexTuple;
5105                 Form_pg_index indexStruct;
5106                 int                     i;
5107
5108                 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
5109                 if (!HeapTupleIsValid(indexTuple))
5110                         elog(ERROR, "cache lookup failed for index %u", indexoid);
5111                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5112
5113                 /* If the index is not a primary key, skip the check */
5114                 if (indexStruct->indisprimary)
5115                 {
5116                         /*
5117                          * Loop over each attribute in the primary key and see if it
5118                          * matches the to-be-altered attribute
5119                          */
5120                         for (i = 0; i < indexStruct->indnatts; i++)
5121                         {
5122                                 if (indexStruct->indkey.values[i] == attnum)
5123                                         ereport(ERROR,
5124                                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5125                                                          errmsg("column \"%s\" is in a primary key",
5126                                                                         colName)));
5127                         }
5128                 }
5129
5130                 ReleaseSysCache(indexTuple);
5131         }
5132
5133         list_free(indexoidlist);
5134
5135         /*
5136          * Okay, actually perform the catalog change ... if needed
5137          */
5138         if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
5139         {
5140                 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
5141
5142                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5143
5144                 /* keep the system catalog indexes current */
5145                 CatalogUpdateIndexes(attr_rel, tuple);
5146         }
5147
5148         InvokeObjectPostAlterHook(RelationRelationId,
5149                                                           RelationGetRelid(rel), attnum);
5150
5151         heap_close(attr_rel, RowExclusiveLock);
5152 }
5153
5154 /*
5155  * ALTER TABLE ALTER COLUMN SET NOT NULL
5156  */
5157 static void
5158 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
5159                                  const char *colName, LOCKMODE lockmode)
5160 {
5161         HeapTuple       tuple;
5162         AttrNumber      attnum;
5163         Relation        attr_rel;
5164
5165         /*
5166          * lookup the attribute
5167          */
5168         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5169
5170         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5171
5172         if (!HeapTupleIsValid(tuple))
5173                 ereport(ERROR,
5174                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5175                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5176                                                 colName, RelationGetRelationName(rel))));
5177
5178         attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
5179
5180         /* Prevent them from altering a system attribute */
5181         if (attnum <= 0)
5182                 ereport(ERROR,
5183                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5184                                  errmsg("cannot alter system column \"%s\"",
5185                                                 colName)));
5186
5187         /*
5188          * Okay, actually perform the catalog change ... if needed
5189          */
5190         if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
5191         {
5192                 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
5193
5194                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5195
5196                 /* keep the system catalog indexes current */
5197                 CatalogUpdateIndexes(attr_rel, tuple);
5198
5199                 /* Tell Phase 3 it needs to test the constraint */
5200                 tab->new_notnull = true;
5201         }
5202
5203         InvokeObjectPostAlterHook(RelationRelationId,
5204                                                           RelationGetRelid(rel), attnum);
5205
5206         heap_close(attr_rel, RowExclusiveLock);
5207 }
5208
5209 /*
5210  * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
5211  */
5212 static void
5213 ATExecColumnDefault(Relation rel, const char *colName,
5214                                         Node *newDefault, LOCKMODE lockmode)
5215 {
5216         AttrNumber      attnum;
5217
5218         /*
5219          * get the number of the attribute
5220          */
5221         attnum = get_attnum(RelationGetRelid(rel), colName);
5222         if (attnum == InvalidAttrNumber)
5223                 ereport(ERROR,
5224                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5225                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5226                                                 colName, RelationGetRelationName(rel))));
5227
5228         /* Prevent them from altering a system attribute */
5229         if (attnum <= 0)
5230                 ereport(ERROR,
5231                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5232                                  errmsg("cannot alter system column \"%s\"",
5233                                                 colName)));
5234
5235         /*
5236          * Remove any old default for the column.  We use RESTRICT here for
5237          * safety, but at present we do not expect anything to depend on the
5238          * default.
5239          *
5240          * We treat removing the existing default as an internal operation when it
5241          * is preparatory to adding a new default, but as a user-initiated
5242          * operation when the user asked for a drop.
5243          */
5244         RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
5245                                           newDefault == NULL ? false : true);
5246
5247         if (newDefault)
5248         {
5249                 /* SET DEFAULT */
5250                 RawColumnDefault *rawEnt;
5251
5252                 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
5253                 rawEnt->attnum = attnum;
5254                 rawEnt->raw_default = newDefault;
5255
5256                 /*
5257                  * This function is intended for CREATE TABLE, so it processes a
5258                  * _list_ of defaults, but we just do one.
5259                  */
5260                 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
5261                                                                   false, true, false);
5262         }
5263 }
5264
5265 /*
5266  * ALTER TABLE ALTER COLUMN SET STATISTICS
5267  */
5268 static void
5269 ATPrepSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5270 {
5271         /*
5272          * We do our own permission checking because (a) we want to allow SET
5273          * STATISTICS on indexes (for expressional index columns), and (b) we want
5274          * to allow SET STATISTICS on system catalogs without requiring
5275          * allowSystemTableMods to be turned on.
5276          */
5277         if (rel->rd_rel->relkind != RELKIND_RELATION &&
5278                 rel->rd_rel->relkind != RELKIND_MATVIEW &&
5279                 rel->rd_rel->relkind != RELKIND_INDEX &&
5280                 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
5281                 ereport(ERROR,
5282                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5283                                  errmsg("\"%s\" is not a table, materialized view, index, or foreign table",
5284                                                 RelationGetRelationName(rel))));
5285
5286         /* Permissions checks */
5287         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
5288                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5289                                            RelationGetRelationName(rel));
5290 }
5291
5292 static void
5293 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5294 {
5295         int                     newtarget;
5296         Relation        attrelation;
5297         HeapTuple       tuple;
5298         Form_pg_attribute attrtuple;
5299
5300         Assert(IsA(newValue, Integer));
5301         newtarget = intVal(newValue);
5302
5303         /*
5304          * Limit target to a sane range
5305          */
5306         if (newtarget < -1)
5307         {
5308                 ereport(ERROR,
5309                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5310                                  errmsg("statistics target %d is too low",
5311                                                 newtarget)));
5312         }
5313         else if (newtarget > 10000)
5314         {
5315                 newtarget = 10000;
5316                 ereport(WARNING,
5317                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5318                                  errmsg("lowering statistics target to %d",
5319                                                 newtarget)));
5320         }
5321
5322         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5323
5324         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5325
5326         if (!HeapTupleIsValid(tuple))
5327                 ereport(ERROR,
5328                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5329                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5330                                                 colName, RelationGetRelationName(rel))));
5331         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5332
5333         if (attrtuple->attnum <= 0)
5334                 ereport(ERROR,
5335                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5336                                  errmsg("cannot alter system column \"%s\"",
5337                                                 colName)));
5338
5339         attrtuple->attstattarget = newtarget;
5340
5341         simple_heap_update(attrelation, &tuple->t_self, tuple);
5342
5343         /* keep system catalog indexes current */
5344         CatalogUpdateIndexes(attrelation, tuple);
5345
5346         InvokeObjectPostAlterHook(RelationRelationId,
5347                                                           RelationGetRelid(rel),
5348                                                           attrtuple->attnum);
5349         heap_freetuple(tuple);
5350
5351         heap_close(attrelation, RowExclusiveLock);
5352 }
5353
5354 static void
5355 ATExecSetOptions(Relation rel, const char *colName, Node *options,
5356                                  bool isReset, LOCKMODE lockmode)
5357 {
5358         Relation        attrelation;
5359         HeapTuple       tuple,
5360                                 newtuple;
5361         Form_pg_attribute attrtuple;
5362         Datum           datum,
5363                                 newOptions;
5364         bool            isnull;
5365         Datum           repl_val[Natts_pg_attribute];
5366         bool            repl_null[Natts_pg_attribute];
5367         bool            repl_repl[Natts_pg_attribute];
5368
5369         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5370
5371         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5372
5373         if (!HeapTupleIsValid(tuple))
5374                 ereport(ERROR,
5375                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5376                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5377                                                 colName, RelationGetRelationName(rel))));
5378         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5379
5380         if (attrtuple->attnum <= 0)
5381                 ereport(ERROR,
5382                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5383                                  errmsg("cannot alter system column \"%s\"",
5384                                                 colName)));
5385
5386         /* Generate new proposed attoptions (text array) */
5387         Assert(IsA(options, List));
5388         datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
5389                                                         &isnull);
5390         newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5391                                                                          (List *) options, NULL, NULL, false,
5392                                                                          isReset);
5393         /* Validate new options */
5394         (void) attribute_reloptions(newOptions, true);
5395
5396         /* Build new tuple. */
5397         memset(repl_null, false, sizeof(repl_null));
5398         memset(repl_repl, false, sizeof(repl_repl));
5399         if (newOptions != (Datum) 0)
5400                 repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
5401         else
5402                 repl_null[Anum_pg_attribute_attoptions - 1] = true;
5403         repl_repl[Anum_pg_attribute_attoptions - 1] = true;
5404         newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
5405                                                                  repl_val, repl_null, repl_repl);
5406
5407         /* Update system catalog. */
5408         simple_heap_update(attrelation, &newtuple->t_self, newtuple);
5409         CatalogUpdateIndexes(attrelation, newtuple);
5410
5411         InvokeObjectPostAlterHook(RelationRelationId,
5412                                                           RelationGetRelid(rel),
5413                                                           attrtuple->attnum);
5414         heap_freetuple(newtuple);
5415
5416         ReleaseSysCache(tuple);
5417
5418         heap_close(attrelation, RowExclusiveLock);
5419 }
5420
5421 /*
5422  * ALTER TABLE ALTER COLUMN SET STORAGE
5423  */
5424 static void
5425 ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5426 {
5427         char       *storagemode;
5428         char            newstorage;
5429         Relation        attrelation;
5430         HeapTuple       tuple;
5431         Form_pg_attribute attrtuple;
5432
5433         Assert(IsA(newValue, String));
5434         storagemode = strVal(newValue);
5435
5436         if (pg_strcasecmp(storagemode, "plain") == 0)
5437                 newstorage = 'p';
5438         else if (pg_strcasecmp(storagemode, "external") == 0)
5439                 newstorage = 'e';
5440         else if (pg_strcasecmp(storagemode, "extended") == 0)
5441                 newstorage = 'x';
5442         else if (pg_strcasecmp(storagemode, "main") == 0)
5443                 newstorage = 'm';
5444         else
5445         {
5446                 ereport(ERROR,
5447                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5448                                  errmsg("invalid storage type \"%s\"",
5449                                                 storagemode)));
5450                 newstorage = 0;                 /* keep compiler quiet */
5451         }
5452
5453         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5454
5455         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5456
5457         if (!HeapTupleIsValid(tuple))
5458                 ereport(ERROR,
5459                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5460                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5461                                                 colName, RelationGetRelationName(rel))));
5462         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5463
5464         if (attrtuple->attnum <= 0)
5465                 ereport(ERROR,
5466                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5467                                  errmsg("cannot alter system column \"%s\"",
5468                                                 colName)));
5469
5470         /*
5471          * safety check: do not allow toasted storage modes unless column datatype
5472          * is TOAST-aware.
5473          */
5474         if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
5475                 attrtuple->attstorage = newstorage;
5476         else
5477                 ereport(ERROR,
5478                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5479                                  errmsg("column data type %s can only have storage PLAIN",
5480                                                 format_type_be(attrtuple->atttypid))));
5481
5482         simple_heap_update(attrelation, &tuple->t_self, tuple);
5483
5484         /* keep system catalog indexes current */
5485         CatalogUpdateIndexes(attrelation, tuple);
5486
5487         InvokeObjectPostAlterHook(RelationRelationId,
5488                                                           RelationGetRelid(rel),
5489                                                           attrtuple->attnum);
5490
5491         heap_freetuple(tuple);
5492
5493         heap_close(attrelation, RowExclusiveLock);
5494 }
5495
5496
5497 /*
5498  * ALTER TABLE DROP COLUMN
5499  *
5500  * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
5501  * because we have to decide at runtime whether to recurse or not depending
5502  * on whether attinhcount goes to zero or not.  (We can't check this in a
5503  * static pre-pass because it won't handle multiple inheritance situations
5504  * correctly.)
5505  */
5506 static void
5507 ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
5508                                  AlterTableCmd *cmd, LOCKMODE lockmode)
5509 {
5510         if (rel->rd_rel->reloftype && !recursing)
5511                 ereport(ERROR,
5512                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5513                                  errmsg("cannot drop column from typed table")));
5514
5515         if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
5516                 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
5517
5518         if (recurse)
5519                 cmd->subtype = AT_DropColumnRecurse;
5520 }
5521
5522 static void
5523 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
5524                                  DropBehavior behavior,
5525                                  bool recurse, bool recursing,
5526                                  bool missing_ok, LOCKMODE lockmode)
5527 {
5528         HeapTuple       tuple;
5529         Form_pg_attribute targetatt;
5530         AttrNumber      attnum;
5531         List       *children;
5532         ObjectAddress object;
5533
5534         /* At top level, permission check was done in ATPrepCmd, else do it */
5535         if (recursing)
5536                 ATSimplePermissions(rel, ATT_TABLE);
5537
5538         /*
5539          * get the number of the attribute
5540          */
5541         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5542         if (!HeapTupleIsValid(tuple))
5543         {
5544                 if (!missing_ok)
5545                 {
5546                         ereport(ERROR,
5547                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
5548                                          errmsg("column \"%s\" of relation \"%s\" does not exist",
5549                                                         colName, RelationGetRelationName(rel))));
5550                 }
5551                 else
5552                 {
5553                         ereport(NOTICE,
5554                                         (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
5555                                                         colName, RelationGetRelationName(rel))));
5556                         return;
5557                 }
5558         }
5559         targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
5560
5561         attnum = targetatt->attnum;
5562
5563         /* Can't drop a system attribute, except OID */
5564         if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
5565                 ereport(ERROR,
5566                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5567                                  errmsg("cannot drop system column \"%s\"",
5568                                                 colName)));
5569
5570         /* Don't drop inherited columns */
5571         if (targetatt->attinhcount > 0 && !recursing)
5572                 ereport(ERROR,
5573                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5574                                  errmsg("cannot drop inherited column \"%s\"",
5575                                                 colName)));
5576
5577         ReleaseSysCache(tuple);
5578
5579         /*
5580          * Propagate to children as appropriate.  Unlike most other ALTER
5581          * routines, we have to do this one level of recursion at a time; we can't
5582          * use find_all_inheritors to do it in one pass.
5583          */
5584         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5585
5586         if (children)
5587         {
5588                 Relation        attr_rel;
5589                 ListCell   *child;
5590
5591                 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5592                 foreach(child, children)
5593                 {
5594                         Oid                     childrelid = lfirst_oid(child);
5595                         Relation        childrel;
5596                         Form_pg_attribute childatt;
5597
5598                         /* find_inheritance_children already got lock */
5599                         childrel = heap_open(childrelid, NoLock);
5600                         CheckTableNotInUse(childrel, "ALTER TABLE");
5601
5602                         tuple = SearchSysCacheCopyAttName(childrelid, colName);
5603                         if (!HeapTupleIsValid(tuple))           /* shouldn't happen */
5604                                 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
5605                                          colName, childrelid);
5606                         childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5607
5608                         if (childatt->attinhcount <= 0)         /* shouldn't happen */
5609                                 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
5610                                          childrelid, colName);
5611
5612                         if (recurse)
5613                         {
5614                                 /*
5615                                  * If the child column has other definition sources, just
5616                                  * decrement its inheritance count; if not, recurse to delete
5617                                  * it.
5618                                  */
5619                                 if (childatt->attinhcount == 1 && !childatt->attislocal)
5620                                 {
5621                                         /* Time to delete this child column, too */
5622                                         ATExecDropColumn(wqueue, childrel, colName,
5623                                                                          behavior, true, true,
5624                                                                          false, lockmode);
5625                                 }
5626                                 else
5627                                 {
5628                                         /* Child column must survive my deletion */
5629                                         childatt->attinhcount--;
5630
5631                                         simple_heap_update(attr_rel, &tuple->t_self, tuple);
5632
5633                                         /* keep the system catalog indexes current */
5634                                         CatalogUpdateIndexes(attr_rel, tuple);
5635
5636                                         /* Make update visible */
5637                                         CommandCounterIncrement();
5638                                 }
5639                         }
5640                         else
5641                         {
5642                                 /*
5643                                  * If we were told to drop ONLY in this table (no recursion),
5644                                  * we need to mark the inheritors' attributes as locally
5645                                  * defined rather than inherited.
5646                                  */
5647                                 childatt->attinhcount--;
5648                                 childatt->attislocal = true;
5649
5650                                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5651
5652                                 /* keep the system catalog indexes current */
5653                                 CatalogUpdateIndexes(attr_rel, tuple);
5654
5655                                 /* Make update visible */
5656                                 CommandCounterIncrement();
5657                         }
5658
5659                         heap_freetuple(tuple);
5660
5661                         heap_close(childrel, NoLock);
5662                 }
5663                 heap_close(attr_rel, RowExclusiveLock);
5664         }
5665
5666         /*
5667          * Perform the actual column deletion
5668          */
5669         object.classId = RelationRelationId;
5670         object.objectId = RelationGetRelid(rel);
5671         object.objectSubId = attnum;
5672
5673         performDeletion(&object, behavior, 0);
5674
5675         /*
5676          * If we dropped the OID column, must adjust pg_class.relhasoids and tell
5677          * Phase 3 to physically get rid of the column.  We formerly left the
5678          * column in place physically, but this caused subtle problems.  See
5679          * http://archives.postgresql.org/pgsql-hackers/2009-02/msg00363.php
5680          */
5681         if (attnum == ObjectIdAttributeNumber)
5682         {
5683                 Relation        class_rel;
5684                 Form_pg_class tuple_class;
5685                 AlteredTableInfo *tab;
5686
5687                 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5688
5689                 tuple = SearchSysCacheCopy1(RELOID,
5690                                                                         ObjectIdGetDatum(RelationGetRelid(rel)));
5691                 if (!HeapTupleIsValid(tuple))
5692                         elog(ERROR, "cache lookup failed for relation %u",
5693                                  RelationGetRelid(rel));
5694                 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5695
5696                 tuple_class->relhasoids = false;
5697                 simple_heap_update(class_rel, &tuple->t_self, tuple);
5698
5699                 /* Keep the catalog indexes up to date */
5700                 CatalogUpdateIndexes(class_rel, tuple);
5701
5702                 heap_close(class_rel, RowExclusiveLock);
5703
5704                 /* Find or create work queue entry for this table */
5705                 tab = ATGetQueueEntry(wqueue, rel);
5706
5707                 /* Tell Phase 3 to physically remove the OID column */
5708                 tab->rewrite |= AT_REWRITE_ALTER_OID;
5709         }
5710 }
5711
5712 /*
5713  * ALTER TABLE ADD INDEX
5714  *
5715  * There is no such command in the grammar, but parse_utilcmd.c converts
5716  * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands.  This lets
5717  * us schedule creation of the index at the appropriate time during ALTER.
5718  */
5719 static void
5720 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
5721                            IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
5722 {
5723         bool            check_rights;
5724         bool            skip_build;
5725         bool            quiet;
5726         ObjectAddress address;
5727
5728         Assert(IsA(stmt, IndexStmt));
5729         Assert(!stmt->concurrent);
5730
5731         /* The IndexStmt has already been through transformIndexStmt */
5732         Assert(stmt->transformed);
5733
5734         /* suppress schema rights check when rebuilding existing index */
5735         check_rights = !is_rebuild;
5736         /* skip index build if phase 3 will do it or we're reusing an old one */
5737         skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
5738         /* suppress notices when rebuilding existing index */
5739         quiet = is_rebuild;
5740
5741         address = DefineIndex(RelationGetRelid(rel),
5742                                                   stmt,
5743                                                   InvalidOid,   /* no predefined OID */
5744                                                   true, /* is_alter_table */
5745                                                   check_rights,
5746                                                   skip_build,
5747                                                   quiet);
5748
5749         /*
5750          * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
5751          * index instead of building from scratch.  The DROP of the old edition of
5752          * this index will have scheduled the storage for deletion at commit, so
5753          * cancel that pending deletion.
5754          */
5755         if (OidIsValid(stmt->oldNode))
5756         {
5757                 Relation        irel = index_open(address.objectId, NoLock);
5758
5759                 RelationPreserveStorage(irel->rd_node, true);
5760                 index_close(irel, NoLock);
5761         }
5762 }
5763
5764 /*
5765  * ALTER TABLE ADD CONSTRAINT USING INDEX
5766  */
5767 static void
5768 ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
5769                                                  IndexStmt *stmt, LOCKMODE lockmode)
5770 {
5771         Oid                     index_oid = stmt->indexOid;
5772         Relation        indexRel;
5773         char       *indexName;
5774         IndexInfo  *indexInfo;
5775         char       *constraintName;
5776         char            constraintType;
5777
5778         Assert(IsA(stmt, IndexStmt));
5779         Assert(OidIsValid(index_oid));
5780         Assert(stmt->isconstraint);
5781
5782         indexRel = index_open(index_oid, AccessShareLock);
5783
5784         indexName = pstrdup(RelationGetRelationName(indexRel));
5785
5786         indexInfo = BuildIndexInfo(indexRel);
5787
5788         /* this should have been checked at parse time */
5789         if (!indexInfo->ii_Unique)
5790                 elog(ERROR, "index \"%s\" is not unique", indexName);
5791
5792         /*
5793          * Determine name to assign to constraint.  We require a constraint to
5794          * have the same name as the underlying index; therefore, use the index's
5795          * existing name as the default constraint name, and if the user
5796          * explicitly gives some other name for the constraint, rename the index
5797          * to match.
5798          */
5799         constraintName = stmt->idxname;
5800         if (constraintName == NULL)
5801                 constraintName = indexName;
5802         else if (strcmp(constraintName, indexName) != 0)
5803         {
5804                 ereport(NOTICE,
5805                                 (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
5806                                                 indexName, constraintName)));
5807                 RenameRelationInternal(index_oid, constraintName, false);
5808         }
5809
5810         /* Extra checks needed if making primary key */
5811         if (stmt->primary)
5812                 index_check_primary_key(rel, indexInfo, true);
5813
5814         /* Note we currently don't support EXCLUSION constraints here */
5815         if (stmt->primary)
5816                 constraintType = CONSTRAINT_PRIMARY;
5817         else
5818                 constraintType = CONSTRAINT_UNIQUE;
5819
5820         /* Create the catalog entries for the constraint */
5821         index_constraint_create(rel,
5822                                                         index_oid,
5823                                                         indexInfo,
5824                                                         constraintName,
5825                                                         constraintType,
5826                                                         stmt->deferrable,
5827                                                         stmt->initdeferred,
5828                                                         stmt->primary,
5829                                                         true,           /* update pg_index */
5830                                                         true,           /* remove old dependencies */
5831                                                         allowSystemTableMods,
5832                                                         false);         /* is_internal */
5833
5834         index_close(indexRel, NoLock);
5835 }
5836
5837 /*
5838  * ALTER TABLE ADD CONSTRAINT
5839  */
5840 static void
5841 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5842                                         Constraint *newConstraint, bool recurse, bool is_readd,
5843                                         LOCKMODE lockmode)
5844 {
5845         Assert(IsA(newConstraint, Constraint));
5846
5847         /*
5848          * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
5849          * arriving here (see the preprocessing done in parse_utilcmd.c).  Use a
5850          * switch anyway to make it easier to add more code later.
5851          */
5852         switch (newConstraint->contype)
5853         {
5854                 case CONSTR_CHECK:
5855                         ATAddCheckConstraint(wqueue, tab, rel,
5856                                                                  newConstraint, recurse, false, is_readd,
5857                                                                  lockmode);
5858                         break;
5859
5860                 case CONSTR_FOREIGN:
5861
5862                         /*
5863                          * Note that we currently never recurse for FK constraints, so the
5864                          * "recurse" flag is silently ignored.
5865                          *
5866                          * Assign or validate constraint name
5867                          */
5868                         if (newConstraint->conname)
5869                         {
5870                                 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
5871                                                                                  RelationGetRelid(rel),
5872                                                                                  RelationGetNamespace(rel),
5873                                                                                  newConstraint->conname))
5874                                         ereport(ERROR,
5875                                                         (errcode(ERRCODE_DUPLICATE_OBJECT),
5876                                                          errmsg("constraint \"%s\" for relation \"%s\" already exists",
5877                                                                         newConstraint->conname,
5878                                                                         RelationGetRelationName(rel))));
5879                         }
5880                         else
5881                                 newConstraint->conname =
5882                                         ChooseConstraintName(RelationGetRelationName(rel),
5883                                                                    strVal(linitial(newConstraint->fk_attrs)),
5884                                                                                  "fkey",
5885                                                                                  RelationGetNamespace(rel),
5886                                                                                  NIL);
5887
5888                         ATAddForeignKeyConstraint(tab, rel, newConstraint, lockmode);
5889                         break;
5890
5891                 default:
5892                         elog(ERROR, "unrecognized constraint type: %d",
5893                                  (int) newConstraint->contype);
5894         }
5895 }
5896
5897 /*
5898  * Add a check constraint to a single table and its children
5899  *
5900  * Subroutine for ATExecAddConstraint.
5901  *
5902  * We must recurse to child tables during execution, rather than using
5903  * ALTER TABLE's normal prep-time recursion.  The reason is that all the
5904  * constraints *must* be given the same name, else they won't be seen as
5905  * related later.  If the user didn't explicitly specify a name, then
5906  * AddRelationNewConstraints would normally assign different names to the
5907  * child constraints.  To fix that, we must capture the name assigned at
5908  * the parent table and pass that down.
5909  *
5910  * When re-adding a previously existing constraint (during ALTER COLUMN TYPE),
5911  * we don't need to recurse here, because recursion will be carried out at a
5912  * higher level; the constraint name issue doesn't apply because the names
5913  * have already been assigned and are just being re-used.  We need a separate
5914  * "is_readd" flag for that; just setting recurse=false would result in an
5915  * error if there are child tables.
5916  */
5917 static void
5918 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5919                                          Constraint *constr, bool recurse, bool recursing,
5920                                          bool is_readd, LOCKMODE lockmode)
5921 {
5922         List       *newcons;
5923         ListCell   *lcon;
5924         List       *children;
5925         ListCell   *child;
5926
5927         /* At top level, permission check was done in ATPrepCmd, else do it */
5928         if (recursing)
5929                 ATSimplePermissions(rel, ATT_TABLE);
5930
5931         /*
5932          * Call AddRelationNewConstraints to do the work, making sure it works on
5933          * a copy of the Constraint so transformExpr can't modify the original. It
5934          * returns a list of cooked constraints.
5935          *
5936          * If the constraint ends up getting merged with a pre-existing one, it's
5937          * omitted from the returned list, which is what we want: we do not need
5938          * to do any validation work.  That can only happen at child tables,
5939          * though, since we disallow merging at the top level.
5940          */
5941         newcons = AddRelationNewConstraints(rel, NIL,
5942                                                                                 list_make1(copyObject(constr)),
5943                                                                                 recursing,              /* allow_merge */
5944                                                                                 !recursing,             /* is_local */
5945                                                                                 is_readd);              /* is_internal */
5946
5947         /* Add each to-be-validated constraint to Phase 3's queue */
5948         foreach(lcon, newcons)
5949         {
5950                 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
5951
5952                 if (!ccon->skip_validation)
5953                 {
5954                         NewConstraint *newcon;
5955
5956                         newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
5957                         newcon->name = ccon->name;
5958                         newcon->contype = ccon->contype;
5959                         /* ExecQual wants implicit-AND format */
5960                         newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
5961
5962                         tab->constraints = lappend(tab->constraints, newcon);
5963                 }
5964
5965                 /* Save the actually assigned name if it was defaulted */
5966                 if (constr->conname == NULL)
5967                         constr->conname = ccon->name;
5968         }
5969
5970         /* At this point we must have a locked-down name to use */
5971         Assert(constr->conname != NULL);
5972
5973         /* Advance command counter in case same table is visited multiple times */
5974         CommandCounterIncrement();
5975
5976         /*
5977          * If the constraint got merged with an existing constraint, we're done.
5978          * We mustn't recurse to child tables in this case, because they've
5979          * already got the constraint, and visiting them again would lead to an
5980          * incorrect value for coninhcount.
5981          */
5982         if (newcons == NIL)
5983                 return;
5984
5985         /*
5986          * If adding a NO INHERIT constraint, no need to find our children.
5987          * Likewise, in a re-add operation, we don't need to recurse (that will be
5988          * handled at higher levels).
5989          */
5990         if (constr->is_no_inherit || is_readd)
5991                 return;
5992
5993         /*
5994          * Propagate to children as appropriate.  Unlike most other ALTER
5995          * routines, we have to do this one level of recursion at a time; we can't
5996          * use find_all_inheritors to do it in one pass.
5997          */
5998         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5999
6000         /*
6001          * Check if ONLY was specified with ALTER TABLE.  If so, allow the
6002          * contraint creation only if there are no children currently.  Error out
6003          * otherwise.
6004          */
6005         if (!recurse && children != NIL)
6006                 ereport(ERROR,
6007                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6008                                  errmsg("constraint must be added to child tables too")));
6009
6010         foreach(child, children)
6011         {
6012                 Oid                     childrelid = lfirst_oid(child);
6013                 Relation        childrel;
6014                 AlteredTableInfo *childtab;
6015
6016                 /* find_inheritance_children already got lock */
6017                 childrel = heap_open(childrelid, NoLock);
6018                 CheckTableNotInUse(childrel, "ALTER TABLE");
6019
6020                 /* Find or create work queue entry for this table */
6021                 childtab = ATGetQueueEntry(wqueue, childrel);
6022
6023                 /* Recurse to child */
6024                 ATAddCheckConstraint(wqueue, childtab, childrel,
6025                                                          constr, recurse, true, is_readd, lockmode);
6026
6027                 heap_close(childrel, NoLock);
6028         }
6029 }
6030
6031 /*
6032  * Add a foreign-key constraint to a single table
6033  *
6034  * Subroutine for ATExecAddConstraint.  Must already hold exclusive
6035  * lock on the rel, and have done appropriate validity checks for it.
6036  * We do permissions checks here, however.
6037  */
6038 static void
6039 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
6040                                                   Constraint *fkconstraint, LOCKMODE lockmode)
6041 {
6042         Relation        pkrel;
6043         int16           pkattnum[INDEX_MAX_KEYS];
6044         int16           fkattnum[INDEX_MAX_KEYS];
6045         Oid                     pktypoid[INDEX_MAX_KEYS];
6046         Oid                     fktypoid[INDEX_MAX_KEYS];
6047         Oid                     opclasses[INDEX_MAX_KEYS];
6048         Oid                     pfeqoperators[INDEX_MAX_KEYS];
6049         Oid                     ppeqoperators[INDEX_MAX_KEYS];
6050         Oid                     ffeqoperators[INDEX_MAX_KEYS];
6051         int                     i;
6052         int                     numfks,
6053                                 numpks;
6054         Oid                     indexOid;
6055         Oid                     constrOid;
6056         bool            old_check_ok;
6057         ListCell   *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
6058
6059         /*
6060          * Grab an exclusive lock on the pk table, so that someone doesn't delete
6061          * rows out from under us. (Although a lesser lock would do for that
6062          * purpose, we'll need exclusive lock anyway to add triggers to the pk
6063          * table; trying to start with a lesser lock will just create a risk of
6064          * deadlock.)
6065          */
6066         if (OidIsValid(fkconstraint->old_pktable_oid))
6067                 pkrel = heap_open(fkconstraint->old_pktable_oid, AccessExclusiveLock);
6068         else
6069                 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
6070
6071         /*
6072          * Validity checks (permission checks wait till we have the column
6073          * numbers)
6074          */
6075         if (pkrel->rd_rel->relkind != RELKIND_RELATION)
6076                 ereport(ERROR,
6077                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6078                                  errmsg("referenced relation \"%s\" is not a table",
6079                                                 RelationGetRelationName(pkrel))));
6080
6081         if (!allowSystemTableMods && IsSystemRelation(pkrel))
6082                 ereport(ERROR,
6083                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6084                                  errmsg("permission denied: \"%s\" is a system catalog",
6085                                                 RelationGetRelationName(pkrel))));
6086
6087         /*
6088          * References from permanent or unlogged tables to temp tables, and from
6089          * permanent tables to unlogged tables, are disallowed because the
6090          * referenced data can vanish out from under us.  References from temp
6091          * tables to any other table type are also disallowed, because other
6092          * backends might need to run the RI triggers on the perm table, but they
6093          * can't reliably see tuples in the local buffers of other backends.
6094          */
6095         switch (rel->rd_rel->relpersistence)
6096         {
6097                 case RELPERSISTENCE_PERMANENT:
6098                         if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
6099                                 ereport(ERROR,
6100                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6101                                                  errmsg("constraints on permanent tables may reference only permanent tables")));
6102                         break;
6103                 case RELPERSISTENCE_UNLOGGED:
6104                         if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
6105                                 && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
6106                                 ereport(ERROR,
6107                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6108                                                  errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
6109                         break;
6110                 case RELPERSISTENCE_TEMP:
6111                         if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
6112                                 ereport(ERROR,
6113                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6114                                                  errmsg("constraints on temporary tables may reference only temporary tables")));
6115                         if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
6116                                 ereport(ERROR,
6117                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6118                                                  errmsg("constraints on temporary tables must involve temporary tables of this session")));
6119                         break;
6120         }
6121
6122         /*
6123          * Look up the referencing attributes to make sure they exist, and record
6124          * their attnums and type OIDs.
6125          */
6126         MemSet(pkattnum, 0, sizeof(pkattnum));
6127         MemSet(fkattnum, 0, sizeof(fkattnum));
6128         MemSet(pktypoid, 0, sizeof(pktypoid));
6129         MemSet(fktypoid, 0, sizeof(fktypoid));
6130         MemSet(opclasses, 0, sizeof(opclasses));
6131         MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
6132         MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
6133         MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
6134
6135         numfks = transformColumnNameList(RelationGetRelid(rel),
6136                                                                          fkconstraint->fk_attrs,
6137                                                                          fkattnum, fktypoid);
6138
6139         /*
6140          * If the attribute list for the referenced table was omitted, lookup the
6141          * definition of the primary key and use it.  Otherwise, validate the
6142          * supplied attribute list.  In either case, discover the index OID and
6143          * index opclasses, and the attnums and type OIDs of the attributes.
6144          */
6145         if (fkconstraint->pk_attrs == NIL)
6146         {
6147                 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
6148                                                                                         &fkconstraint->pk_attrs,
6149                                                                                         pkattnum, pktypoid,
6150                                                                                         opclasses);
6151         }
6152         else
6153         {
6154                 numpks = transformColumnNameList(RelationGetRelid(pkrel),
6155                                                                                  fkconstraint->pk_attrs,
6156                                                                                  pkattnum, pktypoid);
6157                 /* Look for an index matching the column list */
6158                 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
6159                                                                                    opclasses);
6160         }
6161
6162         /*
6163          * Now we can check permissions.
6164          */
6165         checkFkeyPermissions(pkrel, pkattnum, numpks);
6166         checkFkeyPermissions(rel, fkattnum, numfks);
6167
6168         /*
6169          * Look up the equality operators to use in the constraint.
6170          *
6171          * Note that we have to be careful about the difference between the actual
6172          * PK column type and the opclass' declared input type, which might be
6173          * only binary-compatible with it.  The declared opcintype is the right
6174          * thing to probe pg_amop with.
6175          */
6176         if (numfks != numpks)
6177                 ereport(ERROR,
6178                                 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6179                                  errmsg("number of referencing and referenced columns for foreign key disagree")));
6180
6181         /*
6182          * On the strength of a previous constraint, we might avoid scanning
6183          * tables to validate this one.  See below.
6184          */
6185         old_check_ok = (fkconstraint->old_conpfeqop != NIL);
6186         Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
6187
6188         for (i = 0; i < numpks; i++)
6189         {
6190                 Oid                     pktype = pktypoid[i];
6191                 Oid                     fktype = fktypoid[i];
6192                 Oid                     fktyped;
6193                 HeapTuple       cla_ht;
6194                 Form_pg_opclass cla_tup;
6195                 Oid                     amid;
6196                 Oid                     opfamily;
6197                 Oid                     opcintype;
6198                 Oid                     pfeqop;
6199                 Oid                     ppeqop;
6200                 Oid                     ffeqop;
6201                 int16           eqstrategy;
6202                 Oid                     pfeqop_right;
6203
6204                 /* We need several fields out of the pg_opclass entry */
6205                 cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
6206                 if (!HeapTupleIsValid(cla_ht))
6207                         elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
6208                 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
6209                 amid = cla_tup->opcmethod;
6210                 opfamily = cla_tup->opcfamily;
6211                 opcintype = cla_tup->opcintype;
6212                 ReleaseSysCache(cla_ht);
6213
6214                 /*
6215                  * Check it's a btree; currently this can never fail since no other
6216                  * index AMs support unique indexes.  If we ever did have other types
6217                  * of unique indexes, we'd need a way to determine which operator
6218                  * strategy number is equality.  (Is it reasonable to insist that
6219                  * every such index AM use btree's number for equality?)
6220                  */
6221                 if (amid != BTREE_AM_OID)
6222                         elog(ERROR, "only b-tree indexes are supported for foreign keys");
6223                 eqstrategy = BTEqualStrategyNumber;
6224
6225                 /*
6226                  * There had better be a primary equality operator for the index.
6227                  * We'll use it for PK = PK comparisons.
6228                  */
6229                 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
6230                                                                          eqstrategy);
6231
6232                 if (!OidIsValid(ppeqop))
6233                         elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
6234                                  eqstrategy, opcintype, opcintype, opfamily);
6235
6236                 /*
6237                  * Are there equality operators that take exactly the FK type? Assume
6238                  * we should look through any domain here.
6239                  */
6240                 fktyped = getBaseType(fktype);
6241
6242                 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
6243                                                                          eqstrategy);
6244                 if (OidIsValid(pfeqop))
6245                 {
6246                         pfeqop_right = fktyped;
6247                         ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
6248                                                                                  eqstrategy);
6249                 }
6250                 else
6251                 {
6252                         /* keep compiler quiet */
6253                         pfeqop_right = InvalidOid;
6254                         ffeqop = InvalidOid;
6255                 }
6256
6257                 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6258                 {
6259                         /*
6260                          * Otherwise, look for an implicit cast from the FK type to the
6261                          * opcintype, and if found, use the primary equality operator.
6262                          * This is a bit tricky because opcintype might be a polymorphic
6263                          * type such as ANYARRAY or ANYENUM; so what we have to test is
6264                          * whether the two actual column types can be concurrently cast to
6265                          * that type.  (Otherwise, we'd fail to reject combinations such
6266                          * as int[] and point[].)
6267                          */
6268                         Oid                     input_typeids[2];
6269                         Oid                     target_typeids[2];
6270
6271                         input_typeids[0] = pktype;
6272                         input_typeids[1] = fktype;
6273                         target_typeids[0] = opcintype;
6274                         target_typeids[1] = opcintype;
6275                         if (can_coerce_type(2, input_typeids, target_typeids,
6276                                                                 COERCION_IMPLICIT))
6277                         {
6278                                 pfeqop = ffeqop = ppeqop;
6279                                 pfeqop_right = opcintype;
6280                         }
6281                 }
6282
6283                 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6284                         ereport(ERROR,
6285                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
6286                                          errmsg("foreign key constraint \"%s\" "
6287                                                         "cannot be implemented",
6288                                                         fkconstraint->conname),
6289                                          errdetail("Key columns \"%s\" and \"%s\" "
6290                                                            "are of incompatible types: %s and %s.",
6291                                                            strVal(list_nth(fkconstraint->fk_attrs, i)),
6292                                                            strVal(list_nth(fkconstraint->pk_attrs, i)),
6293                                                            format_type_be(fktype),
6294                                                            format_type_be(pktype))));
6295
6296                 if (old_check_ok)
6297                 {
6298                         /*
6299                          * When a pfeqop changes, revalidate the constraint.  We could
6300                          * permit intra-opfamily changes, but that adds subtle complexity
6301                          * without any concrete benefit for core types.  We need not
6302                          * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
6303                          */
6304                         old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
6305                         old_pfeqop_item = lnext(old_pfeqop_item);
6306                 }
6307                 if (old_check_ok)
6308                 {
6309                         Oid                     old_fktype;
6310                         Oid                     new_fktype;
6311                         CoercionPathType old_pathtype;
6312                         CoercionPathType new_pathtype;
6313                         Oid                     old_castfunc;
6314                         Oid                     new_castfunc;
6315
6316                         /*
6317                          * Identify coercion pathways from each of the old and new FK-side
6318                          * column types to the right (foreign) operand type of the pfeqop.
6319                          * We may assume that pg_constraint.conkey is not changing.
6320                          */
6321                         old_fktype = tab->oldDesc->attrs[fkattnum[i] - 1]->atttypid;
6322                         new_fktype = fktype;
6323                         old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
6324                                                                                 &old_castfunc);
6325                         new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
6326                                                                                 &new_castfunc);
6327
6328                         /*
6329                          * Upon a change to the cast from the FK column to its pfeqop
6330                          * operand, revalidate the constraint.  For this evaluation, a
6331                          * binary coercion cast is equivalent to no cast at all.  While
6332                          * type implementors should design implicit casts with an eye
6333                          * toward consistency of operations like equality, we cannot
6334                          * assume here that they have done so.
6335                          *
6336                          * A function with a polymorphic argument could change behavior
6337                          * arbitrarily in response to get_fn_expr_argtype().  Therefore,
6338                          * when the cast destination is polymorphic, we only avoid
6339                          * revalidation if the input type has not changed at all.  Given
6340                          * just the core data types and operator classes, this requirement
6341                          * prevents no would-be optimizations.
6342                          *
6343                          * If the cast converts from a base type to a domain thereon, then
6344                          * that domain type must be the opcintype of the unique index.
6345                          * Necessarily, the primary key column must then be of the domain
6346                          * type.  Since the constraint was previously valid, all values on
6347                          * the foreign side necessarily exist on the primary side and in
6348                          * turn conform to the domain.  Consequently, we need not treat
6349                          * domains specially here.
6350                          *
6351                          * Since we require that all collations share the same notion of
6352                          * equality (which they do, because texteq reduces to bitwise
6353                          * equality), we don't compare collation here.
6354                          *
6355                          * We need not directly consider the PK type.  It's necessarily
6356                          * binary coercible to the opcintype of the unique index column,
6357                          * and ri_triggers.c will only deal with PK datums in terms of
6358                          * that opcintype.  Changing the opcintype also changes pfeqop.
6359                          */
6360                         old_check_ok = (new_pathtype == old_pathtype &&
6361                                                         new_castfunc == old_castfunc &&
6362                                                         (!IsPolymorphicType(pfeqop_right) ||
6363                                                          new_fktype == old_fktype));
6364
6365                 }
6366
6367                 pfeqoperators[i] = pfeqop;
6368                 ppeqoperators[i] = ppeqop;
6369                 ffeqoperators[i] = ffeqop;
6370         }
6371
6372         /*
6373          * Record the FK constraint in pg_constraint.
6374          */
6375         constrOid = CreateConstraintEntry(fkconstraint->conname,
6376                                                                           RelationGetNamespace(rel),
6377                                                                           CONSTRAINT_FOREIGN,
6378                                                                           fkconstraint->deferrable,
6379                                                                           fkconstraint->initdeferred,
6380                                                                           fkconstraint->initially_valid,
6381                                                                           RelationGetRelid(rel),
6382                                                                           fkattnum,
6383                                                                           numfks,
6384                                                                           InvalidOid,           /* not a domain
6385                                                                                                                  * constraint */
6386                                                                           indexOid,
6387                                                                           RelationGetRelid(pkrel),
6388                                                                           pkattnum,
6389                                                                           pfeqoperators,
6390                                                                           ppeqoperators,
6391                                                                           ffeqoperators,
6392                                                                           numpks,
6393                                                                           fkconstraint->fk_upd_action,
6394                                                                           fkconstraint->fk_del_action,
6395                                                                           fkconstraint->fk_matchtype,
6396                                                                           NULL,         /* no exclusion constraint */
6397                                                                           NULL,         /* no check constraint */
6398                                                                           NULL,
6399                                                                           NULL,
6400                                                                           true,         /* islocal */
6401                                                                           0,            /* inhcount */
6402                                                                           true,         /* isnoinherit */
6403                                                                           false);       /* is_internal */
6404
6405         /*
6406          * Create the triggers that will enforce the constraint.
6407          */
6408         createForeignKeyTriggers(rel, RelationGetRelid(pkrel), fkconstraint,
6409                                                          constrOid, indexOid);
6410
6411         /*
6412          * Tell Phase 3 to check that the constraint is satisfied by existing
6413          * rows. We can skip this during table creation, when requested explicitly
6414          * by specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
6415          * recreating a constraint following a SET DATA TYPE operation that did
6416          * not impugn its validity.
6417          */
6418         if (!old_check_ok && !fkconstraint->skip_validation)
6419         {
6420                 NewConstraint *newcon;
6421
6422                 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
6423                 newcon->name = fkconstraint->conname;
6424                 newcon->contype = CONSTR_FOREIGN;
6425                 newcon->refrelid = RelationGetRelid(pkrel);
6426                 newcon->refindid = indexOid;
6427                 newcon->conid = constrOid;
6428                 newcon->qual = (Node *) fkconstraint;
6429
6430                 tab->constraints = lappend(tab->constraints, newcon);
6431         }
6432
6433         /*
6434          * Close pk table, but keep lock until we've committed.
6435          */
6436         heap_close(pkrel, NoLock);
6437 }
6438
6439 /*
6440  * ALTER TABLE ALTER CONSTRAINT
6441  *
6442  * Update the attributes of a constraint.
6443  *
6444  * Currently only works for Foreign Key constraints.
6445  * Foreign keys do not inherit, so we purposely ignore the
6446  * recursion bit here, but we keep the API the same for when
6447  * other constraint types are supported.
6448  */
6449 static void
6450 ATExecAlterConstraint(Relation rel, AlterTableCmd *cmd,
6451                                           bool recurse, bool recursing, LOCKMODE lockmode)
6452 {
6453         Relation        conrel;
6454         SysScanDesc scan;
6455         ScanKeyData key;
6456         HeapTuple       contuple;
6457         Form_pg_constraint currcon = NULL;
6458         Constraint *cmdcon = NULL;
6459         bool            found = false;
6460
6461         Assert(IsA(cmd->def, Constraint));
6462         cmdcon = (Constraint *) cmd->def;
6463
6464         conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6465
6466         /*
6467          * Find and check the target constraint
6468          */
6469         ScanKeyInit(&key,
6470                                 Anum_pg_constraint_conrelid,
6471                                 BTEqualStrategyNumber, F_OIDEQ,
6472                                 ObjectIdGetDatum(RelationGetRelid(rel)));
6473         scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6474                                                           true, NULL, 1, &key);
6475
6476         while (HeapTupleIsValid(contuple = systable_getnext(scan)))
6477         {
6478                 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
6479                 if (strcmp(NameStr(currcon->conname), cmdcon->conname) == 0)
6480                 {
6481                         found = true;
6482                         break;
6483                 }
6484         }
6485
6486         if (!found)
6487                 ereport(ERROR,
6488                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6489                                  errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6490                                                 cmdcon->conname, RelationGetRelationName(rel))));
6491
6492         if (currcon->contype != CONSTRAINT_FOREIGN)
6493                 ereport(ERROR,
6494                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6495                                  errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
6496                                                 cmdcon->conname, RelationGetRelationName(rel))));
6497
6498         if (currcon->condeferrable != cmdcon->deferrable ||
6499                 currcon->condeferred != cmdcon->initdeferred)
6500         {
6501                 HeapTuple       copyTuple;
6502                 HeapTuple       tgtuple;
6503                 Form_pg_constraint copy_con;
6504                 Form_pg_trigger copy_tg;
6505                 ScanKeyData tgkey;
6506                 SysScanDesc tgscan;
6507                 Relation        tgrel;
6508
6509                 /*
6510                  * Now update the catalog, while we have the door open.
6511                  */
6512                 copyTuple = heap_copytuple(contuple);
6513                 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
6514                 copy_con->condeferrable = cmdcon->deferrable;
6515                 copy_con->condeferred = cmdcon->initdeferred;
6516                 simple_heap_update(conrel, &copyTuple->t_self, copyTuple);
6517                 CatalogUpdateIndexes(conrel, copyTuple);
6518
6519                 InvokeObjectPostAlterHook(ConstraintRelationId,
6520                                                                   HeapTupleGetOid(contuple), 0);
6521
6522                 heap_freetuple(copyTuple);
6523
6524                 /*
6525                  * Now we need to update the multiple entries in pg_trigger that
6526                  * implement the constraint.
6527                  */
6528                 tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
6529
6530                 ScanKeyInit(&tgkey,
6531                                         Anum_pg_trigger_tgconstraint,
6532                                         BTEqualStrategyNumber, F_OIDEQ,
6533                                         ObjectIdGetDatum(HeapTupleGetOid(contuple)));
6534
6535                 tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
6536                                                                         NULL, 1, &tgkey);
6537
6538                 while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
6539                 {
6540                         copyTuple = heap_copytuple(tgtuple);
6541                         copy_tg = (Form_pg_trigger) GETSTRUCT(copyTuple);
6542                         copy_tg->tgdeferrable = cmdcon->deferrable;
6543                         copy_tg->tginitdeferred = cmdcon->initdeferred;
6544                         simple_heap_update(tgrel, &copyTuple->t_self, copyTuple);
6545                         CatalogUpdateIndexes(tgrel, copyTuple);
6546
6547                         InvokeObjectPostAlterHook(TriggerRelationId,
6548                                                                           HeapTupleGetOid(tgtuple), 0);
6549
6550                         heap_freetuple(copyTuple);
6551                 }
6552
6553                 systable_endscan(tgscan);
6554
6555                 heap_close(tgrel, RowExclusiveLock);
6556
6557                 /*
6558                  * Invalidate relcache so that others see the new attributes.
6559                  */
6560                 CacheInvalidateRelcache(rel);
6561         }
6562
6563         systable_endscan(scan);
6564
6565         heap_close(conrel, RowExclusiveLock);
6566 }
6567
6568 /*
6569  * ALTER TABLE VALIDATE CONSTRAINT
6570  *
6571  * XXX The reason we handle recursion here rather than at Phase 1 is because
6572  * there's no good way to skip recursing when handling foreign keys: there is
6573  * no need to lock children in that case, yet we wouldn't be able to avoid
6574  * doing so at that level.
6575  */
6576 static void
6577 ATExecValidateConstraint(Relation rel, char *constrName, bool recurse,
6578                                                  bool recursing, LOCKMODE lockmode)
6579 {
6580         Relation        conrel;
6581         SysScanDesc scan;
6582         ScanKeyData key;
6583         HeapTuple       tuple;
6584         Form_pg_constraint con = NULL;
6585         bool            found = false;
6586
6587         conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6588
6589         /*
6590          * Find and check the target constraint
6591          */
6592         ScanKeyInit(&key,
6593                                 Anum_pg_constraint_conrelid,
6594                                 BTEqualStrategyNumber, F_OIDEQ,
6595                                 ObjectIdGetDatum(RelationGetRelid(rel)));
6596         scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6597                                                           true, NULL, 1, &key);
6598
6599         while (HeapTupleIsValid(tuple = systable_getnext(scan)))
6600         {
6601                 con = (Form_pg_constraint) GETSTRUCT(tuple);
6602                 if (strcmp(NameStr(con->conname), constrName) == 0)
6603                 {
6604                         found = true;
6605                         break;
6606                 }
6607         }
6608
6609         if (!found)
6610                 ereport(ERROR,
6611                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6612                                  errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6613                                                 constrName, RelationGetRelationName(rel))));
6614
6615         if (con->contype != CONSTRAINT_FOREIGN &&
6616                 con->contype != CONSTRAINT_CHECK)
6617                 ereport(ERROR,
6618                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6619                                  errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key or check constraint",
6620                                                 constrName, RelationGetRelationName(rel))));
6621
6622         if (!con->convalidated)
6623         {
6624                 HeapTuple       copyTuple;
6625                 Form_pg_constraint copy_con;
6626
6627                 if (con->contype == CONSTRAINT_FOREIGN)
6628                 {
6629                         Oid                     conid = HeapTupleGetOid(tuple);
6630                         Relation        refrel;
6631
6632                         /*
6633                          * Triggers are already in place on both tables, so a concurrent
6634                          * write that alters the result here is not possible. Normally we
6635                          * can run a query here to do the validation, which would only
6636                          * require AccessShareLock. In some cases, it is possible that we
6637                          * might need to fire triggers to perform the check, so we take a
6638                          * lock at RowShareLock level just in case.
6639                          */
6640                         refrel = heap_open(con->confrelid, RowShareLock);
6641
6642                         validateForeignKeyConstraint(constrName, rel, refrel,
6643                                                                                  con->conindid,
6644                                                                                  conid);
6645                         heap_close(refrel, NoLock);
6646
6647                         /*
6648                          * Foreign keys do not inherit, so we purposely ignore the
6649                          * recursion bit here
6650                          */
6651                 }
6652                 else if (con->contype == CONSTRAINT_CHECK)
6653                 {
6654                         List       *children = NIL;
6655                         ListCell   *child;
6656
6657                         /*
6658                          * If we're recursing, the parent has already done this, so skip
6659                          * it.
6660                          */
6661                         if (!recursing)
6662                                 children = find_all_inheritors(RelationGetRelid(rel),
6663                                                                                            lockmode, NULL);
6664
6665                         /*
6666                          * For CHECK constraints, we must ensure that we only mark the
6667                          * constraint as validated on the parent if it's already validated
6668                          * on the children.
6669                          *
6670                          * We recurse before validating on the parent, to reduce risk of
6671                          * deadlocks.
6672                          */
6673                         foreach(child, children)
6674                         {
6675                                 Oid                     childoid = lfirst_oid(child);
6676                                 Relation        childrel;
6677
6678                                 if (childoid == RelationGetRelid(rel))
6679                                         continue;
6680
6681                                 /*
6682                                  * If we are told not to recurse, there had better not be any
6683                                  * child tables; else the addition would put them out of step.
6684                                  */
6685                                 if (!recurse)
6686                                         ereport(ERROR,
6687                                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6688                                                          errmsg("constraint must be validated on child tables too")));
6689
6690                                 /* find_all_inheritors already got lock */
6691                                 childrel = heap_open(childoid, NoLock);
6692
6693                                 ATExecValidateConstraint(childrel, constrName, false,
6694                                                                                  true, lockmode);
6695                                 heap_close(childrel, NoLock);
6696                         }
6697
6698                         validateCheckConstraint(rel, tuple);
6699
6700                         /*
6701                          * Invalidate relcache so that others see the new validated
6702                          * constraint.
6703                          */
6704                         CacheInvalidateRelcache(rel);
6705                 }
6706
6707                 /*
6708                  * Now update the catalog, while we have the door open.
6709                  */
6710                 copyTuple = heap_copytuple(tuple);
6711                 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
6712                 copy_con->convalidated = true;
6713                 simple_heap_update(conrel, &copyTuple->t_self, copyTuple);
6714                 CatalogUpdateIndexes(conrel, copyTuple);
6715
6716                 InvokeObjectPostAlterHook(ConstraintRelationId,
6717                                                                   HeapTupleGetOid(tuple), 0);
6718
6719                 heap_freetuple(copyTuple);
6720         }
6721
6722         systable_endscan(scan);
6723
6724         heap_close(conrel, RowExclusiveLock);
6725 }
6726
6727
6728 /*
6729  * transformColumnNameList - transform list of column names
6730  *
6731  * Lookup each name and return its attnum and type OID
6732  */
6733 static int
6734 transformColumnNameList(Oid relId, List *colList,
6735                                                 int16 *attnums, Oid *atttypids)
6736 {
6737         ListCell   *l;
6738         int                     attnum;
6739
6740         attnum = 0;
6741         foreach(l, colList)
6742         {
6743                 char       *attname = strVal(lfirst(l));
6744                 HeapTuple       atttuple;
6745
6746                 atttuple = SearchSysCacheAttName(relId, attname);
6747                 if (!HeapTupleIsValid(atttuple))
6748                         ereport(ERROR,
6749                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
6750                                          errmsg("column \"%s\" referenced in foreign key constraint does not exist",
6751                                                         attname)));
6752                 if (attnum >= INDEX_MAX_KEYS)
6753                         ereport(ERROR,
6754                                         (errcode(ERRCODE_TOO_MANY_COLUMNS),
6755                                          errmsg("cannot have more than %d keys in a foreign key",
6756                                                         INDEX_MAX_KEYS)));
6757                 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
6758                 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
6759                 ReleaseSysCache(atttuple);
6760                 attnum++;
6761         }
6762
6763         return attnum;
6764 }
6765
6766 /*
6767  * transformFkeyGetPrimaryKey -
6768  *
6769  *      Look up the names, attnums, and types of the primary key attributes
6770  *      for the pkrel.  Also return the index OID and index opclasses of the
6771  *      index supporting the primary key.
6772  *
6773  *      All parameters except pkrel are output parameters.  Also, the function
6774  *      return value is the number of attributes in the primary key.
6775  *
6776  *      Used when the column list in the REFERENCES specification is omitted.
6777  */
6778 static int
6779 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
6780                                                    List **attnamelist,
6781                                                    int16 *attnums, Oid *atttypids,
6782                                                    Oid *opclasses)
6783 {
6784         List       *indexoidlist;
6785         ListCell   *indexoidscan;
6786         HeapTuple       indexTuple = NULL;
6787         Form_pg_index indexStruct = NULL;
6788         Datum           indclassDatum;
6789         bool            isnull;
6790         oidvector  *indclass;
6791         int                     i;
6792
6793         /*
6794          * Get the list of index OIDs for the table from the relcache, and look up
6795          * each one in the pg_index syscache until we find one marked primary key
6796          * (hopefully there isn't more than one such).  Insist it's valid, too.
6797          */
6798         *indexOid = InvalidOid;
6799
6800         indexoidlist = RelationGetIndexList(pkrel);
6801
6802         foreach(indexoidscan, indexoidlist)
6803         {
6804                 Oid                     indexoid = lfirst_oid(indexoidscan);
6805
6806                 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6807                 if (!HeapTupleIsValid(indexTuple))
6808                         elog(ERROR, "cache lookup failed for index %u", indexoid);
6809                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6810                 if (indexStruct->indisprimary && IndexIsValid(indexStruct))
6811                 {
6812                         /*
6813                          * Refuse to use a deferrable primary key.  This is per SQL spec,
6814                          * and there would be a lot of interesting semantic problems if we
6815                          * tried to allow it.
6816                          */
6817                         if (!indexStruct->indimmediate)
6818                                 ereport(ERROR,
6819                                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6820                                                  errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
6821                                                                 RelationGetRelationName(pkrel))));
6822
6823                         *indexOid = indexoid;
6824                         break;
6825                 }
6826                 ReleaseSysCache(indexTuple);
6827         }
6828
6829         list_free(indexoidlist);
6830
6831         /*
6832          * Check that we found it
6833          */
6834         if (!OidIsValid(*indexOid))
6835                 ereport(ERROR,
6836                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6837                                  errmsg("there is no primary key for referenced table \"%s\"",
6838                                                 RelationGetRelationName(pkrel))));
6839
6840         /* Must get indclass the hard way */
6841         indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6842                                                                         Anum_pg_index_indclass, &isnull);
6843         Assert(!isnull);
6844         indclass = (oidvector *) DatumGetPointer(indclassDatum);
6845
6846         /*
6847          * Now build the list of PK attributes from the indkey definition (we
6848          * assume a primary key cannot have expressional elements)
6849          */
6850         *attnamelist = NIL;
6851         for (i = 0; i < indexStruct->indnatts; i++)
6852         {
6853                 int                     pkattno = indexStruct->indkey.values[i];
6854
6855                 attnums[i] = pkattno;
6856                 atttypids[i] = attnumTypeId(pkrel, pkattno);
6857                 opclasses[i] = indclass->values[i];
6858                 *attnamelist = lappend(*attnamelist,
6859                            makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
6860         }
6861
6862         ReleaseSysCache(indexTuple);
6863
6864         return i;
6865 }
6866
6867 /*
6868  * transformFkeyCheckAttrs -
6869  *
6870  *      Make sure that the attributes of a referenced table belong to a unique
6871  *      (or primary key) constraint.  Return the OID of the index supporting
6872  *      the constraint, as well as the opclasses associated with the index
6873  *      columns.
6874  */
6875 static Oid
6876 transformFkeyCheckAttrs(Relation pkrel,
6877                                                 int numattrs, int16 *attnums,
6878                                                 Oid *opclasses) /* output parameter */
6879 {
6880         Oid                     indexoid = InvalidOid;
6881         bool            found = false;
6882         bool            found_deferrable = false;
6883         List       *indexoidlist;
6884         ListCell   *indexoidscan;
6885         int                     i,
6886                                 j;
6887
6888         /*
6889          * Reject duplicate appearances of columns in the referenced-columns list.
6890          * Such a case is forbidden by the SQL standard, and even if we thought it
6891          * useful to allow it, there would be ambiguity about how to match the
6892          * list to unique indexes (in particular, it'd be unclear which index
6893          * opclass goes with which FK column).
6894          */
6895         for (i = 0; i < numattrs; i++)
6896         {
6897                 for (j = i + 1; j < numattrs; j++)
6898                 {
6899                         if (attnums[i] == attnums[j])
6900                                 ereport(ERROR,
6901                                                 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6902                                                  errmsg("foreign key referenced-columns list must not contain duplicates")));
6903                 }
6904         }
6905
6906         /*
6907          * Get the list of index OIDs for the table from the relcache, and look up
6908          * each one in the pg_index syscache, and match unique indexes to the list
6909          * of attnums we are given.
6910          */
6911         indexoidlist = RelationGetIndexList(pkrel);
6912
6913         foreach(indexoidscan, indexoidlist)
6914         {
6915                 HeapTuple       indexTuple;
6916                 Form_pg_index indexStruct;
6917
6918                 indexoid = lfirst_oid(indexoidscan);
6919                 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6920                 if (!HeapTupleIsValid(indexTuple))
6921                         elog(ERROR, "cache lookup failed for index %u", indexoid);
6922                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6923
6924                 /*
6925                  * Must have the right number of columns; must be unique and not a
6926                  * partial index; forget it if there are any expressions, too. Invalid
6927                  * indexes are out as well.
6928                  */
6929                 if (indexStruct->indnatts == numattrs &&
6930                         indexStruct->indisunique &&
6931                         IndexIsValid(indexStruct) &&
6932                         heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
6933                         heap_attisnull(indexTuple, Anum_pg_index_indexprs))
6934                 {
6935                         Datum           indclassDatum;
6936                         bool            isnull;
6937                         oidvector  *indclass;
6938
6939                         /* Must get indclass the hard way */
6940                         indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6941                                                                                         Anum_pg_index_indclass, &isnull);
6942                         Assert(!isnull);
6943                         indclass = (oidvector *) DatumGetPointer(indclassDatum);
6944
6945                         /*
6946                          * The given attnum list may match the index columns in any order.
6947                          * Check for a match, and extract the appropriate opclasses while
6948                          * we're at it.
6949                          *
6950                          * We know that attnums[] is duplicate-free per the test at the
6951                          * start of this function, and we checked above that the number of
6952                          * index columns agrees, so if we find a match for each attnums[]
6953                          * entry then we must have a one-to-one match in some order.
6954                          */
6955                         for (i = 0; i < numattrs; i++)
6956                         {
6957                                 found = false;
6958                                 for (j = 0; j < numattrs; j++)
6959                                 {
6960                                         if (attnums[i] == indexStruct->indkey.values[j])
6961                                         {
6962                                                 opclasses[i] = indclass->values[j];
6963                                                 found = true;
6964                                                 break;
6965                                         }
6966                                 }
6967                                 if (!found)
6968                                         break;
6969                         }
6970
6971                         /*
6972                          * Refuse to use a deferrable unique/primary key.  This is per SQL
6973                          * spec, and there would be a lot of interesting semantic problems
6974                          * if we tried to allow it.
6975                          */
6976                         if (found && !indexStruct->indimmediate)
6977                         {
6978                                 /*
6979                                  * Remember that we found an otherwise matching index, so that
6980                                  * we can generate a more appropriate error message.
6981                                  */
6982                                 found_deferrable = true;
6983                                 found = false;
6984                         }
6985                 }
6986                 ReleaseSysCache(indexTuple);
6987                 if (found)
6988                         break;
6989         }
6990
6991         if (!found)
6992         {
6993                 if (found_deferrable)
6994                         ereport(ERROR,
6995                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6996                                          errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
6997                                                         RelationGetRelationName(pkrel))));
6998                 else
6999                         ereport(ERROR,
7000                                         (errcode(ERRCODE_INVALID_FOREIGN_KEY),
7001                                          errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
7002                                                         RelationGetRelationName(pkrel))));
7003         }
7004
7005         list_free(indexoidlist);
7006
7007         return indexoid;
7008 }
7009
7010 /*
7011  * findFkeyCast -
7012  *
7013  *      Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
7014  *      Caller has equal regard for binary coercibility and for an exact match.
7015 */
7016 static CoercionPathType
7017 findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
7018 {
7019         CoercionPathType ret;
7020
7021         if (targetTypeId == sourceTypeId)
7022         {
7023                 ret = COERCION_PATH_RELABELTYPE;
7024                 *funcid = InvalidOid;
7025         }
7026         else
7027         {
7028                 ret = find_coercion_pathway(targetTypeId, sourceTypeId,
7029                                                                         COERCION_IMPLICIT, funcid);
7030                 if (ret == COERCION_PATH_NONE)
7031                         /* A previously-relied-upon cast is now gone. */
7032                         elog(ERROR, "could not find cast from %u to %u",
7033                                  sourceTypeId, targetTypeId);
7034         }
7035
7036         return ret;
7037 }
7038
7039 /* Permissions checks for ADD FOREIGN KEY */
7040 static void
7041 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
7042 {
7043         Oid                     roleid = GetUserId();
7044         AclResult       aclresult;
7045         int                     i;
7046
7047         /* Okay if we have relation-level REFERENCES permission */
7048         aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
7049                                                                   ACL_REFERENCES);
7050         if (aclresult == ACLCHECK_OK)
7051                 return;
7052         /* Else we must have REFERENCES on each column */
7053         for (i = 0; i < natts; i++)
7054         {
7055                 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
7056                                                                                   roleid, ACL_REFERENCES);
7057                 if (aclresult != ACLCHECK_OK)
7058                         aclcheck_error(aclresult, ACL_KIND_CLASS,
7059                                                    RelationGetRelationName(rel));
7060         }
7061 }
7062
7063 /*
7064  * Scan the existing rows in a table to verify they meet a proposed
7065  * CHECK constraint.
7066  *
7067  * The caller must have opened and locked the relation appropriately.
7068  */
7069 static void
7070 validateCheckConstraint(Relation rel, HeapTuple constrtup)
7071 {
7072         EState     *estate;
7073         Datum           val;
7074         char       *conbin;
7075         Expr       *origexpr;
7076         List       *exprstate;
7077         TupleDesc       tupdesc;
7078         HeapScanDesc scan;
7079         HeapTuple       tuple;
7080         ExprContext *econtext;
7081         MemoryContext oldcxt;
7082         TupleTableSlot *slot;
7083         Form_pg_constraint constrForm;
7084         bool            isnull;
7085         Snapshot        snapshot;
7086
7087         constrForm = (Form_pg_constraint) GETSTRUCT(constrtup);
7088
7089         estate = CreateExecutorState();
7090
7091         /*
7092          * XXX this tuple doesn't really come from a syscache, but this doesn't
7093          * matter to SysCacheGetAttr, because it only wants to be able to fetch
7094          * the tupdesc
7095          */
7096         val = SysCacheGetAttr(CONSTROID, constrtup, Anum_pg_constraint_conbin,
7097                                                   &isnull);
7098         if (isnull)
7099                 elog(ERROR, "null conbin for constraint %u",
7100                          HeapTupleGetOid(constrtup));
7101         conbin = TextDatumGetCString(val);
7102         origexpr = (Expr *) stringToNode(conbin);
7103         exprstate = (List *)
7104                 ExecPrepareExpr((Expr *) make_ands_implicit(origexpr), estate);
7105
7106         econtext = GetPerTupleExprContext(estate);
7107         tupdesc = RelationGetDescr(rel);
7108         slot = MakeSingleTupleTableSlot(tupdesc);
7109         econtext->ecxt_scantuple = slot;
7110
7111         snapshot = RegisterSnapshot(GetLatestSnapshot());
7112         scan = heap_beginscan(rel, snapshot, 0, NULL);
7113
7114         /*
7115          * Switch to per-tuple memory context and reset it for each tuple
7116          * produced, so we don't leak memory.
7117          */
7118         oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
7119
7120         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7121         {
7122                 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
7123
7124                 if (!ExecQual(exprstate, econtext, true))
7125                         ereport(ERROR,
7126                                         (errcode(ERRCODE_CHECK_VIOLATION),
7127                                          errmsg("check constraint \"%s\" is violated by some row",
7128                                                         NameStr(constrForm->conname)),
7129                                          errtableconstraint(rel, NameStr(constrForm->conname))));
7130
7131                 ResetExprContext(econtext);
7132         }
7133
7134         MemoryContextSwitchTo(oldcxt);
7135         heap_endscan(scan);
7136         UnregisterSnapshot(snapshot);
7137         ExecDropSingleTupleTableSlot(slot);
7138         FreeExecutorState(estate);
7139 }
7140
7141 /*
7142  * Scan the existing rows in a table to verify they meet a proposed FK
7143  * constraint.
7144  *
7145  * Caller must have opened and locked both relations appropriately.
7146  */
7147 static void
7148 validateForeignKeyConstraint(char *conname,
7149                                                          Relation rel,
7150                                                          Relation pkrel,
7151                                                          Oid pkindOid,
7152                                                          Oid constraintOid)
7153 {
7154         HeapScanDesc scan;
7155         HeapTuple       tuple;
7156         Trigger         trig;
7157         Snapshot        snapshot;
7158
7159         ereport(DEBUG1,
7160                         (errmsg("validating foreign key constraint \"%s\"", conname)));
7161
7162         /*
7163          * Build a trigger call structure; we'll need it either way.
7164          */
7165         MemSet(&trig, 0, sizeof(trig));
7166         trig.tgoid = InvalidOid;
7167         trig.tgname = conname;
7168         trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
7169         trig.tgisinternal = TRUE;
7170         trig.tgconstrrelid = RelationGetRelid(pkrel);
7171         trig.tgconstrindid = pkindOid;
7172         trig.tgconstraint = constraintOid;
7173         trig.tgdeferrable = FALSE;
7174         trig.tginitdeferred = FALSE;
7175         /* we needn't fill in tgargs or tgqual */
7176
7177         /*
7178          * See if we can do it with a single LEFT JOIN query.  A FALSE result
7179          * indicates we must proceed with the fire-the-trigger method.
7180          */
7181         if (RI_Initial_Check(&trig, rel, pkrel))
7182                 return;
7183
7184         /*
7185          * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
7186          * if that tuple had just been inserted.  If any of those fail, it should
7187          * ereport(ERROR) and that's that.
7188          */
7189         snapshot = RegisterSnapshot(GetLatestSnapshot());
7190         scan = heap_beginscan(rel, snapshot, 0, NULL);
7191
7192         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7193         {
7194                 FunctionCallInfoData fcinfo;
7195                 TriggerData trigdata;
7196
7197                 /*
7198                  * Make a call to the trigger function
7199                  *
7200                  * No parameters are passed, but we do set a context
7201                  */
7202                 MemSet(&fcinfo, 0, sizeof(fcinfo));
7203
7204                 /*
7205                  * We assume RI_FKey_check_ins won't look at flinfo...
7206                  */
7207                 trigdata.type = T_TriggerData;
7208                 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
7209                 trigdata.tg_relation = rel;
7210                 trigdata.tg_trigtuple = tuple;
7211                 trigdata.tg_newtuple = NULL;
7212                 trigdata.tg_trigger = &trig;
7213                 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
7214                 trigdata.tg_newtuplebuf = InvalidBuffer;
7215
7216                 fcinfo.context = (Node *) &trigdata;
7217
7218                 RI_FKey_check_ins(&fcinfo);
7219         }
7220
7221         heap_endscan(scan);
7222         UnregisterSnapshot(snapshot);
7223 }
7224
7225 static void
7226 CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
7227                                          Oid constraintOid, Oid indexOid, bool on_insert)
7228 {
7229         CreateTrigStmt *fk_trigger;
7230
7231         /*
7232          * Note: for a self-referential FK (referencing and referenced tables are
7233          * the same), it is important that the ON UPDATE action fires before the
7234          * CHECK action, since both triggers will fire on the same row during an
7235          * UPDATE event; otherwise the CHECK trigger will be checking a non-final
7236          * state of the row.  Triggers fire in name order, so we ensure this by
7237          * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
7238          * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
7239          */
7240         fk_trigger = makeNode(CreateTrigStmt);
7241         fk_trigger->trigname = "RI_ConstraintTrigger_c";
7242         fk_trigger->relation = NULL;
7243         fk_trigger->row = true;
7244         fk_trigger->timing = TRIGGER_TYPE_AFTER;
7245
7246         /* Either ON INSERT or ON UPDATE */
7247         if (on_insert)
7248         {
7249                 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
7250                 fk_trigger->events = TRIGGER_TYPE_INSERT;
7251         }
7252         else
7253         {
7254                 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
7255                 fk_trigger->events = TRIGGER_TYPE_UPDATE;
7256         }
7257
7258         fk_trigger->columns = NIL;
7259         fk_trigger->whenClause = NULL;
7260         fk_trigger->isconstraint = true;
7261         fk_trigger->deferrable = fkconstraint->deferrable;
7262         fk_trigger->initdeferred = fkconstraint->initdeferred;
7263         fk_trigger->constrrel = NULL;
7264         fk_trigger->args = NIL;
7265
7266         (void) CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid, constraintOid,
7267                                                  indexOid, true);
7268
7269         /* Make changes-so-far visible */
7270         CommandCounterIncrement();
7271 }
7272
7273 /*
7274  * Create the triggers that implement an FK constraint.
7275  */
7276 static void
7277 createForeignKeyTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint,
7278                                                  Oid constraintOid, Oid indexOid)
7279 {
7280         Oid                     myRelOid;
7281         CreateTrigStmt *fk_trigger;
7282
7283         myRelOid = RelationGetRelid(rel);
7284
7285         /* Make changes-so-far visible */
7286         CommandCounterIncrement();
7287
7288         /*
7289          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
7290          * DELETE action on the referenced table.
7291          */
7292         fk_trigger = makeNode(CreateTrigStmt);
7293         fk_trigger->trigname = "RI_ConstraintTrigger_a";
7294         fk_trigger->relation = NULL;
7295         fk_trigger->row = true;
7296         fk_trigger->timing = TRIGGER_TYPE_AFTER;
7297         fk_trigger->events = TRIGGER_TYPE_DELETE;
7298         fk_trigger->columns = NIL;
7299         fk_trigger->whenClause = NULL;
7300         fk_trigger->isconstraint = true;
7301         fk_trigger->constrrel = NULL;
7302         switch (fkconstraint->fk_del_action)
7303         {
7304                 case FKCONSTR_ACTION_NOACTION:
7305                         fk_trigger->deferrable = fkconstraint->deferrable;
7306                         fk_trigger->initdeferred = fkconstraint->initdeferred;
7307                         fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
7308                         break;
7309                 case FKCONSTR_ACTION_RESTRICT:
7310                         fk_trigger->deferrable = false;
7311                         fk_trigger->initdeferred = false;
7312                         fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
7313                         break;
7314                 case FKCONSTR_ACTION_CASCADE:
7315                         fk_trigger->deferrable = false;
7316                         fk_trigger->initdeferred = false;
7317                         fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
7318                         break;
7319                 case FKCONSTR_ACTION_SETNULL:
7320                         fk_trigger->deferrable = false;
7321                         fk_trigger->initdeferred = false;
7322                         fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
7323                         break;
7324                 case FKCONSTR_ACTION_SETDEFAULT:
7325                         fk_trigger->deferrable = false;
7326                         fk_trigger->initdeferred = false;
7327                         fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
7328                         break;
7329                 default:
7330                         elog(ERROR, "unrecognized FK action type: %d",
7331                                  (int) fkconstraint->fk_del_action);
7332                         break;
7333         }
7334         fk_trigger->args = NIL;
7335
7336         (void) CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid, constraintOid,
7337                                                  indexOid, true);
7338
7339         /* Make changes-so-far visible */
7340         CommandCounterIncrement();
7341
7342         /*
7343          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
7344          * UPDATE action on the referenced table.
7345          */
7346         fk_trigger = makeNode(CreateTrigStmt);
7347         fk_trigger->trigname = "RI_ConstraintTrigger_a";
7348         fk_trigger->relation = NULL;
7349         fk_trigger->row = true;
7350         fk_trigger->timing = TRIGGER_TYPE_AFTER;
7351         fk_trigger->events = TRIGGER_TYPE_UPDATE;
7352         fk_trigger->columns = NIL;
7353         fk_trigger->whenClause = NULL;
7354         fk_trigger->isconstraint = true;
7355         fk_trigger->constrrel = NULL;
7356         switch (fkconstraint->fk_upd_action)
7357         {
7358                 case FKCONSTR_ACTION_NOACTION:
7359                         fk_trigger->deferrable = fkconstraint->deferrable;
7360                         fk_trigger->initdeferred = fkconstraint->initdeferred;
7361                         fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
7362                         break;
7363                 case FKCONSTR_ACTION_RESTRICT:
7364                         fk_trigger->deferrable = false;
7365                         fk_trigger->initdeferred = false;
7366                         fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
7367                         break;
7368                 case FKCONSTR_ACTION_CASCADE:
7369                         fk_trigger->deferrable = false;
7370                         fk_trigger->initdeferred = false;
7371                         fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
7372                         break;
7373                 case FKCONSTR_ACTION_SETNULL:
7374                         fk_trigger->deferrable = false;
7375                         fk_trigger->initdeferred = false;
7376                         fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
7377                         break;
7378                 case FKCONSTR_ACTION_SETDEFAULT:
7379                         fk_trigger->deferrable = false;
7380                         fk_trigger->initdeferred = false;
7381                         fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
7382                         break;
7383                 default:
7384                         elog(ERROR, "unrecognized FK action type: %d",
7385                                  (int) fkconstraint->fk_upd_action);
7386                         break;
7387         }
7388         fk_trigger->args = NIL;
7389
7390         (void) CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid, constraintOid,
7391                                                  indexOid, true);
7392
7393         /* Make changes-so-far visible */
7394         CommandCounterIncrement();
7395
7396         /*
7397          * Build and execute CREATE CONSTRAINT TRIGGER statements for the CHECK
7398          * action for both INSERTs and UPDATEs on the referencing table.
7399          */
7400         CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint, constraintOid,
7401                                                  indexOid, true);
7402         CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint, constraintOid,
7403                                                  indexOid, false);
7404 }
7405
7406 /*
7407  * ALTER TABLE DROP CONSTRAINT
7408  *
7409  * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
7410  */
7411 static void
7412 ATExecDropConstraint(Relation rel, const char *constrName,
7413                                          DropBehavior behavior,
7414                                          bool recurse, bool recursing,
7415                                          bool missing_ok, LOCKMODE lockmode)
7416 {
7417         List       *children;
7418         ListCell   *child;
7419         Relation        conrel;
7420         Form_pg_constraint con;
7421         SysScanDesc scan;
7422         ScanKeyData key;
7423         HeapTuple       tuple;
7424         bool            found = false;
7425         bool            is_no_inherit_constraint = false;
7426
7427         /* At top level, permission check was done in ATPrepCmd, else do it */
7428         if (recursing)
7429                 ATSimplePermissions(rel, ATT_TABLE);
7430
7431         conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
7432
7433         /*
7434          * Find and drop the target constraint
7435          */
7436         ScanKeyInit(&key,
7437                                 Anum_pg_constraint_conrelid,
7438                                 BTEqualStrategyNumber, F_OIDEQ,
7439                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7440         scan = systable_beginscan(conrel, ConstraintRelidIndexId,
7441                                                           true, NULL, 1, &key);
7442
7443         while (HeapTupleIsValid(tuple = systable_getnext(scan)))
7444         {
7445                 ObjectAddress conobj;
7446
7447                 con = (Form_pg_constraint) GETSTRUCT(tuple);
7448
7449                 if (strcmp(NameStr(con->conname), constrName) != 0)
7450                         continue;
7451
7452                 /* Don't drop inherited constraints */
7453                 if (con->coninhcount > 0 && !recursing)
7454                         ereport(ERROR,
7455                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7456                                          errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
7457                                                         constrName, RelationGetRelationName(rel))));
7458
7459                 is_no_inherit_constraint = con->connoinherit;
7460
7461                 /*
7462                  * Perform the actual constraint deletion
7463                  */
7464                 conobj.classId = ConstraintRelationId;
7465                 conobj.objectId = HeapTupleGetOid(tuple);
7466                 conobj.objectSubId = 0;
7467
7468                 performDeletion(&conobj, behavior, 0);
7469
7470                 found = true;
7471
7472                 /* constraint found and dropped -- no need to keep looping */
7473                 break;
7474         }
7475
7476         systable_endscan(scan);
7477
7478         if (!found)
7479         {
7480                 if (!missing_ok)
7481                 {
7482                         ereport(ERROR,
7483                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
7484                                 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
7485                                            constrName, RelationGetRelationName(rel))));
7486                 }
7487                 else
7488                 {
7489                         ereport(NOTICE,
7490                                         (errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
7491                                                         constrName, RelationGetRelationName(rel))));
7492                         heap_close(conrel, RowExclusiveLock);
7493                         return;
7494                 }
7495         }
7496
7497         /*
7498          * Propagate to children as appropriate.  Unlike most other ALTER
7499          * routines, we have to do this one level of recursion at a time; we can't
7500          * use find_all_inheritors to do it in one pass.
7501          */
7502         if (!is_no_inherit_constraint)
7503                 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
7504         else
7505                 children = NIL;
7506
7507         foreach(child, children)
7508         {
7509                 Oid                     childrelid = lfirst_oid(child);
7510                 Relation        childrel;
7511                 HeapTuple       copy_tuple;
7512
7513                 /* find_inheritance_children already got lock */
7514                 childrel = heap_open(childrelid, NoLock);
7515                 CheckTableNotInUse(childrel, "ALTER TABLE");
7516
7517                 ScanKeyInit(&key,
7518                                         Anum_pg_constraint_conrelid,
7519                                         BTEqualStrategyNumber, F_OIDEQ,
7520                                         ObjectIdGetDatum(childrelid));
7521                 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
7522                                                                   true, NULL, 1, &key);
7523
7524                 /* scan for matching tuple - there should only be one */
7525                 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
7526                 {
7527                         con = (Form_pg_constraint) GETSTRUCT(tuple);
7528
7529                         /* Right now only CHECK constraints can be inherited */
7530                         if (con->contype != CONSTRAINT_CHECK)
7531                                 continue;
7532
7533                         if (strcmp(NameStr(con->conname), constrName) == 0)
7534                                 break;
7535                 }
7536
7537                 if (!HeapTupleIsValid(tuple))
7538                         ereport(ERROR,
7539                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
7540                                 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
7541                                            constrName,
7542                                            RelationGetRelationName(childrel))));
7543
7544                 copy_tuple = heap_copytuple(tuple);
7545
7546                 systable_endscan(scan);
7547
7548                 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
7549
7550                 if (con->coninhcount <= 0)              /* shouldn't happen */
7551                         elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7552                                  childrelid, constrName);
7553
7554                 if (recurse)
7555                 {
7556                         /*
7557                          * If the child constraint has other definition sources, just
7558                          * decrement its inheritance count; if not, recurse to delete it.
7559                          */
7560                         if (con->coninhcount == 1 && !con->conislocal)
7561                         {
7562                                 /* Time to delete this child constraint, too */
7563                                 ATExecDropConstraint(childrel, constrName, behavior,
7564                                                                          true, true,
7565                                                                          false, lockmode);
7566                         }
7567                         else
7568                         {
7569                                 /* Child constraint must survive my deletion */
7570                                 con->coninhcount--;
7571                                 simple_heap_update(conrel, &copy_tuple->t_self, copy_tuple);
7572                                 CatalogUpdateIndexes(conrel, copy_tuple);
7573
7574                                 /* Make update visible */
7575                                 CommandCounterIncrement();
7576                         }
7577                 }
7578                 else
7579                 {
7580                         /*
7581                          * If we were told to drop ONLY in this table (no recursion), we
7582                          * need to mark the inheritors' constraints as locally defined
7583                          * rather than inherited.
7584                          */
7585                         con->coninhcount--;
7586                         con->conislocal = true;
7587
7588                         simple_heap_update(conrel, &copy_tuple->t_self, copy_tuple);
7589                         CatalogUpdateIndexes(conrel, copy_tuple);
7590
7591                         /* Make update visible */
7592                         CommandCounterIncrement();
7593                 }
7594
7595                 heap_freetuple(copy_tuple);
7596
7597                 heap_close(childrel, NoLock);
7598         }
7599
7600         heap_close(conrel, RowExclusiveLock);
7601 }
7602
7603 /*
7604  * ALTER COLUMN TYPE
7605  */
7606 static void
7607 ATPrepAlterColumnType(List **wqueue,
7608                                           AlteredTableInfo *tab, Relation rel,
7609                                           bool recurse, bool recursing,
7610                                           AlterTableCmd *cmd, LOCKMODE lockmode)
7611 {
7612         char       *colName = cmd->name;
7613         ColumnDef  *def = (ColumnDef *) cmd->def;
7614         TypeName   *typeName = def->typeName;
7615         Node       *transform = def->raw_default;
7616         HeapTuple       tuple;
7617         Form_pg_attribute attTup;
7618         AttrNumber      attnum;
7619         Oid                     targettype;
7620         int32           targettypmod;
7621         Oid                     targetcollid;
7622         NewColumnValue *newval;
7623         ParseState *pstate = make_parsestate(NULL);
7624         AclResult       aclresult;
7625
7626         if (rel->rd_rel->reloftype && !recursing)
7627                 ereport(ERROR,
7628                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7629                                  errmsg("cannot alter column type of typed table")));
7630
7631         /* lookup the attribute so we can check inheritance status */
7632         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
7633         if (!HeapTupleIsValid(tuple))
7634                 ereport(ERROR,
7635                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
7636                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
7637                                                 colName, RelationGetRelationName(rel))));
7638         attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7639         attnum = attTup->attnum;
7640
7641         /* Can't alter a system attribute */
7642         if (attnum <= 0)
7643                 ereport(ERROR,
7644                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7645                                  errmsg("cannot alter system column \"%s\"",
7646                                                 colName)));
7647
7648         /* Don't alter inherited columns */
7649         if (attTup->attinhcount > 0 && !recursing)
7650                 ereport(ERROR,
7651                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7652                                  errmsg("cannot alter inherited column \"%s\"",
7653                                                 colName)));
7654
7655         /* Look up the target type */
7656         typenameTypeIdAndMod(NULL, typeName, &targettype, &targettypmod);
7657
7658         aclresult = pg_type_aclcheck(targettype, GetUserId(), ACL_USAGE);
7659         if (aclresult != ACLCHECK_OK)
7660                 aclcheck_error_type(aclresult, targettype);
7661
7662         /* And the collation */
7663         targetcollid = GetColumnDefCollation(NULL, def, targettype);
7664
7665         /* make sure datatype is legal for a column */
7666         CheckAttributeType(colName, targettype, targetcollid,
7667                                            list_make1_oid(rel->rd_rel->reltype),
7668                                            false);
7669
7670         if (tab->relkind == RELKIND_RELATION)
7671         {
7672                 /*
7673                  * Set up an expression to transform the old data value to the new
7674                  * type. If a USING option was given, transform and use that
7675                  * expression, else just take the old value and try to coerce it.  We
7676                  * do this first so that type incompatibility can be detected before
7677                  * we waste effort, and because we need the expression to be parsed
7678                  * against the original table row type.
7679                  */
7680                 if (transform)
7681                 {
7682                         RangeTblEntry *rte;
7683
7684                         /* Expression must be able to access vars of old table */
7685                         rte = addRangeTableEntryForRelation(pstate,
7686                                                                                                 rel,
7687                                                                                                 NULL,
7688                                                                                                 false,
7689                                                                                                 true);
7690                         addRTEtoQuery(pstate, rte, false, true, true);
7691
7692                         transform = transformExpr(pstate, transform,
7693                                                                           EXPR_KIND_ALTER_COL_TRANSFORM);
7694
7695                         /* It can't return a set */
7696                         if (expression_returns_set(transform))
7697                                 ereport(ERROR,
7698                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
7699                                           errmsg("transform expression must not return a set")));
7700                 }
7701                 else
7702                 {
7703                         transform = (Node *) makeVar(1, attnum,
7704                                                                                  attTup->atttypid, attTup->atttypmod,
7705                                                                                  attTup->attcollation,
7706                                                                                  0);
7707                 }
7708
7709                 transform = coerce_to_target_type(pstate,
7710                                                                                   transform, exprType(transform),
7711                                                                                   targettype, targettypmod,
7712                                                                                   COERCION_ASSIGNMENT,
7713                                                                                   COERCE_IMPLICIT_CAST,
7714                                                                                   -1);
7715                 if (transform == NULL)
7716                         ereport(ERROR,
7717                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
7718                           errmsg("column \"%s\" cannot be cast automatically to type %s",
7719                                          colName, format_type_be(targettype)),
7720                                          errhint("Specify a USING expression to perform the conversion.")));
7721
7722                 /* Fix collations after all else */
7723                 assign_expr_collations(pstate, transform);
7724
7725                 /* Plan the expr now so we can accurately assess the need to rewrite. */
7726                 transform = (Node *) expression_planner((Expr *) transform);
7727
7728                 /*
7729                  * Add a work queue item to make ATRewriteTable update the column
7730                  * contents.
7731                  */
7732                 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
7733                 newval->attnum = attnum;
7734                 newval->expr = (Expr *) transform;
7735
7736                 tab->newvals = lappend(tab->newvals, newval);
7737                 if (ATColumnChangeRequiresRewrite(transform, attnum))
7738                         tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
7739         }
7740         else if (transform)
7741                 ereport(ERROR,
7742                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7743                                  errmsg("\"%s\" is not a table",
7744                                                 RelationGetRelationName(rel))));
7745
7746         if (tab->relkind == RELKIND_COMPOSITE_TYPE ||
7747                 tab->relkind == RELKIND_FOREIGN_TABLE)
7748         {
7749                 /*
7750                  * For composite types, do this check now.  Tables will check it later
7751                  * when the table is being rewritten.
7752                  */
7753                 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
7754         }
7755
7756         ReleaseSysCache(tuple);
7757
7758         /*
7759          * The recursion case is handled by ATSimpleRecursion.  However, if we are
7760          * told not to recurse, there had better not be any child tables; else the
7761          * alter would put them out of step.
7762          */
7763         if (recurse)
7764                 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
7765         else if (!recursing &&
7766                          find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
7767                 ereport(ERROR,
7768                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7769                                  errmsg("type of inherited column \"%s\" must be changed in child tables too",
7770                                                 colName)));
7771
7772         if (tab->relkind == RELKIND_COMPOSITE_TYPE)
7773                 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
7774 }
7775
7776 /*
7777  * When the data type of a column is changed, a rewrite might not be required
7778  * if the new type is sufficiently identical to the old one, and the USING
7779  * clause isn't trying to insert some other value.  It's safe to skip the
7780  * rewrite if the old type is binary coercible to the new type, or if the
7781  * new type is an unconstrained domain over the old type.  In the case of a
7782  * constrained domain, we could get by with scanning the table and checking
7783  * the constraint rather than actually rewriting it, but we don't currently
7784  * try to do that.
7785  */
7786 static bool
7787 ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
7788 {
7789         Assert(expr != NULL);
7790
7791         for (;;)
7792         {
7793                 /* only one varno, so no need to check that */
7794                 if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
7795                         return false;
7796                 else if (IsA(expr, RelabelType))
7797                         expr = (Node *) ((RelabelType *) expr)->arg;
7798                 else if (IsA(expr, CoerceToDomain))
7799                 {
7800                         CoerceToDomain *d = (CoerceToDomain *) expr;
7801
7802                         if (DomainHasConstraints(d->resulttype))
7803                                 return true;
7804                         expr = (Node *) d->arg;
7805                 }
7806                 else
7807                         return true;
7808         }
7809 }
7810
7811 static void
7812 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
7813                                           AlterTableCmd *cmd, LOCKMODE lockmode)
7814 {
7815         char       *colName = cmd->name;
7816         ColumnDef  *def = (ColumnDef *) cmd->def;
7817         TypeName   *typeName = def->typeName;
7818         HeapTuple       heapTup;
7819         Form_pg_attribute attTup;
7820         AttrNumber      attnum;
7821         HeapTuple       typeTuple;
7822         Form_pg_type tform;
7823         Oid                     targettype;
7824         int32           targettypmod;
7825         Oid                     targetcollid;
7826         Node       *defaultexpr;
7827         Relation        attrelation;
7828         Relation        depRel;
7829         ScanKeyData key[3];
7830         SysScanDesc scan;
7831         HeapTuple       depTup;
7832
7833         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
7834
7835         /* Look up the target column */
7836         heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7837         if (!HeapTupleIsValid(heapTup))         /* shouldn't happen */
7838                 ereport(ERROR,
7839                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
7840                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
7841                                                 colName, RelationGetRelationName(rel))));
7842         attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
7843         attnum = attTup->attnum;
7844
7845         /* Check for multiple ALTER TYPE on same column --- can't cope */
7846         if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
7847                 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
7848                 ereport(ERROR,
7849                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7850                                  errmsg("cannot alter type of column \"%s\" twice",
7851                                                 colName)));
7852
7853         /* Look up the target type (should not fail, since prep found it) */
7854         typeTuple = typenameType(NULL, typeName, &targettypmod);
7855         tform = (Form_pg_type) GETSTRUCT(typeTuple);
7856         targettype = HeapTupleGetOid(typeTuple);
7857         /* And the collation */
7858         targetcollid = GetColumnDefCollation(NULL, def, targettype);
7859
7860         /*
7861          * If there is a default expression for the column, get it and ensure we
7862          * can coerce it to the new datatype.  (We must do this before changing
7863          * the column type, because build_column_default itself will try to
7864          * coerce, and will not issue the error message we want if it fails.)
7865          *
7866          * We remove any implicit coercion steps at the top level of the old
7867          * default expression; this has been agreed to satisfy the principle of
7868          * least surprise.  (The conversion to the new column type should act like
7869          * it started from what the user sees as the stored expression, and the
7870          * implicit coercions aren't going to be shown.)
7871          */
7872         if (attTup->atthasdef)
7873         {
7874                 defaultexpr = build_column_default(rel, attnum);
7875                 Assert(defaultexpr);
7876                 defaultexpr = strip_implicit_coercions(defaultexpr);
7877                 defaultexpr = coerce_to_target_type(NULL,               /* no UNKNOWN params */
7878                                                                                   defaultexpr, exprType(defaultexpr),
7879                                                                                         targettype, targettypmod,
7880                                                                                         COERCION_ASSIGNMENT,
7881                                                                                         COERCE_IMPLICIT_CAST,
7882                                                                                         -1);
7883                 if (defaultexpr == NULL)
7884                         ereport(ERROR,
7885                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
7886                                          errmsg("default for column \"%s\" cannot be cast automatically to type %s",
7887                                                         colName, format_type_be(targettype))));
7888         }
7889         else
7890                 defaultexpr = NULL;
7891
7892         /*
7893          * Find everything that depends on the column (constraints, indexes, etc),
7894          * and record enough information to let us recreate the objects.
7895          *
7896          * The actual recreation does not happen here, but only after we have
7897          * performed all the individual ALTER TYPE operations.  We have to save
7898          * the info before executing ALTER TYPE, though, else the deparser will
7899          * get confused.
7900          *
7901          * There could be multiple entries for the same object, so we must check
7902          * to ensure we process each one only once.  Note: we assume that an index
7903          * that implements a constraint will not show a direct dependency on the
7904          * column.
7905          */
7906         depRel = heap_open(DependRelationId, RowExclusiveLock);
7907
7908         ScanKeyInit(&key[0],
7909                                 Anum_pg_depend_refclassid,
7910                                 BTEqualStrategyNumber, F_OIDEQ,
7911                                 ObjectIdGetDatum(RelationRelationId));
7912         ScanKeyInit(&key[1],
7913                                 Anum_pg_depend_refobjid,
7914                                 BTEqualStrategyNumber, F_OIDEQ,
7915                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7916         ScanKeyInit(&key[2],
7917                                 Anum_pg_depend_refobjsubid,
7918                                 BTEqualStrategyNumber, F_INT4EQ,
7919                                 Int32GetDatum((int32) attnum));
7920
7921         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7922                                                           NULL, 3, key);
7923
7924         while (HeapTupleIsValid(depTup = systable_getnext(scan)))
7925         {
7926                 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
7927                 ObjectAddress foundObject;
7928
7929                 /* We don't expect any PIN dependencies on columns */
7930                 if (foundDep->deptype == DEPENDENCY_PIN)
7931                         elog(ERROR, "cannot alter type of a pinned column");
7932
7933                 foundObject.classId = foundDep->classid;
7934                 foundObject.objectId = foundDep->objid;
7935                 foundObject.objectSubId = foundDep->objsubid;
7936
7937                 switch (getObjectClass(&foundObject))
7938                 {
7939                         case OCLASS_CLASS:
7940                                 {
7941                                         char            relKind = get_rel_relkind(foundObject.objectId);
7942
7943                                         if (relKind == RELKIND_INDEX)
7944                                         {
7945                                                 Assert(foundObject.objectSubId == 0);
7946                                                 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
7947                                                 {
7948                                                         tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
7949                                                                                                            foundObject.objectId);
7950                                                         tab->changedIndexDefs = lappend(tab->changedIndexDefs,
7951                                                            pg_get_indexdef_string(foundObject.objectId));
7952                                                 }
7953                                         }
7954                                         else if (relKind == RELKIND_SEQUENCE)
7955                                         {
7956                                                 /*
7957                                                  * This must be a SERIAL column's sequence.  We need
7958                                                  * not do anything to it.
7959                                                  */
7960                                                 Assert(foundObject.objectSubId == 0);
7961                                         }
7962                                         else
7963                                         {
7964                                                 /* Not expecting any other direct dependencies... */
7965                                                 elog(ERROR, "unexpected object depending on column: %s",
7966                                                          getObjectDescription(&foundObject));
7967                                         }
7968                                         break;
7969                                 }
7970
7971                         case OCLASS_CONSTRAINT:
7972                                 Assert(foundObject.objectSubId == 0);
7973                                 if (!list_member_oid(tab->changedConstraintOids,
7974                                                                          foundObject.objectId))
7975                                 {
7976                                         char       *defstring = pg_get_constraintdef_string(foundObject.objectId);
7977
7978                                         /*
7979                                          * Put NORMAL dependencies at the front of the list and
7980                                          * AUTO dependencies at the back.  This makes sure that
7981                                          * foreign-key constraints depending on this column will
7982                                          * be dropped before unique or primary-key constraints of
7983                                          * the column; which we must have because the FK
7984                                          * constraints depend on the indexes belonging to the
7985                                          * unique constraints.
7986                                          */
7987                                         if (foundDep->deptype == DEPENDENCY_NORMAL)
7988                                         {
7989                                                 tab->changedConstraintOids =
7990                                                         lcons_oid(foundObject.objectId,
7991                                                                           tab->changedConstraintOids);
7992                                                 tab->changedConstraintDefs =
7993                                                         lcons(defstring,
7994                                                                   tab->changedConstraintDefs);
7995                                         }
7996                                         else
7997                                         {
7998                                                 tab->changedConstraintOids =
7999                                                         lappend_oid(tab->changedConstraintOids,
8000                                                                                 foundObject.objectId);
8001                                                 tab->changedConstraintDefs =
8002                                                         lappend(tab->changedConstraintDefs,
8003                                                                         defstring);
8004                                         }
8005                                 }
8006                                 break;
8007
8008                         case OCLASS_REWRITE:
8009                                 /* XXX someday see if we can cope with revising views */
8010                                 ereport(ERROR,
8011                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8012                                                  errmsg("cannot alter type of a column used by a view or rule"),
8013                                                  errdetail("%s depends on column \"%s\"",
8014                                                                    getObjectDescription(&foundObject),
8015                                                                    colName)));
8016                                 break;
8017
8018                         case OCLASS_TRIGGER:
8019
8020                                 /*
8021                                  * A trigger can depend on a column because the column is
8022                                  * specified as an update target, or because the column is
8023                                  * used in the trigger's WHEN condition.  The first case would
8024                                  * not require any extra work, but the second case would
8025                                  * require updating the WHEN expression, which will take a
8026                                  * significant amount of new code.  Since we can't easily tell
8027                                  * which case applies, we punt for both.  FIXME someday.
8028                                  */
8029                                 ereport(ERROR,
8030                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8031                                                  errmsg("cannot alter type of a column used in a trigger definition"),
8032                                                  errdetail("%s depends on column \"%s\"",
8033                                                                    getObjectDescription(&foundObject),
8034                                                                    colName)));
8035                                 break;
8036
8037                         case OCLASS_POLICY:
8038
8039                                 /*
8040                                  * A policy can depend on a column because the column is
8041                                  * specified in the policy's USING or WITH CHECK qual
8042                                  * expressions.  It might be possible to rewrite and recheck
8043                                  * the policy expression, but punt for now.  It's certainly
8044                                  * easy enough to remove and recreate the policy; still,
8045                                  * FIXME someday.
8046                                  */
8047                                 ereport(ERROR,
8048                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8049                                                  errmsg("cannot alter type of a column used in a policy definition"),
8050                                                  errdetail("%s depends on column \"%s\"",
8051                                                                    getObjectDescription(&foundObject),
8052                                                                    colName)));
8053                                 break;
8054
8055                         case OCLASS_DEFAULT:
8056
8057                                 /*
8058                                  * Ignore the column's default expression, since we will fix
8059                                  * it below.
8060                                  */
8061                                 Assert(defaultexpr);
8062                                 break;
8063
8064                         case OCLASS_PROC:
8065                         case OCLASS_TYPE:
8066                         case OCLASS_CAST:
8067                         case OCLASS_COLLATION:
8068                         case OCLASS_CONVERSION:
8069                         case OCLASS_LANGUAGE:
8070                         case OCLASS_LARGEOBJECT:
8071                         case OCLASS_OPERATOR:
8072                         case OCLASS_OPCLASS:
8073                         case OCLASS_OPFAMILY:
8074                         case OCLASS_AMOP:
8075                         case OCLASS_AMPROC:
8076                         case OCLASS_SCHEMA:
8077                         case OCLASS_TSPARSER:
8078                         case OCLASS_TSDICT:
8079                         case OCLASS_TSTEMPLATE:
8080                         case OCLASS_TSCONFIG:
8081                         case OCLASS_ROLE:
8082                         case OCLASS_DATABASE:
8083                         case OCLASS_TBLSPACE:
8084                         case OCLASS_FDW:
8085                         case OCLASS_FOREIGN_SERVER:
8086                         case OCLASS_USER_MAPPING:
8087                         case OCLASS_DEFACL:
8088                         case OCLASS_EXTENSION:
8089
8090                                 /*
8091                                  * We don't expect any of these sorts of objects to depend on
8092                                  * a column.
8093                                  */
8094                                 elog(ERROR, "unexpected object depending on column: %s",
8095                                          getObjectDescription(&foundObject));
8096                                 break;
8097
8098                         default:
8099                                 elog(ERROR, "unrecognized object class: %u",
8100                                          foundObject.classId);
8101                 }
8102         }
8103
8104         systable_endscan(scan);
8105
8106         /*
8107          * Now scan for dependencies of this column on other things.  The only
8108          * thing we should find is the dependency on the column datatype, which we
8109          * want to remove, and possibly a collation dependency.
8110          */
8111         ScanKeyInit(&key[0],
8112                                 Anum_pg_depend_classid,
8113                                 BTEqualStrategyNumber, F_OIDEQ,
8114                                 ObjectIdGetDatum(RelationRelationId));
8115         ScanKeyInit(&key[1],
8116                                 Anum_pg_depend_objid,
8117                                 BTEqualStrategyNumber, F_OIDEQ,
8118                                 ObjectIdGetDatum(RelationGetRelid(rel)));
8119         ScanKeyInit(&key[2],
8120                                 Anum_pg_depend_objsubid,
8121                                 BTEqualStrategyNumber, F_INT4EQ,
8122                                 Int32GetDatum((int32) attnum));
8123
8124         scan = systable_beginscan(depRel, DependDependerIndexId, true,
8125                                                           NULL, 3, key);
8126
8127         while (HeapTupleIsValid(depTup = systable_getnext(scan)))
8128         {
8129                 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
8130
8131                 if (foundDep->deptype != DEPENDENCY_NORMAL)
8132                         elog(ERROR, "found unexpected dependency type '%c'",
8133                                  foundDep->deptype);
8134                 if (!(foundDep->refclassid == TypeRelationId &&
8135                           foundDep->refobjid == attTup->atttypid) &&
8136                         !(foundDep->refclassid == CollationRelationId &&
8137                           foundDep->refobjid == attTup->attcollation))
8138                         elog(ERROR, "found unexpected dependency for column");
8139
8140                 simple_heap_delete(depRel, &depTup->t_self);
8141         }
8142
8143         systable_endscan(scan);
8144
8145         heap_close(depRel, RowExclusiveLock);
8146
8147         /*
8148          * Here we go --- change the recorded column type and collation.  (Note
8149          * heapTup is a copy of the syscache entry, so okay to scribble on.)
8150          */
8151         attTup->atttypid = targettype;
8152         attTup->atttypmod = targettypmod;
8153         attTup->attcollation = targetcollid;
8154         attTup->attndims = list_length(typeName->arrayBounds);
8155         attTup->attlen = tform->typlen;
8156         attTup->attbyval = tform->typbyval;
8157         attTup->attalign = tform->typalign;
8158         attTup->attstorage = tform->typstorage;
8159
8160         ReleaseSysCache(typeTuple);
8161
8162         simple_heap_update(attrelation, &heapTup->t_self, heapTup);
8163
8164         /* keep system catalog indexes current */
8165         CatalogUpdateIndexes(attrelation, heapTup);
8166
8167         heap_close(attrelation, RowExclusiveLock);
8168
8169         /* Install dependencies on new datatype and collation */
8170         add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
8171         add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
8172
8173         /*
8174          * Drop any pg_statistic entry for the column, since it's now wrong type
8175          */
8176         RemoveStatistics(RelationGetRelid(rel), attnum);
8177
8178         InvokeObjectPostAlterHook(RelationRelationId,
8179                                                           RelationGetRelid(rel), attnum);
8180
8181         /*
8182          * Update the default, if present, by brute force --- remove and re-add
8183          * the default.  Probably unsafe to take shortcuts, since the new version
8184          * may well have additional dependencies.  (It's okay to do this now,
8185          * rather than after other ALTER TYPE commands, since the default won't
8186          * depend on other column types.)
8187          */
8188         if (defaultexpr)
8189         {
8190                 /* Must make new row visible since it will be updated again */
8191                 CommandCounterIncrement();
8192
8193                 /*
8194                  * We use RESTRICT here for safety, but at present we do not expect
8195                  * anything to depend on the default.
8196                  */
8197                 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
8198                                                   true);
8199
8200                 StoreAttrDefault(rel, attnum, defaultexpr, true);
8201         }
8202
8203         /* Cleanup */
8204         heap_freetuple(heapTup);
8205 }
8206
8207 static void
8208 ATExecAlterColumnGenericOptions(Relation rel,
8209                                                                 const char *colName,
8210                                                                 List *options,
8211                                                                 LOCKMODE lockmode)
8212 {
8213         Relation        ftrel;
8214         Relation        attrel;
8215         ForeignServer *server;
8216         ForeignDataWrapper *fdw;
8217         HeapTuple       tuple;
8218         HeapTuple       newtuple;
8219         bool            isnull;
8220         Datum           repl_val[Natts_pg_attribute];
8221         bool            repl_null[Natts_pg_attribute];
8222         bool            repl_repl[Natts_pg_attribute];
8223         Datum           datum;
8224         Form_pg_foreign_table fttableform;
8225         Form_pg_attribute atttableform;
8226
8227         if (options == NIL)
8228                 return;
8229
8230         /* First, determine FDW validator associated to the foreign table. */
8231         ftrel = heap_open(ForeignTableRelationId, AccessShareLock);
8232         tuple = SearchSysCache1(FOREIGNTABLEREL, rel->rd_id);
8233         if (!HeapTupleIsValid(tuple))
8234                 ereport(ERROR,
8235                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
8236                                  errmsg("foreign table \"%s\" does not exist",
8237                                                 RelationGetRelationName(rel))));
8238         fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
8239         server = GetForeignServer(fttableform->ftserver);
8240         fdw = GetForeignDataWrapper(server->fdwid);
8241
8242         heap_close(ftrel, AccessShareLock);
8243         ReleaseSysCache(tuple);
8244
8245         attrel = heap_open(AttributeRelationId, RowExclusiveLock);
8246         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8247         if (!HeapTupleIsValid(tuple))
8248                 ereport(ERROR,
8249                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
8250                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
8251                                                 colName, RelationGetRelationName(rel))));
8252
8253         /* Prevent them from altering a system attribute */
8254         atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
8255         if (atttableform->attnum <= 0)
8256                 ereport(ERROR,
8257                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8258                                  errmsg("cannot alter system column \"%s\"", colName)));
8259
8260
8261         /* Initialize buffers for new tuple values */
8262         memset(repl_val, 0, sizeof(repl_val));
8263         memset(repl_null, false, sizeof(repl_null));
8264         memset(repl_repl, false, sizeof(repl_repl));
8265
8266         /* Extract the current options */
8267         datum = SysCacheGetAttr(ATTNAME,
8268                                                         tuple,
8269                                                         Anum_pg_attribute_attfdwoptions,
8270                                                         &isnull);
8271         if (isnull)
8272                 datum = PointerGetDatum(NULL);
8273
8274         /* Transform the options */
8275         datum = transformGenericOptions(AttributeRelationId,
8276                                                                         datum,
8277                                                                         options,
8278                                                                         fdw->fdwvalidator);
8279
8280         if (PointerIsValid(DatumGetPointer(datum)))
8281                 repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
8282         else
8283                 repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
8284
8285         repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
8286
8287         /* Everything looks good - update the tuple */
8288
8289         newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
8290                                                                  repl_val, repl_null, repl_repl);
8291
8292         simple_heap_update(attrel, &newtuple->t_self, newtuple);
8293         CatalogUpdateIndexes(attrel, newtuple);
8294
8295         InvokeObjectPostAlterHook(RelationRelationId,
8296                                                           RelationGetRelid(rel),
8297                                                           atttableform->attnum);
8298
8299         ReleaseSysCache(tuple);
8300
8301         heap_close(attrel, RowExclusiveLock);
8302
8303         heap_freetuple(newtuple);
8304 }
8305
8306 /*
8307  * Cleanup after we've finished all the ALTER TYPE operations for a
8308  * particular relation.  We have to drop and recreate all the indexes
8309  * and constraints that depend on the altered columns.
8310  */
8311 static void
8312 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
8313 {
8314         ObjectAddress obj;
8315         ListCell   *def_item;
8316         ListCell   *oid_item;
8317
8318         /*
8319          * Re-parse the index and constraint definitions, and attach them to the
8320          * appropriate work queue entries.  We do this before dropping because in
8321          * the case of a FOREIGN KEY constraint, we might not yet have exclusive
8322          * lock on the table the constraint is attached to, and we need to get
8323          * that before dropping.  It's safe because the parser won't actually look
8324          * at the catalogs to detect the existing entry.
8325          *
8326          * We can't rely on the output of deparsing to tell us which relation to
8327          * operate on, because concurrent activity might have made the name
8328          * resolve differently.  Instead, we've got to use the OID of the
8329          * constraint or index we're processing to figure out which relation to
8330          * operate on.
8331          */
8332         forboth(oid_item, tab->changedConstraintOids,
8333                         def_item, tab->changedConstraintDefs)
8334         {
8335                 Oid                     oldId = lfirst_oid(oid_item);
8336                 Oid                     relid;
8337                 Oid                     confrelid;
8338
8339                 get_constraint_relation_oids(oldId, &relid, &confrelid);
8340                 ATPostAlterTypeParse(oldId, relid, confrelid,
8341                                                          (char *) lfirst(def_item),
8342                                                          wqueue, lockmode, tab->rewrite);
8343         }
8344         forboth(oid_item, tab->changedIndexOids,
8345                         def_item, tab->changedIndexDefs)
8346         {
8347                 Oid                     oldId = lfirst_oid(oid_item);
8348                 Oid                     relid;
8349
8350                 relid = IndexGetRelation(oldId, false);
8351                 ATPostAlterTypeParse(oldId, relid, InvalidOid,
8352                                                          (char *) lfirst(def_item),
8353                                                          wqueue, lockmode, tab->rewrite);
8354         }
8355
8356         /*
8357          * Now we can drop the existing constraints and indexes --- constraints
8358          * first, since some of them might depend on the indexes.  In fact, we
8359          * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
8360          * we already ordered the constraint list to ensure that would happen. It
8361          * should be okay to use DROP_RESTRICT here, since nothing else should be
8362          * depending on these objects.
8363          */
8364         foreach(oid_item, tab->changedConstraintOids)
8365         {
8366                 obj.classId = ConstraintRelationId;
8367                 obj.objectId = lfirst_oid(oid_item);
8368                 obj.objectSubId = 0;
8369                 performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8370         }
8371
8372         foreach(oid_item, tab->changedIndexOids)
8373         {
8374                 obj.classId = RelationRelationId;
8375                 obj.objectId = lfirst_oid(oid_item);
8376                 obj.objectSubId = 0;
8377                 performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8378         }
8379
8380         /*
8381          * The objects will get recreated during subsequent passes over the work
8382          * queue.
8383          */
8384 }
8385
8386 static void
8387 ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
8388                                          List **wqueue, LOCKMODE lockmode, bool rewrite)
8389 {
8390         List       *raw_parsetree_list;
8391         List       *querytree_list;
8392         ListCell   *list_item;
8393         Relation        rel;
8394
8395         /*
8396          * We expect that we will get only ALTER TABLE and CREATE INDEX
8397          * statements. Hence, there is no need to pass them through
8398          * parse_analyze() or the rewriter, but instead we need to pass them
8399          * through parse_utilcmd.c to make them ready for execution.
8400          */
8401         raw_parsetree_list = raw_parser(cmd);
8402         querytree_list = NIL;
8403         foreach(list_item, raw_parsetree_list)
8404         {
8405                 Node       *stmt = (Node *) lfirst(list_item);
8406
8407                 if (IsA(stmt, IndexStmt))
8408                         querytree_list = lappend(querytree_list,
8409                                                                          transformIndexStmt(oldRelId,
8410                                                                                                                 (IndexStmt *) stmt,
8411                                                                                                                 cmd));
8412                 else if (IsA(stmt, AlterTableStmt))
8413                         querytree_list = list_concat(querytree_list,
8414                                                                                  transformAlterTableStmt(oldRelId,
8415                                                                                                          (AlterTableStmt *) stmt,
8416                                                                                                                                  cmd));
8417                 else
8418                         querytree_list = lappend(querytree_list, stmt);
8419         }
8420
8421         /* Caller should already have acquired whatever lock we need. */
8422         rel = relation_open(oldRelId, NoLock);
8423
8424         /*
8425          * Attach each generated command to the proper place in the work queue.
8426          * Note this could result in creation of entirely new work-queue entries.
8427          *
8428          * Also note that we have to tweak the command subtypes, because it turns
8429          * out that re-creation of indexes and constraints has to act a bit
8430          * differently from initial creation.
8431          */
8432         foreach(list_item, querytree_list)
8433         {
8434                 Node       *stm = (Node *) lfirst(list_item);
8435                 AlteredTableInfo *tab;
8436
8437                 switch (nodeTag(stm))
8438                 {
8439                         case T_IndexStmt:
8440                                 {
8441                                         IndexStmt  *stmt = (IndexStmt *) stm;
8442                                         AlterTableCmd *newcmd;
8443
8444                                         if (!rewrite)
8445                                                 TryReuseIndex(oldId, stmt);
8446
8447                                         tab = ATGetQueueEntry(wqueue, rel);
8448                                         newcmd = makeNode(AlterTableCmd);
8449                                         newcmd->subtype = AT_ReAddIndex;
8450                                         newcmd->def = (Node *) stmt;
8451                                         tab->subcmds[AT_PASS_OLD_INDEX] =
8452                                                 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
8453                                         break;
8454                                 }
8455                         case T_AlterTableStmt:
8456                                 {
8457                                         AlterTableStmt *stmt = (AlterTableStmt *) stm;
8458                                         ListCell   *lcmd;
8459
8460                                         tab = ATGetQueueEntry(wqueue, rel);
8461                                         foreach(lcmd, stmt->cmds)
8462                                         {
8463                                                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
8464                                                 Constraint *con;
8465
8466                                                 switch (cmd->subtype)
8467                                                 {
8468                                                         case AT_AddIndex:
8469                                                                 Assert(IsA(cmd->def, IndexStmt));
8470                                                                 if (!rewrite)
8471                                                                         TryReuseIndex(get_constraint_index(oldId),
8472                                                                                                   (IndexStmt *) cmd->def);
8473                                                                 cmd->subtype = AT_ReAddIndex;
8474                                                                 tab->subcmds[AT_PASS_OLD_INDEX] =
8475                                                                         lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
8476                                                                 break;
8477                                                         case AT_AddConstraint:
8478                                                                 Assert(IsA(cmd->def, Constraint));
8479                                                                 con = (Constraint *) cmd->def;
8480                                                                 con->old_pktable_oid = refRelId;
8481                                                                 /* rewriting neither side of a FK */
8482                                                                 if (con->contype == CONSTR_FOREIGN &&
8483                                                                         !rewrite && tab->rewrite == 0)
8484                                                                         TryReuseForeignKey(oldId, con);
8485                                                                 cmd->subtype = AT_ReAddConstraint;
8486                                                                 tab->subcmds[AT_PASS_OLD_CONSTR] =
8487                                                                         lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
8488                                                                 break;
8489                                                         default:
8490                                                                 elog(ERROR, "unexpected statement type: %d",
8491                                                                          (int) cmd->subtype);
8492                                                 }
8493                                         }
8494                                         break;
8495                                 }
8496                         default:
8497                                 elog(ERROR, "unexpected statement type: %d",
8498                                          (int) nodeTag(stm));
8499                 }
8500         }
8501
8502         relation_close(rel, NoLock);
8503 }
8504
8505 /*
8506  * Subroutine for ATPostAlterTypeParse().  Calls out to CheckIndexCompatible()
8507  * for the real analysis, then mutates the IndexStmt based on that verdict.
8508  */
8509 static void
8510 TryReuseIndex(Oid oldId, IndexStmt *stmt)
8511 {
8512         if (CheckIndexCompatible(oldId,
8513                                                          stmt->accessMethod,
8514                                                          stmt->indexParams,
8515                                                          stmt->excludeOpNames))
8516         {
8517                 Relation        irel = index_open(oldId, NoLock);
8518
8519                 stmt->oldNode = irel->rd_node.relNode;
8520                 index_close(irel, NoLock);
8521         }
8522 }
8523
8524 /*
8525  * Subroutine for ATPostAlterTypeParse().
8526  *
8527  * Stash the old P-F equality operator into the Constraint node, for possible
8528  * use by ATAddForeignKeyConstraint() in determining whether revalidation of
8529  * this constraint can be skipped.
8530  */
8531 static void
8532 TryReuseForeignKey(Oid oldId, Constraint *con)
8533 {
8534         HeapTuple       tup;
8535         Datum           adatum;
8536         bool            isNull;
8537         ArrayType  *arr;
8538         Oid                *rawarr;
8539         int                     numkeys;
8540         int                     i;
8541
8542         Assert(con->contype == CONSTR_FOREIGN);
8543         Assert(con->old_conpfeqop == NIL);      /* already prepared this node */
8544
8545         tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
8546         if (!HeapTupleIsValid(tup)) /* should not happen */
8547                 elog(ERROR, "cache lookup failed for constraint %u", oldId);
8548
8549         adatum = SysCacheGetAttr(CONSTROID, tup,
8550                                                          Anum_pg_constraint_conpfeqop, &isNull);
8551         if (isNull)
8552                 elog(ERROR, "null conpfeqop for constraint %u", oldId);
8553         arr = DatumGetArrayTypeP(adatum);       /* ensure not toasted */
8554         numkeys = ARR_DIMS(arr)[0];
8555         /* test follows the one in ri_FetchConstraintInfo() */
8556         if (ARR_NDIM(arr) != 1 ||
8557                 ARR_HASNULL(arr) ||
8558                 ARR_ELEMTYPE(arr) != OIDOID)
8559                 elog(ERROR, "conpfeqop is not a 1-D Oid array");
8560         rawarr = (Oid *) ARR_DATA_PTR(arr);
8561
8562         /* stash a List of the operator Oids in our Constraint node */
8563         for (i = 0; i < numkeys; i++)
8564                 con->old_conpfeqop = lcons_oid(rawarr[i], con->old_conpfeqop);
8565
8566         ReleaseSysCache(tup);
8567 }
8568
8569 /*
8570  * ALTER TABLE OWNER
8571  *
8572  * recursing is true if we are recursing from a table to its indexes,
8573  * sequences, or toast table.  We don't allow the ownership of those things to
8574  * be changed separately from the parent table.  Also, we can skip permission
8575  * checks (this is necessary not just an optimization, else we'd fail to
8576  * handle toast tables properly).
8577  *
8578  * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
8579  * free-standing composite type.
8580  */
8581 void
8582 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
8583 {
8584         Relation        target_rel;
8585         Relation        class_rel;
8586         HeapTuple       tuple;
8587         Form_pg_class tuple_class;
8588
8589         /*
8590          * Get exclusive lock till end of transaction on the target table. Use
8591          * relation_open so that we can work on indexes and sequences.
8592          */
8593         target_rel = relation_open(relationOid, lockmode);
8594
8595         /* Get its pg_class tuple, too */
8596         class_rel = heap_open(RelationRelationId, RowExclusiveLock);
8597
8598         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
8599         if (!HeapTupleIsValid(tuple))
8600                 elog(ERROR, "cache lookup failed for relation %u", relationOid);
8601         tuple_class = (Form_pg_class) GETSTRUCT(tuple);
8602
8603         /* Can we change the ownership of this tuple? */
8604         switch (tuple_class->relkind)
8605         {
8606                 case RELKIND_RELATION:
8607                 case RELKIND_VIEW:
8608                 case RELKIND_MATVIEW:
8609                 case RELKIND_FOREIGN_TABLE:
8610                         /* ok to change owner */
8611                         break;
8612                 case RELKIND_INDEX:
8613                         if (!recursing)
8614                         {
8615                                 /*
8616                                  * Because ALTER INDEX OWNER used to be allowed, and in fact
8617                                  * is generated by old versions of pg_dump, we give a warning
8618                                  * and do nothing rather than erroring out.  Also, to avoid
8619                                  * unnecessary chatter while restoring those old dumps, say
8620                                  * nothing at all if the command would be a no-op anyway.
8621                                  */
8622                                 if (tuple_class->relowner != newOwnerId)
8623                                         ereport(WARNING,
8624                                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8625                                                          errmsg("cannot change owner of index \"%s\"",
8626                                                                         NameStr(tuple_class->relname)),
8627                                                          errhint("Change the ownership of the index's table, instead.")));
8628                                 /* quick hack to exit via the no-op path */
8629                                 newOwnerId = tuple_class->relowner;
8630                         }
8631                         break;
8632                 case RELKIND_SEQUENCE:
8633                         if (!recursing &&
8634                                 tuple_class->relowner != newOwnerId)
8635                         {
8636                                 /* if it's an owned sequence, disallow changing it by itself */
8637                                 Oid                     tableId;
8638                                 int32           colId;
8639
8640                                 if (sequenceIsOwned(relationOid, &tableId, &colId))
8641                                         ereport(ERROR,
8642                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8643                                                          errmsg("cannot change owner of sequence \"%s\"",
8644                                                                         NameStr(tuple_class->relname)),
8645                                           errdetail("Sequence \"%s\" is linked to table \"%s\".",
8646                                                                 NameStr(tuple_class->relname),
8647                                                                 get_rel_name(tableId))));
8648                         }
8649                         break;
8650                 case RELKIND_COMPOSITE_TYPE:
8651                         if (recursing)
8652                                 break;
8653                         ereport(ERROR,
8654                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8655                                          errmsg("\"%s\" is a composite type",
8656                                                         NameStr(tuple_class->relname)),
8657                                          errhint("Use ALTER TYPE instead.")));
8658                         break;
8659                 case RELKIND_TOASTVALUE:
8660                         if (recursing)
8661                                 break;
8662                         /* FALL THRU */
8663                 default:
8664                         ereport(ERROR,
8665                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8666                         errmsg("\"%s\" is not a table, view, sequence, or foreign table",
8667                                    NameStr(tuple_class->relname))));
8668         }
8669
8670         /*
8671          * If the new owner is the same as the existing owner, consider the
8672          * command to have succeeded.  This is for dump restoration purposes.
8673          */
8674         if (tuple_class->relowner != newOwnerId)
8675         {
8676                 Datum           repl_val[Natts_pg_class];
8677                 bool            repl_null[Natts_pg_class];
8678                 bool            repl_repl[Natts_pg_class];
8679                 Acl                *newAcl;
8680                 Datum           aclDatum;
8681                 bool            isNull;
8682                 HeapTuple       newtuple;
8683
8684                 /* skip permission checks when recursing to index or toast table */
8685                 if (!recursing)
8686                 {
8687                         /* Superusers can always do it */
8688                         if (!superuser())
8689                         {
8690                                 Oid                     namespaceOid = tuple_class->relnamespace;
8691                                 AclResult       aclresult;
8692
8693                                 /* Otherwise, must be owner of the existing object */
8694                                 if (!pg_class_ownercheck(relationOid, GetUserId()))
8695                                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
8696                                                                    RelationGetRelationName(target_rel));
8697
8698                                 /* Must be able to become new owner */
8699                                 check_is_member_of_role(GetUserId(), newOwnerId);
8700
8701                                 /* New owner must have CREATE privilege on namespace */
8702                                 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
8703                                                                                                   ACL_CREATE);
8704                                 if (aclresult != ACLCHECK_OK)
8705                                         aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
8706                                                                    get_namespace_name(namespaceOid));
8707                         }
8708                 }
8709
8710                 memset(repl_null, false, sizeof(repl_null));
8711                 memset(repl_repl, false, sizeof(repl_repl));
8712
8713                 repl_repl[Anum_pg_class_relowner - 1] = true;
8714                 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
8715
8716                 /*
8717                  * Determine the modified ACL for the new owner.  This is only
8718                  * necessary when the ACL is non-null.
8719                  */
8720                 aclDatum = SysCacheGetAttr(RELOID, tuple,
8721                                                                    Anum_pg_class_relacl,
8722                                                                    &isNull);
8723                 if (!isNull)
8724                 {
8725                         newAcl = aclnewowner(DatumGetAclP(aclDatum),
8726                                                                  tuple_class->relowner, newOwnerId);
8727                         repl_repl[Anum_pg_class_relacl - 1] = true;
8728                         repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
8729                 }
8730
8731                 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
8732
8733                 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
8734                 CatalogUpdateIndexes(class_rel, newtuple);
8735
8736                 heap_freetuple(newtuple);
8737
8738                 /*
8739                  * We must similarly update any per-column ACLs to reflect the new
8740                  * owner; for neatness reasons that's split out as a subroutine.
8741                  */
8742                 change_owner_fix_column_acls(relationOid,
8743                                                                          tuple_class->relowner,
8744                                                                          newOwnerId);
8745
8746                 /*
8747                  * Update owner dependency reference, if any.  A composite type has
8748                  * none, because it's tracked for the pg_type entry instead of here;
8749                  * indexes and TOAST tables don't have their own entries either.
8750                  */
8751                 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
8752                         tuple_class->relkind != RELKIND_INDEX &&
8753                         tuple_class->relkind != RELKIND_TOASTVALUE)
8754                         changeDependencyOnOwner(RelationRelationId, relationOid,
8755                                                                         newOwnerId);
8756
8757                 /*
8758                  * Also change the ownership of the table's row type, if it has one
8759                  */
8760                 if (tuple_class->relkind != RELKIND_INDEX)
8761                         AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
8762                                                          tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
8763
8764                 /*
8765                  * If we are operating on a table or materialized view, also change
8766                  * the ownership of any indexes and sequences that belong to the
8767                  * relation, as well as its toast table (if it has one).
8768                  */
8769                 if (tuple_class->relkind == RELKIND_RELATION ||
8770                         tuple_class->relkind == RELKIND_MATVIEW ||
8771                         tuple_class->relkind == RELKIND_TOASTVALUE)
8772                 {
8773                         List       *index_oid_list;
8774                         ListCell   *i;
8775
8776                         /* Find all the indexes belonging to this relation */
8777                         index_oid_list = RelationGetIndexList(target_rel);
8778
8779                         /* For each index, recursively change its ownership */
8780                         foreach(i, index_oid_list)
8781                                 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
8782
8783                         list_free(index_oid_list);
8784                 }
8785
8786                 if (tuple_class->relkind == RELKIND_RELATION ||
8787                         tuple_class->relkind == RELKIND_MATVIEW)
8788                 {
8789                         /* If it has a toast table, recurse to change its ownership */
8790                         if (tuple_class->reltoastrelid != InvalidOid)
8791                                 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
8792                                                                   true, lockmode);
8793
8794                         /* If it has dependent sequences, recurse to change them too */
8795                         change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
8796                 }
8797         }
8798
8799         InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
8800
8801         ReleaseSysCache(tuple);
8802         heap_close(class_rel, RowExclusiveLock);
8803         relation_close(target_rel, NoLock);
8804 }
8805
8806 /*
8807  * change_owner_fix_column_acls
8808  *
8809  * Helper function for ATExecChangeOwner.  Scan the columns of the table
8810  * and fix any non-null column ACLs to reflect the new owner.
8811  */
8812 static void
8813 change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
8814 {
8815         Relation        attRelation;
8816         SysScanDesc scan;
8817         ScanKeyData key[1];
8818         HeapTuple       attributeTuple;
8819
8820         attRelation = heap_open(AttributeRelationId, RowExclusiveLock);
8821         ScanKeyInit(&key[0],
8822                                 Anum_pg_attribute_attrelid,
8823                                 BTEqualStrategyNumber, F_OIDEQ,
8824                                 ObjectIdGetDatum(relationOid));
8825         scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
8826                                                           true, NULL, 1, key);
8827         while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
8828         {
8829                 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
8830                 Datum           repl_val[Natts_pg_attribute];
8831                 bool            repl_null[Natts_pg_attribute];
8832                 bool            repl_repl[Natts_pg_attribute];
8833                 Acl                *newAcl;
8834                 Datum           aclDatum;
8835                 bool            isNull;
8836                 HeapTuple       newtuple;
8837
8838                 /* Ignore dropped columns */
8839                 if (att->attisdropped)
8840                         continue;
8841
8842                 aclDatum = heap_getattr(attributeTuple,
8843                                                                 Anum_pg_attribute_attacl,
8844                                                                 RelationGetDescr(attRelation),
8845                                                                 &isNull);
8846                 /* Null ACLs do not require changes */
8847                 if (isNull)
8848                         continue;
8849
8850                 memset(repl_null, false, sizeof(repl_null));
8851                 memset(repl_repl, false, sizeof(repl_repl));
8852
8853                 newAcl = aclnewowner(DatumGetAclP(aclDatum),
8854                                                          oldOwnerId, newOwnerId);
8855                 repl_repl[Anum_pg_attribute_attacl - 1] = true;
8856                 repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
8857
8858                 newtuple = heap_modify_tuple(attributeTuple,
8859                                                                          RelationGetDescr(attRelation),
8860                                                                          repl_val, repl_null, repl_repl);
8861
8862                 simple_heap_update(attRelation, &newtuple->t_self, newtuple);
8863                 CatalogUpdateIndexes(attRelation, newtuple);
8864
8865                 heap_freetuple(newtuple);
8866         }
8867         systable_endscan(scan);
8868         heap_close(attRelation, RowExclusiveLock);
8869 }
8870
8871 /*
8872  * change_owner_recurse_to_sequences
8873  *
8874  * Helper function for ATExecChangeOwner.  Examines pg_depend searching
8875  * for sequences that are dependent on serial columns, and changes their
8876  * ownership.
8877  */
8878 static void
8879 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
8880 {
8881         Relation        depRel;
8882         SysScanDesc scan;
8883         ScanKeyData key[2];
8884         HeapTuple       tup;
8885
8886         /*
8887          * SERIAL sequences are those having an auto dependency on one of the
8888          * table's columns (we don't care *which* column, exactly).
8889          */
8890         depRel = heap_open(DependRelationId, AccessShareLock);
8891
8892         ScanKeyInit(&key[0],
8893                                 Anum_pg_depend_refclassid,
8894                                 BTEqualStrategyNumber, F_OIDEQ,
8895                                 ObjectIdGetDatum(RelationRelationId));
8896         ScanKeyInit(&key[1],
8897                                 Anum_pg_depend_refobjid,
8898                                 BTEqualStrategyNumber, F_OIDEQ,
8899                                 ObjectIdGetDatum(relationOid));
8900         /* we leave refobjsubid unspecified */
8901
8902         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
8903                                                           NULL, 2, key);
8904
8905         while (HeapTupleIsValid(tup = systable_getnext(scan)))
8906         {
8907                 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
8908                 Relation        seqRel;
8909
8910                 /* skip dependencies other than auto dependencies on columns */
8911                 if (depForm->refobjsubid == 0 ||
8912                         depForm->classid != RelationRelationId ||
8913                         depForm->objsubid != 0 ||
8914                         depForm->deptype != DEPENDENCY_AUTO)
8915                         continue;
8916
8917                 /* Use relation_open just in case it's an index */
8918                 seqRel = relation_open(depForm->objid, lockmode);
8919
8920                 /* skip non-sequence relations */
8921                 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
8922                 {
8923                         /* No need to keep the lock */
8924                         relation_close(seqRel, lockmode);
8925                         continue;
8926                 }
8927
8928                 /* We don't need to close the sequence while we alter it. */
8929                 ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
8930
8931                 /* Now we can close it.  Keep the lock till end of transaction. */
8932                 relation_close(seqRel, NoLock);
8933         }
8934
8935         systable_endscan(scan);
8936
8937         relation_close(depRel, AccessShareLock);
8938 }
8939
8940 /*
8941  * ALTER TABLE CLUSTER ON
8942  *
8943  * The only thing we have to do is to change the indisclustered bits.
8944  */
8945 static void
8946 ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
8947 {
8948         Oid                     indexOid;
8949
8950         indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
8951
8952         if (!OidIsValid(indexOid))
8953                 ereport(ERROR,
8954                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
8955                                  errmsg("index \"%s\" for table \"%s\" does not exist",
8956                                                 indexName, RelationGetRelationName(rel))));
8957
8958         /* Check index is valid to cluster on */
8959         check_index_is_clusterable(rel, indexOid, false, lockmode);
8960
8961         /* And do the work */
8962         mark_index_clustered(rel, indexOid, false);
8963 }
8964
8965 /*
8966  * ALTER TABLE SET WITHOUT CLUSTER
8967  *
8968  * We have to find any indexes on the table that have indisclustered bit
8969  * set and turn it off.
8970  */
8971 static void
8972 ATExecDropCluster(Relation rel, LOCKMODE lockmode)
8973 {
8974         mark_index_clustered(rel, InvalidOid, false);
8975 }
8976
8977 /*
8978  * ALTER TABLE SET TABLESPACE
8979  */
8980 static void
8981 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename, LOCKMODE lockmode)
8982 {
8983         Oid                     tablespaceId;
8984
8985         /* Check that the tablespace exists */
8986         tablespaceId = get_tablespace_oid(tablespacename, false);
8987
8988         /* Check permissions except when moving to database's default */
8989         if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
8990         {
8991                 AclResult       aclresult;
8992
8993                 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
8994                 if (aclresult != ACLCHECK_OK)
8995                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
8996         }
8997
8998         /* Save info for Phase 3 to do the real work */
8999         if (OidIsValid(tab->newTableSpace))
9000                 ereport(ERROR,
9001                                 (errcode(ERRCODE_SYNTAX_ERROR),
9002                                  errmsg("cannot have multiple SET TABLESPACE subcommands")));
9003
9004         tab->newTableSpace = tablespaceId;
9005 }
9006
9007 /*
9008  * Set, reset, or replace reloptions.
9009  */
9010 static void
9011 ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
9012                                         LOCKMODE lockmode)
9013 {
9014         Oid                     relid;
9015         Relation        pgclass;
9016         HeapTuple       tuple;
9017         HeapTuple       newtuple;
9018         Datum           datum;
9019         bool            isnull;
9020         Datum           newOptions;
9021         Datum           repl_val[Natts_pg_class];
9022         bool            repl_null[Natts_pg_class];
9023         bool            repl_repl[Natts_pg_class];
9024         static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
9025
9026         if (defList == NIL && operation != AT_ReplaceRelOptions)
9027                 return;                                 /* nothing to do */
9028
9029         pgclass = heap_open(RelationRelationId, RowExclusiveLock);
9030
9031         /* Fetch heap tuple */
9032         relid = RelationGetRelid(rel);
9033         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
9034         if (!HeapTupleIsValid(tuple))
9035                 elog(ERROR, "cache lookup failed for relation %u", relid);
9036
9037         if (operation == AT_ReplaceRelOptions)
9038         {
9039                 /*
9040                  * If we're supposed to replace the reloptions list, we just pretend
9041                  * there were none before.
9042                  */
9043                 datum = (Datum) 0;
9044                 isnull = true;
9045         }
9046         else
9047         {
9048                 /* Get the old reloptions */
9049                 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
9050                                                                 &isnull);
9051         }
9052
9053         /* Generate new proposed reloptions (text array) */
9054         newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9055                                                                          defList, NULL, validnsps, false,
9056                                                                          operation == AT_ResetRelOptions);
9057
9058         /* Validate */
9059         switch (rel->rd_rel->relkind)
9060         {
9061                 case RELKIND_RELATION:
9062                 case RELKIND_TOASTVALUE:
9063                 case RELKIND_MATVIEW:
9064                         (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
9065                         break;
9066                 case RELKIND_VIEW:
9067                         (void) view_reloptions(newOptions, true);
9068                         break;
9069                 case RELKIND_INDEX:
9070                         (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
9071                         break;
9072                 default:
9073                         ereport(ERROR,
9074                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9075                                          errmsg("\"%s\" is not a table, view, materialized view, index, or TOAST table",
9076                                                         RelationGetRelationName(rel))));
9077                         break;
9078         }
9079
9080         /* Special-case validation of view options */
9081         if (rel->rd_rel->relkind == RELKIND_VIEW)
9082         {
9083                 Query      *view_query = get_view_query(rel);
9084                 List       *view_options = untransformRelOptions(newOptions);
9085                 ListCell   *cell;
9086                 bool            check_option = false;
9087
9088                 foreach(cell, view_options)
9089                 {
9090                         DefElem    *defel = (DefElem *) lfirst(cell);
9091
9092                         if (pg_strcasecmp(defel->defname, "check_option") == 0)
9093                                 check_option = true;
9094                 }
9095
9096                 /*
9097                  * If the check option is specified, look to see if the view is
9098                  * actually auto-updatable or not.
9099                  */
9100                 if (check_option)
9101                 {
9102                         const char *view_updatable_error =
9103                         view_query_is_auto_updatable(view_query, true);
9104
9105                         if (view_updatable_error)
9106                                 ereport(ERROR,
9107                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9108                                                  errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
9109                                                  errhint("%s", view_updatable_error)));
9110                 }
9111         }
9112
9113         /*
9114          * All we need do here is update the pg_class row; the new options will be
9115          * propagated into relcaches during post-commit cache inval.
9116          */
9117         memset(repl_val, 0, sizeof(repl_val));
9118         memset(repl_null, false, sizeof(repl_null));
9119         memset(repl_repl, false, sizeof(repl_repl));
9120
9121         if (newOptions != (Datum) 0)
9122                 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
9123         else
9124                 repl_null[Anum_pg_class_reloptions - 1] = true;
9125
9126         repl_repl[Anum_pg_class_reloptions - 1] = true;
9127
9128         newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
9129                                                                  repl_val, repl_null, repl_repl);
9130
9131         simple_heap_update(pgclass, &newtuple->t_self, newtuple);
9132
9133         CatalogUpdateIndexes(pgclass, newtuple);
9134
9135         InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
9136
9137         heap_freetuple(newtuple);
9138
9139         ReleaseSysCache(tuple);
9140
9141         /* repeat the whole exercise for the toast table, if there's one */
9142         if (OidIsValid(rel->rd_rel->reltoastrelid))
9143         {
9144                 Relation        toastrel;
9145                 Oid                     toastid = rel->rd_rel->reltoastrelid;
9146
9147                 toastrel = heap_open(toastid, lockmode);
9148
9149                 /* Fetch heap tuple */
9150                 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
9151                 if (!HeapTupleIsValid(tuple))
9152                         elog(ERROR, "cache lookup failed for relation %u", toastid);
9153
9154                 if (operation == AT_ReplaceRelOptions)
9155                 {
9156                         /*
9157                          * If we're supposed to replace the reloptions list, we just
9158                          * pretend there were none before.
9159                          */
9160                         datum = (Datum) 0;
9161                         isnull = true;
9162                 }
9163                 else
9164                 {
9165                         /* Get the old reloptions */
9166                         datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
9167                                                                         &isnull);
9168                 }
9169
9170                 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9171                                                                                  defList, "toast", validnsps, false,
9172                                                                                  operation == AT_ResetRelOptions);
9173
9174                 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
9175
9176                 memset(repl_val, 0, sizeof(repl_val));
9177                 memset(repl_null, false, sizeof(repl_null));
9178                 memset(repl_repl, false, sizeof(repl_repl));
9179
9180                 if (newOptions != (Datum) 0)
9181                         repl_val[Anum_pg_class_reloptions - 1] = newOptions;
9182                 else
9183                         repl_null[Anum_pg_class_reloptions - 1] = true;
9184
9185                 repl_repl[Anum_pg_class_reloptions - 1] = true;
9186
9187                 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
9188                                                                          repl_val, repl_null, repl_repl);
9189
9190                 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
9191
9192                 CatalogUpdateIndexes(pgclass, newtuple);
9193
9194                 InvokeObjectPostAlterHookArg(RelationRelationId,
9195                                                                          RelationGetRelid(toastrel), 0,
9196                                                                          InvalidOid, true);
9197
9198                 heap_freetuple(newtuple);
9199
9200                 ReleaseSysCache(tuple);
9201
9202                 heap_close(toastrel, NoLock);
9203         }
9204
9205         heap_close(pgclass, RowExclusiveLock);
9206 }
9207
9208 /*
9209  * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
9210  * rewriting to be done, so we just want to copy the data as fast as possible.
9211  */
9212 static void
9213 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
9214 {
9215         Relation        rel;
9216         Oid                     oldTableSpace;
9217         Oid                     reltoastrelid;
9218         Oid                     newrelfilenode;
9219         RelFileNode newrnode;
9220         SMgrRelation dstrel;
9221         Relation        pg_class;
9222         HeapTuple       tuple;
9223         Form_pg_class rd_rel;
9224         ForkNumber      forkNum;
9225         List       *reltoastidxids = NIL;
9226         ListCell   *lc;
9227
9228         /*
9229          * Need lock here in case we are recursing to toast table or index
9230          */
9231         rel = relation_open(tableOid, lockmode);
9232
9233         /*
9234          * No work if no change in tablespace.
9235          */
9236         oldTableSpace = rel->rd_rel->reltablespace;
9237         if (newTableSpace == oldTableSpace ||
9238                 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
9239         {
9240                 InvokeObjectPostAlterHook(RelationRelationId,
9241                                                                   RelationGetRelid(rel), 0);
9242
9243                 relation_close(rel, NoLock);
9244                 return;
9245         }
9246
9247         /*
9248          * We cannot support moving mapped relations into different tablespaces.
9249          * (In particular this eliminates all shared catalogs.)
9250          */
9251         if (RelationIsMapped(rel))
9252                 ereport(ERROR,
9253                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9254                                  errmsg("cannot move system relation \"%s\"",
9255                                                 RelationGetRelationName(rel))));
9256
9257         /* Can't move a non-shared relation into pg_global */
9258         if (newTableSpace == GLOBALTABLESPACE_OID)
9259                 ereport(ERROR,
9260                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9261                                  errmsg("only shared relations can be placed in pg_global tablespace")));
9262
9263         /*
9264          * Don't allow moving temp tables of other backends ... their local buffer
9265          * manager is not going to cope.
9266          */
9267         if (RELATION_IS_OTHER_TEMP(rel))
9268                 ereport(ERROR,
9269                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9270                                  errmsg("cannot move temporary tables of other sessions")));
9271
9272         reltoastrelid = rel->rd_rel->reltoastrelid;
9273         /* Fetch the list of indexes on toast relation if necessary */
9274         if (OidIsValid(reltoastrelid))
9275         {
9276                 Relation        toastRel = relation_open(reltoastrelid, lockmode);
9277
9278                 reltoastidxids = RelationGetIndexList(toastRel);
9279                 relation_close(toastRel, lockmode);
9280         }
9281
9282         /* Get a modifiable copy of the relation's pg_class row */
9283         pg_class = heap_open(RelationRelationId, RowExclusiveLock);
9284
9285         tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(tableOid));
9286         if (!HeapTupleIsValid(tuple))
9287                 elog(ERROR, "cache lookup failed for relation %u", tableOid);
9288         rd_rel = (Form_pg_class) GETSTRUCT(tuple);
9289
9290         /*
9291          * Since we copy the file directly without looking at the shared buffers,
9292          * we'd better first flush out any pages of the source relation that are
9293          * in shared buffers.  We assume no new changes will be made while we are
9294          * holding exclusive lock on the rel.
9295          */
9296         FlushRelationBuffers(rel);
9297
9298         /*
9299          * Relfilenodes are not unique in databases across tablespaces, so we need
9300          * to allocate a new one in the new tablespace.
9301          */
9302         newrelfilenode = GetNewRelFileNode(newTableSpace, NULL,
9303                                                                            rel->rd_rel->relpersistence);
9304
9305         /* Open old and new relation */
9306         newrnode = rel->rd_node;
9307         newrnode.relNode = newrelfilenode;
9308         newrnode.spcNode = newTableSpace;
9309         dstrel = smgropen(newrnode, rel->rd_backend);
9310
9311         RelationOpenSmgr(rel);
9312
9313         /*
9314          * Create and copy all forks of the relation, and schedule unlinking of
9315          * old physical files.
9316          *
9317          * NOTE: any conflict in relfilenode value will be caught in
9318          * RelationCreateStorage().
9319          */
9320         RelationCreateStorage(newrnode, rel->rd_rel->relpersistence);
9321
9322         /* copy main fork */
9323         copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM,
9324                                            rel->rd_rel->relpersistence);
9325
9326         /* copy those extra forks that exist */
9327         for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
9328         {
9329                 if (smgrexists(rel->rd_smgr, forkNum))
9330                 {
9331                         smgrcreate(dstrel, forkNum, false);
9332                         copy_relation_data(rel->rd_smgr, dstrel, forkNum,
9333                                                            rel->rd_rel->relpersistence);
9334                 }
9335         }
9336
9337         /* drop old relation, and close new one */
9338         RelationDropStorage(rel);
9339         smgrclose(dstrel);
9340
9341         /* update the pg_class row */
9342         rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
9343         rd_rel->relfilenode = newrelfilenode;
9344         simple_heap_update(pg_class, &tuple->t_self, tuple);
9345         CatalogUpdateIndexes(pg_class, tuple);
9346
9347         InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
9348
9349         heap_freetuple(tuple);
9350
9351         heap_close(pg_class, RowExclusiveLock);
9352
9353         relation_close(rel, NoLock);
9354
9355         /* Make sure the reltablespace change is visible */
9356         CommandCounterIncrement();
9357
9358         /* Move associated toast relation and/or indexes, too */
9359         if (OidIsValid(reltoastrelid))
9360                 ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
9361         foreach(lc, reltoastidxids)
9362                 ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
9363
9364         /* Clean up */
9365         list_free(reltoastidxids);
9366 }
9367
9368 /*
9369  * Alter Table ALL ... SET TABLESPACE
9370  *
9371  * Allows a user to move all objects of some type in a given tablespace in the
9372  * current database to another tablespace.  Objects can be chosen based on the
9373  * owner of the object also, to allow users to move only their objects.
9374  * The user must have CREATE rights on the new tablespace, as usual.   The main
9375  * permissions handling is done by the lower-level table move function.
9376  *
9377  * All to-be-moved objects are locked first. If NOWAIT is specified and the
9378  * lock can't be acquired then we ereport(ERROR).
9379  */
9380 Oid
9381 AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
9382 {
9383         List       *relations = NIL;
9384         ListCell   *l;
9385         ScanKeyData key[1];
9386         Relation        rel;
9387         HeapScanDesc scan;
9388         HeapTuple       tuple;
9389         Oid                     orig_tablespaceoid;
9390         Oid                     new_tablespaceoid;
9391         List       *role_oids = roleSpecsToIds(stmt->roles);
9392
9393         /* Ensure we were not asked to move something we can't */
9394         if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
9395                 stmt->objtype != OBJECT_MATVIEW)
9396                 ereport(ERROR,
9397                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9398                                  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
9399
9400         /* Get the orig and new tablespace OIDs */
9401         orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
9402         new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
9403
9404         /* Can't move shared relations in to or out of pg_global */
9405         /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
9406         if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
9407                 new_tablespaceoid == GLOBALTABLESPACE_OID)
9408                 ereport(ERROR,
9409                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9410                                  errmsg("cannot move relations in to or out of pg_global tablespace")));
9411
9412         /*
9413          * Must have CREATE rights on the new tablespace, unless it is the
9414          * database default tablespace (which all users implicitly have CREATE
9415          * rights on).
9416          */
9417         if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
9418         {
9419                 AclResult       aclresult;
9420
9421                 aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
9422                                                                                    ACL_CREATE);
9423                 if (aclresult != ACLCHECK_OK)
9424                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
9425                                                    get_tablespace_name(new_tablespaceoid));
9426         }
9427
9428         /*
9429          * Now that the checks are done, check if we should set either to
9430          * InvalidOid because it is our database's default tablespace.
9431          */
9432         if (orig_tablespaceoid == MyDatabaseTableSpace)
9433                 orig_tablespaceoid = InvalidOid;
9434
9435         if (new_tablespaceoid == MyDatabaseTableSpace)
9436                 new_tablespaceoid = InvalidOid;
9437
9438         /* no-op */
9439         if (orig_tablespaceoid == new_tablespaceoid)
9440                 return new_tablespaceoid;
9441
9442         /*
9443          * Walk the list of objects in the tablespace and move them. This will
9444          * only find objects in our database, of course.
9445          */
9446         ScanKeyInit(&key[0],
9447                                 Anum_pg_class_reltablespace,
9448                                 BTEqualStrategyNumber, F_OIDEQ,
9449                                 ObjectIdGetDatum(orig_tablespaceoid));
9450
9451         rel = heap_open(RelationRelationId, AccessShareLock);
9452         scan = heap_beginscan_catalog(rel, 1, key);
9453         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
9454         {
9455                 Oid                     relOid = HeapTupleGetOid(tuple);
9456                 Form_pg_class relForm;
9457
9458                 relForm = (Form_pg_class) GETSTRUCT(tuple);
9459
9460                 /*
9461                  * Do not move objects in pg_catalog as part of this, if an admin
9462                  * really wishes to do so, they can issue the individual ALTER
9463                  * commands directly.
9464                  *
9465                  * Also, explicitly avoid any shared tables, temp tables, or TOAST
9466                  * (TOAST will be moved with the main table).
9467                  */
9468                 if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
9469                         isAnyTempNamespace(relForm->relnamespace) ||
9470                         relForm->relnamespace == PG_TOAST_NAMESPACE)
9471                         continue;
9472
9473                 /* Only move the object type requested */
9474                 if ((stmt->objtype == OBJECT_TABLE &&
9475                          relForm->relkind != RELKIND_RELATION) ||
9476                         (stmt->objtype == OBJECT_INDEX &&
9477                          relForm->relkind != RELKIND_INDEX) ||
9478                         (stmt->objtype == OBJECT_MATVIEW &&
9479                          relForm->relkind != RELKIND_MATVIEW))
9480                         continue;
9481
9482                 /* Check if we are only moving objects owned by certain roles */
9483                 if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
9484                         continue;
9485
9486                 /*
9487                  * Handle permissions-checking here since we are locking the tables
9488                  * and also to avoid doing a bunch of work only to fail part-way. Note
9489                  * that permissions will also be checked by AlterTableInternal().
9490                  *
9491                  * Caller must be considered an owner on the table to move it.
9492                  */
9493                 if (!pg_class_ownercheck(relOid, GetUserId()))
9494                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
9495                                                    NameStr(relForm->relname));
9496
9497                 if (stmt->nowait &&
9498                         !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
9499                         ereport(ERROR,
9500                                         (errcode(ERRCODE_OBJECT_IN_USE),
9501                            errmsg("aborting because lock on relation \"%s\".\"%s\" is not available",
9502                                           get_namespace_name(relForm->relnamespace),
9503                                           NameStr(relForm->relname))));
9504                 else
9505                         LockRelationOid(relOid, AccessExclusiveLock);
9506
9507                 /* Add to our list of objects to move */
9508                 relations = lappend_oid(relations, relOid);
9509         }
9510
9511         heap_endscan(scan);
9512         heap_close(rel, AccessShareLock);
9513
9514         if (relations == NIL)
9515                 ereport(NOTICE,
9516                                 (errcode(ERRCODE_NO_DATA_FOUND),
9517                                  errmsg("no matching relations in tablespace \"%s\" found",
9518                                         orig_tablespaceoid == InvalidOid ? "(database default)" :
9519                                                 get_tablespace_name(orig_tablespaceoid))));
9520
9521         /* Everything is locked, loop through and move all of the relations. */
9522         foreach(l, relations)
9523         {
9524                 List       *cmds = NIL;
9525                 AlterTableCmd *cmd = makeNode(AlterTableCmd);
9526
9527                 cmd->subtype = AT_SetTableSpace;
9528                 cmd->name = stmt->new_tablespacename;
9529
9530                 cmds = lappend(cmds, cmd);
9531
9532                 AlterTableInternal(lfirst_oid(l), cmds, false);
9533         }
9534
9535         return new_tablespaceoid;
9536 }
9537
9538 /*
9539  * Copy data, block by block
9540  */
9541 static void
9542 copy_relation_data(SMgrRelation src, SMgrRelation dst,
9543                                    ForkNumber forkNum, char relpersistence)
9544 {
9545         char       *buf;
9546         Page            page;
9547         bool            use_wal;
9548         BlockNumber nblocks;
9549         BlockNumber blkno;
9550
9551         /*
9552          * palloc the buffer so that it's MAXALIGN'd.  If it were just a local
9553          * char[] array, the compiler might align it on any byte boundary, which
9554          * can seriously hurt transfer speed to and from the kernel; not to
9555          * mention possibly making log_newpage's accesses to the page header fail.
9556          */
9557         buf = (char *) palloc(BLCKSZ);
9558         page = (Page) buf;
9559
9560         /*
9561          * We need to log the copied data in WAL iff WAL archiving/streaming is
9562          * enabled AND it's a permanent relation.
9563          */
9564         use_wal = XLogIsNeeded() && relpersistence == RELPERSISTENCE_PERMANENT;
9565
9566         nblocks = smgrnblocks(src, forkNum);
9567
9568         for (blkno = 0; blkno < nblocks; blkno++)
9569         {
9570                 /* If we got a cancel signal during the copy of the data, quit */
9571                 CHECK_FOR_INTERRUPTS();
9572
9573                 smgrread(src, forkNum, blkno, buf);
9574
9575                 if (!PageIsVerified(page, blkno))
9576                         ereport(ERROR,
9577                                         (errcode(ERRCODE_DATA_CORRUPTED),
9578                                          errmsg("invalid page in block %u of relation %s",
9579                                                         blkno,
9580                                                         relpathbackend(src->smgr_rnode.node,
9581                                                                                    src->smgr_rnode.backend,
9582                                                                                    forkNum))));
9583
9584                 /*
9585                  * WAL-log the copied page. Unfortunately we don't know what kind of a
9586                  * page this is, so we have to log the full page including any unused
9587                  * space.
9588                  */
9589                 if (use_wal)
9590                         log_newpage(&dst->smgr_rnode.node, forkNum, blkno, page, false);
9591
9592                 PageSetChecksumInplace(page, blkno);
9593
9594                 /*
9595                  * Now write the page.  We say isTemp = true even if it's not a temp
9596                  * rel, because there's no need for smgr to schedule an fsync for this
9597                  * write; we'll do it ourselves below.
9598                  */
9599                 smgrextend(dst, forkNum, blkno, buf, true);
9600         }
9601
9602         pfree(buf);
9603
9604         /*
9605          * If the rel is WAL-logged, must fsync before commit.  We use heap_sync
9606          * to ensure that the toast table gets fsync'd too.  (For a temp or
9607          * unlogged rel we don't care since the data will be gone after a crash
9608          * anyway.)
9609          *
9610          * It's obvious that we must do this when not WAL-logging the copy. It's
9611          * less obvious that we have to do it even if we did WAL-log the copied
9612          * pages. The reason is that since we're copying outside shared buffers, a
9613          * CHECKPOINT occurring during the copy has no way to flush the previously
9614          * written data to disk (indeed it won't know the new rel even exists).  A
9615          * crash later on would replay WAL from the checkpoint, therefore it
9616          * wouldn't replay our earlier WAL entries. If we do not fsync those pages
9617          * here, they might still not be on disk when the crash occurs.
9618          */
9619         if (relpersistence == RELPERSISTENCE_PERMANENT)
9620                 smgrimmedsync(dst, forkNum);
9621 }
9622
9623 /*
9624  * ALTER TABLE ENABLE/DISABLE TRIGGER
9625  *
9626  * We just pass this off to trigger.c.
9627  */
9628 static void
9629 ATExecEnableDisableTrigger(Relation rel, char *trigname,
9630                                                 char fires_when, bool skip_system, LOCKMODE lockmode)
9631 {
9632         EnableDisableTrigger(rel, trigname, fires_when, skip_system);
9633 }
9634
9635 /*
9636  * ALTER TABLE ENABLE/DISABLE RULE
9637  *
9638  * We just pass this off to rewriteDefine.c.
9639  */
9640 static void
9641 ATExecEnableDisableRule(Relation rel, char *trigname,
9642                                                 char fires_when, LOCKMODE lockmode)
9643 {
9644         EnableDisableRule(rel, trigname, fires_when);
9645 }
9646
9647 /*
9648  * ALTER TABLE INHERIT
9649  *
9650  * Add a parent to the child's parents. This verifies that all the columns and
9651  * check constraints of the parent appear in the child and that they have the
9652  * same data types and expressions.
9653  */
9654 static void
9655 ATPrepAddInherit(Relation child_rel)
9656 {
9657         if (child_rel->rd_rel->reloftype)
9658                 ereport(ERROR,
9659                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9660                                  errmsg("cannot change inheritance of typed table")));
9661 }
9662
9663 static void
9664 ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
9665 {
9666         Relation        parent_rel,
9667                                 catalogRelation;
9668         SysScanDesc scan;
9669         ScanKeyData key;
9670         HeapTuple       inheritsTuple;
9671         int32           inhseqno;
9672         List       *children;
9673
9674         /*
9675          * A self-exclusive lock is needed here.  See the similar case in
9676          * MergeAttributes() for a full explanation.
9677          */
9678         parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
9679
9680         /*
9681          * Must be owner of both parent and child -- child was checked by
9682          * ATSimplePermissions call in ATPrepCmd
9683          */
9684         ATSimplePermissions(parent_rel, ATT_TABLE);
9685
9686         /* Permanent rels cannot inherit from temporary ones */
9687         if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9688                 child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
9689                 ereport(ERROR,
9690                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9691                                  errmsg("cannot inherit from temporary relation \"%s\"",
9692                                                 RelationGetRelationName(parent_rel))));
9693
9694         /* If parent rel is temp, it must belong to this session */
9695         if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9696                 !parent_rel->rd_islocaltemp)
9697                 ereport(ERROR,
9698                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9699                 errmsg("cannot inherit from temporary relation of another session")));
9700
9701         /* Ditto for the child */
9702         if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9703                 !child_rel->rd_islocaltemp)
9704                 ereport(ERROR,
9705                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9706                  errmsg("cannot inherit to temporary relation of another session")));
9707
9708         /*
9709          * Check for duplicates in the list of parents, and determine the highest
9710          * inhseqno already present; we'll use the next one for the new parent.
9711          * (Note: get RowExclusiveLock because we will write pg_inherits below.)
9712          *
9713          * Note: we do not reject the case where the child already inherits from
9714          * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
9715          */
9716         catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
9717         ScanKeyInit(&key,
9718                                 Anum_pg_inherits_inhrelid,
9719                                 BTEqualStrategyNumber, F_OIDEQ,
9720                                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
9721         scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
9722                                                           true, NULL, 1, &key);
9723
9724         /* inhseqno sequences start at 1 */
9725         inhseqno = 0;
9726         while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
9727         {
9728                 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
9729
9730                 if (inh->inhparent == RelationGetRelid(parent_rel))
9731                         ereport(ERROR,
9732                                         (errcode(ERRCODE_DUPLICATE_TABLE),
9733                          errmsg("relation \"%s\" would be inherited from more than once",
9734                                         RelationGetRelationName(parent_rel))));
9735                 if (inh->inhseqno > inhseqno)
9736                         inhseqno = inh->inhseqno;
9737         }
9738         systable_endscan(scan);
9739
9740         /*
9741          * Prevent circularity by seeing if proposed parent inherits from child.
9742          * (In particular, this disallows making a rel inherit from itself.)
9743          *
9744          * This is not completely bulletproof because of race conditions: in
9745          * multi-level inheritance trees, someone else could concurrently be
9746          * making another inheritance link that closes the loop but does not join
9747          * either of the rels we have locked.  Preventing that seems to require
9748          * exclusive locks on the entire inheritance tree, which is a cure worse
9749          * than the disease.  find_all_inheritors() will cope with circularity
9750          * anyway, so don't sweat it too much.
9751          *
9752          * We use weakest lock we can on child's children, namely AccessShareLock.
9753          */
9754         children = find_all_inheritors(RelationGetRelid(child_rel),
9755                                                                    AccessShareLock, NULL);
9756
9757         if (list_member_oid(children, RelationGetRelid(parent_rel)))
9758                 ereport(ERROR,
9759                                 (errcode(ERRCODE_DUPLICATE_TABLE),
9760                                  errmsg("circular inheritance not allowed"),
9761                                  errdetail("\"%s\" is already a child of \"%s\".",
9762                                                    parent->relname,
9763                                                    RelationGetRelationName(child_rel))));
9764
9765         /* If parent has OIDs then child must have OIDs */
9766         if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
9767                 ereport(ERROR,
9768                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9769                                  errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
9770                                                 RelationGetRelationName(child_rel),
9771                                                 RelationGetRelationName(parent_rel))));
9772
9773         /* Match up the columns and bump attinhcount as needed */
9774         MergeAttributesIntoExisting(child_rel, parent_rel);
9775
9776         /* Match up the constraints and bump coninhcount as needed */
9777         MergeConstraintsIntoExisting(child_rel, parent_rel);
9778
9779         /*
9780          * OK, it looks valid.  Make the catalog entries that show inheritance.
9781          */
9782         StoreCatalogInheritance1(RelationGetRelid(child_rel),
9783                                                          RelationGetRelid(parent_rel),
9784                                                          inhseqno + 1,
9785                                                          catalogRelation);
9786
9787         /* Now we're done with pg_inherits */
9788         heap_close(catalogRelation, RowExclusiveLock);
9789
9790         /* keep our lock on the parent relation until commit */
9791         heap_close(parent_rel, NoLock);
9792 }
9793
9794 /*
9795  * Obtain the source-text form of the constraint expression for a check
9796  * constraint, given its pg_constraint tuple
9797  */
9798 static char *
9799 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
9800 {
9801         Form_pg_constraint con;
9802         bool            isnull;
9803         Datum           attr;
9804         Datum           expr;
9805
9806         con = (Form_pg_constraint) GETSTRUCT(contup);
9807         attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
9808         if (isnull)
9809                 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
9810
9811         expr = DirectFunctionCall2(pg_get_expr, attr,
9812                                                            ObjectIdGetDatum(con->conrelid));
9813         return TextDatumGetCString(expr);
9814 }
9815
9816 /*
9817  * Determine whether two check constraints are functionally equivalent
9818  *
9819  * The test we apply is to see whether they reverse-compile to the same
9820  * source string.  This insulates us from issues like whether attributes
9821  * have the same physical column numbers in parent and child relations.
9822  */
9823 static bool
9824 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
9825 {
9826         Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
9827         Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
9828
9829         if (acon->condeferrable != bcon->condeferrable ||
9830                 acon->condeferred != bcon->condeferred ||
9831                 strcmp(decompile_conbin(a, tupleDesc),
9832                            decompile_conbin(b, tupleDesc)) != 0)
9833                 return false;
9834         else
9835                 return true;
9836 }
9837
9838 /*
9839  * Check columns in child table match up with columns in parent, and increment
9840  * their attinhcount.
9841  *
9842  * Called by ATExecAddInherit
9843  *
9844  * Currently all parent columns must be found in child. Missing columns are an
9845  * error.  One day we might consider creating new columns like CREATE TABLE
9846  * does.  However, that is widely unpopular --- in the common use case of
9847  * partitioned tables it's a foot-gun.
9848  *
9849  * The data type must match exactly. If the parent column is NOT NULL then
9850  * the child must be as well. Defaults are not compared, however.
9851  */
9852 static void
9853 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
9854 {
9855         Relation        attrrel;
9856         AttrNumber      parent_attno;
9857         int                     parent_natts;
9858         TupleDesc       tupleDesc;
9859         HeapTuple       tuple;
9860
9861         attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
9862
9863         tupleDesc = RelationGetDescr(parent_rel);
9864         parent_natts = tupleDesc->natts;
9865
9866         for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
9867         {
9868                 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
9869                 char       *attributeName = NameStr(attribute->attname);
9870
9871                 /* Ignore dropped columns in the parent. */
9872                 if (attribute->attisdropped)
9873                         continue;
9874
9875                 /* Find same column in child (matching on column name). */
9876                 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
9877                                                                                   attributeName);
9878                 if (HeapTupleIsValid(tuple))
9879                 {
9880                         /* Check they are same type, typmod, and collation */
9881                         Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
9882
9883                         if (attribute->atttypid != childatt->atttypid ||
9884                                 attribute->atttypmod != childatt->atttypmod)
9885                                 ereport(ERROR,
9886                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
9887                                                  errmsg("child table \"%s\" has different type for column \"%s\"",
9888                                                                 RelationGetRelationName(child_rel),
9889                                                                 attributeName)));
9890
9891                         if (attribute->attcollation != childatt->attcollation)
9892                                 ereport(ERROR,
9893                                                 (errcode(ERRCODE_COLLATION_MISMATCH),
9894                                                  errmsg("child table \"%s\" has different collation for column \"%s\"",
9895                                                                 RelationGetRelationName(child_rel),
9896                                                                 attributeName)));
9897
9898                         /*
9899                          * Check child doesn't discard NOT NULL property.  (Other
9900                          * constraints are checked elsewhere.)
9901                          */
9902                         if (attribute->attnotnull && !childatt->attnotnull)
9903                                 ereport(ERROR,
9904                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
9905                                 errmsg("column \"%s\" in child table must be marked NOT NULL",
9906                                            attributeName)));
9907
9908                         /*
9909                          * OK, bump the child column's inheritance count.  (If we fail
9910                          * later on, this change will just roll back.)
9911                          */
9912                         childatt->attinhcount++;
9913                         simple_heap_update(attrrel, &tuple->t_self, tuple);
9914                         CatalogUpdateIndexes(attrrel, tuple);
9915                         heap_freetuple(tuple);
9916                 }
9917                 else
9918                 {
9919                         ereport(ERROR,
9920                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
9921                                          errmsg("child table is missing column \"%s\"",
9922                                                         attributeName)));
9923                 }
9924         }
9925
9926         heap_close(attrrel, RowExclusiveLock);
9927 }
9928
9929 /*
9930  * Check constraints in child table match up with constraints in parent,
9931  * and increment their coninhcount.
9932  *
9933  * Constraints that are marked ONLY in the parent are ignored.
9934  *
9935  * Called by ATExecAddInherit
9936  *
9937  * Currently all constraints in parent must be present in the child. One day we
9938  * may consider adding new constraints like CREATE TABLE does.
9939  *
9940  * XXX This is O(N^2) which may be an issue with tables with hundreds of
9941  * constraints. As long as tables have more like 10 constraints it shouldn't be
9942  * a problem though. Even 100 constraints ought not be the end of the world.
9943  *
9944  * XXX See MergeWithExistingConstraint too if you change this code.
9945  */
9946 static void
9947 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
9948 {
9949         Relation        catalog_relation;
9950         TupleDesc       tuple_desc;
9951         SysScanDesc parent_scan;
9952         ScanKeyData parent_key;
9953         HeapTuple       parent_tuple;
9954
9955         catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
9956         tuple_desc = RelationGetDescr(catalog_relation);
9957
9958         /* Outer loop scans through the parent's constraint definitions */
9959         ScanKeyInit(&parent_key,
9960                                 Anum_pg_constraint_conrelid,
9961                                 BTEqualStrategyNumber, F_OIDEQ,
9962                                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
9963         parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
9964                                                                          true, NULL, 1, &parent_key);
9965
9966         while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
9967         {
9968                 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
9969                 SysScanDesc child_scan;
9970                 ScanKeyData child_key;
9971                 HeapTuple       child_tuple;
9972                 bool            found = false;
9973
9974                 if (parent_con->contype != CONSTRAINT_CHECK)
9975                         continue;
9976
9977                 /* if the parent's constraint is marked NO INHERIT, it's not inherited */
9978                 if (parent_con->connoinherit)
9979                         continue;
9980
9981                 /* Search for a child constraint matching this one */
9982                 ScanKeyInit(&child_key,
9983                                         Anum_pg_constraint_conrelid,
9984                                         BTEqualStrategyNumber, F_OIDEQ,
9985                                         ObjectIdGetDatum(RelationGetRelid(child_rel)));
9986                 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
9987                                                                                 true, NULL, 1, &child_key);
9988
9989                 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
9990                 {
9991                         Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
9992                         HeapTuple       child_copy;
9993
9994                         if (child_con->contype != CONSTRAINT_CHECK)
9995                                 continue;
9996
9997                         if (strcmp(NameStr(parent_con->conname),
9998                                            NameStr(child_con->conname)) != 0)
9999                                 continue;
10000
10001                         if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
10002                                 ereport(ERROR,
10003                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
10004                                                  errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
10005                                                                 RelationGetRelationName(child_rel),
10006                                                                 NameStr(parent_con->conname))));
10007
10008                         /* If the constraint is "no inherit" then cannot merge */
10009                         if (child_con->connoinherit)
10010                                 ereport(ERROR,
10011                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
10012                                                  errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
10013                                                                 NameStr(child_con->conname),
10014                                                                 RelationGetRelationName(child_rel))));
10015
10016                         /*
10017                          * OK, bump the child constraint's inheritance count.  (If we fail
10018                          * later on, this change will just roll back.)
10019                          */
10020                         child_copy = heap_copytuple(child_tuple);
10021                         child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
10022                         child_con->coninhcount++;
10023                         simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
10024                         CatalogUpdateIndexes(catalog_relation, child_copy);
10025                         heap_freetuple(child_copy);
10026
10027                         found = true;
10028                         break;
10029                 }
10030
10031                 systable_endscan(child_scan);
10032
10033                 if (!found)
10034                         ereport(ERROR,
10035                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
10036                                          errmsg("child table is missing constraint \"%s\"",
10037                                                         NameStr(parent_con->conname))));
10038         }
10039
10040         systable_endscan(parent_scan);
10041         heap_close(catalog_relation, RowExclusiveLock);
10042 }
10043
10044 /*
10045  * ALTER TABLE NO INHERIT
10046  *
10047  * Drop a parent from the child's parents. This just adjusts the attinhcount
10048  * and attislocal of the columns and removes the pg_inherit and pg_depend
10049  * entries.
10050  *
10051  * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
10052  * up attislocal stays true, which means if a child is ever removed from a
10053  * parent then its columns will never be automatically dropped which may
10054  * surprise. But at least we'll never surprise by dropping columns someone
10055  * isn't expecting to be dropped which would actually mean data loss.
10056  *
10057  * coninhcount and conislocal for inherited constraints are adjusted in
10058  * exactly the same way.
10059  */
10060 static void
10061 ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
10062 {
10063         Relation        parent_rel;
10064         Relation        catalogRelation;
10065         SysScanDesc scan;
10066         ScanKeyData key[3];
10067         HeapTuple       inheritsTuple,
10068                                 attributeTuple,
10069                                 constraintTuple;
10070         List       *connames;
10071         bool            found = false;
10072
10073         /*
10074          * AccessShareLock on the parent is probably enough, seeing that DROP
10075          * TABLE doesn't lock parent tables at all.  We need some lock since we'll
10076          * be inspecting the parent's schema.
10077          */
10078         parent_rel = heap_openrv(parent, AccessShareLock);
10079
10080         /*
10081          * We don't bother to check ownership of the parent table --- ownership of
10082          * the child is presumed enough rights.
10083          */
10084
10085         /*
10086          * Find and destroy the pg_inherits entry linking the two, or error out if
10087          * there is none.
10088          */
10089         catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
10090         ScanKeyInit(&key[0],
10091                                 Anum_pg_inherits_inhrelid,
10092                                 BTEqualStrategyNumber, F_OIDEQ,
10093                                 ObjectIdGetDatum(RelationGetRelid(rel)));
10094         scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
10095                                                           true, NULL, 1, key);
10096
10097         while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
10098         {
10099                 Oid                     inhparent;
10100
10101                 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
10102                 if (inhparent == RelationGetRelid(parent_rel))
10103                 {
10104                         simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
10105                         found = true;
10106                         break;
10107                 }
10108         }
10109
10110         systable_endscan(scan);
10111         heap_close(catalogRelation, RowExclusiveLock);
10112
10113         if (!found)
10114                 ereport(ERROR,
10115                                 (errcode(ERRCODE_UNDEFINED_TABLE),
10116                                  errmsg("relation \"%s\" is not a parent of relation \"%s\"",
10117                                                 RelationGetRelationName(parent_rel),
10118                                                 RelationGetRelationName(rel))));
10119
10120         /*
10121          * Search through child columns looking for ones matching parent rel
10122          */
10123         catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
10124         ScanKeyInit(&key[0],
10125                                 Anum_pg_attribute_attrelid,
10126                                 BTEqualStrategyNumber, F_OIDEQ,
10127                                 ObjectIdGetDatum(RelationGetRelid(rel)));
10128         scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
10129                                                           true, NULL, 1, key);
10130         while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
10131         {
10132                 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
10133
10134                 /* Ignore if dropped or not inherited */
10135                 if (att->attisdropped)
10136                         continue;
10137                 if (att->attinhcount <= 0)
10138                         continue;
10139
10140                 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
10141                                                                                 NameStr(att->attname)))
10142                 {
10143                         /* Decrement inhcount and possibly set islocal to true */
10144                         HeapTuple       copyTuple = heap_copytuple(attributeTuple);
10145                         Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
10146
10147                         copy_att->attinhcount--;
10148                         if (copy_att->attinhcount == 0)
10149                                 copy_att->attislocal = true;
10150
10151                         simple_heap_update(catalogRelation, &copyTuple->t_self, copyTuple);
10152                         CatalogUpdateIndexes(catalogRelation, copyTuple);
10153                         heap_freetuple(copyTuple);
10154                 }
10155         }
10156         systable_endscan(scan);
10157         heap_close(catalogRelation, RowExclusiveLock);
10158
10159         /*
10160          * Likewise, find inherited check constraints and disinherit them. To do
10161          * this, we first need a list of the names of the parent's check
10162          * constraints.  (We cheat a bit by only checking for name matches,
10163          * assuming that the expressions will match.)
10164          */
10165         catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
10166         ScanKeyInit(&key[0],
10167                                 Anum_pg_constraint_conrelid,
10168                                 BTEqualStrategyNumber, F_OIDEQ,
10169                                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
10170         scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
10171                                                           true, NULL, 1, key);
10172
10173         connames = NIL;
10174
10175         while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
10176         {
10177                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
10178
10179                 if (con->contype == CONSTRAINT_CHECK)
10180                         connames = lappend(connames, pstrdup(NameStr(con->conname)));
10181         }
10182
10183         systable_endscan(scan);
10184
10185         /* Now scan the child's constraints */
10186         ScanKeyInit(&key[0],
10187                                 Anum_pg_constraint_conrelid,
10188                                 BTEqualStrategyNumber, F_OIDEQ,
10189                                 ObjectIdGetDatum(RelationGetRelid(rel)));
10190         scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
10191                                                           true, NULL, 1, key);
10192
10193         while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
10194         {
10195                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
10196                 bool            match;
10197                 ListCell   *lc;
10198
10199                 if (con->contype != CONSTRAINT_CHECK)
10200                         continue;
10201
10202                 match = false;
10203                 foreach(lc, connames)
10204                 {
10205                         if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
10206                         {
10207                                 match = true;
10208                                 break;
10209                         }
10210                 }
10211
10212                 if (match)
10213                 {
10214                         /* Decrement inhcount and possibly set islocal to true */
10215                         HeapTuple       copyTuple = heap_copytuple(constraintTuple);
10216                         Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
10217
10218                         if (copy_con->coninhcount <= 0)         /* shouldn't happen */
10219                                 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
10220                                          RelationGetRelid(rel), NameStr(copy_con->conname));
10221
10222                         copy_con->coninhcount--;
10223                         if (copy_con->coninhcount == 0)
10224                                 copy_con->conislocal = true;
10225
10226                         simple_heap_update(catalogRelation, &copyTuple->t_self, copyTuple);
10227                         CatalogUpdateIndexes(catalogRelation, copyTuple);
10228                         heap_freetuple(copyTuple);
10229                 }
10230         }
10231
10232         systable_endscan(scan);
10233         heap_close(catalogRelation, RowExclusiveLock);
10234
10235         drop_parent_dependency(RelationGetRelid(rel),
10236                                                    RelationRelationId,
10237                                                    RelationGetRelid(parent_rel));
10238
10239         /*
10240          * Post alter hook of this inherits. Since object_access_hook doesn't take
10241          * multiple object identifiers, we relay oid of parent relation using
10242          * auxiliary_id argument.
10243          */
10244         InvokeObjectPostAlterHookArg(InheritsRelationId,
10245                                                                  RelationGetRelid(rel), 0,
10246                                                                  RelationGetRelid(parent_rel), false);
10247
10248         /* keep our lock on the parent relation until commit */
10249         heap_close(parent_rel, NoLock);
10250 }
10251
10252 /*
10253  * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
10254  * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
10255  * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
10256  * be TypeRelationId).  There's no convenient way to do this, so go trawling
10257  * through pg_depend.
10258  */
10259 static void
10260 drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid)
10261 {
10262         Relation        catalogRelation;
10263         SysScanDesc scan;
10264         ScanKeyData key[3];
10265         HeapTuple       depTuple;
10266
10267         catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
10268
10269         ScanKeyInit(&key[0],
10270                                 Anum_pg_depend_classid,
10271                                 BTEqualStrategyNumber, F_OIDEQ,
10272                                 ObjectIdGetDatum(RelationRelationId));
10273         ScanKeyInit(&key[1],
10274                                 Anum_pg_depend_objid,
10275                                 BTEqualStrategyNumber, F_OIDEQ,
10276                                 ObjectIdGetDatum(relid));
10277         ScanKeyInit(&key[2],
10278                                 Anum_pg_depend_objsubid,
10279                                 BTEqualStrategyNumber, F_INT4EQ,
10280                                 Int32GetDatum(0));
10281
10282         scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
10283                                                           NULL, 3, key);
10284
10285         while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
10286         {
10287                 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
10288
10289                 if (dep->refclassid == refclassid &&
10290                         dep->refobjid == refobjid &&
10291                         dep->refobjsubid == 0 &&
10292                         dep->deptype == DEPENDENCY_NORMAL)
10293                         simple_heap_delete(catalogRelation, &depTuple->t_self);
10294         }
10295
10296         systable_endscan(scan);
10297         heap_close(catalogRelation, RowExclusiveLock);
10298 }
10299
10300 /*
10301  * ALTER TABLE OF
10302  *
10303  * Attach a table to a composite type, as though it had been created with CREATE
10304  * TABLE OF.  All attname, atttypid, atttypmod and attcollation must match.  The
10305  * subject table must not have inheritance parents.  These restrictions ensure
10306  * that you cannot create a configuration impossible with CREATE TABLE OF alone.
10307  */
10308 static void
10309 ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
10310 {
10311         Oid                     relid = RelationGetRelid(rel);
10312         Type            typetuple;
10313         Oid                     typeid;
10314         Relation        inheritsRelation,
10315                                 relationRelation;
10316         SysScanDesc scan;
10317         ScanKeyData key;
10318         AttrNumber      table_attno,
10319                                 type_attno;
10320         TupleDesc       typeTupleDesc,
10321                                 tableTupleDesc;
10322         ObjectAddress tableobj,
10323                                 typeobj;
10324         HeapTuple       classtuple;
10325
10326         /* Validate the type. */
10327         typetuple = typenameType(NULL, ofTypename, NULL);
10328         check_of_type(typetuple);
10329         typeid = HeapTupleGetOid(typetuple);
10330
10331         /* Fail if the table has any inheritance parents. */
10332         inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
10333         ScanKeyInit(&key,
10334                                 Anum_pg_inherits_inhrelid,
10335                                 BTEqualStrategyNumber, F_OIDEQ,
10336                                 ObjectIdGetDatum(relid));
10337         scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
10338                                                           true, NULL, 1, &key);
10339         if (HeapTupleIsValid(systable_getnext(scan)))
10340                 ereport(ERROR,
10341                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10342                                  errmsg("typed tables cannot inherit")));
10343         systable_endscan(scan);
10344         heap_close(inheritsRelation, AccessShareLock);
10345
10346         /*
10347          * Check the tuple descriptors for compatibility.  Unlike inheritance, we
10348          * require that the order also match.  However, attnotnull need not match.
10349          * Also unlike inheritance, we do not require matching relhasoids.
10350          */
10351         typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
10352         tableTupleDesc = RelationGetDescr(rel);
10353         table_attno = 1;
10354         for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
10355         {
10356                 Form_pg_attribute type_attr,
10357                                         table_attr;
10358                 const char *type_attname,
10359                                    *table_attname;
10360
10361                 /* Get the next non-dropped type attribute. */
10362                 type_attr = typeTupleDesc->attrs[type_attno - 1];
10363                 if (type_attr->attisdropped)
10364                         continue;
10365                 type_attname = NameStr(type_attr->attname);
10366
10367                 /* Get the next non-dropped table attribute. */
10368                 do
10369                 {
10370                         if (table_attno > tableTupleDesc->natts)
10371                                 ereport(ERROR,
10372                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
10373                                                  errmsg("table is missing column \"%s\"",
10374                                                                 type_attname)));
10375                         table_attr = tableTupleDesc->attrs[table_attno++ - 1];
10376                 } while (table_attr->attisdropped);
10377                 table_attname = NameStr(table_attr->attname);
10378
10379                 /* Compare name. */
10380                 if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
10381                         ereport(ERROR,
10382                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
10383                                  errmsg("table has column \"%s\" where type requires \"%s\"",
10384                                                 table_attname, type_attname)));
10385
10386                 /* Compare type. */
10387                 if (table_attr->atttypid != type_attr->atttypid ||
10388                         table_attr->atttypmod != type_attr->atttypmod ||
10389                         table_attr->attcollation != type_attr->attcollation)
10390                         ereport(ERROR,
10391                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
10392                                   errmsg("table \"%s\" has different type for column \"%s\"",
10393                                                  RelationGetRelationName(rel), type_attname)));
10394         }
10395         DecrTupleDescRefCount(typeTupleDesc);
10396
10397         /* Any remaining columns at the end of the table had better be dropped. */
10398         for (; table_attno <= tableTupleDesc->natts; table_attno++)
10399         {
10400                 Form_pg_attribute table_attr = tableTupleDesc->attrs[table_attno - 1];
10401
10402                 if (!table_attr->attisdropped)
10403                         ereport(ERROR,
10404                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
10405                                          errmsg("table has extra column \"%s\"",
10406                                                         NameStr(table_attr->attname))));
10407         }
10408
10409         /* If the table was already typed, drop the existing dependency. */
10410         if (rel->rd_rel->reloftype)
10411                 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
10412
10413         /* Record a dependency on the new type. */
10414         tableobj.classId = RelationRelationId;
10415         tableobj.objectId = relid;
10416         tableobj.objectSubId = 0;
10417         typeobj.classId = TypeRelationId;
10418         typeobj.objectId = typeid;
10419         typeobj.objectSubId = 0;
10420         recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
10421
10422         /* Update pg_class.reloftype */
10423         relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
10424         classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10425         if (!HeapTupleIsValid(classtuple))
10426                 elog(ERROR, "cache lookup failed for relation %u", relid);
10427         ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
10428         simple_heap_update(relationRelation, &classtuple->t_self, classtuple);
10429         CatalogUpdateIndexes(relationRelation, classtuple);
10430
10431         InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
10432
10433         heap_freetuple(classtuple);
10434         heap_close(relationRelation, RowExclusiveLock);
10435
10436         ReleaseSysCache(typetuple);
10437 }
10438
10439 /*
10440  * ALTER TABLE NOT OF
10441  *
10442  * Detach a typed table from its originating type.  Just clear reloftype and
10443  * remove the dependency.
10444  */
10445 static void
10446 ATExecDropOf(Relation rel, LOCKMODE lockmode)
10447 {
10448         Oid                     relid = RelationGetRelid(rel);
10449         Relation        relationRelation;
10450         HeapTuple       tuple;
10451
10452         if (!OidIsValid(rel->rd_rel->reloftype))
10453                 ereport(ERROR,
10454                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10455                                  errmsg("\"%s\" is not a typed table",
10456                                                 RelationGetRelationName(rel))));
10457
10458         /*
10459          * We don't bother to check ownership of the type --- ownership of the
10460          * table is presumed enough rights.  No lock required on the type, either.
10461          */
10462
10463         drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
10464
10465         /* Clear pg_class.reloftype */
10466         relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
10467         tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10468         if (!HeapTupleIsValid(tuple))
10469                 elog(ERROR, "cache lookup failed for relation %u", relid);
10470         ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
10471         simple_heap_update(relationRelation, &tuple->t_self, tuple);
10472         CatalogUpdateIndexes(relationRelation, tuple);
10473
10474         InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
10475
10476         heap_freetuple(tuple);
10477         heap_close(relationRelation, RowExclusiveLock);
10478 }
10479
10480 /*
10481  * relation_mark_replica_identity: Update a table's replica identity
10482  *
10483  * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
10484  * index. Otherwise, it should be InvalidOid.
10485  */
10486 static void
10487 relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
10488                                                            bool is_internal)
10489 {
10490         Relation        pg_index;
10491         Relation        pg_class;
10492         HeapTuple       pg_class_tuple;
10493         HeapTuple       pg_index_tuple;
10494         Form_pg_class pg_class_form;
10495         Form_pg_index pg_index_form;
10496
10497         ListCell   *index;
10498
10499         /*
10500          * Check whether relreplident has changed, and update it if so.
10501          */
10502         pg_class = heap_open(RelationRelationId, RowExclusiveLock);
10503         pg_class_tuple = SearchSysCacheCopy1(RELOID,
10504                                                                         ObjectIdGetDatum(RelationGetRelid(rel)));
10505         if (!HeapTupleIsValid(pg_class_tuple))
10506                 elog(ERROR, "cache lookup failed for relation \"%s\"",
10507                          RelationGetRelationName(rel));
10508         pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
10509         if (pg_class_form->relreplident != ri_type)
10510         {
10511                 pg_class_form->relreplident = ri_type;
10512                 simple_heap_update(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
10513                 CatalogUpdateIndexes(pg_class, pg_class_tuple);
10514         }
10515         heap_close(pg_class, RowExclusiveLock);
10516         heap_freetuple(pg_class_tuple);
10517
10518         /*
10519          * Check whether the correct index is marked indisreplident; if so, we're
10520          * done.
10521          */
10522         if (OidIsValid(indexOid))
10523         {
10524                 Assert(ri_type == REPLICA_IDENTITY_INDEX);
10525
10526                 pg_index_tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexOid));
10527                 if (!HeapTupleIsValid(pg_index_tuple))
10528                         elog(ERROR, "cache lookup failed for index %u", indexOid);
10529                 pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
10530
10531                 if (pg_index_form->indisreplident)
10532                 {
10533                         ReleaseSysCache(pg_index_tuple);
10534                         return;
10535                 }
10536                 ReleaseSysCache(pg_index_tuple);
10537         }
10538
10539         /*
10540          * Clear the indisreplident flag from any index that had it previously,
10541          * and set it for any index that should have it now.
10542          */
10543         pg_index = heap_open(IndexRelationId, RowExclusiveLock);
10544         foreach(index, RelationGetIndexList(rel))
10545         {
10546                 Oid                     thisIndexOid = lfirst_oid(index);
10547                 bool            dirty = false;
10548
10549                 pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
10550                                                                                          ObjectIdGetDatum(thisIndexOid));
10551                 if (!HeapTupleIsValid(pg_index_tuple))
10552                         elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
10553                 pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
10554
10555                 /*
10556                  * Unset the bit if set.  We know it's wrong because we checked this
10557                  * earlier.
10558                  */
10559                 if (pg_index_form->indisreplident)
10560                 {
10561                         dirty = true;
10562                         pg_index_form->indisreplident = false;
10563                 }
10564                 else if (thisIndexOid == indexOid)
10565                 {
10566                         dirty = true;
10567                         pg_index_form->indisreplident = true;
10568                 }
10569
10570                 if (dirty)
10571                 {
10572                         simple_heap_update(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
10573                         CatalogUpdateIndexes(pg_index, pg_index_tuple);
10574                         InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
10575                                                                                  InvalidOid, is_internal);
10576                 }
10577                 heap_freetuple(pg_index_tuple);
10578         }
10579
10580         heap_close(pg_index, RowExclusiveLock);
10581 }
10582
10583 /*
10584  * ALTER TABLE <name> REPLICA IDENTITY ...
10585  */
10586 static void
10587 ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
10588 {
10589         Oid                     indexOid;
10590         Relation        indexRel;
10591         int                     key;
10592
10593         if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
10594         {
10595                 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
10596                 return;
10597         }
10598         else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
10599         {
10600                 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
10601                 return;
10602         }
10603         else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
10604         {
10605                 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
10606                 return;
10607         }
10608         else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
10609         {
10610                  /* fallthrough */ ;
10611         }
10612         else
10613                 elog(ERROR, "unexpected identity type %u", stmt->identity_type);
10614
10615
10616         /* Check that the index exists */
10617         indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
10618         if (!OidIsValid(indexOid))
10619                 ereport(ERROR,
10620                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
10621                                  errmsg("index \"%s\" for table \"%s\" does not exist",
10622                                                 stmt->name, RelationGetRelationName(rel))));
10623
10624         indexRel = index_open(indexOid, ShareLock);
10625
10626         /* Check that the index is on the relation we're altering. */
10627         if (indexRel->rd_index == NULL ||
10628                 indexRel->rd_index->indrelid != RelationGetRelid(rel))
10629                 ereport(ERROR,
10630                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10631                                  errmsg("\"%s\" is not an index for table \"%s\"",
10632                                                 RelationGetRelationName(indexRel),
10633                                                 RelationGetRelationName(rel))));
10634         /* The AM must support uniqueness, and the index must in fact be unique. */
10635         if (!indexRel->rd_am->amcanunique || !indexRel->rd_index->indisunique)
10636                 ereport(ERROR,
10637                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10638                          errmsg("cannot use non-unique index \"%s\" as replica identity",
10639                                         RelationGetRelationName(indexRel))));
10640         /* Deferred indexes are not guaranteed to be always unique. */
10641         if (!indexRel->rd_index->indimmediate)
10642                 ereport(ERROR,
10643                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10644                   errmsg("cannot use non-immediate index \"%s\" as replica identity",
10645                                  RelationGetRelationName(indexRel))));
10646         /* Expression indexes aren't supported. */
10647         if (RelationGetIndexExpressions(indexRel) != NIL)
10648                 ereport(ERROR,
10649                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10650                          errmsg("cannot use expression index \"%s\" as replica identity",
10651                                         RelationGetRelationName(indexRel))));
10652         /* Predicate indexes aren't supported. */
10653         if (RelationGetIndexPredicate(indexRel) != NIL)
10654                 ereport(ERROR,
10655                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10656                                  errmsg("cannot use partial index \"%s\" as replica identity",
10657                                                 RelationGetRelationName(indexRel))));
10658         /* And neither are invalid indexes. */
10659         if (!IndexIsValid(indexRel->rd_index))
10660                 ereport(ERROR,
10661                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10662                                  errmsg("cannot use invalid index \"%s\" as replica identity",
10663                                                 RelationGetRelationName(indexRel))));
10664
10665         /* Check index for nullable columns. */
10666         for (key = 0; key < indexRel->rd_index->indnatts; key++)
10667         {
10668                 int16           attno = indexRel->rd_index->indkey.values[key];
10669                 Form_pg_attribute attr;
10670
10671                 /* Of the system columns, only oid is indexable. */
10672                 if (attno <= 0 && attno != ObjectIdAttributeNumber)
10673                         elog(ERROR, "internal column %u in unique index \"%s\"",
10674                                  attno, RelationGetRelationName(indexRel));
10675
10676                 attr = rel->rd_att->attrs[attno - 1];
10677                 if (!attr->attnotnull)
10678                         ereport(ERROR,
10679                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10680                                          errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
10681                                                         RelationGetRelationName(indexRel),
10682                                                         NameStr(attr->attname))));
10683         }
10684
10685         /* This index is suitable for use as a replica identity. Mark it. */
10686         relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
10687
10688         index_close(indexRel, NoLock);
10689 }
10690
10691 /*
10692  * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
10693  */
10694 static void
10695 ATExecEnableRowSecurity(Relation rel)
10696 {
10697         Relation                pg_class;
10698         Oid                             relid;
10699         HeapTuple               tuple;
10700
10701         relid = RelationGetRelid(rel);
10702
10703         pg_class = heap_open(RelationRelationId, RowExclusiveLock);
10704
10705         tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10706
10707         if (!HeapTupleIsValid(tuple))
10708                 elog(ERROR, "cache lookup failed for relation %u", relid);
10709
10710         ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = true;
10711         simple_heap_update(pg_class, &tuple->t_self, tuple);
10712
10713         /* keep catalog indexes current */
10714         CatalogUpdateIndexes(pg_class, tuple);
10715
10716         heap_close(pg_class, RowExclusiveLock);
10717         heap_freetuple(tuple);
10718 }
10719
10720 static void
10721 ATExecDisableRowSecurity(Relation rel)
10722 {
10723         Relation                pg_class;
10724         Oid                             relid;
10725         HeapTuple               tuple;
10726
10727         relid = RelationGetRelid(rel);
10728
10729         /* Pull the record for this relation and update it */
10730         pg_class = heap_open(RelationRelationId, RowExclusiveLock);
10731
10732         tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10733
10734         if (!HeapTupleIsValid(tuple))
10735                 elog(ERROR, "cache lookup failed for relation %u", relid);
10736
10737         ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = false;
10738         simple_heap_update(pg_class, &tuple->t_self, tuple);
10739
10740         /* keep catalog indexes current */
10741         CatalogUpdateIndexes(pg_class, tuple);
10742
10743         heap_close(pg_class, RowExclusiveLock);
10744         heap_freetuple(tuple);
10745 }
10746
10747 /*
10748  * ALTER FOREIGN TABLE <name> OPTIONS (...)
10749  */
10750 static void
10751 ATExecGenericOptions(Relation rel, List *options)
10752 {
10753         Relation        ftrel;
10754         ForeignServer *server;
10755         ForeignDataWrapper *fdw;
10756         HeapTuple       tuple;
10757         bool            isnull;
10758         Datum           repl_val[Natts_pg_foreign_table];
10759         bool            repl_null[Natts_pg_foreign_table];
10760         bool            repl_repl[Natts_pg_foreign_table];
10761         Datum           datum;
10762         Form_pg_foreign_table tableform;
10763
10764         if (options == NIL)
10765                 return;
10766
10767         ftrel = heap_open(ForeignTableRelationId, RowExclusiveLock);
10768
10769         tuple = SearchSysCacheCopy1(FOREIGNTABLEREL, rel->rd_id);
10770         if (!HeapTupleIsValid(tuple))
10771                 ereport(ERROR,
10772                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
10773                                  errmsg("foreign table \"%s\" does not exist",
10774                                                 RelationGetRelationName(rel))));
10775         tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
10776         server = GetForeignServer(tableform->ftserver);
10777         fdw = GetForeignDataWrapper(server->fdwid);
10778
10779         memset(repl_val, 0, sizeof(repl_val));
10780         memset(repl_null, false, sizeof(repl_null));
10781         memset(repl_repl, false, sizeof(repl_repl));
10782
10783         /* Extract the current options */
10784         datum = SysCacheGetAttr(FOREIGNTABLEREL,
10785                                                         tuple,
10786                                                         Anum_pg_foreign_table_ftoptions,
10787                                                         &isnull);
10788         if (isnull)
10789                 datum = PointerGetDatum(NULL);
10790
10791         /* Transform the options */
10792         datum = transformGenericOptions(ForeignTableRelationId,
10793                                                                         datum,
10794                                                                         options,
10795                                                                         fdw->fdwvalidator);
10796
10797         if (PointerIsValid(DatumGetPointer(datum)))
10798                 repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
10799         else
10800                 repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
10801
10802         repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
10803
10804         /* Everything looks good - update the tuple */
10805
10806         tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
10807                                                           repl_val, repl_null, repl_repl);
10808
10809         simple_heap_update(ftrel, &tuple->t_self, tuple);
10810         CatalogUpdateIndexes(ftrel, tuple);
10811
10812         InvokeObjectPostAlterHook(ForeignTableRelationId,
10813                                                           RelationGetRelid(rel), 0);
10814
10815         heap_close(ftrel, RowExclusiveLock);
10816
10817         heap_freetuple(tuple);
10818 }
10819
10820 /*
10821  * Preparation phase for SET LOGGED/UNLOGGED
10822  *
10823  * This verifies that we're not trying to change a temp table.  Also,
10824  * existing foreign key constraints are checked to avoid ending up with
10825  * permanent tables referencing unlogged tables.
10826  *
10827  * Return value is false if the operation is a no-op (in which case the
10828  * checks are skipped), otherwise true.
10829  */
10830 static bool
10831 ATPrepChangePersistence(Relation rel, bool toLogged)
10832 {
10833         Relation        pg_constraint;
10834         HeapTuple       tuple;
10835         SysScanDesc scan;
10836         ScanKeyData skey[1];
10837
10838         /*
10839          * Disallow changing status for a temp table.  Also verify whether we can
10840          * get away with doing nothing; in such cases we don't need to run the
10841          * checks below, either.
10842          */
10843         switch (rel->rd_rel->relpersistence)
10844         {
10845                 case RELPERSISTENCE_TEMP:
10846                         ereport(ERROR,
10847                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10848                                          errmsg("cannot change logged status of table %s",
10849                                                         RelationGetRelationName(rel)),
10850                                          errdetail("Table %s is temporary.",
10851                                                            RelationGetRelationName(rel)),
10852                                          errtable(rel)));
10853                         break;
10854                 case RELPERSISTENCE_PERMANENT:
10855                         if (toLogged)
10856                                 /* nothing to do */
10857                                 return false;
10858                         break;
10859                 case RELPERSISTENCE_UNLOGGED:
10860                         if (!toLogged)
10861                                 /* nothing to do */
10862                                 return false;
10863                         break;
10864         }
10865
10866         /*
10867          * Check existing foreign key constraints to preserve the invariant that
10868          * no permanent tables cannot reference unlogged ones.  Self-referencing
10869          * foreign keys can safely be ignored.
10870          */
10871         pg_constraint = heap_open(ConstraintRelationId, AccessShareLock);
10872
10873         /*
10874          * Scan conrelid if changing to permanent, else confrelid.  This also
10875          * determines whether a useful index exists.
10876          */
10877         ScanKeyInit(&skey[0],
10878                                 toLogged ? Anum_pg_constraint_conrelid :
10879                                 Anum_pg_constraint_confrelid,
10880                                 BTEqualStrategyNumber, F_OIDEQ,
10881                                 ObjectIdGetDatum(RelationGetRelid(rel)));
10882         scan = systable_beginscan(pg_constraint,
10883                                                           toLogged ? ConstraintRelidIndexId : InvalidOid,
10884                                                           true, NULL, 1, skey);
10885
10886         while (HeapTupleIsValid(tuple = systable_getnext(scan)))
10887         {
10888                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
10889
10890                 if (con->contype == CONSTRAINT_FOREIGN)
10891                 {
10892                         Oid                     foreignrelid;
10893                         Relation        foreignrel;
10894
10895                         /* the opposite end of what we used as scankey */
10896                         foreignrelid = toLogged ? con->confrelid : con->conrelid;
10897
10898                         /* ignore if self-referencing */
10899                         if (RelationGetRelid(rel) == foreignrelid)
10900                                 continue;
10901
10902                         foreignrel = relation_open(foreignrelid, AccessShareLock);
10903
10904                         if (toLogged)
10905                         {
10906                                 if (foreignrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
10907                                         ereport(ERROR,
10908                                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10909                                                  errmsg("cannot change status of table %s to logged",
10910                                                                 RelationGetRelationName(rel)),
10911                                                   errdetail("Table %s references unlogged table %s.",
10912                                                                         RelationGetRelationName(rel),
10913                                                                         RelationGetRelationName(foreignrel)),
10914                                                          errtableconstraint(rel, NameStr(con->conname))));
10915                         }
10916                         else
10917                         {
10918                                 if (foreignrel->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
10919                                         ereport(ERROR,
10920                                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10921                                            errmsg("cannot change status of table %s to unlogged",
10922                                                           RelationGetRelationName(rel)),
10923                                           errdetail("Logged table %s is referenced by table %s.",
10924                                                                 RelationGetRelationName(foreignrel),
10925                                                                 RelationGetRelationName(rel)),
10926                                                          errtableconstraint(rel, NameStr(con->conname))));
10927                         }
10928
10929                         relation_close(foreignrel, AccessShareLock);
10930                 }
10931         }
10932
10933         systable_endscan(scan);
10934
10935         heap_close(pg_constraint, AccessShareLock);
10936
10937         return true;
10938 }
10939
10940 /*
10941  * Execute ALTER TABLE SET SCHEMA
10942  */
10943 ObjectAddress
10944 AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
10945 {
10946         Relation        rel;
10947         Oid                     relid;
10948         Oid                     oldNspOid;
10949         Oid                     nspOid;
10950         RangeVar   *newrv;
10951         ObjectAddresses *objsMoved;
10952         ObjectAddress myself;
10953
10954         relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
10955                                                                          stmt->missing_ok, false,
10956                                                                          RangeVarCallbackForAlterRelation,
10957                                                                          (void *) stmt);
10958
10959         if (!OidIsValid(relid))
10960         {
10961                 ereport(NOTICE,
10962                                 (errmsg("relation \"%s\" does not exist, skipping",
10963                                                 stmt->relation->relname)));
10964                 return InvalidObjectAddress;
10965         }
10966
10967         rel = relation_open(relid, NoLock);
10968
10969         oldNspOid = RelationGetNamespace(rel);
10970
10971         /* If it's an owned sequence, disallow moving it by itself. */
10972         if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
10973         {
10974                 Oid                     tableId;
10975                 int32           colId;
10976
10977                 if (sequenceIsOwned(relid, &tableId, &colId))
10978                         ereport(ERROR,
10979                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10980                                  errmsg("cannot move an owned sequence into another schema"),
10981                                          errdetail("Sequence \"%s\" is linked to table \"%s\".",
10982                                                            RelationGetRelationName(rel),
10983                                                            get_rel_name(tableId))));
10984         }
10985
10986         /* Get and lock schema OID and check its permissions. */
10987         newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
10988         nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
10989
10990         /* common checks on switching namespaces */
10991         CheckSetNamespace(oldNspOid, nspOid, RelationRelationId, relid);
10992
10993         objsMoved = new_object_addresses();
10994         AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
10995         free_object_addresses(objsMoved);
10996
10997         ObjectAddressSet(myself, RelationRelationId, relid);
10998
10999         if (oldschema)
11000                 *oldschema = oldNspOid;
11001
11002         /* close rel, but keep lock until commit */
11003         relation_close(rel, NoLock);
11004
11005         return myself;
11006 }
11007
11008 /*
11009  * The guts of relocating a table or materialized view to another namespace:
11010  * besides moving the relation itself, its dependent objects are relocated to
11011  * the new schema.
11012  */
11013 void
11014 AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
11015                                                         ObjectAddresses *objsMoved)
11016 {
11017         Relation        classRel;
11018
11019         Assert(objsMoved != NULL);
11020
11021         /* OK, modify the pg_class row and pg_depend entry */
11022         classRel = heap_open(RelationRelationId, RowExclusiveLock);
11023
11024         AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
11025                                                                    nspOid, true, objsMoved);
11026
11027         /* Fix the table's row type too */
11028         AlterTypeNamespaceInternal(rel->rd_rel->reltype,
11029                                                            nspOid, false, false, objsMoved);
11030
11031         /* Fix other dependent stuff */
11032         if (rel->rd_rel->relkind == RELKIND_RELATION ||
11033                 rel->rd_rel->relkind == RELKIND_MATVIEW)
11034         {
11035                 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
11036                 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
11037                                                    objsMoved, AccessExclusiveLock);
11038                 AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
11039                                                                   false, objsMoved);
11040         }
11041
11042         heap_close(classRel, RowExclusiveLock);
11043 }
11044
11045 /*
11046  * The guts of relocating a relation to another namespace: fix the pg_class
11047  * entry, and the pg_depend entry if any.  Caller must already have
11048  * opened and write-locked pg_class.
11049  */
11050 void
11051 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
11052                                                            Oid oldNspOid, Oid newNspOid,
11053                                                            bool hasDependEntry,
11054                                                            ObjectAddresses *objsMoved)
11055 {
11056         HeapTuple       classTup;
11057         Form_pg_class classForm;
11058         ObjectAddress thisobj;
11059
11060         classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
11061         if (!HeapTupleIsValid(classTup))
11062                 elog(ERROR, "cache lookup failed for relation %u", relOid);
11063         classForm = (Form_pg_class) GETSTRUCT(classTup);
11064
11065         Assert(classForm->relnamespace == oldNspOid);
11066
11067         thisobj.classId = RelationRelationId;
11068         thisobj.objectId = relOid;
11069         thisobj.objectSubId = 0;
11070
11071         /*
11072          * Do nothing when there's nothing to do.
11073          */
11074         if (!object_address_present(&thisobj, objsMoved))
11075         {
11076                 /* check for duplicate name (more friendly than unique-index failure) */
11077                 if (get_relname_relid(NameStr(classForm->relname),
11078                                                           newNspOid) != InvalidOid)
11079                         ereport(ERROR,
11080                                         (errcode(ERRCODE_DUPLICATE_TABLE),
11081                                          errmsg("relation \"%s\" already exists in schema \"%s\"",
11082                                                         NameStr(classForm->relname),
11083                                                         get_namespace_name(newNspOid))));
11084
11085                 /* classTup is a copy, so OK to scribble on */
11086                 classForm->relnamespace = newNspOid;
11087
11088                 simple_heap_update(classRel, &classTup->t_self, classTup);
11089                 CatalogUpdateIndexes(classRel, classTup);
11090
11091                 /* Update dependency on schema if caller said so */
11092                 if (hasDependEntry &&
11093                         changeDependencyFor(RelationRelationId,
11094                                                                 relOid,
11095                                                                 NamespaceRelationId,
11096                                                                 oldNspOid,
11097                                                                 newNspOid) != 1)
11098                         elog(ERROR, "failed to change schema dependency for relation \"%s\"",
11099                                  NameStr(classForm->relname));
11100
11101                 add_exact_object_address(&thisobj, objsMoved);
11102
11103                 InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
11104         }
11105
11106         heap_freetuple(classTup);
11107 }
11108
11109 /*
11110  * Move all indexes for the specified relation to another namespace.
11111  *
11112  * Note: we assume adequate permission checking was done by the caller,
11113  * and that the caller has a suitable lock on the owning relation.
11114  */
11115 static void
11116 AlterIndexNamespaces(Relation classRel, Relation rel,
11117                                          Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
11118 {
11119         List       *indexList;
11120         ListCell   *l;
11121
11122         indexList = RelationGetIndexList(rel);
11123
11124         foreach(l, indexList)
11125         {
11126                 Oid                     indexOid = lfirst_oid(l);
11127                 ObjectAddress thisobj;
11128
11129                 thisobj.classId = RelationRelationId;
11130                 thisobj.objectId = indexOid;
11131                 thisobj.objectSubId = 0;
11132
11133                 /*
11134                  * Note: currently, the index will not have its own dependency on the
11135                  * namespace, so we don't need to do changeDependencyFor(). There's no
11136                  * row type in pg_type, either.
11137                  *
11138                  * XXX this objsMoved test may be pointless -- surely we have a single
11139                  * dependency link from a relation to each index?
11140                  */
11141                 if (!object_address_present(&thisobj, objsMoved))
11142                 {
11143                         AlterRelationNamespaceInternal(classRel, indexOid,
11144                                                                                    oldNspOid, newNspOid,
11145                                                                                    false, objsMoved);
11146                         add_exact_object_address(&thisobj, objsMoved);
11147                 }
11148         }
11149
11150         list_free(indexList);
11151 }
11152
11153 /*
11154  * Move all SERIAL-column sequences of the specified relation to another
11155  * namespace.
11156  *
11157  * Note: we assume adequate permission checking was done by the caller,
11158  * and that the caller has a suitable lock on the owning relation.
11159  */
11160 static void
11161 AlterSeqNamespaces(Relation classRel, Relation rel,
11162                                    Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
11163                                    LOCKMODE lockmode)
11164 {
11165         Relation        depRel;
11166         SysScanDesc scan;
11167         ScanKeyData key[2];
11168         HeapTuple       tup;
11169
11170         /*
11171          * SERIAL sequences are those having an auto dependency on one of the
11172          * table's columns (we don't care *which* column, exactly).
11173          */
11174         depRel = heap_open(DependRelationId, AccessShareLock);
11175
11176         ScanKeyInit(&key[0],
11177                                 Anum_pg_depend_refclassid,
11178                                 BTEqualStrategyNumber, F_OIDEQ,
11179                                 ObjectIdGetDatum(RelationRelationId));
11180         ScanKeyInit(&key[1],
11181                                 Anum_pg_depend_refobjid,
11182                                 BTEqualStrategyNumber, F_OIDEQ,
11183                                 ObjectIdGetDatum(RelationGetRelid(rel)));
11184         /* we leave refobjsubid unspecified */
11185
11186         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
11187                                                           NULL, 2, key);
11188
11189         while (HeapTupleIsValid(tup = systable_getnext(scan)))
11190         {
11191                 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
11192                 Relation        seqRel;
11193
11194                 /* skip dependencies other than auto dependencies on columns */
11195                 if (depForm->refobjsubid == 0 ||
11196                         depForm->classid != RelationRelationId ||
11197                         depForm->objsubid != 0 ||
11198                         depForm->deptype != DEPENDENCY_AUTO)
11199                         continue;
11200
11201                 /* Use relation_open just in case it's an index */
11202                 seqRel = relation_open(depForm->objid, lockmode);
11203
11204                 /* skip non-sequence relations */
11205                 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
11206                 {
11207                         /* No need to keep the lock */
11208                         relation_close(seqRel, lockmode);
11209                         continue;
11210                 }
11211
11212                 /* Fix the pg_class and pg_depend entries */
11213                 AlterRelationNamespaceInternal(classRel, depForm->objid,
11214                                                                            oldNspOid, newNspOid,
11215                                                                            true, objsMoved);
11216
11217                 /*
11218                  * Sequences have entries in pg_type. We need to be careful to move
11219                  * them to the new namespace, too.
11220                  */
11221                 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
11222                                                                    newNspOid, false, false, objsMoved);
11223
11224                 /* Now we can close it.  Keep the lock till end of transaction. */
11225                 relation_close(seqRel, NoLock);
11226         }
11227
11228         systable_endscan(scan);
11229
11230         relation_close(depRel, AccessShareLock);
11231 }
11232
11233
11234 /*
11235  * This code supports
11236  *      CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
11237  *
11238  * Because we only support this for TEMP tables, it's sufficient to remember
11239  * the state in a backend-local data structure.
11240  */
11241
11242 /*
11243  * Register a newly-created relation's ON COMMIT action.
11244  */
11245 void
11246 register_on_commit_action(Oid relid, OnCommitAction action)
11247 {
11248         OnCommitItem *oc;
11249         MemoryContext oldcxt;
11250
11251         /*
11252          * We needn't bother registering the relation unless there is an ON COMMIT
11253          * action we need to take.
11254          */
11255         if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
11256                 return;
11257
11258         oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
11259
11260         oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
11261         oc->relid = relid;
11262         oc->oncommit = action;
11263         oc->creating_subid = GetCurrentSubTransactionId();
11264         oc->deleting_subid = InvalidSubTransactionId;
11265
11266         on_commits = lcons(oc, on_commits);
11267
11268         MemoryContextSwitchTo(oldcxt);
11269 }
11270
11271 /*
11272  * Unregister any ON COMMIT action when a relation is deleted.
11273  *
11274  * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
11275  */
11276 void
11277 remove_on_commit_action(Oid relid)
11278 {
11279         ListCell   *l;
11280
11281         foreach(l, on_commits)
11282         {
11283                 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
11284
11285                 if (oc->relid == relid)
11286                 {
11287                         oc->deleting_subid = GetCurrentSubTransactionId();
11288                         break;
11289                 }
11290         }
11291 }
11292
11293 /*
11294  * Perform ON COMMIT actions.
11295  *
11296  * This is invoked just before actually committing, since it's possible
11297  * to encounter errors.
11298  */
11299 void
11300 PreCommit_on_commit_actions(void)
11301 {
11302         ListCell   *l;
11303         List       *oids_to_truncate = NIL;
11304
11305         foreach(l, on_commits)
11306         {
11307                 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
11308
11309                 /* Ignore entry if already dropped in this xact */
11310                 if (oc->deleting_subid != InvalidSubTransactionId)
11311                         continue;
11312
11313                 switch (oc->oncommit)
11314                 {
11315                         case ONCOMMIT_NOOP:
11316                         case ONCOMMIT_PRESERVE_ROWS:
11317                                 /* Do nothing (there shouldn't be such entries, actually) */
11318                                 break;
11319                         case ONCOMMIT_DELETE_ROWS:
11320
11321                                 /*
11322                                  * If this transaction hasn't accessed any temporary
11323                                  * relations, we can skip truncating ON COMMIT DELETE ROWS
11324                                  * tables, as they must still be empty.
11325                                  */
11326                                 if (MyXactAccessedTempRel)
11327                                         oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
11328                                 break;
11329                         case ONCOMMIT_DROP:
11330                                 {
11331                                         ObjectAddress object;
11332
11333                                         object.classId = RelationRelationId;
11334                                         object.objectId = oc->relid;
11335                                         object.objectSubId = 0;
11336
11337                                         /*
11338                                          * Since this is an automatic drop, rather than one
11339                                          * directly initiated by the user, we pass the
11340                                          * PERFORM_DELETION_INTERNAL flag.
11341                                          */
11342                                         performDeletion(&object,
11343                                                                         DROP_CASCADE, PERFORM_DELETION_INTERNAL);
11344
11345                                         /*
11346                                          * Note that table deletion will call
11347                                          * remove_on_commit_action, so the entry should get marked
11348                                          * as deleted.
11349                                          */
11350                                         Assert(oc->deleting_subid != InvalidSubTransactionId);
11351                                         break;
11352                                 }
11353                 }
11354         }
11355         if (oids_to_truncate != NIL)
11356         {
11357                 heap_truncate(oids_to_truncate);
11358                 CommandCounterIncrement();              /* XXX needed? */
11359         }
11360 }
11361
11362 /*
11363  * Post-commit or post-abort cleanup for ON COMMIT management.
11364  *
11365  * All we do here is remove no-longer-needed OnCommitItem entries.
11366  *
11367  * During commit, remove entries that were deleted during this transaction;
11368  * during abort, remove those created during this transaction.
11369  */
11370 void
11371 AtEOXact_on_commit_actions(bool isCommit)
11372 {
11373         ListCell   *cur_item;
11374         ListCell   *prev_item;
11375
11376         prev_item = NULL;
11377         cur_item = list_head(on_commits);
11378
11379         while (cur_item != NULL)
11380         {
11381                 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
11382
11383                 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
11384                         oc->creating_subid != InvalidSubTransactionId)
11385                 {
11386                         /* cur_item must be removed */
11387                         on_commits = list_delete_cell(on_commits, cur_item, prev_item);
11388                         pfree(oc);
11389                         if (prev_item)
11390                                 cur_item = lnext(prev_item);
11391                         else
11392                                 cur_item = list_head(on_commits);
11393                 }
11394                 else
11395                 {
11396                         /* cur_item must be preserved */
11397                         oc->creating_subid = InvalidSubTransactionId;
11398                         oc->deleting_subid = InvalidSubTransactionId;
11399                         prev_item = cur_item;
11400                         cur_item = lnext(prev_item);
11401                 }
11402         }
11403 }
11404
11405 /*
11406  * Post-subcommit or post-subabort cleanup for ON COMMIT management.
11407  *
11408  * During subabort, we can immediately remove entries created during this
11409  * subtransaction.  During subcommit, just relabel entries marked during
11410  * this subtransaction as being the parent's responsibility.
11411  */
11412 void
11413 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
11414                                                           SubTransactionId parentSubid)
11415 {
11416         ListCell   *cur_item;
11417         ListCell   *prev_item;
11418
11419         prev_item = NULL;
11420         cur_item = list_head(on_commits);
11421
11422         while (cur_item != NULL)
11423         {
11424                 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
11425
11426                 if (!isCommit && oc->creating_subid == mySubid)
11427                 {
11428                         /* cur_item must be removed */
11429                         on_commits = list_delete_cell(on_commits, cur_item, prev_item);
11430                         pfree(oc);
11431                         if (prev_item)
11432                                 cur_item = lnext(prev_item);
11433                         else
11434                                 cur_item = list_head(on_commits);
11435                 }
11436                 else
11437                 {
11438                         /* cur_item must be preserved */
11439                         if (oc->creating_subid == mySubid)
11440                                 oc->creating_subid = parentSubid;
11441                         if (oc->deleting_subid == mySubid)
11442                                 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
11443                         prev_item = cur_item;
11444                         cur_item = lnext(prev_item);
11445                 }
11446         }
11447 }
11448
11449 /*
11450  * This is intended as a callback for RangeVarGetRelidExtended().  It allows
11451  * the relation to be locked only if (1) it's a plain table, materialized
11452  * view, or TOAST table and (2) the current user is the owner (or the
11453  * superuser).  This meets the permission-checking needs of CLUSTER, REINDEX
11454  * TABLE, and REFRESH MATERIALIZED VIEW; we expose it here so that it can be
11455  * used by all.
11456  */
11457 void
11458 RangeVarCallbackOwnsTable(const RangeVar *relation,
11459                                                   Oid relId, Oid oldRelId, void *arg)
11460 {
11461         char            relkind;
11462
11463         /* Nothing to do if the relation was not found. */
11464         if (!OidIsValid(relId))
11465                 return;
11466
11467         /*
11468          * If the relation does exist, check whether it's an index.  But note that
11469          * the relation might have been dropped between the time we did the name
11470          * lookup and now.  In that case, there's nothing to do.
11471          */
11472         relkind = get_rel_relkind(relId);
11473         if (!relkind)
11474                 return;
11475         if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
11476                 relkind != RELKIND_MATVIEW)
11477                 ereport(ERROR,
11478                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11479                                  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
11480
11481         /* Check permissions */
11482         if (!pg_class_ownercheck(relId, GetUserId()))
11483                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, relation->relname);
11484 }
11485
11486 /*
11487  * Callback to RangeVarGetRelidExtended(), similar to
11488  * RangeVarCallbackOwnsTable() but without checks on the type of the relation.
11489  */
11490 void
11491 RangeVarCallbackOwnsRelation(const RangeVar *relation,
11492                                                          Oid relId, Oid oldRelId, void *arg)
11493 {
11494         HeapTuple       tuple;
11495
11496         /* Nothing to do if the relation was not found. */
11497         if (!OidIsValid(relId))
11498                 return;
11499
11500         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
11501         if (!HeapTupleIsValid(tuple))           /* should not happen */
11502                 elog(ERROR, "cache lookup failed for relation %u", relId);
11503
11504         if (!pg_class_ownercheck(relId, GetUserId()))
11505                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
11506                                            relation->relname);
11507
11508         if (!allowSystemTableMods &&
11509                 IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
11510                 ereport(ERROR,
11511                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
11512                                  errmsg("permission denied: \"%s\" is a system catalog",
11513                                                 relation->relname)));
11514
11515         ReleaseSysCache(tuple);
11516 }
11517
11518 /*
11519  * Common RangeVarGetRelid callback for rename, set schema, and alter table
11520  * processing.
11521  */
11522 static void
11523 RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
11524                                                                  void *arg)
11525 {
11526         Node       *stmt = (Node *) arg;
11527         ObjectType      reltype;
11528         HeapTuple       tuple;
11529         Form_pg_class classform;
11530         AclResult       aclresult;
11531         char            relkind;
11532
11533         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
11534         if (!HeapTupleIsValid(tuple))
11535                 return;                                 /* concurrently dropped */
11536         classform = (Form_pg_class) GETSTRUCT(tuple);
11537         relkind = classform->relkind;
11538
11539         /* Must own relation. */
11540         if (!pg_class_ownercheck(relid, GetUserId()))
11541                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, rv->relname);
11542
11543         /* No system table modifications unless explicitly allowed. */
11544         if (!allowSystemTableMods && IsSystemClass(relid, classform))
11545                 ereport(ERROR,
11546                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
11547                                  errmsg("permission denied: \"%s\" is a system catalog",
11548                                                 rv->relname)));
11549
11550         /*
11551          * Extract the specified relation type from the statement parse tree.
11552          *
11553          * Also, for ALTER .. RENAME, check permissions: the user must (still)
11554          * have CREATE rights on the containing namespace.
11555          */
11556         if (IsA(stmt, RenameStmt))
11557         {
11558                 aclresult = pg_namespace_aclcheck(classform->relnamespace,
11559                                                                                   GetUserId(), ACL_CREATE);
11560                 if (aclresult != ACLCHECK_OK)
11561                         aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
11562                                                    get_namespace_name(classform->relnamespace));
11563                 reltype = ((RenameStmt *) stmt)->renameType;
11564         }
11565         else if (IsA(stmt, AlterObjectSchemaStmt))
11566                 reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
11567
11568         else if (IsA(stmt, AlterTableStmt))
11569                 reltype = ((AlterTableStmt *) stmt)->relkind;
11570         else
11571         {
11572                 reltype = OBJECT_TABLE; /* placate compiler */
11573                 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
11574         }
11575
11576         /*
11577          * For compatibility with prior releases, we allow ALTER TABLE to be used
11578          * with most other types of relations (but not composite types). We allow
11579          * similar flexibility for ALTER INDEX in the case of RENAME, but not
11580          * otherwise.  Otherwise, the user must select the correct form of the
11581          * command for the relation at issue.
11582          */
11583         if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
11584                 ereport(ERROR,
11585                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11586                                  errmsg("\"%s\" is not a sequence", rv->relname)));
11587
11588         if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
11589                 ereport(ERROR,
11590                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11591                                  errmsg("\"%s\" is not a view", rv->relname)));
11592
11593         if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
11594                 ereport(ERROR,
11595                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11596                                  errmsg("\"%s\" is not a materialized view", rv->relname)));
11597
11598         if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
11599                 ereport(ERROR,
11600                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11601                                  errmsg("\"%s\" is not a foreign table", rv->relname)));
11602
11603         if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
11604                 ereport(ERROR,
11605                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11606                                  errmsg("\"%s\" is not a composite type", rv->relname)));
11607
11608         if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX
11609                 && !IsA(stmt, RenameStmt))
11610                 ereport(ERROR,
11611                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11612                                  errmsg("\"%s\" is not an index", rv->relname)));
11613
11614         /*
11615          * Don't allow ALTER TABLE on composite types. We want people to use ALTER
11616          * TYPE for that.
11617          */
11618         if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
11619                 ereport(ERROR,
11620                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11621                                  errmsg("\"%s\" is a composite type", rv->relname),
11622                                  errhint("Use ALTER TYPE instead.")));
11623
11624         /*
11625          * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
11626          * to a different schema, such as indexes and TOAST tables.
11627          */
11628         if (IsA(stmt, AlterObjectSchemaStmt) &&
11629                 relkind != RELKIND_RELATION &&
11630                 relkind != RELKIND_VIEW &&
11631                 relkind != RELKIND_MATVIEW &&
11632                 relkind != RELKIND_SEQUENCE &&
11633                 relkind != RELKIND_FOREIGN_TABLE)
11634                 ereport(ERROR,
11635                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11636                                  errmsg("\"%s\" is not a table, view, materialized view, sequence, or foreign table",
11637                                                 rv->relname)));
11638
11639         ReleaseSysCache(tuple);
11640 }