]> granicus.if.org Git - postgresql/blob - src/backend/commands/tablecmds.c
Improve error message for the case where a requested foreign key constraint
[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-2009, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.297 2009/08/12 23:00:12 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/relscan.h"
21 #include "access/sysattr.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/dependency.h"
25 #include "catalog/heap.h"
26 #include "catalog/index.h"
27 #include "catalog/indexing.h"
28 #include "catalog/namespace.h"
29 #include "catalog/pg_constraint.h"
30 #include "catalog/pg_depend.h"
31 #include "catalog/pg_inherits.h"
32 #include "catalog/pg_inherits_fn.h"
33 #include "catalog/pg_namespace.h"
34 #include "catalog/pg_opclass.h"
35 #include "catalog/pg_tablespace.h"
36 #include "catalog/pg_trigger.h"
37 #include "catalog/pg_type.h"
38 #include "catalog/pg_type_fn.h"
39 #include "catalog/storage.h"
40 #include "catalog/toasting.h"
41 #include "commands/cluster.h"
42 #include "commands/defrem.h"
43 #include "commands/sequence.h"
44 #include "commands/tablecmds.h"
45 #include "commands/tablespace.h"
46 #include "commands/trigger.h"
47 #include "commands/typecmds.h"
48 #include "executor/executor.h"
49 #include "miscadmin.h"
50 #include "nodes/makefuncs.h"
51 #include "nodes/nodeFuncs.h"
52 #include "nodes/parsenodes.h"
53 #include "optimizer/clauses.h"
54 #include "parser/parse_clause.h"
55 #include "parser/parse_coerce.h"
56 #include "parser/parse_expr.h"
57 #include "parser/parse_oper.h"
58 #include "parser/parse_relation.h"
59 #include "parser/parse_type.h"
60 #include "parser/parse_utilcmd.h"
61 #include "parser/parser.h"
62 #include "rewrite/rewriteDefine.h"
63 #include "rewrite/rewriteHandler.h"
64 #include "storage/bufmgr.h"
65 #include "storage/lmgr.h"
66 #include "storage/smgr.h"
67 #include "utils/acl.h"
68 #include "utils/builtins.h"
69 #include "utils/fmgroids.h"
70 #include "utils/inval.h"
71 #include "utils/lsyscache.h"
72 #include "utils/memutils.h"
73 #include "utils/relcache.h"
74 #include "utils/snapmgr.h"
75 #include "utils/syscache.h"
76 #include "utils/tqual.h"
77
78
79 /*
80  * ON COMMIT action list
81  */
82 typedef struct OnCommitItem
83 {
84         Oid                     relid;                  /* relid of relation */
85         OnCommitAction oncommit;        /* what to do at end of xact */
86
87         /*
88          * If this entry was created during the current transaction,
89          * creating_subid is the ID of the creating subxact; if created in a prior
90          * transaction, creating_subid is zero.  If deleted during the current
91          * transaction, deleting_subid is the ID of the deleting subxact; if no
92          * deletion request is pending, deleting_subid is zero.
93          */
94         SubTransactionId creating_subid;
95         SubTransactionId deleting_subid;
96 } OnCommitItem;
97
98 static List *on_commits = NIL;
99
100
101 /*
102  * State information for ALTER TABLE
103  *
104  * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
105  * structs, one for each table modified by the operation (the named table
106  * plus any child tables that are affected).  We save lists of subcommands
107  * to apply to this table (possibly modified by parse transformation steps);
108  * these lists will be executed in Phase 2.  If a Phase 3 step is needed,
109  * necessary information is stored in the constraints and newvals lists.
110  *
111  * Phase 2 is divided into multiple passes; subcommands are executed in
112  * a pass determined by subcommand type.
113  */
114
115 #define AT_PASS_DROP                    0               /* DROP (all flavors) */
116 #define AT_PASS_ALTER_TYPE              1               /* ALTER COLUMN TYPE */
117 #define AT_PASS_OLD_INDEX               2               /* re-add existing indexes */
118 #define AT_PASS_OLD_CONSTR              3               /* re-add existing constraints */
119 #define AT_PASS_COL_ATTRS               4               /* set other column attributes */
120 /* We could support a RENAME COLUMN pass here, but not currently used */
121 #define AT_PASS_ADD_COL                 5               /* ADD COLUMN */
122 #define AT_PASS_ADD_INDEX               6               /* ADD indexes */
123 #define AT_PASS_ADD_CONSTR              7               /* ADD constraints, defaults */
124 #define AT_PASS_MISC                    8               /* other stuff */
125 #define AT_NUM_PASSES                   9
126
127 typedef struct AlteredTableInfo
128 {
129         /* Information saved before any work commences: */
130         Oid                     relid;                  /* Relation to work on */
131         char            relkind;                /* Its relkind */
132         TupleDesc       oldDesc;                /* Pre-modification tuple descriptor */
133         /* Information saved by Phase 1 for Phase 2: */
134         List       *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
135         /* Information saved by Phases 1/2 for Phase 3: */
136         List       *constraints;        /* List of NewConstraint */
137         List       *newvals;            /* List of NewColumnValue */
138         bool            new_notnull;    /* T if we added new NOT NULL constraints */
139         bool            new_changeoids; /* T if we added/dropped the OID column */
140         Oid                     newTableSpace;  /* new tablespace; 0 means no change */
141         /* Objects to rebuild after completing ALTER TYPE operations */
142         List       *changedConstraintOids;      /* OIDs of constraints to rebuild */
143         List       *changedConstraintDefs;      /* string definitions of same */
144         List       *changedIndexOids;           /* OIDs of indexes to rebuild */
145         List       *changedIndexDefs;           /* string definitions of same */
146 } AlteredTableInfo;
147
148 /* Struct describing one new constraint to check in Phase 3 scan */
149 /* Note: new NOT NULL constraints are handled elsewhere */
150 typedef struct NewConstraint
151 {
152         char       *name;                       /* Constraint name, or NULL if none */
153         ConstrType      contype;                /* CHECK or FOREIGN */
154         Oid                     refrelid;               /* PK rel, if FOREIGN */
155         Oid                     refindid;               /* OID of PK's index, if FOREIGN */
156         Oid                     conid;                  /* OID of pg_constraint entry, if FOREIGN */
157         Node       *qual;                       /* Check expr or CONSTR_FOREIGN Constraint */
158         List       *qualstate;          /* Execution state for CHECK */
159 } NewConstraint;
160
161 /*
162  * Struct describing one new column value that needs to be computed during
163  * Phase 3 copy (this could be either a new column with a non-null default, or
164  * a column that we're changing the type of).  Columns without such an entry
165  * are just copied from the old table during ATRewriteTable.  Note that the
166  * expr is an expression over *old* table values.
167  */
168 typedef struct NewColumnValue
169 {
170         AttrNumber      attnum;                 /* which column */
171         Expr       *expr;                       /* expression to compute */
172         ExprState  *exprstate;          /* execution state */
173 } NewColumnValue;
174
175 /*
176  * Error-reporting support for RemoveRelations
177  */
178 struct dropmsgstrings
179 {
180         char            kind;
181         int                     nonexistent_code;
182         const char *nonexistent_msg;
183         const char *skipping_msg;
184         const char *nota_msg;
185         const char *drophint_msg;
186 };
187
188 static const struct dropmsgstrings dropmsgstringarray[] = {
189         {RELKIND_RELATION,
190                 ERRCODE_UNDEFINED_TABLE,
191                 gettext_noop("table \"%s\" does not exist"),
192                 gettext_noop("table \"%s\" does not exist, skipping"),
193                 gettext_noop("\"%s\" is not a table"),
194         gettext_noop("Use DROP TABLE to remove a table.")},
195         {RELKIND_SEQUENCE,
196                 ERRCODE_UNDEFINED_TABLE,
197                 gettext_noop("sequence \"%s\" does not exist"),
198                 gettext_noop("sequence \"%s\" does not exist, skipping"),
199                 gettext_noop("\"%s\" is not a sequence"),
200         gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
201         {RELKIND_VIEW,
202                 ERRCODE_UNDEFINED_TABLE,
203                 gettext_noop("view \"%s\" does not exist"),
204                 gettext_noop("view \"%s\" does not exist, skipping"),
205                 gettext_noop("\"%s\" is not a view"),
206         gettext_noop("Use DROP VIEW to remove a view.")},
207         {RELKIND_INDEX,
208                 ERRCODE_UNDEFINED_OBJECT,
209                 gettext_noop("index \"%s\" does not exist"),
210                 gettext_noop("index \"%s\" does not exist, skipping"),
211                 gettext_noop("\"%s\" is not an index"),
212         gettext_noop("Use DROP INDEX to remove an index.")},
213         {RELKIND_COMPOSITE_TYPE,
214                 ERRCODE_UNDEFINED_OBJECT,
215                 gettext_noop("type \"%s\" does not exist"),
216                 gettext_noop("type \"%s\" does not exist, skipping"),
217                 gettext_noop("\"%s\" is not a type"),
218         gettext_noop("Use DROP TYPE to remove a type.")},
219         {'\0', 0, NULL, NULL, NULL, NULL}
220 };
221
222
223 static void truncate_check_rel(Relation rel);
224 static List *MergeAttributes(List *schema, List *supers, bool istemp,
225                                 List **supOids, List **supconstr, int *supOidCount);
226 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
227 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
228 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
229 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
230 static void StoreCatalogInheritance(Oid relationId, List *supers);
231 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
232                                                  int16 seqNumber, Relation inhRelation);
233 static int      findAttrByName(const char *attributeName, List *schema);
234 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
235 static void AlterIndexNamespaces(Relation classRel, Relation rel,
236                                          Oid oldNspOid, Oid newNspOid);
237 static void AlterSeqNamespaces(Relation classRel, Relation rel,
238                                    Oid oldNspOid, Oid newNspOid,
239                                    const char *newNspName);
240 static int transformColumnNameList(Oid relId, List *colList,
241                                                 int16 *attnums, Oid *atttypids);
242 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
243                                                    List **attnamelist,
244                                                    int16 *attnums, Oid *atttypids,
245                                                    Oid *opclasses);
246 static Oid transformFkeyCheckAttrs(Relation pkrel,
247                                                 int numattrs, int16 *attnums,
248                                                 Oid *opclasses);
249 static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
250 static void validateForeignKeyConstraint(Constraint *fkconstraint,
251                                                          Relation rel, Relation pkrel,
252                                                          Oid pkindOid, Oid constraintOid);
253 static void createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
254                                                  Oid constraintOid, Oid indexOid);
255 static void ATController(Relation rel, List *cmds, bool recurse);
256 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
257                   bool recurse, bool recursing);
258 static void ATRewriteCatalogs(List **wqueue);
259 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
260                   AlterTableCmd *cmd);
261 static void ATRewriteTables(List **wqueue);
262 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
263 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
264 static void ATSimplePermissions(Relation rel, bool allowView);
265 static void ATSimplePermissionsRelationOrIndex(Relation rel);
266 static void ATSimpleRecursion(List **wqueue, Relation rel,
267                                   AlterTableCmd *cmd, bool recurse);
268 static void ATOneLevelRecursion(List **wqueue, Relation rel,
269                                         AlterTableCmd *cmd);
270 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
271                                 AlterTableCmd *cmd);
272 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
273                                 ColumnDef *colDef, bool isOid);
274 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
275 static void ATPrepAddOids(List **wqueue, Relation rel, bool recurse,
276                           AlterTableCmd *cmd);
277 static void ATExecDropNotNull(Relation rel, const char *colName);
278 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
279                                  const char *colName);
280 static void ATExecColumnDefault(Relation rel, const char *colName,
281                                         Node *newDefault);
282 static void ATPrepSetStatistics(Relation rel, const char *colName,
283                                         Node *newValue);
284 static void ATExecSetStatistics(Relation rel, const char *colName,
285                                         Node *newValue);
286 static void ATPrepSetDistinct(Relation rel, const char *colName,
287                                         Node *newValue);
288 static void ATExecSetDistinct(Relation rel, const char *colName,
289                                  Node *newValue);
290 static void ATExecSetStorage(Relation rel, const char *colName,
291                                  Node *newValue);
292 static void ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
293                                  DropBehavior behavior,
294                                  bool recurse, bool recursing,
295                                  bool missing_ok);
296 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
297                            IndexStmt *stmt, bool is_rebuild);
298 static void ATExecAddConstraint(List **wqueue,
299                                         AlteredTableInfo *tab, Relation rel,
300                                         Constraint *newConstraint, bool recurse);
301 static void ATAddCheckConstraint(List **wqueue,
302                                          AlteredTableInfo *tab, Relation rel,
303                                          Constraint *constr,
304                                          bool recurse, bool recursing);
305 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
306                                                   Constraint *fkconstraint);
307 static void ATExecDropConstraint(Relation rel, const char *constrName,
308                                                                  DropBehavior behavior,
309                                                                  bool recurse, bool recursing,
310                                                                  bool missing_ok);
311 static void ATPrepAlterColumnType(List **wqueue,
312                                           AlteredTableInfo *tab, Relation rel,
313                                           bool recurse, bool recursing,
314                                           AlterTableCmd *cmd);
315 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
316                                           const char *colName, TypeName *typeName);
317 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
318 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
319 static void change_owner_recurse_to_sequences(Oid relationOid,
320                                                                   Oid newOwnerId);
321 static void ATExecClusterOn(Relation rel, const char *indexName);
322 static void ATExecDropCluster(Relation rel);
323 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
324                                         char *tablespacename);
325 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
326 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
327 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
328                                                    char fires_when, bool skip_system);
329 static void ATExecEnableDisableRule(Relation rel, char *rulename,
330                                                 char fires_when);
331 static void ATExecAddInherit(Relation rel, RangeVar *parent);
332 static void ATExecDropInherit(Relation rel, RangeVar *parent);
333 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
334                                    ForkNumber forkNum, bool istemp);
335
336
337 /* ----------------------------------------------------------------
338  *              DefineRelation
339  *                              Creates a new relation.
340  *
341  * If successful, returns the OID of the new relation.
342  * ----------------------------------------------------------------
343  */
344 Oid
345 DefineRelation(CreateStmt *stmt, char relkind)
346 {
347         char            relname[NAMEDATALEN];
348         Oid                     namespaceId;
349         List       *schema = stmt->tableElts;
350         Oid                     relationId;
351         Oid                     tablespaceId;
352         Relation        rel;
353         TupleDesc       descriptor;
354         List       *inheritOids;
355         List       *old_constraints;
356         bool            localHasOids;
357         int                     parentOidCount;
358         List       *rawDefaults;
359         List       *cookedDefaults;
360         Datum           reloptions;
361         ListCell   *listptr;
362         AttrNumber      attnum;
363         static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
364
365         /*
366          * Truncate relname to appropriate length (probably a waste of time, as
367          * parser should have done this already).
368          */
369         StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
370
371         /*
372          * Check consistency of arguments
373          */
374         if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
375                 ereport(ERROR,
376                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
377                                  errmsg("ON COMMIT can only be used on temporary tables")));
378
379         /*
380          * Look up the namespace in which we are supposed to create the relation.
381          * Check we have permission to create there. Skip check if bootstrapping,
382          * since permissions machinery may not be working yet.
383          */
384         namespaceId = RangeVarGetCreationNamespace(stmt->relation);
385
386         if (!IsBootstrapProcessingMode())
387         {
388                 AclResult       aclresult;
389
390                 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
391                                                                                   ACL_CREATE);
392                 if (aclresult != ACLCHECK_OK)
393                         aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
394                                                    get_namespace_name(namespaceId));
395         }
396
397         /*
398          * Select tablespace to use.  If not specified, use default tablespace
399          * (which may in turn default to database's default).
400          */
401         if (stmt->tablespacename)
402         {
403                 tablespaceId = get_tablespace_oid(stmt->tablespacename);
404                 if (!OidIsValid(tablespaceId))
405                         ereport(ERROR,
406                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
407                                          errmsg("tablespace \"%s\" does not exist",
408                                                         stmt->tablespacename)));
409         }
410         else
411         {
412                 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
413                 /* note InvalidOid is OK in this case */
414         }
415
416         /* Check permissions except when using database's default */
417         if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
418         {
419                 AclResult       aclresult;
420
421                 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
422                                                                                    ACL_CREATE);
423                 if (aclresult != ACLCHECK_OK)
424                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
425                                                    get_tablespace_name(tablespaceId));
426         }
427
428         /*
429          * Parse and validate reloptions, if any.
430          */
431         reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
432                                                                          true, false);
433
434         (void) heap_reloptions(relkind, reloptions, true);
435
436         /*
437          * Look up inheritance ancestors and generate relation schema, including
438          * inherited attributes.
439          */
440         schema = MergeAttributes(schema, stmt->inhRelations,
441                                                          stmt->relation->istemp,
442                                                          &inheritOids, &old_constraints, &parentOidCount);
443
444         /*
445          * Create a tuple descriptor from the relation schema.  Note that this
446          * deals with column names, types, and NOT NULL constraints, but not
447          * default values or CHECK constraints; we handle those below.
448          */
449         descriptor = BuildDescForRelation(schema);
450
451         localHasOids = interpretOidsOption(stmt->options);
452         descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
453
454         /*
455          * Find columns with default values and prepare for insertion of the
456          * defaults.  Pre-cooked (that is, inherited) defaults go into a list of
457          * CookedConstraint structs that we'll pass to heap_create_with_catalog,
458          * while raw defaults go into a list of RawColumnDefault structs that will
459          * be processed by AddRelationNewConstraints.  (We can't deal with raw
460          * expressions until we can do transformExpr.)
461          *
462          * We can set the atthasdef flags now in the tuple descriptor; this just
463          * saves StoreAttrDefault from having to do an immediate update of the
464          * pg_attribute rows.
465          */
466         rawDefaults = NIL;
467         cookedDefaults = NIL;
468         attnum = 0;
469
470         foreach(listptr, schema)
471         {
472                 ColumnDef  *colDef = lfirst(listptr);
473
474                 attnum++;
475
476                 if (colDef->raw_default != NULL)
477                 {
478                         RawColumnDefault *rawEnt;
479
480                         Assert(colDef->cooked_default == NULL);
481
482                         rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
483                         rawEnt->attnum = attnum;
484                         rawEnt->raw_default = colDef->raw_default;
485                         rawDefaults = lappend(rawDefaults, rawEnt);
486                         descriptor->attrs[attnum - 1]->atthasdef = true;
487                 }
488                 else if (colDef->cooked_default != NULL)
489                 {
490                         CookedConstraint *cooked;
491
492                         cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
493                         cooked->contype = CONSTR_DEFAULT;
494                         cooked->name = NULL;
495                         cooked->attnum = attnum;
496                         cooked->expr = stringToNode(colDef->cooked_default);
497                         cooked->is_local = true;        /* not used for defaults */
498                         cooked->inhcount = 0;           /* ditto */
499                         cookedDefaults = lappend(cookedDefaults, cooked);
500                         descriptor->attrs[attnum - 1]->atthasdef = true;
501                 }
502         }
503
504         /*
505          * Create the relation.  Inherited defaults and constraints are passed in
506          * for immediate handling --- since they don't need parsing, they can be
507          * stored immediately.
508          */
509         relationId = heap_create_with_catalog(relname,
510                                                                                   namespaceId,
511                                                                                   tablespaceId,
512                                                                                   InvalidOid,
513                                                                                   GetUserId(),
514                                                                                   descriptor,
515                                                                                   list_concat(cookedDefaults,
516                                                                                                           old_constraints),
517                                                                                   relkind,
518                                                                                   false,
519                                                                                   localHasOids,
520                                                                                   parentOidCount,
521                                                                                   stmt->oncommit,
522                                                                                   reloptions,
523                                                                                   allowSystemTableMods);
524
525         StoreCatalogInheritance(relationId, inheritOids);
526
527         /*
528          * We must bump the command counter to make the newly-created relation
529          * tuple visible for opening.
530          */
531         CommandCounterIncrement();
532
533         /*
534          * Open the new relation and acquire exclusive lock on it.      This isn't
535          * really necessary for locking out other backends (since they can't see
536          * the new rel anyway until we commit), but it keeps the lock manager from
537          * complaining about deadlock risks.
538          */
539         rel = relation_open(relationId, AccessExclusiveLock);
540
541         /*
542          * Now add any newly specified column default values and CHECK constraints
543          * to the new relation.  These are passed to us in the form of raw
544          * parsetrees; we need to transform them to executable expression trees
545          * before they can be added. The most convenient way to do that is to
546          * apply the parser's transformExpr routine, but transformExpr doesn't
547          * work unless we have a pre-existing relation. So, the transformation has
548          * to be postponed to this final step of CREATE TABLE.
549          */
550         if (rawDefaults || stmt->constraints)
551                 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
552                                                                   true, true);
553
554         /*
555          * Clean up.  We keep lock on new relation (although it shouldn't be
556          * visible to anyone else anyway, until commit).
557          */
558         relation_close(rel, NoLock);
559
560         return relationId;
561 }
562
563 /*
564  * Emit the right error or warning message for a "DROP" command issued on a
565  * non-existent relation
566  */
567 static void
568 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
569 {
570         const struct dropmsgstrings *rentry;
571
572         for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
573         {
574                 if (rentry->kind == rightkind)
575                 {
576                         if (!missing_ok)
577                         {
578                                 ereport(ERROR,
579                                                 (errcode(rentry->nonexistent_code),
580                                                  errmsg(rentry->nonexistent_msg, relname)));
581                         }
582                         else
583                         {
584                                 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
585                                 break;
586                         }
587                 }
588         }
589
590         Assert(rentry->kind != '\0');           /* Should be impossible */
591 }
592
593 /*
594  * Emit the right error message for a "DROP" command issued on a
595  * relation of the wrong type
596  */
597 static void
598 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
599 {
600         const struct dropmsgstrings *rentry;
601         const struct dropmsgstrings *wentry;
602
603         for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
604                 if (rentry->kind == rightkind)
605                         break;
606         Assert(rentry->kind != '\0');
607
608         for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
609                 if (wentry->kind == wrongkind)
610                         break;
611         /* wrongkind could be something we don't have in our table... */
612
613         ereport(ERROR,
614                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
615                          errmsg(rentry->nota_msg, relname),
616            (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
617 }
618
619 /*
620  * RemoveRelations
621  *              Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW
622  */
623 void
624 RemoveRelations(DropStmt *drop)
625 {
626         ObjectAddresses *objects;
627         char            relkind;
628         ListCell   *cell;
629
630         /*
631          * First we identify all the relations, then we delete them in a single
632          * performMultipleDeletions() call.  This is to avoid unwanted DROP
633          * RESTRICT errors if one of the relations depends on another.
634          */
635
636         /* Determine required relkind */
637         switch (drop->removeType)
638         {
639                 case OBJECT_TABLE:
640                         relkind = RELKIND_RELATION;
641                         break;
642
643                 case OBJECT_INDEX:
644                         relkind = RELKIND_INDEX;
645                         break;
646
647                 case OBJECT_SEQUENCE:
648                         relkind = RELKIND_SEQUENCE;
649                         break;
650
651                 case OBJECT_VIEW:
652                         relkind = RELKIND_VIEW;
653                         break;
654
655                 default:
656                         elog(ERROR, "unrecognized drop object type: %d",
657                                  (int) drop->removeType);
658                         relkind = 0;            /* keep compiler quiet */
659                         break;
660         }
661
662         /* Lock and validate each relation; build a list of object addresses */
663         objects = new_object_addresses();
664
665         foreach(cell, drop->objects)
666         {
667                 RangeVar   *rel = makeRangeVarFromNameList((List *) lfirst(cell));
668                 Oid                     relOid;
669                 HeapTuple       tuple;
670                 Form_pg_class classform;
671                 ObjectAddress obj;
672
673                 /*
674                  * These next few steps are a great deal like relation_openrv, but we
675                  * don't bother building a relcache entry since we don't need it.
676                  *
677                  * Check for shared-cache-inval messages before trying to access the
678                  * relation.  This is needed to cover the case where the name
679                  * identifies a rel that has been dropped and recreated since the
680                  * start of our transaction: if we don't flush the old syscache entry,
681                  * then we'll latch onto that entry and suffer an error later.
682                  */
683                 AcceptInvalidationMessages();
684
685                 /* Look up the appropriate relation using namespace search */
686                 relOid = RangeVarGetRelid(rel, true);
687
688                 /* Not there? */
689                 if (!OidIsValid(relOid))
690                 {
691                         DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
692                         continue;
693                 }
694
695                 /*
696                  * In DROP INDEX, attempt to acquire lock on the parent table before
697                  * locking the index.  index_drop() will need this anyway, and since
698                  * regular queries lock tables before their indexes, we risk deadlock
699                  * if we do it the other way around.  No error if we don't find a
700                  * pg_index entry, though --- that most likely means it isn't an
701                  * index, and we'll fail below.
702                  */
703                 if (relkind == RELKIND_INDEX)
704                 {
705                         tuple = SearchSysCache(INDEXRELID,
706                                                                    ObjectIdGetDatum(relOid),
707                                                                    0, 0, 0);
708                         if (HeapTupleIsValid(tuple))
709                         {
710                                 Form_pg_index index = (Form_pg_index) GETSTRUCT(tuple);
711
712                                 LockRelationOid(index->indrelid, AccessExclusiveLock);
713                                 ReleaseSysCache(tuple);
714                         }
715                 }
716
717                 /* Get the lock before trying to fetch the syscache entry */
718                 LockRelationOid(relOid, AccessExclusiveLock);
719
720                 tuple = SearchSysCache(RELOID,
721                                                            ObjectIdGetDatum(relOid),
722                                                            0, 0, 0);
723                 if (!HeapTupleIsValid(tuple))
724                         elog(ERROR, "cache lookup failed for relation %u", relOid);
725                 classform = (Form_pg_class) GETSTRUCT(tuple);
726
727                 if (classform->relkind != relkind)
728                         DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
729
730                 /* Allow DROP to either table owner or schema owner */
731                 if (!pg_class_ownercheck(relOid, GetUserId()) &&
732                         !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
733                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
734                                                    rel->relname);
735
736                 if (!allowSystemTableMods && IsSystemClass(classform))
737                         ereport(ERROR,
738                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
739                                          errmsg("permission denied: \"%s\" is a system catalog",
740                                                         rel->relname)));
741
742                 /* OK, we're ready to delete this one */
743                 obj.classId = RelationRelationId;
744                 obj.objectId = relOid;
745                 obj.objectSubId = 0;
746
747                 add_exact_object_address(&obj, objects);
748
749                 ReleaseSysCache(tuple);
750         }
751
752         performMultipleDeletions(objects, drop->behavior);
753
754         free_object_addresses(objects);
755 }
756
757 /*
758  * ExecuteTruncate
759  *              Executes a TRUNCATE command.
760  *
761  * This is a multi-relation truncate.  We first open and grab exclusive
762  * lock on all relations involved, checking permissions and otherwise
763  * verifying that the relation is OK for truncation.  In CASCADE mode,
764  * relations having FK references to the targeted relations are automatically
765  * added to the group; in RESTRICT mode, we check that all FK references are
766  * internal to the group that's being truncated.  Finally all the relations
767  * are truncated and reindexed.
768  */
769 void
770 ExecuteTruncate(TruncateStmt *stmt)
771 {
772         List       *rels = NIL;
773         List       *relids = NIL;
774         List       *seq_relids = NIL;
775         EState     *estate;
776         ResultRelInfo *resultRelInfos;
777         ResultRelInfo *resultRelInfo;
778         ListCell   *cell;
779
780         /*
781          * Open, exclusive-lock, and check all the explicitly-specified relations
782          */
783         foreach(cell, stmt->relations)
784         {
785                 RangeVar   *rv = lfirst(cell);
786                 Relation        rel;
787                 bool            recurse = interpretInhOption(rv->inhOpt);
788                 Oid                     myrelid;
789
790                 rel = heap_openrv(rv, AccessExclusiveLock);
791                 myrelid = RelationGetRelid(rel);
792                 /* don't throw error for "TRUNCATE foo, foo" */
793                 if (list_member_oid(relids, myrelid))
794                 {
795                         heap_close(rel, AccessExclusiveLock);
796                         continue;
797                 }
798                 truncate_check_rel(rel);
799                 rels = lappend(rels, rel);
800                 relids = lappend_oid(relids, myrelid);
801
802                 if (recurse)
803                 {
804                         ListCell   *child;
805                         List       *children;
806
807                         children = find_all_inheritors(myrelid, AccessExclusiveLock);
808
809                         foreach(child, children)
810                         {
811                                 Oid                     childrelid = lfirst_oid(child);
812
813                                 if (list_member_oid(relids, childrelid))
814                                         continue;
815
816                                 /* find_all_inheritors already got lock */
817                                 rel = heap_open(childrelid, NoLock);
818                                 truncate_check_rel(rel);
819                                 rels = lappend(rels, rel);
820                                 relids = lappend_oid(relids, childrelid);
821                         }
822                 }
823         }
824
825         /*
826          * In CASCADE mode, suck in all referencing relations as well.  This
827          * requires multiple iterations to find indirectly-dependent relations. At
828          * each phase, we need to exclusive-lock new rels before looking for their
829          * dependencies, else we might miss something.  Also, we check each rel as
830          * soon as we open it, to avoid a faux pas such as holding lock for a long
831          * time on a rel we have no permissions for.
832          */
833         if (stmt->behavior == DROP_CASCADE)
834         {
835                 for (;;)
836                 {
837                         List       *newrelids;
838
839                         newrelids = heap_truncate_find_FKs(relids);
840                         if (newrelids == NIL)
841                                 break;                  /* nothing else to add */
842
843                         foreach(cell, newrelids)
844                         {
845                                 Oid                     relid = lfirst_oid(cell);
846                                 Relation        rel;
847
848                                 rel = heap_open(relid, AccessExclusiveLock);
849                                 ereport(NOTICE,
850                                                 (errmsg("truncate cascades to table \"%s\"",
851                                                                 RelationGetRelationName(rel))));
852                                 truncate_check_rel(rel);
853                                 rels = lappend(rels, rel);
854                                 relids = lappend_oid(relids, relid);
855                         }
856                 }
857         }
858
859         /*
860          * Check foreign key references.  In CASCADE mode, this should be
861          * unnecessary since we just pulled in all the references; but as a
862          * cross-check, do it anyway if in an Assert-enabled build.
863          */
864 #ifdef USE_ASSERT_CHECKING
865         heap_truncate_check_FKs(rels, false);
866 #else
867         if (stmt->behavior == DROP_RESTRICT)
868                 heap_truncate_check_FKs(rels, false);
869 #endif
870
871         /*
872          * If we are asked to restart sequences, find all the sequences, lock them
873          * (we only need AccessShareLock because that's all that ALTER SEQUENCE
874          * takes), and check permissions.  We want to do this early since it's
875          * pointless to do all the truncation work only to fail on sequence
876          * permissions.
877          */
878         if (stmt->restart_seqs)
879         {
880                 foreach(cell, rels)
881                 {
882                         Relation        rel = (Relation) lfirst(cell);
883                         List       *seqlist = getOwnedSequences(RelationGetRelid(rel));
884                         ListCell   *seqcell;
885
886                         foreach(seqcell, seqlist)
887                         {
888                                 Oid                     seq_relid = lfirst_oid(seqcell);
889                                 Relation        seq_rel;
890
891                                 seq_rel = relation_open(seq_relid, AccessShareLock);
892
893                                 /* This check must match AlterSequence! */
894                                 if (!pg_class_ownercheck(seq_relid, GetUserId()))
895                                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
896                                                                    RelationGetRelationName(seq_rel));
897
898                                 seq_relids = lappend_oid(seq_relids, seq_relid);
899
900                                 relation_close(seq_rel, NoLock);
901                         }
902                 }
903         }
904
905         /* Prepare to catch AFTER triggers. */
906         AfterTriggerBeginQuery();
907
908         /*
909          * To fire triggers, we'll need an EState as well as a ResultRelInfo for
910          * each relation.
911          */
912         estate = CreateExecutorState();
913         resultRelInfos = (ResultRelInfo *)
914                 palloc(list_length(rels) * sizeof(ResultRelInfo));
915         resultRelInfo = resultRelInfos;
916         foreach(cell, rels)
917         {
918                 Relation        rel = (Relation) lfirst(cell);
919
920                 InitResultRelInfo(resultRelInfo,
921                                                   rel,
922                                                   0,    /* dummy rangetable index */
923                                                   CMD_DELETE,   /* don't need any index info */
924                                                   false);
925                 resultRelInfo++;
926         }
927         estate->es_result_relations = resultRelInfos;
928         estate->es_num_result_relations = list_length(rels);
929
930         /*
931          * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
932          * truncating (this is because one of them might throw an error). Also, if
933          * we were to allow them to prevent statement execution, that would need
934          * to be handled here.
935          */
936         resultRelInfo = resultRelInfos;
937         foreach(cell, rels)
938         {
939                 estate->es_result_relation_info = resultRelInfo;
940                 ExecBSTruncateTriggers(estate, resultRelInfo);
941                 resultRelInfo++;
942         }
943
944         /*
945          * OK, truncate each table.
946          */
947         foreach(cell, rels)
948         {
949                 Relation        rel = (Relation) lfirst(cell);
950                 Oid                     heap_relid;
951                 Oid                     toast_relid;
952
953                 /*
954                  * Create a new empty storage file for the relation, and assign it as
955                  * the relfilenode value.       The old storage file is scheduled for
956                  * deletion at commit.
957                  */
958                 setNewRelfilenode(rel, RecentXmin);
959
960                 heap_relid = RelationGetRelid(rel);
961                 toast_relid = rel->rd_rel->reltoastrelid;
962
963                 /*
964                  * The same for the toast table, if any.
965                  */
966                 if (OidIsValid(toast_relid))
967                 {
968                         rel = relation_open(toast_relid, AccessExclusiveLock);
969                         setNewRelfilenode(rel, RecentXmin);
970                         heap_close(rel, NoLock);
971                 }
972
973                 /*
974                  * Reconstruct the indexes to match, and we're done.
975                  */
976                 reindex_relation(heap_relid, true);
977         }
978
979         /*
980          * Process all AFTER STATEMENT TRUNCATE triggers.
981          */
982         resultRelInfo = resultRelInfos;
983         foreach(cell, rels)
984         {
985                 estate->es_result_relation_info = resultRelInfo;
986                 ExecASTruncateTriggers(estate, resultRelInfo);
987                 resultRelInfo++;
988         }
989
990         /* Handle queued AFTER triggers */
991         AfterTriggerEndQuery(estate);
992
993         /* We can clean up the EState now */
994         FreeExecutorState(estate);
995
996         /* And close the rels (can't do this while EState still holds refs) */
997         foreach(cell, rels)
998         {
999                 Relation        rel = (Relation) lfirst(cell);
1000
1001                 heap_close(rel, NoLock);
1002         }
1003
1004         /*
1005          * Lastly, restart any owned sequences if we were asked to.  This is done
1006          * last because it's nontransactional: restarts will not roll back if we
1007          * abort later.  Hence it's important to postpone them as long as
1008          * possible.  (This is also a big reason why we locked and
1009          * permission-checked the sequences beforehand.)
1010          */
1011         if (stmt->restart_seqs)
1012         {
1013                 List       *options = list_make1(makeDefElem("restart", NULL));
1014
1015                 foreach(cell, seq_relids)
1016                 {
1017                         Oid                     seq_relid = lfirst_oid(cell);
1018
1019                         AlterSequenceInternal(seq_relid, options);
1020                 }
1021         }
1022 }
1023
1024 /*
1025  * Check that a given rel is safe to truncate.  Subroutine for ExecuteTruncate
1026  */
1027 static void
1028 truncate_check_rel(Relation rel)
1029 {
1030         AclResult       aclresult;
1031
1032         /* Only allow truncate on regular tables */
1033         if (rel->rd_rel->relkind != RELKIND_RELATION)
1034                 ereport(ERROR,
1035                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1036                                  errmsg("\"%s\" is not a table",
1037                                                 RelationGetRelationName(rel))));
1038
1039         /* Permissions checks */
1040         aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1041                                                                   ACL_TRUNCATE);
1042         if (aclresult != ACLCHECK_OK)
1043                 aclcheck_error(aclresult, ACL_KIND_CLASS,
1044                                            RelationGetRelationName(rel));
1045
1046         if (!allowSystemTableMods && IsSystemRelation(rel))
1047                 ereport(ERROR,
1048                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1049                                  errmsg("permission denied: \"%s\" is a system catalog",
1050                                                 RelationGetRelationName(rel))));
1051
1052         /*
1053          * We can never allow truncation of shared or nailed-in-cache relations,
1054          * because we can't support changing their relfilenode values.
1055          */
1056         if (rel->rd_rel->relisshared || rel->rd_isnailed)
1057                 ereport(ERROR,
1058                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1059                                  errmsg("cannot truncate system relation \"%s\"",
1060                                                 RelationGetRelationName(rel))));
1061
1062         /*
1063          * Don't allow truncate on temp tables of other backends ... their local
1064          * buffer manager is not going to cope.
1065          */
1066         if (RELATION_IS_OTHER_TEMP(rel))
1067                 ereport(ERROR,
1068                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1069                           errmsg("cannot truncate temporary tables of other sessions")));
1070
1071         /*
1072          * Also check for active uses of the relation in the current transaction,
1073          * including open scans and pending AFTER trigger events.
1074          */
1075         CheckTableNotInUse(rel, "TRUNCATE");
1076 }
1077
1078 /*----------
1079  * MergeAttributes
1080  *              Returns new schema given initial schema and superclasses.
1081  *
1082  * Input arguments:
1083  * 'schema' is the column/attribute definition for the table. (It's a list
1084  *              of ColumnDef's.) It is destructively changed.
1085  * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1086  * 'istemp' is TRUE if we are creating a temp relation.
1087  *
1088  * Output arguments:
1089  * 'supOids' receives a list of the OIDs of the parent relations.
1090  * 'supconstr' receives a list of constraints belonging to the parents,
1091  *              updated as necessary to be valid for the child.
1092  * 'supOidCount' is set to the number of parents that have OID columns.
1093  *
1094  * Return value:
1095  * Completed schema list.
1096  *
1097  * Notes:
1098  *        The order in which the attributes are inherited is very important.
1099  *        Intuitively, the inherited attributes should come first. If a table
1100  *        inherits from multiple parents, the order of those attributes are
1101  *        according to the order of the parents specified in CREATE TABLE.
1102  *
1103  *        Here's an example:
1104  *
1105  *              create table person (name text, age int4, location point);
1106  *              create table emp (salary int4, manager text) inherits(person);
1107  *              create table student (gpa float8) inherits (person);
1108  *              create table stud_emp (percent int4) inherits (emp, student);
1109  *
1110  *        The order of the attributes of stud_emp is:
1111  *
1112  *                                                      person {1:name, 2:age, 3:location}
1113  *                                                      /        \
1114  *                         {6:gpa}      student   emp {4:salary, 5:manager}
1115  *                                                      \        /
1116  *                                                 stud_emp {7:percent}
1117  *
1118  *         If the same attribute name appears multiple times, then it appears
1119  *         in the result table in the proper location for its first appearance.
1120  *
1121  *         Constraints (including NOT NULL constraints) for the child table
1122  *         are the union of all relevant constraints, from both the child schema
1123  *         and parent tables.
1124  *
1125  *         The default value for a child column is defined as:
1126  *              (1) If the child schema specifies a default, that value is used.
1127  *              (2) If neither the child nor any parent specifies a default, then
1128  *                      the column will not have a default.
1129  *              (3) If conflicting defaults are inherited from different parents
1130  *                      (and not overridden by the child), an error is raised.
1131  *              (4) Otherwise the inherited default is used.
1132  *              Rule (3) is new in Postgres 7.1; in earlier releases you got a
1133  *              rather arbitrary choice of which parent default to use.
1134  *----------
1135  */
1136 static List *
1137 MergeAttributes(List *schema, List *supers, bool istemp,
1138                                 List **supOids, List **supconstr, int *supOidCount)
1139 {
1140         ListCell   *entry;
1141         List       *inhSchema = NIL;
1142         List       *parentOids = NIL;
1143         List       *constraints = NIL;
1144         int                     parentsWithOids = 0;
1145         bool            have_bogus_defaults = false;
1146         char       *bogus_marker = "Bogus!";            /* marks conflicting defaults */
1147         int                     child_attno;
1148
1149         /*
1150          * Check for and reject tables with too many columns. We perform this
1151          * check relatively early for two reasons: (a) we don't run the risk of
1152          * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1153          * okay if we're processing <= 1600 columns, but could take minutes to
1154          * execute if the user attempts to create a table with hundreds of
1155          * thousands of columns.
1156          *
1157          * Note that we also need to check that any we do not exceed this figure
1158          * after including columns from inherited relations.
1159          */
1160         if (list_length(schema) > MaxHeapAttributeNumber)
1161                 ereport(ERROR,
1162                                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1163                                  errmsg("tables can have at most %d columns",
1164                                                 MaxHeapAttributeNumber)));
1165
1166         /*
1167          * Check for duplicate names in the explicit list of attributes.
1168          *
1169          * Although we might consider merging such entries in the same way that we
1170          * handle name conflicts for inherited attributes, it seems to make more
1171          * sense to assume such conflicts are errors.
1172          */
1173         foreach(entry, schema)
1174         {
1175                 ColumnDef  *coldef = lfirst(entry);
1176                 ListCell   *rest;
1177
1178                 for_each_cell(rest, lnext(entry))
1179                 {
1180                         ColumnDef  *restdef = lfirst(rest);
1181
1182                         if (strcmp(coldef->colname, restdef->colname) == 0)
1183                                 ereport(ERROR,
1184                                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
1185                                                  errmsg("column \"%s\" specified more than once",
1186                                                                 coldef->colname)));
1187                 }
1188         }
1189
1190         /*
1191          * Scan the parents left-to-right, and merge their attributes to form a
1192          * list of inherited attributes (inhSchema).  Also check to see if we need
1193          * to inherit an OID column.
1194          */
1195         child_attno = 0;
1196         foreach(entry, supers)
1197         {
1198                 RangeVar   *parent = (RangeVar *) lfirst(entry);
1199                 Relation        relation;
1200                 TupleDesc       tupleDesc;
1201                 TupleConstr *constr;
1202                 AttrNumber *newattno;
1203                 AttrNumber      parent_attno;
1204
1205                 relation = heap_openrv(parent, AccessShareLock);
1206
1207                 if (relation->rd_rel->relkind != RELKIND_RELATION)
1208                         ereport(ERROR,
1209                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1210                                          errmsg("inherited relation \"%s\" is not a table",
1211                                                         parent->relname)));
1212                 /* Permanent rels cannot inherit from temporary ones */
1213                 if (!istemp && relation->rd_istemp)
1214                         ereport(ERROR,
1215                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1216                                          errmsg("cannot inherit from temporary relation \"%s\"",
1217                                                         parent->relname)));
1218
1219                 /*
1220                  * We should have an UNDER permission flag for this, but for now,
1221                  * demand that creator of a child table own the parent.
1222                  */
1223                 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1224                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1225                                                    RelationGetRelationName(relation));
1226
1227                 /*
1228                  * Reject duplications in the list of parents.
1229                  */
1230                 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1231                         ereport(ERROR,
1232                                         (errcode(ERRCODE_DUPLICATE_TABLE),
1233                          errmsg("relation \"%s\" would be inherited from more than once",
1234                                         parent->relname)));
1235
1236                 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1237
1238                 if (relation->rd_rel->relhasoids)
1239                         parentsWithOids++;
1240
1241                 tupleDesc = RelationGetDescr(relation);
1242                 constr = tupleDesc->constr;
1243
1244                 /*
1245                  * newattno[] will contain the child-table attribute numbers for the
1246                  * attributes of this parent table.  (They are not the same for
1247                  * parents after the first one, nor if we have dropped columns.)
1248                  */
1249                 newattno = (AttrNumber *)
1250                         palloc(tupleDesc->natts * sizeof(AttrNumber));
1251
1252                 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1253                          parent_attno++)
1254                 {
1255                         Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1256                         char       *attributeName = NameStr(attribute->attname);
1257                         int                     exist_attno;
1258                         ColumnDef  *def;
1259
1260                         /*
1261                          * Ignore dropped columns in the parent.
1262                          */
1263                         if (attribute->attisdropped)
1264                         {
1265                                 /*
1266                                  * change_varattnos_of_a_node asserts that this is greater
1267                                  * than zero, so if anything tries to use it, we should find
1268                                  * out.
1269                                  */
1270                                 newattno[parent_attno - 1] = 0;
1271                                 continue;
1272                         }
1273
1274                         /*
1275                          * Does it conflict with some previously inherited column?
1276                          */
1277                         exist_attno = findAttrByName(attributeName, inhSchema);
1278                         if (exist_attno > 0)
1279                         {
1280                                 Oid                     defTypeId;
1281                                 int32           deftypmod;
1282
1283                                 /*
1284                                  * Yes, try to merge the two column definitions. They must
1285                                  * have the same type and typmod.
1286                                  */
1287                                 ereport(NOTICE,
1288                                                 (errmsg("merging multiple inherited definitions of column \"%s\"",
1289                                                                 attributeName)));
1290                                 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1291                                 defTypeId = typenameTypeId(NULL, def->typeName, &deftypmod);
1292                                 if (defTypeId != attribute->atttypid ||
1293                                         deftypmod != attribute->atttypmod)
1294                                         ereport(ERROR,
1295                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1296                                                 errmsg("inherited column \"%s\" has a type conflict",
1297                                                            attributeName),
1298                                                          errdetail("%s versus %s",
1299                                                                            TypeNameToString(def->typeName),
1300                                                                            format_type_be(attribute->atttypid))));
1301                                 def->inhcount++;
1302                                 /* Merge of NOT NULL constraints = OR 'em together */
1303                                 def->is_not_null |= attribute->attnotnull;
1304                                 /* Default and other constraints are handled below */
1305                                 newattno[parent_attno - 1] = exist_attno;
1306                         }
1307                         else
1308                         {
1309                                 /*
1310                                  * No, create a new inherited column
1311                                  */
1312                                 def = makeNode(ColumnDef);
1313                                 def->colname = pstrdup(attributeName);
1314                                 def->typeName = makeTypeNameFromOid(attribute->atttypid,
1315                                                                                                         attribute->atttypmod);
1316                                 def->inhcount = 1;
1317                                 def->is_local = false;
1318                                 def->is_not_null = attribute->attnotnull;
1319                                 def->raw_default = NULL;
1320                                 def->cooked_default = NULL;
1321                                 def->constraints = NIL;
1322                                 inhSchema = lappend(inhSchema, def);
1323                                 newattno[parent_attno - 1] = ++child_attno;
1324                         }
1325
1326                         /*
1327                          * Copy default if any
1328                          */
1329                         if (attribute->atthasdef)
1330                         {
1331                                 char       *this_default = NULL;
1332                                 AttrDefault *attrdef;
1333                                 int                     i;
1334
1335                                 /* Find default in constraint structure */
1336                                 Assert(constr != NULL);
1337                                 attrdef = constr->defval;
1338                                 for (i = 0; i < constr->num_defval; i++)
1339                                 {
1340                                         if (attrdef[i].adnum == parent_attno)
1341                                         {
1342                                                 this_default = attrdef[i].adbin;
1343                                                 break;
1344                                         }
1345                                 }
1346                                 Assert(this_default != NULL);
1347
1348                                 /*
1349                                  * If default expr could contain any vars, we'd need to fix
1350                                  * 'em, but it can't; so default is ready to apply to child.
1351                                  *
1352                                  * If we already had a default from some prior parent, check
1353                                  * to see if they are the same.  If so, no problem; if not,
1354                                  * mark the column as having a bogus default. Below, we will
1355                                  * complain if the bogus default isn't overridden by the child
1356                                  * schema.
1357                                  */
1358                                 Assert(def->raw_default == NULL);
1359                                 if (def->cooked_default == NULL)
1360                                         def->cooked_default = pstrdup(this_default);
1361                                 else if (strcmp(def->cooked_default, this_default) != 0)
1362                                 {
1363                                         def->cooked_default = bogus_marker;
1364                                         have_bogus_defaults = true;
1365                                 }
1366                         }
1367                 }
1368
1369                 /*
1370                  * Now copy the CHECK constraints of this parent, adjusting attnos
1371                  * using the completed newattno[] map.  Identically named constraints
1372                  * are merged if possible, else we throw error.
1373                  */
1374                 if (constr && constr->num_check > 0)
1375                 {
1376                         ConstrCheck *check = constr->check;
1377                         int                     i;
1378
1379                         for (i = 0; i < constr->num_check; i++)
1380                         {
1381                                 char       *name = check[i].ccname;
1382                                 Node       *expr;
1383
1384                                 /* adjust varattnos of ccbin here */
1385                                 expr = stringToNode(check[i].ccbin);
1386                                 change_varattnos_of_a_node(expr, newattno);
1387
1388                                 /* check for duplicate */
1389                                 if (!MergeCheckConstraint(constraints, name, expr))
1390                                 {
1391                                         /* nope, this is a new one */
1392                                         CookedConstraint *cooked;
1393
1394                                         cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1395                                         cooked->contype = CONSTR_CHECK;
1396                                         cooked->name = pstrdup(name);
1397                                         cooked->attnum = 0; /* not used for constraints */
1398                                         cooked->expr = expr;
1399                                         cooked->is_local = false;
1400                                         cooked->inhcount = 1;
1401                                         constraints = lappend(constraints, cooked);
1402                                 }
1403                         }
1404                 }
1405
1406                 pfree(newattno);
1407
1408                 /*
1409                  * Close the parent rel, but keep our AccessShareLock on it until xact
1410                  * commit.      That will prevent someone else from deleting or ALTERing
1411                  * the parent before the child is committed.
1412                  */
1413                 heap_close(relation, NoLock);
1414         }
1415
1416         /*
1417          * If we had no inherited attributes, the result schema is just the
1418          * explicitly declared columns.  Otherwise, we need to merge the declared
1419          * columns into the inherited schema list.
1420          */
1421         if (inhSchema != NIL)
1422         {
1423                 foreach(entry, schema)
1424                 {
1425                         ColumnDef  *newdef = lfirst(entry);
1426                         char       *attributeName = newdef->colname;
1427                         int                     exist_attno;
1428
1429                         /*
1430                          * Does it conflict with some previously inherited column?
1431                          */
1432                         exist_attno = findAttrByName(attributeName, inhSchema);
1433                         if (exist_attno > 0)
1434                         {
1435                                 ColumnDef  *def;
1436                                 Oid                     defTypeId,
1437                                                         newTypeId;
1438                                 int32           deftypmod,
1439                                                         newtypmod;
1440
1441                                 /*
1442                                  * Yes, try to merge the two column definitions. They must
1443                                  * have the same type and typmod.
1444                                  */
1445                                 ereport(NOTICE,
1446                                    (errmsg("merging column \"%s\" with inherited definition",
1447                                                    attributeName)));
1448                                 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1449                                 defTypeId = typenameTypeId(NULL, def->typeName, &deftypmod);
1450                                 newTypeId = typenameTypeId(NULL, newdef->typeName, &newtypmod);
1451                                 if (defTypeId != newTypeId || deftypmod != newtypmod)
1452                                         ereport(ERROR,
1453                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1454                                                          errmsg("column \"%s\" has a type conflict",
1455                                                                         attributeName),
1456                                                          errdetail("%s versus %s",
1457                                                                            TypeNameToString(def->typeName),
1458                                                                            TypeNameToString(newdef->typeName))));
1459                                 /* Mark the column as locally defined */
1460                                 def->is_local = true;
1461                                 /* Merge of NOT NULL constraints = OR 'em together */
1462                                 def->is_not_null |= newdef->is_not_null;
1463                                 /* If new def has a default, override previous default */
1464                                 if (newdef->raw_default != NULL)
1465                                 {
1466                                         def->raw_default = newdef->raw_default;
1467                                         def->cooked_default = newdef->cooked_default;
1468                                 }
1469                         }
1470                         else
1471                         {
1472                                 /*
1473                                  * No, attach new column to result schema
1474                                  */
1475                                 inhSchema = lappend(inhSchema, newdef);
1476                         }
1477                 }
1478
1479                 schema = inhSchema;
1480
1481                 /*
1482                  * Check that we haven't exceeded the legal # of columns after merging
1483                  * in inherited columns.
1484                  */
1485                 if (list_length(schema) > MaxHeapAttributeNumber)
1486                         ereport(ERROR,
1487                                         (errcode(ERRCODE_TOO_MANY_COLUMNS),
1488                                          errmsg("tables can have at most %d columns",
1489                                                         MaxHeapAttributeNumber)));
1490         }
1491
1492         /*
1493          * If we found any conflicting parent default values, check to make sure
1494          * they were overridden by the child.
1495          */
1496         if (have_bogus_defaults)
1497         {
1498                 foreach(entry, schema)
1499                 {
1500                         ColumnDef  *def = lfirst(entry);
1501
1502                         if (def->cooked_default == bogus_marker)
1503                                 ereport(ERROR,
1504                                                 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1505                                   errmsg("column \"%s\" inherits conflicting default values",
1506                                                  def->colname),
1507                                                  errhint("To resolve the conflict, specify a default explicitly.")));
1508                 }
1509         }
1510
1511         *supOids = parentOids;
1512         *supconstr = constraints;
1513         *supOidCount = parentsWithOids;
1514         return schema;
1515 }
1516
1517
1518 /*
1519  * MergeCheckConstraint
1520  *              Try to merge an inherited CHECK constraint with previous ones
1521  *
1522  * If we inherit identically-named constraints from multiple parents, we must
1523  * merge them, or throw an error if they don't have identical definitions.
1524  *
1525  * constraints is a list of CookedConstraint structs for previous constraints.
1526  *
1527  * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1528  * got a so-far-unique name, or throws error if conflict.
1529  */
1530 static bool
1531 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1532 {
1533         ListCell   *lc;
1534
1535         foreach(lc, constraints)
1536         {
1537                 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1538
1539                 Assert(ccon->contype == CONSTR_CHECK);
1540
1541                 /* Non-matching names never conflict */
1542                 if (strcmp(ccon->name, name) != 0)
1543                         continue;
1544
1545                 if (equal(expr, ccon->expr))
1546                 {
1547                         /* OK to merge */
1548                         ccon->inhcount++;
1549                         return true;
1550                 }
1551
1552                 ereport(ERROR,
1553                                 (errcode(ERRCODE_DUPLICATE_OBJECT),
1554                                  errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1555                                                 name)));
1556         }
1557
1558         return false;
1559 }
1560
1561
1562 /*
1563  * Replace varattno values in an expression tree according to the given
1564  * map array, that is, varattno N is replaced by newattno[N-1].  It is
1565  * caller's responsibility to ensure that the array is long enough to
1566  * define values for all user varattnos present in the tree.  System column
1567  * attnos remain unchanged.
1568  *
1569  * Note that the passed node tree is modified in-place!
1570  */
1571 void
1572 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1573 {
1574         /* no setup needed, so away we go */
1575         (void) change_varattnos_walker(node, newattno);
1576 }
1577
1578 static bool
1579 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1580 {
1581         if (node == NULL)
1582                 return false;
1583         if (IsA(node, Var))
1584         {
1585                 Var                *var = (Var *) node;
1586
1587                 if (var->varlevelsup == 0 && var->varno == 1 &&
1588                         var->varattno > 0)
1589                 {
1590                         /*
1591                          * ??? the following may be a problem when the node is multiply
1592                          * referenced though stringToNode() doesn't create such a node
1593                          * currently.
1594                          */
1595                         Assert(newattno[var->varattno - 1] > 0);
1596                         var->varattno = var->varoattno = newattno[var->varattno - 1];
1597                 }
1598                 return false;
1599         }
1600         return expression_tree_walker(node, change_varattnos_walker,
1601                                                                   (void *) newattno);
1602 }
1603
1604 /*
1605  * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1606  * matching according to column name.
1607  */
1608 AttrNumber *
1609 varattnos_map(TupleDesc olddesc, TupleDesc newdesc)
1610 {
1611         AttrNumber *attmap;
1612         int                     i,
1613                                 j;
1614
1615         attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * olddesc->natts);
1616         for (i = 1; i <= olddesc->natts; i++)
1617         {
1618                 if (olddesc->attrs[i - 1]->attisdropped)
1619                         continue;                       /* leave the entry as zero */
1620
1621                 for (j = 1; j <= newdesc->natts; j++)
1622                 {
1623                         if (strcmp(NameStr(olddesc->attrs[i - 1]->attname),
1624                                            NameStr(newdesc->attrs[j - 1]->attname)) == 0)
1625                         {
1626                                 attmap[i - 1] = j;
1627                                 break;
1628                         }
1629                 }
1630         }
1631         return attmap;
1632 }
1633
1634 /*
1635  * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1636  * of ColumnDefs
1637  */
1638 AttrNumber *
1639 varattnos_map_schema(TupleDesc old, List *schema)
1640 {
1641         AttrNumber *attmap;
1642         int                     i;
1643
1644         attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1645         for (i = 1; i <= old->natts; i++)
1646         {
1647                 if (old->attrs[i - 1]->attisdropped)
1648                         continue;                       /* leave the entry as zero */
1649
1650                 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1651                                                                            schema);
1652         }
1653         return attmap;
1654 }
1655
1656
1657 /*
1658  * StoreCatalogInheritance
1659  *              Updates the system catalogs with proper inheritance information.
1660  *
1661  * supers is a list of the OIDs of the new relation's direct ancestors.
1662  */
1663 static void
1664 StoreCatalogInheritance(Oid relationId, List *supers)
1665 {
1666         Relation        relation;
1667         int16           seqNumber;
1668         ListCell   *entry;
1669
1670         /*
1671          * sanity checks
1672          */
1673         AssertArg(OidIsValid(relationId));
1674
1675         if (supers == NIL)
1676                 return;
1677
1678         /*
1679          * Store INHERITS information in pg_inherits using direct ancestors only.
1680          * Also enter dependencies on the direct ancestors, and make sure they are
1681          * marked with relhassubclass = true.
1682          *
1683          * (Once upon a time, both direct and indirect ancestors were found here
1684          * and then entered into pg_ipl.  Since that catalog doesn't exist
1685          * anymore, there's no need to look for indirect ancestors.)
1686          */
1687         relation = heap_open(InheritsRelationId, RowExclusiveLock);
1688
1689         seqNumber = 1;
1690         foreach(entry, supers)
1691         {
1692                 Oid                     parentOid = lfirst_oid(entry);
1693
1694                 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1695                 seqNumber++;
1696         }
1697
1698         heap_close(relation, RowExclusiveLock);
1699 }
1700
1701 /*
1702  * Make catalog entries showing relationId as being an inheritance child
1703  * of parentOid.  inhRelation is the already-opened pg_inherits catalog.
1704  */
1705 static void
1706 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1707                                                  int16 seqNumber, Relation inhRelation)
1708 {
1709         TupleDesc       desc = RelationGetDescr(inhRelation);
1710         Datum           datum[Natts_pg_inherits];
1711         bool            nullarr[Natts_pg_inherits];
1712         ObjectAddress childobject,
1713                                 parentobject;
1714         HeapTuple       tuple;
1715
1716         /*
1717          * Make the pg_inherits entry
1718          */
1719         datum[0] = ObjectIdGetDatum(relationId);        /* inhrelid */
1720         datum[1] = ObjectIdGetDatum(parentOid);         /* inhparent */
1721         datum[2] = Int16GetDatum(seqNumber);            /* inhseqno */
1722
1723         nullarr[0] = false;
1724         nullarr[1] = false;
1725         nullarr[2] = false;
1726
1727         tuple = heap_form_tuple(desc, datum, nullarr);
1728
1729         simple_heap_insert(inhRelation, tuple);
1730
1731         CatalogUpdateIndexes(inhRelation, tuple);
1732
1733         heap_freetuple(tuple);
1734
1735         /*
1736          * Store a dependency too
1737          */
1738         parentobject.classId = RelationRelationId;
1739         parentobject.objectId = parentOid;
1740         parentobject.objectSubId = 0;
1741         childobject.classId = RelationRelationId;
1742         childobject.objectId = relationId;
1743         childobject.objectSubId = 0;
1744
1745         recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1746
1747         /*
1748          * Mark the parent as having subclasses.
1749          */
1750         setRelhassubclassInRelation(parentOid, true);
1751 }
1752
1753 /*
1754  * Look for an existing schema entry with the given name.
1755  *
1756  * Returns the index (starting with 1) if attribute already exists in schema,
1757  * 0 if it doesn't.
1758  */
1759 static int
1760 findAttrByName(const char *attributeName, List *schema)
1761 {
1762         ListCell   *s;
1763         int                     i = 1;
1764
1765         foreach(s, schema)
1766         {
1767                 ColumnDef  *def = lfirst(s);
1768
1769                 if (strcmp(attributeName, def->colname) == 0)
1770                         return i;
1771
1772                 i++;
1773         }
1774         return 0;
1775 }
1776
1777 /*
1778  * Update a relation's pg_class.relhassubclass entry to the given value
1779  */
1780 static void
1781 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1782 {
1783         Relation        relationRelation;
1784         HeapTuple       tuple;
1785         Form_pg_class classtuple;
1786
1787         /*
1788          * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1789          *
1790          * If the tuple already has the right relhassubclass setting, we don't
1791          * need to update it, but we still need to issue an SI inval message.
1792          */
1793         relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1794         tuple = SearchSysCacheCopy(RELOID,
1795                                                            ObjectIdGetDatum(relationId),
1796                                                            0, 0, 0);
1797         if (!HeapTupleIsValid(tuple))
1798                 elog(ERROR, "cache lookup failed for relation %u", relationId);
1799         classtuple = (Form_pg_class) GETSTRUCT(tuple);
1800
1801         if (classtuple->relhassubclass != relhassubclass)
1802         {
1803                 classtuple->relhassubclass = relhassubclass;
1804                 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1805
1806                 /* keep the catalog indexes up to date */
1807                 CatalogUpdateIndexes(relationRelation, tuple);
1808         }
1809         else
1810         {
1811                 /* no need to change tuple, but force relcache rebuild anyway */
1812                 CacheInvalidateRelcacheByTuple(tuple);
1813         }
1814
1815         heap_freetuple(tuple);
1816         heap_close(relationRelation, RowExclusiveLock);
1817 }
1818
1819
1820 /*
1821  *              renameatt               - changes the name of a attribute in a relation
1822  *
1823  *              Attname attribute is changed in attribute catalog.
1824  *              No record of the previous attname is kept (correct?).
1825  *
1826  *              get proper relrelation from relation catalog (if not arg)
1827  *              scan attribute catalog
1828  *                              for name conflict (within rel)
1829  *                              for original attribute (if not arg)
1830  *              modify attname in attribute tuple
1831  *              insert modified attribute in attribute catalog
1832  *              delete original attribute from attribute catalog
1833  */
1834 void
1835 renameatt(Oid myrelid,
1836                   const char *oldattname,
1837                   const char *newattname,
1838                   bool recurse,
1839                   bool recursing)
1840 {
1841         Relation        targetrelation;
1842         Relation        attrelation;
1843         HeapTuple       atttup;
1844         Form_pg_attribute attform;
1845         int                     attnum;
1846         List       *indexoidlist;
1847         ListCell   *indexoidscan;
1848
1849         /*
1850          * Grab an exclusive lock on the target table, which we will NOT release
1851          * until end of transaction.
1852          */
1853         targetrelation = relation_open(myrelid, AccessExclusiveLock);
1854
1855         /*
1856          * permissions checking.  this would normally be done in utility.c, but
1857          * this particular routine is recursive.
1858          *
1859          * normally, only the owner of a class can change its schema.
1860          */
1861         if (!pg_class_ownercheck(myrelid, GetUserId()))
1862                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1863                                            RelationGetRelationName(targetrelation));
1864         if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1865                 ereport(ERROR,
1866                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1867                                  errmsg("permission denied: \"%s\" is a system catalog",
1868                                                 RelationGetRelationName(targetrelation))));
1869
1870         /*
1871          * if the 'recurse' flag is set then we are supposed to rename this
1872          * attribute in all classes that inherit from 'relname' (as well as in
1873          * 'relname').
1874          *
1875          * any permissions or problems with duplicate attributes will cause the
1876          * whole transaction to abort, which is what we want -- all or nothing.
1877          */
1878         if (recurse)
1879         {
1880                 ListCell   *child;
1881                 List       *children;
1882
1883                 children = find_all_inheritors(myrelid, AccessExclusiveLock);
1884
1885                 /*
1886                  * find_all_inheritors does the recursive search of the inheritance
1887                  * hierarchy, so all we have to do is process all of the relids in the
1888                  * list that it returns.
1889                  */
1890                 foreach(child, children)
1891                 {
1892                         Oid                     childrelid = lfirst_oid(child);
1893
1894                         if (childrelid == myrelid)
1895                                 continue;
1896                         /* note we need not recurse again */
1897                         renameatt(childrelid, oldattname, newattname, false, true);
1898                 }
1899         }
1900         else
1901         {
1902                 /*
1903                  * If we are told not to recurse, there had better not be any child
1904                  * tables; else the rename would put them out of step.
1905                  */
1906                 if (!recursing &&
1907                         find_inheritance_children(myrelid, NoLock) != NIL)
1908                         ereport(ERROR,
1909                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1910                                          errmsg("inherited column \"%s\" must be renamed in child tables too",
1911                                                         oldattname)));
1912         }
1913
1914         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1915
1916         atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1917         if (!HeapTupleIsValid(atttup))
1918                 ereport(ERROR,
1919                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1920                                  errmsg("column \"%s\" does not exist",
1921                                                 oldattname)));
1922         attform = (Form_pg_attribute) GETSTRUCT(atttup);
1923
1924         attnum = attform->attnum;
1925         if (attnum <= 0)
1926                 ereport(ERROR,
1927                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1928                                  errmsg("cannot rename system column \"%s\"",
1929                                                 oldattname)));
1930
1931         /*
1932          * if the attribute is inherited, forbid the renaming, unless we are
1933          * already inside a recursive rename.
1934          */
1935         if (attform->attinhcount > 0 && !recursing)
1936                 ereport(ERROR,
1937                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1938                                  errmsg("cannot rename inherited column \"%s\"",
1939                                                 oldattname)));
1940
1941         /* should not already exist */
1942         /* this test is deliberately not attisdropped-aware */
1943         if (SearchSysCacheExists(ATTNAME,
1944                                                          ObjectIdGetDatum(myrelid),
1945                                                          PointerGetDatum(newattname),
1946                                                          0, 0))
1947                 ereport(ERROR,
1948                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
1949                                  errmsg("column \"%s\" of relation \"%s\" already exists",
1950                                           newattname, RelationGetRelationName(targetrelation))));
1951
1952         namestrcpy(&(attform->attname), newattname);
1953
1954         simple_heap_update(attrelation, &atttup->t_self, atttup);
1955
1956         /* keep system catalog indexes current */
1957         CatalogUpdateIndexes(attrelation, atttup);
1958
1959         heap_freetuple(atttup);
1960
1961         /*
1962          * Update column names of indexes that refer to the column being renamed.
1963          */
1964         indexoidlist = RelationGetIndexList(targetrelation);
1965
1966         foreach(indexoidscan, indexoidlist)
1967         {
1968                 Oid                     indexoid = lfirst_oid(indexoidscan);
1969                 HeapTuple       indextup;
1970                 Form_pg_index indexform;
1971                 int                     i;
1972
1973                 /*
1974                  * Scan through index columns to see if there's any simple index
1975                  * entries for this attribute.  We ignore expressional entries.
1976                  */
1977                 indextup = SearchSysCache(INDEXRELID,
1978                                                                   ObjectIdGetDatum(indexoid),
1979                                                                   0, 0, 0);
1980                 if (!HeapTupleIsValid(indextup))
1981                         elog(ERROR, "cache lookup failed for index %u", indexoid);
1982                 indexform = (Form_pg_index) GETSTRUCT(indextup);
1983
1984                 for (i = 0; i < indexform->indnatts; i++)
1985                 {
1986                         if (attnum != indexform->indkey.values[i])
1987                                 continue;
1988
1989                         /*
1990                          * Found one, rename it.
1991                          */
1992                         atttup = SearchSysCacheCopy(ATTNUM,
1993                                                                                 ObjectIdGetDatum(indexoid),
1994                                                                                 Int16GetDatum(i + 1),
1995                                                                                 0, 0);
1996                         if (!HeapTupleIsValid(atttup))
1997                                 continue;               /* should we raise an error? */
1998
1999                         /*
2000                          * Update the (copied) attribute tuple.
2001                          */
2002                         namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
2003                                            newattname);
2004
2005                         simple_heap_update(attrelation, &atttup->t_self, atttup);
2006
2007                         /* keep system catalog indexes current */
2008                         CatalogUpdateIndexes(attrelation, atttup);
2009
2010                         heap_freetuple(atttup);
2011                 }
2012
2013                 ReleaseSysCache(indextup);
2014         }
2015
2016         list_free(indexoidlist);
2017
2018         heap_close(attrelation, RowExclusiveLock);
2019
2020         relation_close(targetrelation, NoLock);         /* close rel but keep lock */
2021 }
2022
2023
2024 /*
2025  * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
2026  *
2027  * Caller has already done permissions checks.
2028  */
2029 void
2030 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
2031 {
2032         Relation        targetrelation;
2033         Oid                     namespaceId;
2034         char            relkind;
2035
2036         /*
2037          * Grab an exclusive lock on the target table, index, sequence or view,
2038          * which we will NOT release until end of transaction.
2039          */
2040         targetrelation = relation_open(myrelid, AccessExclusiveLock);
2041
2042         namespaceId = RelationGetNamespace(targetrelation);
2043         relkind = targetrelation->rd_rel->relkind;
2044
2045         /*
2046          * For compatibility with prior releases, we don't complain if ALTER TABLE
2047          * or ALTER INDEX is used to rename a sequence or view.
2048          */
2049         if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
2050                 ereport(ERROR,
2051                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2052                                  errmsg("\"%s\" is not a sequence",
2053                                                 RelationGetRelationName(targetrelation))));
2054
2055         if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
2056                 ereport(ERROR,
2057                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2058                                  errmsg("\"%s\" is not a view",
2059                                                 RelationGetRelationName(targetrelation))));
2060
2061         /*
2062          * Don't allow ALTER TABLE on composite types. We want people to use ALTER
2063          * TYPE for that.
2064          */
2065         if (relkind == RELKIND_COMPOSITE_TYPE)
2066                 ereport(ERROR,
2067                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2068                                  errmsg("\"%s\" is a composite type",
2069                                                 RelationGetRelationName(targetrelation)),
2070                                  errhint("Use ALTER TYPE instead.")));
2071
2072         /* Do the work */
2073         RenameRelationInternal(myrelid, newrelname, namespaceId);
2074
2075         /*
2076          * Close rel, but keep exclusive lock!
2077          */
2078         relation_close(targetrelation, NoLock);
2079 }
2080
2081 /*
2082  *              RenameRelationInternal - change the name of a relation
2083  *
2084  *              XXX - When renaming sequences, we don't bother to modify the
2085  *                        sequence name that is stored within the sequence itself
2086  *                        (this would cause problems with MVCC). In the future,
2087  *                        the sequence name should probably be removed from the
2088  *                        sequence, AFAIK there's no need for it to be there.
2089  */
2090 void
2091 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
2092 {
2093         Relation        targetrelation;
2094         Relation        relrelation;    /* for RELATION relation */
2095         HeapTuple       reltup;
2096         Form_pg_class relform;
2097
2098         /*
2099          * Grab an exclusive lock on the target table, index, sequence or view,
2100          * which we will NOT release until end of transaction.
2101          */
2102         targetrelation = relation_open(myrelid, AccessExclusiveLock);
2103
2104         /*
2105          * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2106          */
2107         relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2108
2109         reltup = SearchSysCacheCopy(RELOID,
2110                                                                 ObjectIdGetDatum(myrelid),
2111                                                                 0, 0, 0);
2112         if (!HeapTupleIsValid(reltup))          /* shouldn't happen */
2113                 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2114         relform = (Form_pg_class) GETSTRUCT(reltup);
2115
2116         if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2117                 ereport(ERROR,
2118                                 (errcode(ERRCODE_DUPLICATE_TABLE),
2119                                  errmsg("relation \"%s\" already exists",
2120                                                 newrelname)));
2121
2122         /*
2123          * Update pg_class tuple with new relname.      (Scribbling on reltup is OK
2124          * because it's a copy...)
2125          */
2126         namestrcpy(&(relform->relname), newrelname);
2127
2128         simple_heap_update(relrelation, &reltup->t_self, reltup);
2129
2130         /* keep the system catalog indexes current */
2131         CatalogUpdateIndexes(relrelation, reltup);
2132
2133         heap_freetuple(reltup);
2134         heap_close(relrelation, RowExclusiveLock);
2135
2136         /*
2137          * Also rename the associated type, if any.
2138          */
2139         if (OidIsValid(targetrelation->rd_rel->reltype))
2140                 RenameTypeInternal(targetrelation->rd_rel->reltype,
2141                                                    newrelname, namespaceId);
2142
2143         /*
2144          * Also rename the associated constraint, if any.
2145          */
2146         if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2147         {
2148                 Oid                     constraintId = get_index_constraint(myrelid);
2149
2150                 if (OidIsValid(constraintId))
2151                         RenameConstraintById(constraintId, newrelname);
2152         }
2153
2154         /*
2155          * Close rel, but keep exclusive lock!
2156          */
2157         relation_close(targetrelation, NoLock);
2158 }
2159
2160 /*
2161  * Disallow ALTER TABLE (and similar commands) when the current backend has
2162  * any open reference to the target table besides the one just acquired by
2163  * the calling command; this implies there's an open cursor or active plan.
2164  * We need this check because our AccessExclusiveLock doesn't protect us
2165  * against stomping on our own foot, only other people's feet!
2166  *
2167  * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2168  * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2169  * possibly be relaxed to only error out for certain types of alterations.
2170  * But the use-case for allowing any of these things is not obvious, so we
2171  * won't work hard at it for now.
2172  *
2173  * We also reject these commands if there are any pending AFTER trigger events
2174  * for the rel.  This is certainly necessary for the rewriting variants of
2175  * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2176  * events would try to fetch the wrong tuples.  It might be overly cautious
2177  * in other cases, but again it seems better to err on the side of paranoia.
2178  *
2179  * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2180  * we are worried about active indexscans on the index.  The trigger-event
2181  * check can be skipped, since we are doing no damage to the parent table.
2182  *
2183  * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2184  */
2185 void
2186 CheckTableNotInUse(Relation rel, const char *stmt)
2187 {
2188         int                     expected_refcnt;
2189
2190         expected_refcnt = rel->rd_isnailed ? 2 : 1;
2191         if (rel->rd_refcnt != expected_refcnt)
2192                 ereport(ERROR,
2193                                 (errcode(ERRCODE_OBJECT_IN_USE),
2194                 /* translator: first %s is a SQL command, eg ALTER TABLE */
2195                                  errmsg("cannot %s \"%s\" because "
2196                                                 "it is being used by active queries in this session",
2197                                                 stmt, RelationGetRelationName(rel))));
2198
2199         if (rel->rd_rel->relkind != RELKIND_INDEX &&
2200                 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2201                 ereport(ERROR,
2202                                 (errcode(ERRCODE_OBJECT_IN_USE),
2203                 /* translator: first %s is a SQL command, eg ALTER TABLE */
2204                                  errmsg("cannot %s \"%s\" because "
2205                                                 "it has pending trigger events",
2206                                                 stmt, RelationGetRelationName(rel))));
2207 }
2208
2209 /*
2210  * AlterTable
2211  *              Execute ALTER TABLE, which can be a list of subcommands
2212  *
2213  * ALTER TABLE is performed in three phases:
2214  *              1. Examine subcommands and perform pre-transformation checking.
2215  *              2. Update system catalogs.
2216  *              3. Scan table(s) to check new constraints, and optionally recopy
2217  *                 the data into new table(s).
2218  * Phase 3 is not performed unless one or more of the subcommands requires
2219  * it.  The intention of this design is to allow multiple independent
2220  * updates of the table schema to be performed with only one pass over the
2221  * data.
2222  *
2223  * ATPrepCmd performs phase 1.  A "work queue" entry is created for
2224  * each table to be affected (there may be multiple affected tables if the
2225  * commands traverse a table inheritance hierarchy).  Also we do preliminary
2226  * validation of the subcommands, including parse transformation of those
2227  * expressions that need to be evaluated with respect to the old table
2228  * schema.
2229  *
2230  * ATRewriteCatalogs performs phase 2 for each affected table.  (Note that
2231  * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2232  * did it --- although some subcommands have to recurse in phase 2 instead.)
2233  * Certain subcommands need to be performed before others to avoid
2234  * unnecessary conflicts; for example, DROP COLUMN should come before
2235  * ADD COLUMN.  Therefore phase 1 divides the subcommands into multiple
2236  * lists, one for each logical "pass" of phase 2.
2237  *
2238  * ATRewriteTables performs phase 3 for those tables that need it.
2239  *
2240  * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2241  * the whole operation; we don't have to do anything special to clean up.
2242  */
2243 void
2244 AlterTable(AlterTableStmt *stmt)
2245 {
2246         Relation        rel = relation_openrv(stmt->relation, AccessExclusiveLock);
2247
2248         CheckTableNotInUse(rel, "ALTER TABLE");
2249
2250         /* Check relation type against type specified in the ALTER command */
2251         switch (stmt->relkind)
2252         {
2253                 case OBJECT_TABLE:
2254
2255                         /*
2256                          * For mostly-historical reasons, we allow ALTER TABLE to apply to
2257                          * all relation types.
2258                          */
2259                         break;
2260
2261                 case OBJECT_INDEX:
2262                         if (rel->rd_rel->relkind != RELKIND_INDEX)
2263                                 ereport(ERROR,
2264                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2265                                                  errmsg("\"%s\" is not an index",
2266                                                                 RelationGetRelationName(rel))));
2267                         break;
2268
2269                 case OBJECT_SEQUENCE:
2270                         if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2271                                 ereport(ERROR,
2272                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2273                                                  errmsg("\"%s\" is not a sequence",
2274                                                                 RelationGetRelationName(rel))));
2275                         break;
2276
2277                 case OBJECT_VIEW:
2278                         if (rel->rd_rel->relkind != RELKIND_VIEW)
2279                                 ereport(ERROR,
2280                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2281                                                  errmsg("\"%s\" is not a view",
2282                                                                 RelationGetRelationName(rel))));
2283                         break;
2284
2285                 default:
2286                         elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2287         }
2288
2289         ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
2290 }
2291
2292 /*
2293  * AlterTableInternal
2294  *
2295  * ALTER TABLE with target specified by OID
2296  *
2297  * We do not reject if the relation is already open, because it's quite
2298  * likely that one or more layers of caller have it open.  That means it
2299  * is unsafe to use this entry point for alterations that could break
2300  * existing query plans.  On the assumption it's not used for such, we
2301  * don't have to reject pending AFTER triggers, either.
2302  */
2303 void
2304 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2305 {
2306         Relation        rel = relation_open(relid, AccessExclusiveLock);
2307
2308         ATController(rel, cmds, recurse);
2309 }
2310
2311 static void
2312 ATController(Relation rel, List *cmds, bool recurse)
2313 {
2314         List       *wqueue = NIL;
2315         ListCell   *lcmd;
2316
2317         /* Phase 1: preliminary examination of commands, create work queue */
2318         foreach(lcmd, cmds)
2319         {
2320                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2321
2322                 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
2323         }
2324
2325         /* Close the relation, but keep lock until commit */
2326         relation_close(rel, NoLock);
2327
2328         /* Phase 2: update system catalogs */
2329         ATRewriteCatalogs(&wqueue);
2330
2331         /* Phase 3: scan/rewrite tables as needed */
2332         ATRewriteTables(&wqueue);
2333 }
2334
2335 /*
2336  * ATPrepCmd
2337  *
2338  * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2339  * recursion and permission checks.
2340  *
2341  * Caller must have acquired AccessExclusiveLock on relation already.
2342  * This lock should be held until commit.
2343  */
2344 static void
2345 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2346                   bool recurse, bool recursing)
2347 {
2348         AlteredTableInfo *tab;
2349         int                     pass;
2350
2351         /* Find or create work queue entry for this table */
2352         tab = ATGetQueueEntry(wqueue, rel);
2353
2354         /*
2355          * Copy the original subcommand for each table.  This avoids conflicts
2356          * when different child tables need to make different parse
2357          * transformations (for example, the same column may have different column
2358          * numbers in different children).
2359          */
2360         cmd = copyObject(cmd);
2361
2362         /*
2363          * Do permissions checking, recursion to child tables if needed, and any
2364          * additional phase-1 processing needed.
2365          */
2366         switch (cmd->subtype)
2367         {
2368                 case AT_AddColumn:              /* ADD COLUMN */
2369                         ATSimplePermissions(rel, false);
2370                         /* Performs own recursion */
2371                         ATPrepAddColumn(wqueue, rel, recurse, cmd);
2372                         pass = AT_PASS_ADD_COL;
2373                         break;
2374                 case AT_AddColumnToView:                /* add column via CREATE OR REPLACE
2375                                                                                  * VIEW */
2376                         ATSimplePermissions(rel, true);
2377                         /* Performs own recursion */
2378                         ATPrepAddColumn(wqueue, rel, recurse, cmd);
2379                         pass = AT_PASS_ADD_COL;
2380                         break;
2381                 case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
2382
2383                         /*
2384                          * We allow defaults on views so that INSERT into a view can have
2385                          * default-ish behavior.  This works because the rewriter
2386                          * substitutes default values into INSERTs before it expands
2387                          * rules.
2388                          */
2389                         ATSimplePermissions(rel, true);
2390                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2391                         /* No command-specific prep needed */
2392                         pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2393                         break;
2394                 case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
2395                         ATSimplePermissions(rel, false);
2396                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2397                         /* No command-specific prep needed */
2398                         pass = AT_PASS_DROP;
2399                         break;
2400                 case AT_SetNotNull:             /* ALTER COLUMN SET NOT NULL */
2401                         ATSimplePermissions(rel, false);
2402                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2403                         /* No command-specific prep needed */
2404                         pass = AT_PASS_ADD_CONSTR;
2405                         break;
2406                 case AT_SetStatistics:  /* ALTER COLUMN SET STATISTICS */
2407                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2408                         /* Performs own permission checks */
2409                         ATPrepSetStatistics(rel, cmd->name, cmd->def);
2410                         pass = AT_PASS_COL_ATTRS;
2411                         break;
2412                 case AT_SetDistinct:    /* ALTER COLUMN SET STATISTICS DISTINCT */
2413                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2414                         /* Performs own permission checks */
2415                         ATPrepSetDistinct(rel, cmd->name, cmd->def);
2416                         pass = AT_PASS_COL_ATTRS;
2417                         break;
2418                 case AT_SetStorage:             /* ALTER COLUMN SET STORAGE */
2419                         ATSimplePermissions(rel, false);
2420                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2421                         /* No command-specific prep needed */
2422                         pass = AT_PASS_COL_ATTRS;
2423                         break;
2424                 case AT_DropColumn:             /* DROP COLUMN */
2425                         ATSimplePermissions(rel, false);
2426                         /* Recursion occurs during execution phase */
2427                         /* No command-specific prep needed except saving recurse flag */
2428                         if (recurse)
2429                                 cmd->subtype = AT_DropColumnRecurse;
2430                         pass = AT_PASS_DROP;
2431                         break;
2432                 case AT_AddIndex:               /* ADD INDEX */
2433                         ATSimplePermissions(rel, false);
2434                         /* This command never recurses */
2435                         /* No command-specific prep needed */
2436                         pass = AT_PASS_ADD_INDEX;
2437                         break;
2438                 case AT_AddConstraint:  /* ADD CONSTRAINT */
2439                         ATSimplePermissions(rel, false);
2440                         /* Recursion occurs during execution phase */
2441                         /* No command-specific prep needed except saving recurse flag */
2442                         if (recurse)
2443                                 cmd->subtype = AT_AddConstraintRecurse;
2444                         pass = AT_PASS_ADD_CONSTR;
2445                         break;
2446                 case AT_DropConstraint: /* DROP CONSTRAINT */
2447                         ATSimplePermissions(rel, false);
2448                         /* Recursion occurs during execution phase */
2449                         /* No command-specific prep needed except saving recurse flag */
2450                         if (recurse)
2451                                 cmd->subtype = AT_DropConstraintRecurse;
2452                         pass = AT_PASS_DROP;
2453                         break;
2454                 case AT_AlterColumnType:                /* ALTER COLUMN TYPE */
2455                         ATSimplePermissions(rel, false);
2456                         /* Performs own recursion */
2457                         ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2458                         pass = AT_PASS_ALTER_TYPE;
2459                         break;
2460                 case AT_ChangeOwner:    /* ALTER OWNER */
2461                         /* This command never recurses */
2462                         /* No command-specific prep needed */
2463                         pass = AT_PASS_MISC;
2464                         break;
2465                 case AT_ClusterOn:              /* CLUSTER ON */
2466                 case AT_DropCluster:    /* SET WITHOUT CLUSTER */
2467                         ATSimplePermissions(rel, false);
2468                         /* These commands never recurse */
2469                         /* No command-specific prep needed */
2470                         pass = AT_PASS_MISC;
2471                         break;
2472                 case AT_AddOids:                /* SET WITH OIDS */
2473                         ATSimplePermissions(rel, false);
2474                         /* Performs own recursion */
2475                         if (!rel->rd_rel->relhasoids || recursing)
2476                                 ATPrepAddOids(wqueue, rel, recurse, cmd);
2477                         pass = AT_PASS_ADD_COL;
2478                         break;
2479                 case AT_DropOids:               /* SET WITHOUT OIDS */
2480                         ATSimplePermissions(rel, false);
2481                         /* Performs own recursion */
2482                         if (rel->rd_rel->relhasoids)
2483                         {
2484                                 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2485
2486                                 dropCmd->subtype = AT_DropColumn;
2487                                 dropCmd->name = pstrdup("oid");
2488                                 dropCmd->behavior = cmd->behavior;
2489                                 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2490                         }
2491                         pass = AT_PASS_DROP;
2492                         break;
2493                 case AT_SetTableSpace:  /* SET TABLESPACE */
2494                         ATSimplePermissionsRelationOrIndex(rel);
2495                         /* This command never recurses */
2496                         ATPrepSetTableSpace(tab, rel, cmd->name);
2497                         pass = AT_PASS_MISC;    /* doesn't actually matter */
2498                         break;
2499                 case AT_SetRelOptions:  /* SET (...) */
2500                 case AT_ResetRelOptions:                /* RESET (...) */
2501                         ATSimplePermissionsRelationOrIndex(rel);
2502                         /* This command never recurses */
2503                         /* No command-specific prep needed */
2504                         pass = AT_PASS_MISC;
2505                         break;
2506                 case AT_EnableTrig:             /* ENABLE TRIGGER variants */
2507                 case AT_EnableAlwaysTrig:
2508                 case AT_EnableReplicaTrig:
2509                 case AT_EnableTrigAll:
2510                 case AT_EnableTrigUser:
2511                 case AT_DisableTrig:    /* DISABLE TRIGGER variants */
2512                 case AT_DisableTrigAll:
2513                 case AT_DisableTrigUser:
2514                 case AT_EnableRule:             /* ENABLE/DISABLE RULE variants */
2515                 case AT_EnableAlwaysRule:
2516                 case AT_EnableReplicaRule:
2517                 case AT_DisableRule:
2518                 case AT_AddInherit:             /* INHERIT / NO INHERIT */
2519                 case AT_DropInherit:
2520                         ATSimplePermissions(rel, false);
2521                         /* These commands never recurse */
2522                         /* No command-specific prep needed */
2523                         pass = AT_PASS_MISC;
2524                         break;
2525                 default:                                /* oops */
2526                         elog(ERROR, "unrecognized alter table type: %d",
2527                                  (int) cmd->subtype);
2528                         pass = 0;                       /* keep compiler quiet */
2529                         break;
2530         }
2531
2532         /* Add the subcommand to the appropriate list for phase 2 */
2533         tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2534 }
2535
2536 /*
2537  * ATRewriteCatalogs
2538  *
2539  * Traffic cop for ALTER TABLE Phase 2 operations.      Subcommands are
2540  * dispatched in a "safe" execution order (designed to avoid unnecessary
2541  * conflicts).
2542  */
2543 static void
2544 ATRewriteCatalogs(List **wqueue)
2545 {
2546         int                     pass;
2547         ListCell   *ltab;
2548
2549         /*
2550          * We process all the tables "in parallel", one pass at a time.  This is
2551          * needed because we may have to propagate work from one table to another
2552          * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2553          * re-adding of the foreign key constraint to the other table).  Work can
2554          * only be propagated into later passes, however.
2555          */
2556         for (pass = 0; pass < AT_NUM_PASSES; pass++)
2557         {
2558                 /* Go through each table that needs to be processed */
2559                 foreach(ltab, *wqueue)
2560                 {
2561                         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2562                         List       *subcmds = tab->subcmds[pass];
2563                         Relation        rel;
2564                         ListCell   *lcmd;
2565
2566                         if (subcmds == NIL)
2567                                 continue;
2568
2569                         /*
2570                          * Exclusive lock was obtained by phase 1, needn't get it again
2571                          */
2572                         rel = relation_open(tab->relid, NoLock);
2573
2574                         foreach(lcmd, subcmds)
2575                                 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd));
2576
2577                         /*
2578                          * After the ALTER TYPE pass, do cleanup work (this is not done in
2579                          * ATExecAlterColumnType since it should be done only once if
2580                          * multiple columns of a table are altered).
2581                          */
2582                         if (pass == AT_PASS_ALTER_TYPE)
2583                                 ATPostAlterTypeCleanup(wqueue, tab);
2584
2585                         relation_close(rel, NoLock);
2586                 }
2587         }
2588
2589         /*
2590          * Check to see if a toast table must be added, if we executed any
2591          * subcommands that might have added a column or changed column storage.
2592          */
2593         foreach(ltab, *wqueue)
2594         {
2595                 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2596
2597                 if (tab->relkind == RELKIND_RELATION &&
2598                         (tab->subcmds[AT_PASS_ADD_COL] ||
2599                          tab->subcmds[AT_PASS_ALTER_TYPE] ||
2600                          tab->subcmds[AT_PASS_COL_ATTRS]))
2601                         AlterTableCreateToastTable(tab->relid, InvalidOid,
2602                                                                            (Datum) 0, false);
2603         }
2604 }
2605
2606 /*
2607  * ATExecCmd: dispatch a subcommand to appropriate execution routine
2608  */
2609 static void
2610 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
2611                   AlterTableCmd *cmd)
2612 {
2613         switch (cmd->subtype)
2614         {
2615                 case AT_AddColumn:              /* ADD COLUMN */
2616                 case AT_AddColumnToView:                /* add column via CREATE OR REPLACE
2617                                                                                  * VIEW */
2618                         ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def, false);
2619                         break;
2620                 case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
2621                         ATExecColumnDefault(rel, cmd->name, cmd->def);
2622                         break;
2623                 case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
2624                         ATExecDropNotNull(rel, cmd->name);
2625                         break;
2626                 case AT_SetNotNull:             /* ALTER COLUMN SET NOT NULL */
2627                         ATExecSetNotNull(tab, rel, cmd->name);
2628                         break;
2629                 case AT_SetStatistics:  /* ALTER COLUMN SET STATISTICS */
2630                         ATExecSetStatistics(rel, cmd->name, cmd->def);
2631                         break;
2632                 case AT_SetDistinct:    /* ALTER COLUMN SET STATISTICS DISTINCT */
2633                         ATExecSetDistinct(rel, cmd->name, cmd->def);
2634                         break;
2635                 case AT_SetStorage:             /* ALTER COLUMN SET STORAGE */
2636                         ATExecSetStorage(rel, cmd->name, cmd->def);
2637                         break;
2638                 case AT_DropColumn:             /* DROP COLUMN */
2639                         ATExecDropColumn(wqueue, rel, cmd->name,
2640                                                          cmd->behavior, false, false, cmd->missing_ok);
2641                         break;
2642                 case AT_DropColumnRecurse:              /* DROP COLUMN with recursion */
2643                         ATExecDropColumn(wqueue, rel, cmd->name,
2644                                                          cmd->behavior, true, false, cmd->missing_ok);
2645                         break;
2646                 case AT_AddIndex:               /* ADD INDEX */
2647                         ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2648                         break;
2649                 case AT_ReAddIndex:             /* ADD INDEX */
2650                         ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2651                         break;
2652                 case AT_AddConstraint:  /* ADD CONSTRAINT */
2653                         ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
2654                                                                 false);
2655                         break;
2656                 case AT_AddConstraintRecurse:   /* ADD CONSTRAINT with recursion */
2657                         ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
2658                                                                 true);
2659                         break;
2660                 case AT_DropConstraint: /* DROP CONSTRAINT */
2661                         ATExecDropConstraint(rel, cmd->name, cmd->behavior,
2662                                                                  false, false,
2663                                                                  cmd->missing_ok);
2664                         break;
2665                 case AT_DropConstraintRecurse:  /* DROP CONSTRAINT with recursion */
2666                         ATExecDropConstraint(rel, cmd->name, cmd->behavior,
2667                                                                  true, false,
2668                                                                  cmd->missing_ok);
2669                         break;
2670                 case AT_AlterColumnType:                /* ALTER COLUMN TYPE */
2671                         ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2672                         break;
2673                 case AT_ChangeOwner:    /* ALTER OWNER */
2674                         ATExecChangeOwner(RelationGetRelid(rel),
2675                                                           get_roleid_checked(cmd->name),
2676                                                           false);
2677                         break;
2678                 case AT_ClusterOn:              /* CLUSTER ON */
2679                         ATExecClusterOn(rel, cmd->name);
2680                         break;
2681                 case AT_DropCluster:    /* SET WITHOUT CLUSTER */
2682                         ATExecDropCluster(rel);
2683                         break;
2684                 case AT_AddOids:                /* SET WITH OIDS */
2685                         /* Use the ADD COLUMN code, unless prep decided to do nothing */
2686                         if (cmd->def != NULL)
2687                                 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def, true);
2688                         break;
2689                 case AT_DropOids:               /* SET WITHOUT OIDS */
2690
2691                         /*
2692                          * Nothing to do here; we'll have generated a DropColumn
2693                          * subcommand to do the real work
2694                          */
2695                         break;
2696                 case AT_SetTableSpace:  /* SET TABLESPACE */
2697
2698                         /*
2699                          * Nothing to do here; Phase 3 does the work
2700                          */
2701                         break;
2702                 case AT_SetRelOptions:  /* SET (...) */
2703                         ATExecSetRelOptions(rel, (List *) cmd->def, false);
2704                         break;
2705                 case AT_ResetRelOptions:                /* RESET (...) */
2706                         ATExecSetRelOptions(rel, (List *) cmd->def, true);
2707                         break;
2708
2709                 case AT_EnableTrig:             /* ENABLE TRIGGER name */
2710                         ATExecEnableDisableTrigger(rel, cmd->name,
2711                                                                            TRIGGER_FIRES_ON_ORIGIN, false);
2712                         break;
2713                 case AT_EnableAlwaysTrig:               /* ENABLE ALWAYS TRIGGER name */
2714                         ATExecEnableDisableTrigger(rel, cmd->name,
2715                                                                            TRIGGER_FIRES_ALWAYS, false);
2716                         break;
2717                 case AT_EnableReplicaTrig:              /* ENABLE REPLICA TRIGGER name */
2718                         ATExecEnableDisableTrigger(rel, cmd->name,
2719                                                                            TRIGGER_FIRES_ON_REPLICA, false);
2720                         break;
2721                 case AT_DisableTrig:    /* DISABLE TRIGGER name */
2722                         ATExecEnableDisableTrigger(rel, cmd->name,
2723                                                                            TRIGGER_DISABLED, false);
2724                         break;
2725                 case AT_EnableTrigAll:  /* ENABLE TRIGGER ALL */
2726                         ATExecEnableDisableTrigger(rel, NULL,
2727                                                                            TRIGGER_FIRES_ON_ORIGIN, false);
2728                         break;
2729                 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2730                         ATExecEnableDisableTrigger(rel, NULL,
2731                                                                            TRIGGER_DISABLED, false);
2732                         break;
2733                 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2734                         ATExecEnableDisableTrigger(rel, NULL,
2735                                                                            TRIGGER_FIRES_ON_ORIGIN, true);
2736                         break;
2737                 case AT_DisableTrigUser:                /* DISABLE TRIGGER USER */
2738                         ATExecEnableDisableTrigger(rel, NULL,
2739                                                                            TRIGGER_DISABLED, true);
2740                         break;
2741
2742                 case AT_EnableRule:             /* ENABLE RULE name */
2743                         ATExecEnableDisableRule(rel, cmd->name,
2744                                                                         RULE_FIRES_ON_ORIGIN);
2745                         break;
2746                 case AT_EnableAlwaysRule:               /* ENABLE ALWAYS RULE name */
2747                         ATExecEnableDisableRule(rel, cmd->name,
2748                                                                         RULE_FIRES_ALWAYS);
2749                         break;
2750                 case AT_EnableReplicaRule:              /* ENABLE REPLICA RULE name */
2751                         ATExecEnableDisableRule(rel, cmd->name,
2752                                                                         RULE_FIRES_ON_REPLICA);
2753                         break;
2754                 case AT_DisableRule:    /* DISABLE RULE name */
2755                         ATExecEnableDisableRule(rel, cmd->name,
2756                                                                         RULE_DISABLED);
2757                         break;
2758
2759                 case AT_AddInherit:
2760                         ATExecAddInherit(rel, (RangeVar *) cmd->def);
2761                         break;
2762                 case AT_DropInherit:
2763                         ATExecDropInherit(rel, (RangeVar *) cmd->def);
2764                         break;
2765                 default:                                /* oops */
2766                         elog(ERROR, "unrecognized alter table type: %d",
2767                                  (int) cmd->subtype);
2768                         break;
2769         }
2770
2771         /*
2772          * Bump the command counter to ensure the next subcommand in the sequence
2773          * can see the changes so far
2774          */
2775         CommandCounterIncrement();
2776 }
2777
2778 /*
2779  * ATRewriteTables: ALTER TABLE phase 3
2780  */
2781 static void
2782 ATRewriteTables(List **wqueue)
2783 {
2784         ListCell   *ltab;
2785
2786         /* Go through each table that needs to be checked or rewritten */
2787         foreach(ltab, *wqueue)
2788         {
2789                 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2790
2791                 /*
2792                  * We only need to rewrite the table if at least one column needs to
2793                  * be recomputed, or we are adding/removing the OID column.
2794                  */
2795                 if (tab->newvals != NIL || tab->new_changeoids)
2796                 {
2797                         /* Build a temporary relation and copy data */
2798                         Oid                     OIDNewHeap;
2799                         char            NewHeapName[NAMEDATALEN];
2800                         Oid                     NewTableSpace;
2801                         Relation        OldHeap;
2802                         ObjectAddress object;
2803
2804                         OldHeap = heap_open(tab->relid, NoLock);
2805
2806                         /*
2807                          * We can never allow rewriting of shared or nailed-in-cache
2808                          * relations, because we can't support changing their relfilenode
2809                          * values.
2810                          */
2811                         if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2812                                 ereport(ERROR,
2813                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2814                                                  errmsg("cannot rewrite system relation \"%s\"",
2815                                                                 RelationGetRelationName(OldHeap))));
2816
2817                         /*
2818                          * Don't allow rewrite on temp tables of other backends ... their
2819                          * local buffer manager is not going to cope.
2820                          */
2821                         if (RELATION_IS_OTHER_TEMP(OldHeap))
2822                                 ereport(ERROR,
2823                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2824                                 errmsg("cannot rewrite temporary tables of other sessions")));
2825
2826                         /*
2827                          * Select destination tablespace (same as original unless user
2828                          * requested a change)
2829                          */
2830                         if (tab->newTableSpace)
2831                                 NewTableSpace = tab->newTableSpace;
2832                         else
2833                                 NewTableSpace = OldHeap->rd_rel->reltablespace;
2834
2835                         heap_close(OldHeap, NoLock);
2836
2837                         /*
2838                          * Create the new heap, using a temporary name in the same
2839                          * namespace as the existing table.  NOTE: there is some risk of
2840                          * collision with user relnames.  Working around this seems more
2841                          * trouble than it's worth; in particular, we can't create the new
2842                          * heap in a different namespace from the old, or we will have
2843                          * problems with the TEMP status of temp tables.
2844                          */
2845                         snprintf(NewHeapName, sizeof(NewHeapName),
2846                                          "pg_temp_%u", tab->relid);
2847
2848                         OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2849
2850                         /*
2851                          * Copy the heap data into the new table with the desired
2852                          * modifications, and test the current data within the table
2853                          * against new constraints generated by ALTER TABLE commands.
2854                          */
2855                         ATRewriteTable(tab, OIDNewHeap);
2856
2857                         /*
2858                          * Swap the physical files of the old and new heaps.  Since we are
2859                          * generating a new heap, we can use RecentXmin for the table's
2860                          * new relfrozenxid because we rewrote all the tuples on
2861                          * ATRewriteTable, so no older Xid remains on the table.
2862                          */
2863                         swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2864
2865                         CommandCounterIncrement();
2866
2867                         /* Destroy new heap with old filenode */
2868                         object.classId = RelationRelationId;
2869                         object.objectId = OIDNewHeap;
2870                         object.objectSubId = 0;
2871
2872                         /*
2873                          * The new relation is local to our transaction and we know
2874                          * nothing depends on it, so DROP_RESTRICT should be OK.
2875                          */
2876                         performDeletion(&object, DROP_RESTRICT);
2877                         /* performDeletion does CommandCounterIncrement at end */
2878
2879                         /*
2880                          * Rebuild each index on the relation (but not the toast table,
2881                          * which is all-new anyway).  We do not need
2882                          * CommandCounterIncrement() because reindex_relation does it.
2883                          */
2884                         reindex_relation(tab->relid, false);
2885                 }
2886                 else
2887                 {
2888                         /*
2889                          * Test the current data within the table against new constraints
2890                          * generated by ALTER TABLE commands, but don't rebuild data.
2891                          */
2892                         if (tab->constraints != NIL || tab->new_notnull)
2893                                 ATRewriteTable(tab, InvalidOid);
2894
2895                         /*
2896                          * If we had SET TABLESPACE but no reason to reconstruct tuples,
2897                          * just do a block-by-block copy.
2898                          */
2899                         if (tab->newTableSpace)
2900                                 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2901                 }
2902         }
2903
2904         /*
2905          * Foreign key constraints are checked in a final pass, since (a) it's
2906          * generally best to examine each one separately, and (b) it's at least
2907          * theoretically possible that we have changed both relations of the
2908          * foreign key, and we'd better have finished both rewrites before we try
2909          * to read the tables.
2910          */
2911         foreach(ltab, *wqueue)
2912         {
2913                 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2914                 Relation        rel = NULL;
2915                 ListCell   *lcon;
2916
2917                 foreach(lcon, tab->constraints)
2918                 {
2919                         NewConstraint *con = lfirst(lcon);
2920
2921                         if (con->contype == CONSTR_FOREIGN)
2922                         {
2923                                 Constraint *fkconstraint = (Constraint *) con->qual;
2924                                 Relation        refrel;
2925
2926                                 if (rel == NULL)
2927                                 {
2928                                         /* Long since locked, no need for another */
2929                                         rel = heap_open(tab->relid, NoLock);
2930                                 }
2931
2932                                 refrel = heap_open(con->refrelid, RowShareLock);
2933
2934                                 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2935                                                                                          con->refindid,
2936                                                                                          con->conid);
2937
2938                                 heap_close(refrel, NoLock);
2939                         }
2940                 }
2941
2942                 if (rel)
2943                         heap_close(rel, NoLock);
2944         }
2945 }
2946
2947 /*
2948  * ATRewriteTable: scan or rewrite one table
2949  *
2950  * OIDNewHeap is InvalidOid if we don't need to rewrite
2951  */
2952 static void
2953 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2954 {
2955         Relation        oldrel;
2956         Relation        newrel;
2957         TupleDesc       oldTupDesc;
2958         TupleDesc       newTupDesc;
2959         bool            needscan = false;
2960         List       *notnull_attrs;
2961         int                     i;
2962         ListCell   *l;
2963         EState     *estate;
2964
2965         /*
2966          * Open the relation(s).  We have surely already locked the existing
2967          * table.
2968          */
2969         oldrel = heap_open(tab->relid, NoLock);
2970         oldTupDesc = tab->oldDesc;
2971         newTupDesc = RelationGetDescr(oldrel);          /* includes all mods */
2972
2973         if (OidIsValid(OIDNewHeap))
2974                 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2975         else
2976                 newrel = NULL;
2977
2978         /*
2979          * If we need to rewrite the table, the operation has to be propagated to
2980          * tables that use this table's rowtype as a column type.
2981          *
2982          * (Eventually this will probably become true for scans as well, but at
2983          * the moment a composite type does not enforce any constraints, so it's
2984          * not necessary/appropriate to enforce them just during ALTER.)
2985          */
2986         if (newrel)
2987                 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2988                                                                                  RelationGetRelationName(oldrel),
2989                                                                                  NULL);
2990
2991         /*
2992          * Generate the constraint and default execution states
2993          */
2994
2995         estate = CreateExecutorState();
2996
2997         /* Build the needed expression execution states */
2998         foreach(l, tab->constraints)
2999         {
3000                 NewConstraint *con = lfirst(l);
3001
3002                 switch (con->contype)
3003                 {
3004                         case CONSTR_CHECK:
3005                                 needscan = true;
3006                                 con->qualstate = (List *)
3007                                         ExecPrepareExpr((Expr *) con->qual, estate);
3008                                 break;
3009                         case CONSTR_FOREIGN:
3010                                 /* Nothing to do here */
3011                                 break;
3012                         default:
3013                                 elog(ERROR, "unrecognized constraint type: %d",
3014                                          (int) con->contype);
3015                 }
3016         }
3017
3018         foreach(l, tab->newvals)
3019         {
3020                 NewColumnValue *ex = lfirst(l);
3021
3022                 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
3023         }
3024
3025         notnull_attrs = NIL;
3026         if (newrel || tab->new_notnull)
3027         {
3028                 /*
3029                  * If we are rebuilding the tuples OR if we added any new NOT NULL
3030                  * constraints, check all not-null constraints.  This is a bit of
3031                  * overkill but it minimizes risk of bugs, and heap_attisnull is a
3032                  * pretty cheap test anyway.
3033                  */
3034                 for (i = 0; i < newTupDesc->natts; i++)
3035                 {
3036                         if (newTupDesc->attrs[i]->attnotnull &&
3037                                 !newTupDesc->attrs[i]->attisdropped)
3038                                 notnull_attrs = lappend_int(notnull_attrs, i);
3039                 }
3040                 if (notnull_attrs)
3041                         needscan = true;
3042         }
3043
3044         if (newrel || needscan)
3045         {
3046                 ExprContext *econtext;
3047                 Datum      *values;
3048                 bool       *isnull;
3049                 TupleTableSlot *oldslot;
3050                 TupleTableSlot *newslot;
3051                 HeapScanDesc scan;
3052                 HeapTuple       tuple;
3053                 MemoryContext oldCxt;
3054                 List       *dropped_attrs = NIL;
3055                 ListCell   *lc;
3056
3057                 econtext = GetPerTupleExprContext(estate);
3058
3059                 /*
3060                  * Make tuple slots for old and new tuples.  Note that even when the
3061                  * tuples are the same, the tupDescs might not be (consider ADD COLUMN
3062                  * without a default).
3063                  */
3064                 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
3065                 newslot = MakeSingleTupleTableSlot(newTupDesc);
3066
3067                 /* Preallocate values/isnull arrays */
3068                 i = Max(newTupDesc->natts, oldTupDesc->natts);
3069                 values = (Datum *) palloc(i * sizeof(Datum));
3070                 isnull = (bool *) palloc(i * sizeof(bool));
3071                 memset(values, 0, i * sizeof(Datum));
3072                 memset(isnull, true, i * sizeof(bool));
3073
3074                 /*
3075                  * Any attributes that are dropped according to the new tuple
3076                  * descriptor can be set to NULL. We precompute the list of dropped
3077                  * attributes to avoid needing to do so in the per-tuple loop.
3078                  */
3079                 for (i = 0; i < newTupDesc->natts; i++)
3080                 {
3081                         if (newTupDesc->attrs[i]->attisdropped)
3082                                 dropped_attrs = lappend_int(dropped_attrs, i);
3083                 }
3084
3085                 /*
3086                  * Scan through the rows, generating a new row if needed and then
3087                  * checking all the constraints.
3088                  */
3089                 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3090
3091                 /*
3092                  * Switch to per-tuple memory context and reset it for each tuple
3093                  * produced, so we don't leak memory.
3094                  */
3095                 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3096
3097                 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3098                 {
3099                         if (newrel)
3100                         {
3101                                 Oid                     tupOid = InvalidOid;
3102
3103                                 /* Extract data from old tuple */
3104                                 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3105                                 if (oldTupDesc->tdhasoid)
3106                                         tupOid = HeapTupleGetOid(tuple);
3107
3108                                 /* Set dropped attributes to null in new tuple */
3109                                 foreach(lc, dropped_attrs)
3110                                         isnull[lfirst_int(lc)] = true;
3111
3112                                 /*
3113                                  * Process supplied expressions to replace selected columns.
3114                                  * Expression inputs come from the old tuple.
3115                                  */
3116                                 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3117                                 econtext->ecxt_scantuple = oldslot;
3118
3119                                 foreach(l, tab->newvals)
3120                                 {
3121                                         NewColumnValue *ex = lfirst(l);
3122
3123                                         values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3124                                                                                                                   econtext,
3125                                                                                                          &isnull[ex->attnum - 1],
3126                                                                                                                   NULL);
3127                                 }
3128
3129                                 /*
3130                                  * Form the new tuple. Note that we don't explicitly pfree it,
3131                                  * since the per-tuple memory context will be reset shortly.
3132                                  */
3133                                 tuple = heap_form_tuple(newTupDesc, values, isnull);
3134
3135                                 /* Preserve OID, if any */
3136                                 if (newTupDesc->tdhasoid)
3137                                         HeapTupleSetOid(tuple, tupOid);
3138                         }
3139
3140                         /* Now check any constraints on the possibly-changed tuple */
3141                         ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3142                         econtext->ecxt_scantuple = newslot;
3143
3144                         foreach(l, notnull_attrs)
3145                         {
3146                                 int                     attn = lfirst_int(l);
3147
3148                                 if (heap_attisnull(tuple, attn + 1))
3149                                         ereport(ERROR,
3150                                                         (errcode(ERRCODE_NOT_NULL_VIOLATION),
3151                                                          errmsg("column \"%s\" contains null values",
3152                                                                 NameStr(newTupDesc->attrs[attn]->attname))));
3153                         }
3154
3155                         foreach(l, tab->constraints)
3156                         {
3157                                 NewConstraint *con = lfirst(l);
3158
3159                                 switch (con->contype)
3160                                 {
3161                                         case CONSTR_CHECK:
3162                                                 if (!ExecQual(con->qualstate, econtext, true))
3163                                                         ereport(ERROR,
3164                                                                         (errcode(ERRCODE_CHECK_VIOLATION),
3165                                                                          errmsg("check constraint \"%s\" is violated by some row",
3166                                                                                         con->name)));
3167                                                 break;
3168                                         case CONSTR_FOREIGN:
3169                                                 /* Nothing to do here */
3170                                                 break;
3171                                         default:
3172                                                 elog(ERROR, "unrecognized constraint type: %d",
3173                                                          (int) con->contype);
3174                                 }
3175                         }
3176
3177                         /* Write the tuple out to the new relation */
3178                         if (newrel)
3179                                 simple_heap_insert(newrel, tuple);
3180
3181                         ResetExprContext(econtext);
3182
3183                         CHECK_FOR_INTERRUPTS();
3184                 }
3185
3186                 MemoryContextSwitchTo(oldCxt);
3187                 heap_endscan(scan);
3188
3189                 ExecDropSingleTupleTableSlot(oldslot);
3190                 ExecDropSingleTupleTableSlot(newslot);
3191         }
3192
3193         FreeExecutorState(estate);
3194
3195         heap_close(oldrel, NoLock);
3196         if (newrel)
3197                 heap_close(newrel, NoLock);
3198 }
3199
3200 /*
3201  * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3202  */
3203 static AlteredTableInfo *
3204 ATGetQueueEntry(List **wqueue, Relation rel)
3205 {
3206         Oid                     relid = RelationGetRelid(rel);
3207         AlteredTableInfo *tab;
3208         ListCell   *ltab;
3209
3210         foreach(ltab, *wqueue)
3211         {
3212                 tab = (AlteredTableInfo *) lfirst(ltab);
3213                 if (tab->relid == relid)
3214                         return tab;
3215         }
3216
3217         /*
3218          * Not there, so add it.  Note that we make a copy of the relation's
3219          * existing descriptor before anything interesting can happen to it.
3220          */
3221         tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3222         tab->relid = relid;
3223         tab->relkind = rel->rd_rel->relkind;
3224         tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3225
3226         *wqueue = lappend(*wqueue, tab);
3227
3228         return tab;
3229 }
3230
3231 /*
3232  * ATSimplePermissions
3233  *
3234  * - Ensure that it is a relation (or possibly a view)
3235  * - Ensure this user is the owner
3236  * - Ensure that it is not a system table
3237  */
3238 static void
3239 ATSimplePermissions(Relation rel, bool allowView)
3240 {
3241         if (rel->rd_rel->relkind != RELKIND_RELATION)
3242         {
3243                 if (allowView)
3244                 {
3245                         if (rel->rd_rel->relkind != RELKIND_VIEW)
3246                                 ereport(ERROR,
3247                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3248                                                  errmsg("\"%s\" is not a table or view",
3249                                                                 RelationGetRelationName(rel))));
3250                 }
3251                 else
3252                         ereport(ERROR,
3253                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3254                                          errmsg("\"%s\" is not a table",
3255                                                         RelationGetRelationName(rel))));
3256         }
3257
3258         /* Permissions checks */
3259         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3260                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3261                                            RelationGetRelationName(rel));
3262
3263         if (!allowSystemTableMods && IsSystemRelation(rel))
3264                 ereport(ERROR,
3265                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3266                                  errmsg("permission denied: \"%s\" is a system catalog",
3267                                                 RelationGetRelationName(rel))));
3268 }
3269
3270 /*
3271  * ATSimplePermissionsRelationOrIndex
3272  *
3273  * - Ensure that it is a relation or an index
3274  * - Ensure this user is the owner
3275  * - Ensure that it is not a system table
3276  */
3277 static void
3278 ATSimplePermissionsRelationOrIndex(Relation rel)
3279 {
3280         if (rel->rd_rel->relkind != RELKIND_RELATION &&
3281                 rel->rd_rel->relkind != RELKIND_INDEX)
3282                 ereport(ERROR,
3283                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3284                                  errmsg("\"%s\" is not a table or index",
3285                                                 RelationGetRelationName(rel))));
3286
3287         /* Permissions checks */
3288         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3289                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3290                                            RelationGetRelationName(rel));
3291
3292         if (!allowSystemTableMods && IsSystemRelation(rel))
3293                 ereport(ERROR,
3294                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3295                                  errmsg("permission denied: \"%s\" is a system catalog",
3296                                                 RelationGetRelationName(rel))));
3297 }
3298
3299 /*
3300  * ATSimpleRecursion
3301  *
3302  * Simple table recursion sufficient for most ALTER TABLE operations.
3303  * All direct and indirect children are processed in an unspecified order.
3304  * Note that if a child inherits from the original table via multiple
3305  * inheritance paths, it will be visited just once.
3306  */
3307 static void
3308 ATSimpleRecursion(List **wqueue, Relation rel,
3309                                   AlterTableCmd *cmd, bool recurse)
3310 {
3311         /*
3312          * Propagate to children if desired.  Non-table relations never have
3313          * children, so no need to search in that case.
3314          */
3315         if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3316         {
3317                 Oid                     relid = RelationGetRelid(rel);
3318                 ListCell   *child;
3319                 List       *children;
3320
3321                 children = find_all_inheritors(relid, AccessExclusiveLock);
3322
3323                 /*
3324                  * find_all_inheritors does the recursive search of the inheritance
3325                  * hierarchy, so all we have to do is process all of the relids in the
3326                  * list that it returns.
3327                  */
3328                 foreach(child, children)
3329                 {
3330                         Oid                     childrelid = lfirst_oid(child);
3331                         Relation        childrel;
3332
3333                         if (childrelid == relid)
3334                                 continue;
3335                         /* find_all_inheritors already got lock */
3336                         childrel = relation_open(childrelid, NoLock);
3337                         CheckTableNotInUse(childrel, "ALTER TABLE");
3338                         ATPrepCmd(wqueue, childrel, cmd, false, true);
3339                         relation_close(childrel, NoLock);
3340                 }
3341         }
3342 }
3343
3344 /*
3345  * ATOneLevelRecursion
3346  *
3347  * Here, we visit only direct inheritance children.  It is expected that
3348  * the command's prep routine will recurse again to find indirect children.
3349  * When using this technique, a multiply-inheriting child will be visited
3350  * multiple times.
3351  */
3352 static void
3353 ATOneLevelRecursion(List **wqueue, Relation rel,
3354                                         AlterTableCmd *cmd)
3355 {
3356         Oid                     relid = RelationGetRelid(rel);
3357         ListCell   *child;
3358         List       *children;
3359
3360         children = find_inheritance_children(relid, AccessExclusiveLock);
3361
3362         foreach(child, children)
3363         {
3364                 Oid                     childrelid = lfirst_oid(child);
3365                 Relation        childrel;
3366
3367                 /* find_inheritance_children already got lock */
3368                 childrel = relation_open(childrelid, NoLock);
3369                 CheckTableNotInUse(childrel, "ALTER TABLE");
3370                 ATPrepCmd(wqueue, childrel, cmd, true, true);
3371                 relation_close(childrel, NoLock);
3372         }
3373 }
3374
3375
3376 /*
3377  * find_composite_type_dependencies
3378  *
3379  * Check to see if a composite type is being used as a column in some
3380  * other table (possibly nested several levels deep in composite types!).
3381  * Eventually, we'd like to propagate the check or rewrite operation
3382  * into other such tables, but for now, just error out if we find any.
3383  *
3384  * Caller should provide either a table name or a type name (not both) to
3385  * report in the error message, if any.
3386  *
3387  * We assume that functions and views depending on the type are not reasons
3388  * to reject the ALTER.  (How safe is this really?)
3389  */
3390 void
3391 find_composite_type_dependencies(Oid typeOid,
3392                                                                  const char *origTblName,
3393                                                                  const char *origTypeName)
3394 {
3395         Relation        depRel;
3396         ScanKeyData key[2];
3397         SysScanDesc depScan;
3398         HeapTuple       depTup;
3399         Oid                     arrayOid;
3400
3401         /*
3402          * We scan pg_depend to find those things that depend on the rowtype. (We
3403          * assume we can ignore refobjsubid for a rowtype.)
3404          */
3405         depRel = heap_open(DependRelationId, AccessShareLock);
3406
3407         ScanKeyInit(&key[0],
3408                                 Anum_pg_depend_refclassid,
3409                                 BTEqualStrategyNumber, F_OIDEQ,
3410                                 ObjectIdGetDatum(TypeRelationId));
3411         ScanKeyInit(&key[1],
3412                                 Anum_pg_depend_refobjid,
3413                                 BTEqualStrategyNumber, F_OIDEQ,
3414                                 ObjectIdGetDatum(typeOid));
3415
3416         depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3417                                                                  SnapshotNow, 2, key);
3418
3419         while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3420         {
3421                 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3422                 Relation        rel;
3423                 Form_pg_attribute att;
3424
3425                 /* Ignore dependees that aren't user columns of relations */
3426                 /* (we assume system columns are never of rowtypes) */
3427                 if (pg_depend->classid != RelationRelationId ||
3428                         pg_depend->objsubid <= 0)
3429                         continue;
3430
3431                 rel = relation_open(pg_depend->objid, AccessShareLock);
3432                 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3433
3434                 if (rel->rd_rel->relkind == RELKIND_RELATION)
3435                 {
3436                         if (origTblName)
3437                                 ereport(ERROR,
3438                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3439                                                  errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3440                                                                 origTblName,
3441                                                                 RelationGetRelationName(rel),
3442                                                                 NameStr(att->attname))));
3443                         else
3444                                 ereport(ERROR,
3445                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3446                                                  errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3447                                                                 origTypeName,
3448                                                                 RelationGetRelationName(rel),
3449                                                                 NameStr(att->attname))));
3450                 }
3451                 else if (OidIsValid(rel->rd_rel->reltype))
3452                 {
3453                         /*
3454                          * A view or composite type itself isn't a problem, but we must
3455                          * recursively check for indirect dependencies via its rowtype.
3456                          */
3457                         find_composite_type_dependencies(rel->rd_rel->reltype,
3458                                                                                          origTblName, origTypeName);
3459                 }
3460
3461                 relation_close(rel, AccessShareLock);
3462         }
3463
3464         systable_endscan(depScan);
3465
3466         relation_close(depRel, AccessShareLock);
3467
3468         /*
3469          * If there's an array type for the rowtype, must check for uses of it,
3470          * too.
3471          */
3472         arrayOid = get_array_type(typeOid);
3473         if (OidIsValid(arrayOid))
3474                 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3475 }
3476
3477
3478 /*
3479  * ALTER TABLE ADD COLUMN
3480  *
3481  * Adds an additional attribute to a relation making the assumption that
3482  * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3483  * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3484  * AlterTableCmd's.
3485  */
3486 static void
3487 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3488                                 AlterTableCmd *cmd)
3489 {
3490         /*
3491          * Recurse to add the column to child classes, if requested.
3492          *
3493          * We must recurse one level at a time, so that multiply-inheriting
3494          * children are visited the right number of times and end up with the
3495          * right attinhcount.
3496          */
3497         if (recurse)
3498         {
3499                 AlterTableCmd *childCmd = copyObject(cmd);
3500                 ColumnDef  *colDefChild = (ColumnDef *) childCmd->def;
3501
3502                 /* Child should see column as singly inherited */
3503                 colDefChild->inhcount = 1;
3504                 colDefChild->is_local = false;
3505
3506                 ATOneLevelRecursion(wqueue, rel, childCmd);
3507         }
3508         else
3509         {
3510                 /*
3511                  * If we are told not to recurse, there had better not be any child
3512                  * tables; else the addition would put them out of step.
3513                  */
3514                 if (find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
3515                         ereport(ERROR,
3516                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3517                                          errmsg("column must be added to child tables too")));
3518         }
3519 }
3520
3521 static void
3522 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3523                                 ColumnDef *colDef, bool isOid)
3524 {
3525         Oid                     myrelid = RelationGetRelid(rel);
3526         Relation        pgclass,
3527                                 attrdesc;
3528         HeapTuple       reltup;
3529         FormData_pg_attribute attribute;
3530         int                     newattnum;
3531         char            relkind;
3532         HeapTuple       typeTuple;
3533         Oid                     typeOid;
3534         int32           typmod;
3535         Form_pg_type tform;
3536         Expr       *defval;
3537
3538         attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3539
3540         /*
3541          * Are we adding the column to a recursion child?  If so, check whether to
3542          * merge with an existing definition for the column.
3543          */
3544         if (colDef->inhcount > 0)
3545         {
3546                 HeapTuple       tuple;
3547
3548                 /* Does child already have a column by this name? */
3549                 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3550                 if (HeapTupleIsValid(tuple))
3551                 {
3552                         Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3553                         Oid                     ctypeId;
3554                         int32           ctypmod;
3555
3556                         /* Child column must match by type */
3557                         ctypeId = typenameTypeId(NULL, colDef->typeName, &ctypmod);
3558                         if (ctypeId != childatt->atttypid ||
3559                                 ctypmod != childatt->atttypmod)
3560                                 ereport(ERROR,
3561                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3562                                                  errmsg("child table \"%s\" has different type for column \"%s\"",
3563                                                         RelationGetRelationName(rel), colDef->colname)));
3564
3565                         /* If it's OID, child column must actually be OID */
3566                         if (isOid && childatt->attnum != ObjectIdAttributeNumber)
3567                                 ereport(ERROR,
3568                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3569                                  errmsg("child table \"%s\" has a conflicting \"%s\" column",
3570                                                 RelationGetRelationName(rel), colDef->colname)));
3571
3572                         /* Bump the existing child att's inhcount */
3573                         childatt->attinhcount++;
3574                         simple_heap_update(attrdesc, &tuple->t_self, tuple);
3575                         CatalogUpdateIndexes(attrdesc, tuple);
3576
3577                         heap_freetuple(tuple);
3578
3579                         /* Inform the user about the merge */
3580                         ereport(NOTICE,
3581                           (errmsg("merging definition of column \"%s\" for child \"%s\"",
3582                                           colDef->colname, RelationGetRelationName(rel))));
3583
3584                         heap_close(attrdesc, RowExclusiveLock);
3585                         return;
3586                 }
3587         }
3588
3589         pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3590
3591         reltup = SearchSysCacheCopy(RELOID,
3592                                                                 ObjectIdGetDatum(myrelid),
3593                                                                 0, 0, 0);
3594         if (!HeapTupleIsValid(reltup))
3595                 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3596         relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
3597
3598         /*
3599          * this test is deliberately not attisdropped-aware, since if one tries to
3600          * add a column matching a dropped column name, it's gonna fail anyway.
3601          */
3602         if (SearchSysCacheExists(ATTNAME,
3603                                                          ObjectIdGetDatum(myrelid),
3604                                                          PointerGetDatum(colDef->colname),
3605                                                          0, 0))
3606                 ereport(ERROR,
3607                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
3608                                  errmsg("column \"%s\" of relation \"%s\" already exists",
3609                                                 colDef->colname, RelationGetRelationName(rel))));
3610
3611         /* Determine the new attribute's number */
3612         if (isOid)
3613                 newattnum = ObjectIdAttributeNumber;
3614         else
3615         {
3616                 newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
3617                 if (newattnum > MaxHeapAttributeNumber)
3618                         ereport(ERROR,
3619                                         (errcode(ERRCODE_TOO_MANY_COLUMNS),
3620                                          errmsg("tables can have at most %d columns",
3621                                                         MaxHeapAttributeNumber)));
3622         }
3623
3624         typeTuple = typenameType(NULL, colDef->typeName, &typmod);
3625         tform = (Form_pg_type) GETSTRUCT(typeTuple);
3626         typeOid = HeapTupleGetOid(typeTuple);
3627
3628         /* make sure datatype is legal for a column */
3629         CheckAttributeType(colDef->colname, typeOid);
3630
3631         /* construct new attribute's pg_attribute entry */
3632         attribute.attrelid = myrelid;
3633         namestrcpy(&(attribute.attname), colDef->colname);
3634         attribute.atttypid = typeOid;
3635         attribute.attstattarget = (newattnum > 0) ? -1 : 0;
3636         attribute.attdistinct = 0;
3637         attribute.attlen = tform->typlen;
3638         attribute.attcacheoff = -1;
3639         attribute.atttypmod = typmod;
3640         attribute.attnum = newattnum;
3641         attribute.attbyval = tform->typbyval;
3642         attribute.attndims = list_length(colDef->typeName->arrayBounds);
3643         attribute.attstorage = tform->typstorage;
3644         attribute.attalign = tform->typalign;
3645         attribute.attnotnull = colDef->is_not_null;
3646         attribute.atthasdef = false;
3647         attribute.attisdropped = false;
3648         attribute.attislocal = colDef->is_local;
3649         attribute.attinhcount = colDef->inhcount;
3650         /* attribute.attacl is handled by InsertPgAttributeTuple */
3651
3652         ReleaseSysCache(typeTuple);
3653
3654         InsertPgAttributeTuple(attrdesc, &attribute, NULL);
3655
3656         heap_close(attrdesc, RowExclusiveLock);
3657
3658         /*
3659          * Update pg_class tuple as appropriate
3660          */
3661         if (isOid)
3662                 ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
3663         else
3664                 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
3665
3666         simple_heap_update(pgclass, &reltup->t_self, reltup);
3667
3668         /* keep catalog indexes current */
3669         CatalogUpdateIndexes(pgclass, reltup);
3670
3671         heap_freetuple(reltup);
3672
3673         heap_close(pgclass, RowExclusiveLock);
3674
3675         /* Make the attribute's catalog entry visible */
3676         CommandCounterIncrement();
3677
3678         /*
3679          * Store the DEFAULT, if any, in the catalogs
3680          */
3681         if (colDef->raw_default)
3682         {
3683                 RawColumnDefault *rawEnt;
3684
3685                 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3686                 rawEnt->attnum = attribute.attnum;
3687                 rawEnt->raw_default = copyObject(colDef->raw_default);
3688
3689                 /*
3690                  * This function is intended for CREATE TABLE, so it processes a
3691                  * _list_ of defaults, but we just do one.
3692                  */
3693                 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3694
3695                 /* Make the additional catalog changes visible */
3696                 CommandCounterIncrement();
3697         }
3698
3699         /*
3700          * Tell Phase 3 to fill in the default expression, if there is one.
3701          *
3702          * If there is no default, Phase 3 doesn't have to do anything, because
3703          * that effectively means that the default is NULL.  The heap tuple access
3704          * routines always check for attnum > # of attributes in tuple, and return
3705          * NULL if so, so without any modification of the tuple data we will get
3706          * the effect of NULL values in the new column.
3707          *
3708          * An exception occurs when the new column is of a domain type: the domain
3709          * might have a NOT NULL constraint, or a check constraint that indirectly
3710          * rejects nulls.  If there are any domain constraints then we construct
3711          * an explicit NULL default value that will be passed through
3712          * CoerceToDomain processing.  (This is a tad inefficient, since it causes
3713          * rewriting the table which we really don't have to do, but the present
3714          * design of domain processing doesn't offer any simple way of checking
3715          * the constraints more directly.)
3716          *
3717          * Note: we use build_column_default, and not just the cooked default
3718          * returned by AddRelationNewConstraints, so that the right thing happens
3719          * when a datatype's default applies.
3720          *
3721          * We skip this step completely for views.      For a view, we can only get
3722          * here from CREATE OR REPLACE VIEW, which historically doesn't set up
3723          * defaults, not even for domain-typed columns.  And in any case we
3724          * mustn't invoke Phase 3 on a view, since it has no storage.
3725          */
3726         if (relkind != RELKIND_VIEW && attribute.attnum > 0)
3727         {
3728                 defval = (Expr *) build_column_default(rel, attribute.attnum);
3729
3730                 if (!defval && GetDomainConstraints(typeOid) != NIL)
3731                 {
3732                         Oid                     baseTypeId;
3733                         int32           baseTypeMod;
3734
3735                         baseTypeMod = typmod;
3736                         baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3737                         defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3738                         defval = (Expr *) coerce_to_target_type(NULL,
3739                                                                                                         (Node *) defval,
3740                                                                                                         baseTypeId,
3741                                                                                                         typeOid,
3742                                                                                                         typmod,
3743                                                                                                         COERCION_ASSIGNMENT,
3744                                                                                                         COERCE_IMPLICIT_CAST,
3745                                                                                                         -1);
3746                         if (defval == NULL) /* should not happen */
3747                                 elog(ERROR, "failed to coerce base type to domain");
3748                 }
3749
3750                 if (defval)
3751                 {
3752                         NewColumnValue *newval;
3753
3754                         newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3755                         newval->attnum = attribute.attnum;
3756                         newval->expr = defval;
3757
3758                         tab->newvals = lappend(tab->newvals, newval);
3759                 }
3760
3761                 /*
3762                  * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3763                  * (Note we don't do this for an OID column.  OID will be marked not
3764                  * null, but since it's filled specially, there's no need to test
3765                  * anything.)
3766                  */
3767                 tab->new_notnull |= colDef->is_not_null;
3768         }
3769
3770         /*
3771          * If we are adding an OID column, we have to tell Phase 3 to rewrite the
3772          * table to fix that.
3773          */
3774         if (isOid)
3775                 tab->new_changeoids = true;
3776
3777         /*
3778          * Add needed dependency entries for the new column.
3779          */
3780         add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
3781 }
3782
3783 /*
3784  * Install a column's dependency on its datatype.
3785  */
3786 static void
3787 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3788 {
3789         ObjectAddress myself,
3790                                 referenced;
3791
3792         myself.classId = RelationRelationId;
3793         myself.objectId = relid;
3794         myself.objectSubId = attnum;
3795         referenced.classId = TypeRelationId;
3796         referenced.objectId = typid;
3797         referenced.objectSubId = 0;
3798         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3799 }
3800
3801 /*
3802  * ALTER TABLE SET WITH OIDS
3803  *
3804  * Basically this is an ADD COLUMN for the special OID column.  We have
3805  * to cons up a ColumnDef node because the ADD COLUMN code needs one.
3806  */
3807 static void
3808 ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd)
3809 {
3810         /* If we're recursing to a child table, the ColumnDef is already set up */
3811         if (cmd->def == NULL)
3812         {
3813                 ColumnDef  *cdef = makeNode(ColumnDef);
3814
3815                 cdef->colname = pstrdup("oid");
3816                 cdef->typeName = makeTypeNameFromOid(OIDOID, -1);
3817                 cdef->inhcount = 0;
3818                 cdef->is_local = true;
3819                 cdef->is_not_null = true;
3820                 cmd->def = (Node *) cdef;
3821         }
3822         ATPrepAddColumn(wqueue, rel, recurse, cmd);
3823 }
3824
3825 /*
3826  * ALTER TABLE ALTER COLUMN DROP NOT NULL
3827  */
3828 static void
3829 ATExecDropNotNull(Relation rel, const char *colName)
3830 {
3831         HeapTuple       tuple;
3832         AttrNumber      attnum;
3833         Relation        attr_rel;
3834         List       *indexoidlist;
3835         ListCell   *indexoidscan;
3836
3837         /*
3838          * lookup the attribute
3839          */
3840         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3841
3842         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3843
3844         if (!HeapTupleIsValid(tuple))
3845                 ereport(ERROR,
3846                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3847                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3848                                                 colName, RelationGetRelationName(rel))));
3849
3850         attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3851
3852         /* Prevent them from altering a system attribute */
3853         if (attnum <= 0)
3854                 ereport(ERROR,
3855                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3856                                  errmsg("cannot alter system column \"%s\"",
3857                                                 colName)));
3858
3859         /*
3860          * Check that the attribute is not in a primary key
3861          */
3862
3863         /* Loop over all indexes on the relation */
3864         indexoidlist = RelationGetIndexList(rel);
3865
3866         foreach(indexoidscan, indexoidlist)
3867         {
3868                 Oid                     indexoid = lfirst_oid(indexoidscan);
3869                 HeapTuple       indexTuple;
3870                 Form_pg_index indexStruct;
3871                 int                     i;
3872
3873                 indexTuple = SearchSysCache(INDEXRELID,
3874                                                                         ObjectIdGetDatum(indexoid),
3875                                                                         0, 0, 0);
3876                 if (!HeapTupleIsValid(indexTuple))
3877                         elog(ERROR, "cache lookup failed for index %u", indexoid);
3878                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3879
3880                 /* If the index is not a primary key, skip the check */
3881                 if (indexStruct->indisprimary)
3882                 {
3883                         /*
3884                          * Loop over each attribute in the primary key and see if it
3885                          * matches the to-be-altered attribute
3886                          */
3887                         for (i = 0; i < indexStruct->indnatts; i++)
3888                         {
3889                                 if (indexStruct->indkey.values[i] == attnum)
3890                                         ereport(ERROR,
3891                                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3892                                                          errmsg("column \"%s\" is in a primary key",
3893                                                                         colName)));
3894                         }
3895                 }
3896
3897                 ReleaseSysCache(indexTuple);
3898         }
3899
3900         list_free(indexoidlist);
3901
3902         /*
3903          * Okay, actually perform the catalog change ... if needed
3904          */
3905         if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3906         {
3907                 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3908
3909                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3910
3911                 /* keep the system catalog indexes current */
3912                 CatalogUpdateIndexes(attr_rel, tuple);
3913         }
3914
3915         heap_close(attr_rel, RowExclusiveLock);
3916 }
3917
3918 /*
3919  * ALTER TABLE ALTER COLUMN SET NOT NULL
3920  */
3921 static void
3922 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3923                                  const char *colName)
3924 {
3925         HeapTuple       tuple;
3926         AttrNumber      attnum;
3927         Relation        attr_rel;
3928
3929         /*
3930          * lookup the attribute
3931          */
3932         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3933
3934         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3935
3936         if (!HeapTupleIsValid(tuple))
3937                 ereport(ERROR,
3938                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3939                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3940                                                 colName, RelationGetRelationName(rel))));
3941
3942         attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3943
3944         /* Prevent them from altering a system attribute */
3945         if (attnum <= 0)
3946                 ereport(ERROR,
3947                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3948                                  errmsg("cannot alter system column \"%s\"",
3949                                                 colName)));
3950
3951         /*
3952          * Okay, actually perform the catalog change ... if needed
3953          */
3954         if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3955         {
3956                 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3957
3958                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3959
3960                 /* keep the system catalog indexes current */
3961                 CatalogUpdateIndexes(attr_rel, tuple);
3962
3963                 /* Tell Phase 3 it needs to test the constraint */
3964                 tab->new_notnull = true;
3965         }
3966
3967         heap_close(attr_rel, RowExclusiveLock);
3968 }
3969
3970 /*
3971  * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3972  */
3973 static void
3974 ATExecColumnDefault(Relation rel, const char *colName,
3975                                         Node *newDefault)
3976 {
3977         AttrNumber      attnum;
3978
3979         /*
3980          * get the number of the attribute
3981          */
3982         attnum = get_attnum(RelationGetRelid(rel), colName);
3983         if (attnum == InvalidAttrNumber)
3984                 ereport(ERROR,
3985                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3986                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3987                                                 colName, RelationGetRelationName(rel))));
3988
3989         /* Prevent them from altering a system attribute */
3990         if (attnum <= 0)
3991                 ereport(ERROR,
3992                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3993                                  errmsg("cannot alter system column \"%s\"",
3994                                                 colName)));
3995
3996         /*
3997          * Remove any old default for the column.  We use RESTRICT here for
3998          * safety, but at present we do not expect anything to depend on the
3999          * default.
4000          */
4001         RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
4002
4003         if (newDefault)
4004         {
4005                 /* SET DEFAULT */
4006                 RawColumnDefault *rawEnt;
4007
4008                 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4009                 rawEnt->attnum = attnum;
4010                 rawEnt->raw_default = newDefault;
4011
4012                 /*
4013                  * This function is intended for CREATE TABLE, so it processes a
4014                  * _list_ of defaults, but we just do one.
4015                  */
4016                 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
4017         }
4018 }
4019
4020 /*
4021  * ALTER TABLE ALTER COLUMN SET STATISTICS
4022  */
4023 static void
4024 ATPrepSetStatistics(Relation rel, const char *colName, Node *newValue)
4025 {
4026         /*
4027          * We do our own permission checking because (a) we want to allow SET
4028          * STATISTICS on indexes (for expressional index columns), and (b) we want
4029          * to allow SET STATISTICS on system catalogs without requiring
4030          * allowSystemTableMods to be turned on.
4031          */
4032         if (rel->rd_rel->relkind != RELKIND_RELATION &&
4033                 rel->rd_rel->relkind != RELKIND_INDEX)
4034                 ereport(ERROR,
4035                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4036                                  errmsg("\"%s\" is not a table or index",
4037                                                 RelationGetRelationName(rel))));
4038
4039         /* Permissions checks */
4040         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4041                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4042                                            RelationGetRelationName(rel));
4043 }
4044
4045 static void
4046 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
4047 {
4048         int                     newtarget;
4049         Relation        attrelation;
4050         HeapTuple       tuple;
4051         Form_pg_attribute attrtuple;
4052
4053         Assert(IsA(newValue, Integer));
4054         newtarget = intVal(newValue);
4055
4056         /*
4057          * Limit target to a sane range
4058          */
4059         if (newtarget < -1)
4060         {
4061                 ereport(ERROR,
4062                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4063                                  errmsg("statistics target %d is too low",
4064                                                 newtarget)));
4065         }
4066         else if (newtarget > 10000)
4067         {
4068                 newtarget = 10000;
4069                 ereport(WARNING,
4070                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4071                                  errmsg("lowering statistics target to %d",
4072                                                 newtarget)));
4073         }
4074
4075         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4076
4077         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4078
4079         if (!HeapTupleIsValid(tuple))
4080                 ereport(ERROR,
4081                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
4082                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
4083                                                 colName, RelationGetRelationName(rel))));
4084         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4085
4086         if (attrtuple->attnum <= 0)
4087                 ereport(ERROR,
4088                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4089                                  errmsg("cannot alter system column \"%s\"",
4090                                                 colName)));
4091
4092         attrtuple->attstattarget = newtarget;
4093
4094         simple_heap_update(attrelation, &tuple->t_self, tuple);
4095
4096         /* keep system catalog indexes current */
4097         CatalogUpdateIndexes(attrelation, tuple);
4098
4099         heap_freetuple(tuple);
4100
4101         heap_close(attrelation, RowExclusiveLock);
4102 }
4103
4104 /*
4105  * ALTER TABLE ALTER COLUMN SET STATISTICS DISTINCT
4106  */
4107 static void
4108 ATPrepSetDistinct(Relation rel, const char *colName, Node *newValue)
4109 {
4110         /*
4111          * We do our own permission checking because (a) we want to allow SET
4112          * DISTINCT on indexes (for expressional index columns), and (b) we want
4113          * to allow SET DISTINCT on system catalogs without requiring
4114          * allowSystemTableMods to be turned on.
4115          */
4116         if (rel->rd_rel->relkind != RELKIND_RELATION &&
4117                 rel->rd_rel->relkind != RELKIND_INDEX)
4118                 ereport(ERROR,
4119                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4120                                  errmsg("\"%s\" is not a table or index",
4121                                                 RelationGetRelationName(rel))));
4122
4123         /* Permissions checks */
4124         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4125                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4126                                            RelationGetRelationName(rel));
4127 }
4128
4129 static void
4130 ATExecSetDistinct(Relation rel, const char *colName, Node *newValue)
4131 {
4132         float4          newdistinct;
4133         Relation        attrelation;
4134         HeapTuple       tuple;
4135         Form_pg_attribute attrtuple;
4136
4137         switch (nodeTag(newValue))
4138         {
4139                 case T_Integer:
4140                         newdistinct = intVal(newValue);
4141                         break;
4142                 case T_Float:
4143                         newdistinct = floatVal(newValue);
4144                         break;
4145                 default:
4146                         elog(ERROR, "unrecognized node type: %d",
4147                                  (int) nodeTag(newValue));
4148                         newdistinct = 0;        /* keep compiler quiet */
4149                         break;
4150         }
4151
4152         /*
4153          * Limit ndistinct to sane values
4154          */
4155         if (newdistinct < -1.0)
4156         {
4157                 ereport(ERROR,
4158                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4159                                  errmsg("number of distinct values %g is too low",
4160                                                 newdistinct)));
4161         }
4162
4163         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4164
4165         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4166
4167         if (!HeapTupleIsValid(tuple))
4168                 ereport(ERROR,
4169                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
4170                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
4171                                                 colName, RelationGetRelationName(rel))));
4172         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4173
4174         if (attrtuple->attnum <= 0)
4175                 ereport(ERROR,
4176                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4177                                  errmsg("cannot alter system column \"%s\"",
4178                                                 colName)));
4179
4180         attrtuple->attdistinct = newdistinct;
4181
4182         simple_heap_update(attrelation, &tuple->t_self, tuple);
4183
4184         /* keep system catalog indexes current */
4185         CatalogUpdateIndexes(attrelation, tuple);
4186
4187         heap_freetuple(tuple);
4188
4189         heap_close(attrelation, RowExclusiveLock);
4190 }
4191
4192 /*
4193  * ALTER TABLE ALTER COLUMN SET STORAGE
4194  */
4195 static void
4196 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
4197 {
4198         char       *storagemode;
4199         char            newstorage;
4200         Relation        attrelation;
4201         HeapTuple       tuple;
4202         Form_pg_attribute attrtuple;
4203
4204         Assert(IsA(newValue, String));
4205         storagemode = strVal(newValue);
4206
4207         if (pg_strcasecmp(storagemode, "plain") == 0)
4208                 newstorage = 'p';
4209         else if (pg_strcasecmp(storagemode, "external") == 0)
4210                 newstorage = 'e';
4211         else if (pg_strcasecmp(storagemode, "extended") == 0)
4212                 newstorage = 'x';
4213         else if (pg_strcasecmp(storagemode, "main") == 0)
4214                 newstorage = 'm';
4215         else
4216         {
4217                 ereport(ERROR,
4218                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4219                                  errmsg("invalid storage type \"%s\"",
4220                                                 storagemode)));
4221                 newstorage = 0;                 /* keep compiler quiet */
4222         }
4223
4224         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4225
4226         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4227
4228         if (!HeapTupleIsValid(tuple))
4229                 ereport(ERROR,
4230                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
4231                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
4232                                                 colName, RelationGetRelationName(rel))));
4233         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4234
4235         if (attrtuple->attnum <= 0)
4236                 ereport(ERROR,
4237                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4238                                  errmsg("cannot alter system column \"%s\"",
4239                                                 colName)));
4240
4241         /*
4242          * safety check: do not allow toasted storage modes unless column datatype
4243          * is TOAST-aware.
4244          */
4245         if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4246                 attrtuple->attstorage = newstorage;
4247         else
4248                 ereport(ERROR,
4249                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4250                                  errmsg("column data type %s can only have storage PLAIN",
4251                                                 format_type_be(attrtuple->atttypid))));
4252
4253         simple_heap_update(attrelation, &tuple->t_self, tuple);
4254
4255         /* keep system catalog indexes current */
4256         CatalogUpdateIndexes(attrelation, tuple);
4257
4258         heap_freetuple(tuple);
4259
4260         heap_close(attrelation, RowExclusiveLock);
4261 }
4262
4263
4264 /*
4265  * ALTER TABLE DROP COLUMN
4266  *
4267  * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4268  * because we have to decide at runtime whether to recurse or not depending
4269  * on whether attinhcount goes to zero or not.  (We can't check this in a
4270  * static pre-pass because it won't handle multiple inheritance situations
4271  * correctly.)
4272  */
4273 static void
4274 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
4275                                  DropBehavior behavior,
4276                                  bool recurse, bool recursing,
4277                                  bool missing_ok)
4278 {
4279         HeapTuple       tuple;
4280         Form_pg_attribute targetatt;
4281         AttrNumber      attnum;
4282         List       *children;
4283         ObjectAddress object;
4284
4285         /* At top level, permission check was done in ATPrepCmd, else do it */
4286         if (recursing)
4287                 ATSimplePermissions(rel, false);
4288
4289         /*
4290          * get the number of the attribute
4291          */
4292         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4293         if (!HeapTupleIsValid(tuple)){
4294                 if (!missing_ok){
4295                         ereport(ERROR,
4296                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4297                                          errmsg("column \"%s\" of relation \"%s\" does not exist",
4298                                                         colName, RelationGetRelationName(rel))));
4299                 }
4300                 else
4301                 {
4302                         ereport(NOTICE,
4303                                         (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
4304                                                         colName, RelationGetRelationName(rel))));
4305                         return;
4306                 }
4307         }
4308         targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
4309
4310         attnum = targetatt->attnum;
4311
4312         /* Can't drop a system attribute, except OID */
4313         if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
4314                 ereport(ERROR,
4315                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4316                                  errmsg("cannot drop system column \"%s\"",
4317                                                 colName)));
4318
4319         /* Don't drop inherited columns */
4320         if (targetatt->attinhcount > 0 && !recursing)
4321                 ereport(ERROR,
4322                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4323                                  errmsg("cannot drop inherited column \"%s\"",
4324                                                 colName)));
4325
4326         ReleaseSysCache(tuple);
4327
4328         /*
4329          * Propagate to children as appropriate.  Unlike most other ALTER
4330          * routines, we have to do this one level of recursion at a time; we can't
4331          * use find_all_inheritors to do it in one pass.
4332          */
4333         children = find_inheritance_children(RelationGetRelid(rel),
4334                                                                                  AccessExclusiveLock);
4335
4336         if (children)
4337         {
4338                 Relation        attr_rel;
4339                 ListCell   *child;
4340
4341                 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4342                 foreach(child, children)
4343                 {
4344                         Oid                     childrelid = lfirst_oid(child);
4345                         Relation        childrel;
4346                         Form_pg_attribute childatt;
4347
4348                         /* find_inheritance_children already got lock */
4349                         childrel = heap_open(childrelid, NoLock);
4350                         CheckTableNotInUse(childrel, "ALTER TABLE");
4351
4352                         tuple = SearchSysCacheCopyAttName(childrelid, colName);
4353                         if (!HeapTupleIsValid(tuple))           /* shouldn't happen */
4354                                 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
4355                                          colName, childrelid);
4356                         childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4357
4358                         if (childatt->attinhcount <= 0)         /* shouldn't happen */
4359                                 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
4360                                          childrelid, colName);
4361
4362                         if (recurse)
4363                         {
4364                                 /*
4365                                  * If the child column has other definition sources, just
4366                                  * decrement its inheritance count; if not, recurse to delete
4367                                  * it.
4368                                  */
4369                                 if (childatt->attinhcount == 1 && !childatt->attislocal)
4370                                 {
4371                                         /* Time to delete this child column, too */
4372                                         ATExecDropColumn(wqueue, childrel, colName,
4373                                                                          behavior, true, true,
4374                                                                          false);
4375                                 }
4376                                 else
4377                                 {
4378                                         /* Child column must survive my deletion */
4379                                         childatt->attinhcount--;
4380
4381                                         simple_heap_update(attr_rel, &tuple->t_self, tuple);
4382
4383                                         /* keep the system catalog indexes current */
4384                                         CatalogUpdateIndexes(attr_rel, tuple);
4385
4386                                         /* Make update visible */
4387                                         CommandCounterIncrement();
4388                                 }
4389                         }
4390                         else
4391                         {
4392                                 /*
4393                                  * If we were told to drop ONLY in this table (no recursion),
4394                                  * we need to mark the inheritors' attributes as locally
4395                                  * defined rather than inherited.
4396                                  */
4397                                 childatt->attinhcount--;
4398                                 childatt->attislocal = true;
4399
4400                                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4401
4402                                 /* keep the system catalog indexes current */
4403                                 CatalogUpdateIndexes(attr_rel, tuple);
4404
4405                                 /* Make update visible */
4406                                 CommandCounterIncrement();
4407                         }
4408
4409                         heap_freetuple(tuple);
4410
4411                         heap_close(childrel, NoLock);
4412                 }
4413                 heap_close(attr_rel, RowExclusiveLock);
4414         }
4415
4416         /*
4417          * Perform the actual column deletion
4418          */
4419         object.classId = RelationRelationId;
4420         object.objectId = RelationGetRelid(rel);
4421         object.objectSubId = attnum;
4422
4423         performDeletion(&object, behavior);
4424
4425         /*
4426          * If we dropped the OID column, must adjust pg_class.relhasoids and tell
4427          * Phase 3 to physically get rid of the column.
4428          */
4429         if (attnum == ObjectIdAttributeNumber)
4430         {
4431                 Relation        class_rel;
4432                 Form_pg_class tuple_class;
4433                 AlteredTableInfo *tab;
4434
4435                 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
4436
4437                 tuple = SearchSysCacheCopy(RELOID,
4438                                                                    ObjectIdGetDatum(RelationGetRelid(rel)),
4439                                                                    0, 0, 0);
4440                 if (!HeapTupleIsValid(tuple))
4441                         elog(ERROR, "cache lookup failed for relation %u",
4442                                  RelationGetRelid(rel));
4443                 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
4444
4445                 tuple_class->relhasoids = false;
4446                 simple_heap_update(class_rel, &tuple->t_self, tuple);
4447
4448                 /* Keep the catalog indexes up to date */
4449                 CatalogUpdateIndexes(class_rel, tuple);
4450
4451                 heap_close(class_rel, RowExclusiveLock);
4452
4453                 /* Find or create work queue entry for this table */
4454                 tab = ATGetQueueEntry(wqueue, rel);
4455
4456                 /* Tell Phase 3 to physically remove the OID column */
4457                 tab->new_changeoids = true;
4458         }
4459 }
4460
4461 /*
4462  * ALTER TABLE ADD INDEX
4463  *
4464  * There is no such command in the grammar, but parse_utilcmd.c converts
4465  * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands.  This lets
4466  * us schedule creation of the index at the appropriate time during ALTER.
4467  */
4468 static void
4469 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
4470                            IndexStmt *stmt, bool is_rebuild)
4471 {
4472         bool            check_rights;
4473         bool            skip_build;
4474         bool            quiet;
4475
4476         Assert(IsA(stmt, IndexStmt));
4477
4478         /* suppress schema rights check when rebuilding existing index */
4479         check_rights = !is_rebuild;
4480         /* skip index build if phase 3 will have to rewrite table anyway */
4481         skip_build = (tab->newvals != NIL);
4482         /* suppress notices when rebuilding existing index */
4483         quiet = is_rebuild;
4484
4485         /* The IndexStmt has already been through transformIndexStmt */
4486
4487         DefineIndex(stmt->relation, /* relation */
4488                                 stmt->idxname,  /* index name */
4489                                 InvalidOid,             /* no predefined OID */
4490                                 stmt->accessMethod,             /* am name */
4491                                 stmt->tableSpace,
4492                                 stmt->indexParams,              /* parameters */
4493                                 (Expr *) stmt->whereClause,
4494                                 stmt->options,
4495                                 stmt->unique,
4496                                 stmt->primary,
4497                                 stmt->isconstraint,
4498                                 stmt->deferrable,
4499                                 stmt->initdeferred,
4500                                 true,                   /* is_alter_table */
4501                                 check_rights,
4502                                 skip_build,
4503                                 quiet,
4504                                 false);
4505 }
4506
4507 /*
4508  * ALTER TABLE ADD CONSTRAINT
4509  */
4510 static void
4511 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4512                                         Constraint *newConstraint, bool recurse)
4513 {
4514         Assert(IsA(newConstraint, Constraint));
4515
4516         /*
4517          * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
4518          * arriving here (see the preprocessing done in parse_utilcmd.c).  Use a
4519          * switch anyway to make it easier to add more code later.
4520          */
4521         switch (newConstraint->contype)
4522         {
4523                 case CONSTR_CHECK:
4524                         ATAddCheckConstraint(wqueue, tab, rel,
4525                                                                  newConstraint, recurse, false);
4526                         break;
4527
4528                 case CONSTR_FOREIGN:
4529                         /*
4530                          * Note that we currently never recurse for FK constraints, so
4531                          * the "recurse" flag is silently ignored.
4532                          *
4533                          * Assign or validate constraint name
4534                          */
4535                         if (newConstraint->conname)
4536                         {
4537                                 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4538                                                                                  RelationGetRelid(rel),
4539                                                                                  RelationGetNamespace(rel),
4540                                                                                  newConstraint->conname))
4541                                         ereport(ERROR,
4542                                                         (errcode(ERRCODE_DUPLICATE_OBJECT),
4543                                                          errmsg("constraint \"%s\" for relation \"%s\" already exists",
4544                                                                         newConstraint->conname,
4545                                                                         RelationGetRelationName(rel))));
4546                         }
4547                         else
4548                                 newConstraint->conname =
4549                                         ChooseConstraintName(RelationGetRelationName(rel),
4550                                                                                  strVal(linitial(newConstraint->fk_attrs)),
4551                                                                                  "fkey",
4552                                                                                  RelationGetNamespace(rel),
4553                                                                                  NIL);
4554
4555                         ATAddForeignKeyConstraint(tab, rel, newConstraint);
4556                         break;
4557
4558                 default:
4559                         elog(ERROR, "unrecognized constraint type: %d",
4560                                  (int) newConstraint->contype);
4561         }
4562 }
4563
4564 /*
4565  * Add a check constraint to a single table and its children
4566  *
4567  * Subroutine for ATExecAddConstraint.
4568  *
4569  * We must recurse to child tables during execution, rather than using
4570  * ALTER TABLE's normal prep-time recursion.  The reason is that all the
4571  * constraints *must* be given the same name, else they won't be seen as
4572  * related later.  If the user didn't explicitly specify a name, then
4573  * AddRelationNewConstraints would normally assign different names to the
4574  * child constraints.  To fix that, we must capture the name assigned at
4575  * the parent table and pass that down.
4576  */
4577 static void
4578 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4579                                          Constraint *constr, bool recurse, bool recursing)
4580 {
4581         List       *newcons;
4582         ListCell   *lcon;
4583         List       *children;
4584         ListCell   *child;
4585
4586         /* At top level, permission check was done in ATPrepCmd, else do it */
4587         if (recursing)
4588                 ATSimplePermissions(rel, false);
4589
4590         /*
4591          * Call AddRelationNewConstraints to do the work, making sure it works on
4592          * a copy of the Constraint so transformExpr can't modify the original. It
4593          * returns a list of cooked constraints.
4594          *
4595          * If the constraint ends up getting merged with a pre-existing one, it's
4596          * omitted from the returned list, which is what we want: we do not need
4597          * to do any validation work.  That can only happen at child tables,
4598          * though, since we disallow merging at the top level.
4599          */
4600         newcons = AddRelationNewConstraints(rel, NIL,
4601                                                                                 list_make1(copyObject(constr)),
4602                                                                                 recursing, !recursing);
4603
4604         /* Add each constraint to Phase 3's queue */
4605         foreach(lcon, newcons)
4606         {
4607                 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
4608                 NewConstraint *newcon;
4609
4610                 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4611                 newcon->name = ccon->name;
4612                 newcon->contype = ccon->contype;
4613                 /* ExecQual wants implicit-AND format */
4614                 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
4615
4616                 tab->constraints = lappend(tab->constraints, newcon);
4617
4618                 /* Save the actually assigned name if it was defaulted */
4619                 if (constr->conname == NULL)
4620                         constr->conname = ccon->name;
4621         }
4622
4623         /* At this point we must have a locked-down name to use */
4624         Assert(constr->conname != NULL);
4625
4626         /* Advance command counter in case same table is visited multiple times */
4627         CommandCounterIncrement();
4628
4629         /*
4630          * Propagate to children as appropriate.  Unlike most other ALTER
4631          * routines, we have to do this one level of recursion at a time; we can't
4632          * use find_all_inheritors to do it in one pass.
4633          */
4634         children = find_inheritance_children(RelationGetRelid(rel),
4635                                                                                  AccessExclusiveLock);
4636
4637         /*
4638          * If we are told not to recurse, there had better not be any child
4639          * tables; else the addition would put them out of step.
4640          */
4641         if (children && !recurse)
4642                 ereport(ERROR,
4643                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4644                                  errmsg("constraint must be added to child tables too")));
4645
4646         foreach(child, children)
4647         {
4648                 Oid                     childrelid = lfirst_oid(child);
4649                 Relation        childrel;
4650                 AlteredTableInfo *childtab;
4651
4652                 /* find_inheritance_children already got lock */
4653                 childrel = heap_open(childrelid, NoLock);
4654                 CheckTableNotInUse(childrel, "ALTER TABLE");
4655
4656                 /* Find or create work queue entry for this table */
4657                 childtab = ATGetQueueEntry(wqueue, childrel);
4658
4659                 /* Recurse to child */
4660                 ATAddCheckConstraint(wqueue, childtab, childrel,
4661                                                          constr, recurse, true);
4662
4663                 heap_close(childrel, NoLock);
4664         }
4665 }
4666
4667 /*
4668  * Add a foreign-key constraint to a single table
4669  *
4670  * Subroutine for ATExecAddConstraint.  Must already hold exclusive
4671  * lock on the rel, and have done appropriate validity checks for it.
4672  * We do permissions checks here, however.
4673  */
4674 static void
4675 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4676                                                   Constraint *fkconstraint)
4677 {
4678         Relation        pkrel;
4679         int16           pkattnum[INDEX_MAX_KEYS];
4680         int16           fkattnum[INDEX_MAX_KEYS];
4681         Oid                     pktypoid[INDEX_MAX_KEYS];
4682         Oid                     fktypoid[INDEX_MAX_KEYS];
4683         Oid                     opclasses[INDEX_MAX_KEYS];
4684         Oid                     pfeqoperators[INDEX_MAX_KEYS];
4685         Oid                     ppeqoperators[INDEX_MAX_KEYS];
4686         Oid                     ffeqoperators[INDEX_MAX_KEYS];
4687         int                     i;
4688         int                     numfks,
4689                                 numpks;
4690         Oid                     indexOid;
4691         Oid                     constrOid;
4692
4693         /*
4694          * Grab an exclusive lock on the pk table, so that someone doesn't delete
4695          * rows out from under us. (Although a lesser lock would do for that
4696          * purpose, we'll need exclusive lock anyway to add triggers to the pk
4697          * table; trying to start with a lesser lock will just create a risk of
4698          * deadlock.)
4699          */
4700         pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4701
4702         /*
4703          * Validity checks (permission checks wait till we have the column
4704          * numbers)
4705          */
4706         if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4707                 ereport(ERROR,
4708                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4709                                  errmsg("referenced relation \"%s\" is not a table",
4710                                                 RelationGetRelationName(pkrel))));
4711
4712         if (!allowSystemTableMods && IsSystemRelation(pkrel))
4713                 ereport(ERROR,
4714                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4715                                  errmsg("permission denied: \"%s\" is a system catalog",
4716                                                 RelationGetRelationName(pkrel))));
4717
4718         /*
4719          * Disallow reference from permanent table to temp table or vice versa.
4720          * (The ban on perm->temp is for fairly obvious reasons.  The ban on
4721          * temp->perm is because other backends might need to run the RI triggers
4722          * on the perm table, but they can't reliably see tuples the owning
4723          * backend has created in the temp table, because non-shared buffers are
4724          * used for temp tables.)
4725          */
4726         if (pkrel->rd_istemp)
4727         {
4728                 if (!rel->rd_istemp)
4729                         ereport(ERROR,
4730                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4731                                          errmsg("cannot reference temporary table from permanent table constraint")));
4732         }
4733         else
4734         {
4735                 if (rel->rd_istemp)
4736                         ereport(ERROR,
4737                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4738                                          errmsg("cannot reference permanent table from temporary table constraint")));
4739         }
4740
4741         /*
4742          * Look up the referencing attributes to make sure they exist, and record
4743          * their attnums and type OIDs.
4744          */
4745         MemSet(pkattnum, 0, sizeof(pkattnum));
4746         MemSet(fkattnum, 0, sizeof(fkattnum));
4747         MemSet(pktypoid, 0, sizeof(pktypoid));
4748         MemSet(fktypoid, 0, sizeof(fktypoid));
4749         MemSet(opclasses, 0, sizeof(opclasses));
4750         MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4751         MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4752         MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4753
4754         numfks = transformColumnNameList(RelationGetRelid(rel),
4755                                                                          fkconstraint->fk_attrs,
4756                                                                          fkattnum, fktypoid);
4757
4758         /*
4759          * If the attribute list for the referenced table was omitted, lookup the
4760          * definition of the primary key and use it.  Otherwise, validate the
4761          * supplied attribute list.  In either case, discover the index OID and
4762          * index opclasses, and the attnums and type OIDs of the attributes.
4763          */
4764         if (fkconstraint->pk_attrs == NIL)
4765         {
4766                 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4767                                                                                         &fkconstraint->pk_attrs,
4768                                                                                         pkattnum, pktypoid,
4769                                                                                         opclasses);
4770         }
4771         else
4772         {
4773                 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4774                                                                                  fkconstraint->pk_attrs,
4775                                                                                  pkattnum, pktypoid);
4776                 /* Look for an index matching the column list */
4777                 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4778                                                                                    opclasses);
4779         }
4780
4781         /*
4782          * Now we can check permissions.
4783          */
4784         checkFkeyPermissions(pkrel, pkattnum, numpks);
4785         checkFkeyPermissions(rel, fkattnum, numfks);
4786
4787         /*
4788          * Look up the equality operators to use in the constraint.
4789          *
4790          * Note that we have to be careful about the difference between the actual
4791          * PK column type and the opclass' declared input type, which might be
4792          * only binary-compatible with it.      The declared opcintype is the right
4793          * thing to probe pg_amop with.
4794          */
4795         if (numfks != numpks)
4796                 ereport(ERROR,
4797                                 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4798                                  errmsg("number of referencing and referenced columns for foreign key disagree")));
4799
4800         for (i = 0; i < numpks; i++)
4801         {
4802                 Oid                     pktype = pktypoid[i];
4803                 Oid                     fktype = fktypoid[i];
4804                 Oid                     fktyped;
4805                 HeapTuple       cla_ht;
4806                 Form_pg_opclass cla_tup;
4807                 Oid                     amid;
4808                 Oid                     opfamily;
4809                 Oid                     opcintype;
4810                 Oid                     pfeqop;
4811                 Oid                     ppeqop;
4812                 Oid                     ffeqop;
4813                 int16           eqstrategy;
4814
4815                 /* We need several fields out of the pg_opclass entry */
4816                 cla_ht = SearchSysCache(CLAOID,
4817                                                                 ObjectIdGetDatum(opclasses[i]),
4818                                                                 0, 0, 0);
4819                 if (!HeapTupleIsValid(cla_ht))
4820                         elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4821                 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4822                 amid = cla_tup->opcmethod;
4823                 opfamily = cla_tup->opcfamily;
4824                 opcintype = cla_tup->opcintype;
4825                 ReleaseSysCache(cla_ht);
4826
4827                 /*
4828                  * Check it's a btree; currently this can never fail since no other
4829                  * index AMs support unique indexes.  If we ever did have other types
4830                  * of unique indexes, we'd need a way to determine which operator
4831                  * strategy number is equality.  (Is it reasonable to insist that
4832                  * every such index AM use btree's number for equality?)
4833                  */
4834                 if (amid != BTREE_AM_OID)
4835                         elog(ERROR, "only b-tree indexes are supported for foreign keys");
4836                 eqstrategy = BTEqualStrategyNumber;
4837
4838                 /*
4839                  * There had better be a primary equality operator for the index.
4840                  * We'll use it for PK = PK comparisons.
4841                  */
4842                 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4843                                                                          eqstrategy);
4844
4845                 if (!OidIsValid(ppeqop))
4846                         elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4847                                  eqstrategy, opcintype, opcintype, opfamily);
4848
4849                 /*
4850                  * Are there equality operators that take exactly the FK type? Assume
4851                  * we should look through any domain here.
4852                  */
4853                 fktyped = getBaseType(fktype);
4854
4855                 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4856                                                                          eqstrategy);
4857                 if (OidIsValid(pfeqop))
4858                         ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4859                                                                                  eqstrategy);
4860                 else
4861                         ffeqop = InvalidOid;    /* keep compiler quiet */
4862
4863                 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4864                 {
4865                         /*
4866                          * Otherwise, look for an implicit cast from the FK type to the
4867                          * opcintype, and if found, use the primary equality operator.
4868                          * This is a bit tricky because opcintype might be a polymorphic
4869                          * type such as ANYARRAY or ANYENUM; so what we have to test is
4870                          * whether the two actual column types can be concurrently cast to
4871                          * that type.  (Otherwise, we'd fail to reject combinations such
4872                          * as int[] and point[].)
4873                          */
4874                         Oid                     input_typeids[2];
4875                         Oid                     target_typeids[2];
4876
4877                         input_typeids[0] = pktype;
4878                         input_typeids[1] = fktype;
4879                         target_typeids[0] = opcintype;
4880                         target_typeids[1] = opcintype;
4881                         if (can_coerce_type(2, input_typeids, target_typeids,
4882                                                                 COERCION_IMPLICIT))
4883                                 pfeqop = ffeqop = ppeqop;
4884                 }
4885
4886                 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4887                         ereport(ERROR,
4888                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
4889                                          errmsg("foreign key constraint \"%s\" "
4890                                                         "cannot be implemented",
4891                                                         fkconstraint->conname),
4892                                          errdetail("Key columns \"%s\" and \"%s\" "
4893                                                            "are of incompatible types: %s and %s.",
4894                                                            strVal(list_nth(fkconstraint->fk_attrs, i)),
4895                                                            strVal(list_nth(fkconstraint->pk_attrs, i)),
4896                                                            format_type_be(fktype),
4897                                                            format_type_be(pktype))));
4898
4899                 pfeqoperators[i] = pfeqop;
4900                 ppeqoperators[i] = ppeqop;
4901                 ffeqoperators[i] = ffeqop;
4902         }
4903
4904         /*
4905          * Record the FK constraint in pg_constraint.
4906          */
4907         constrOid = CreateConstraintEntry(fkconstraint->conname,
4908                                                                           RelationGetNamespace(rel),
4909                                                                           CONSTRAINT_FOREIGN,
4910                                                                           fkconstraint->deferrable,
4911                                                                           fkconstraint->initdeferred,
4912                                                                           RelationGetRelid(rel),
4913                                                                           fkattnum,
4914                                                                           numfks,
4915                                                                           InvalidOid,           /* not a domain
4916                                                                                                                  * constraint */
4917                                                                           indexOid,
4918                                                                           RelationGetRelid(pkrel),
4919                                                                           pkattnum,
4920                                                                           pfeqoperators,
4921                                                                           ppeqoperators,
4922                                                                           ffeqoperators,
4923                                                                           numpks,
4924                                                                           fkconstraint->fk_upd_action,
4925                                                                           fkconstraint->fk_del_action,
4926                                                                           fkconstraint->fk_matchtype,
4927                                                                           NULL,         /* no check constraint */
4928                                                                           NULL,
4929                                                                           NULL,
4930                                                                           true,         /* islocal */
4931                                                                           0);           /* inhcount */
4932
4933         /*
4934          * Create the triggers that will enforce the constraint.
4935          */
4936         createForeignKeyTriggers(rel, fkconstraint, constrOid, indexOid);
4937
4938         /*
4939          * Tell Phase 3 to check that the constraint is satisfied by existing rows
4940          * (we can skip this during table creation).
4941          */
4942         if (!fkconstraint->skip_validation)
4943         {
4944                 NewConstraint *newcon;
4945
4946                 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4947                 newcon->name = fkconstraint->conname;
4948                 newcon->contype = CONSTR_FOREIGN;
4949                 newcon->refrelid = RelationGetRelid(pkrel);
4950                 newcon->refindid = indexOid;
4951                 newcon->conid = constrOid;
4952                 newcon->qual = (Node *) fkconstraint;
4953
4954                 tab->constraints = lappend(tab->constraints, newcon);
4955         }
4956
4957         /*
4958          * Close pk table, but keep lock until we've committed.
4959          */
4960         heap_close(pkrel, NoLock);
4961 }
4962
4963
4964 /*
4965  * transformColumnNameList - transform list of column names
4966  *
4967  * Lookup each name and return its attnum and type OID
4968  */
4969 static int
4970 transformColumnNameList(Oid relId, List *colList,
4971                                                 int16 *attnums, Oid *atttypids)
4972 {
4973         ListCell   *l;
4974         int                     attnum;
4975
4976         attnum = 0;
4977         foreach(l, colList)
4978         {
4979                 char       *attname = strVal(lfirst(l));
4980                 HeapTuple       atttuple;
4981
4982                 atttuple = SearchSysCacheAttName(relId, attname);
4983                 if (!HeapTupleIsValid(atttuple))
4984                         ereport(ERROR,
4985                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4986                                          errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4987                                                         attname)));
4988                 if (attnum >= INDEX_MAX_KEYS)
4989                         ereport(ERROR,
4990                                         (errcode(ERRCODE_TOO_MANY_COLUMNS),
4991                                          errmsg("cannot have more than %d keys in a foreign key",
4992                                                         INDEX_MAX_KEYS)));
4993                 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4994                 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4995                 ReleaseSysCache(atttuple);
4996                 attnum++;
4997         }
4998
4999         return attnum;
5000 }
5001
5002 /*
5003  * transformFkeyGetPrimaryKey -
5004  *
5005  *      Look up the names, attnums, and types of the primary key attributes
5006  *      for the pkrel.  Also return the index OID and index opclasses of the
5007  *      index supporting the primary key.
5008  *
5009  *      All parameters except pkrel are output parameters.      Also, the function
5010  *      return value is the number of attributes in the primary key.
5011  *
5012  *      Used when the column list in the REFERENCES specification is omitted.
5013  */
5014 static int
5015 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
5016                                                    List **attnamelist,
5017                                                    int16 *attnums, Oid *atttypids,
5018                                                    Oid *opclasses)
5019 {
5020         List       *indexoidlist;
5021         ListCell   *indexoidscan;
5022         HeapTuple       indexTuple = NULL;
5023         Form_pg_index indexStruct = NULL;
5024         Datum           indclassDatum;
5025         bool            isnull;
5026         oidvector  *indclass;
5027         int                     i;
5028
5029         /*
5030          * Get the list of index OIDs for the table from the relcache, and look up
5031          * each one in the pg_index syscache until we find one marked primary key
5032          * (hopefully there isn't more than one such).
5033          */
5034         *indexOid = InvalidOid;
5035
5036         indexoidlist = RelationGetIndexList(pkrel);
5037
5038         foreach(indexoidscan, indexoidlist)
5039         {
5040                 Oid                     indexoid = lfirst_oid(indexoidscan);
5041
5042                 indexTuple = SearchSysCache(INDEXRELID,
5043                                                                         ObjectIdGetDatum(indexoid),
5044                                                                         0, 0, 0);
5045                 if (!HeapTupleIsValid(indexTuple))
5046                         elog(ERROR, "cache lookup failed for index %u", indexoid);
5047                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5048                 if (indexStruct->indisprimary)
5049                 {
5050                         /*
5051                          * Refuse to use a deferrable primary key.  This is per SQL spec,
5052                          * and there would be a lot of interesting semantic problems if
5053                          * we tried to allow it.
5054                          */
5055                         if (!indexStruct->indimmediate)
5056                                 ereport(ERROR,
5057                                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5058                                                  errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
5059                                                                 RelationGetRelationName(pkrel))));
5060
5061                         *indexOid = indexoid;
5062                         break;
5063                 }
5064                 ReleaseSysCache(indexTuple);
5065         }
5066
5067         list_free(indexoidlist);
5068
5069         /*
5070          * Check that we found it
5071          */
5072         if (!OidIsValid(*indexOid))
5073                 ereport(ERROR,
5074                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5075                                  errmsg("there is no primary key for referenced table \"%s\"",
5076                                                 RelationGetRelationName(pkrel))));
5077
5078         /* Must get indclass the hard way */
5079         indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
5080                                                                         Anum_pg_index_indclass, &isnull);
5081         Assert(!isnull);
5082         indclass = (oidvector *) DatumGetPointer(indclassDatum);
5083
5084         /*
5085          * Now build the list of PK attributes from the indkey definition (we
5086          * assume a primary key cannot have expressional elements)
5087          */
5088         *attnamelist = NIL;
5089         for (i = 0; i < indexStruct->indnatts; i++)
5090         {
5091                 int                     pkattno = indexStruct->indkey.values[i];
5092
5093                 attnums[i] = pkattno;
5094                 atttypids[i] = attnumTypeId(pkrel, pkattno);
5095                 opclasses[i] = indclass->values[i];
5096                 *attnamelist = lappend(*attnamelist,
5097                            makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
5098         }
5099
5100         ReleaseSysCache(indexTuple);
5101
5102         return i;
5103 }
5104
5105 /*
5106  * transformFkeyCheckAttrs -
5107  *
5108  *      Make sure that the attributes of a referenced table belong to a unique
5109  *      (or primary key) constraint.  Return the OID of the index supporting
5110  *      the constraint, as well as the opclasses associated with the index
5111  *      columns.
5112  */
5113 static Oid
5114 transformFkeyCheckAttrs(Relation pkrel,
5115                                                 int numattrs, int16 *attnums,
5116                                                 Oid *opclasses) /* output parameter */
5117 {
5118         Oid                     indexoid = InvalidOid;
5119         bool            found = false;
5120         bool            found_deferrable = false;
5121         List       *indexoidlist;
5122         ListCell   *indexoidscan;
5123
5124         /*
5125          * Get the list of index OIDs for the table from the relcache, and look up
5126          * each one in the pg_index syscache, and match unique indexes to the list
5127          * of attnums we are given.
5128          */
5129         indexoidlist = RelationGetIndexList(pkrel);
5130
5131         foreach(indexoidscan, indexoidlist)
5132         {
5133                 HeapTuple       indexTuple;
5134                 Form_pg_index indexStruct;
5135                 int                     i,
5136                                         j;
5137
5138                 indexoid = lfirst_oid(indexoidscan);
5139                 indexTuple = SearchSysCache(INDEXRELID,
5140                                                                         ObjectIdGetDatum(indexoid),
5141                                                                         0, 0, 0);
5142                 if (!HeapTupleIsValid(indexTuple))
5143                         elog(ERROR, "cache lookup failed for index %u", indexoid);
5144                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5145
5146                 /*
5147                  * Must have the right number of columns; must be unique and not a
5148                  * partial index; forget it if there are any expressions, too
5149                  */
5150                 if (indexStruct->indnatts == numattrs &&
5151                         indexStruct->indisunique &&
5152                         heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
5153                         heap_attisnull(indexTuple, Anum_pg_index_indexprs))
5154                 {
5155                         /* Must get indclass the hard way */
5156                         Datum           indclassDatum;
5157                         bool            isnull;
5158                         oidvector  *indclass;
5159
5160                         indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
5161                                                                                         Anum_pg_index_indclass, &isnull);
5162                         Assert(!isnull);
5163                         indclass = (oidvector *) DatumGetPointer(indclassDatum);
5164
5165                         /*
5166                          * The given attnum list may match the index columns in any order.
5167                          * Check that each list is a subset of the other.
5168                          */
5169                         for (i = 0; i < numattrs; i++)
5170                         {
5171                                 found = false;
5172                                 for (j = 0; j < numattrs; j++)
5173                                 {
5174                                         if (attnums[i] == indexStruct->indkey.values[j])
5175                                         {
5176                                                 found = true;
5177                                                 break;
5178                                         }
5179                                 }
5180                                 if (!found)
5181                                         break;
5182                         }
5183                         if (found)
5184                         {
5185                                 for (i = 0; i < numattrs; i++)
5186                                 {
5187                                         found = false;
5188                                         for (j = 0; j < numattrs; j++)
5189                                         {
5190                                                 if (attnums[j] == indexStruct->indkey.values[i])
5191                                                 {
5192                                                         opclasses[j] = indclass->values[i];
5193                                                         found = true;
5194                                                         break;
5195                                                 }
5196                                         }
5197                                         if (!found)
5198                                                 break;
5199                                 }
5200                         }
5201
5202                         /*
5203                          * Refuse to use a deferrable unique/primary key.  This is per
5204                          * SQL spec, and there would be a lot of interesting semantic
5205                          * problems if we tried to allow it.
5206                          */
5207                         if (found && !indexStruct->indimmediate)
5208                         {
5209                                 /*
5210                                  * Remember that we found an otherwise matching index, so
5211                                  * that we can generate a more appropriate error message.
5212                                  */
5213                                 found_deferrable = true;
5214                                 found = false;
5215                         }
5216                 }
5217                 ReleaseSysCache(indexTuple);
5218                 if (found)
5219                         break;
5220         }
5221
5222         if (!found)
5223         {
5224                 if (found_deferrable)
5225                         ereport(ERROR,
5226                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5227                                          errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
5228                                                         RelationGetRelationName(pkrel))));
5229                 else
5230                         ereport(ERROR,
5231                                         (errcode(ERRCODE_INVALID_FOREIGN_KEY),
5232                                          errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
5233                                                         RelationGetRelationName(pkrel))));
5234         }
5235
5236         list_free(indexoidlist);
5237
5238         return indexoid;
5239 }
5240
5241 /* Permissions checks for ADD FOREIGN KEY */
5242 static void
5243 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
5244 {
5245         Oid                     roleid = GetUserId();
5246         AclResult       aclresult;
5247         int                     i;
5248
5249         /* Okay if we have relation-level REFERENCES permission */
5250         aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
5251                                                                   ACL_REFERENCES);
5252         if (aclresult == ACLCHECK_OK)
5253                 return;
5254         /* Else we must have REFERENCES on each column */
5255         for (i = 0; i < natts; i++)
5256         {
5257                 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
5258                                                                                   roleid, ACL_REFERENCES);
5259                 if (aclresult != ACLCHECK_OK)
5260                         aclcheck_error(aclresult, ACL_KIND_CLASS,
5261                                                    RelationGetRelationName(rel));
5262         }
5263 }
5264
5265 /*
5266  * Scan the existing rows in a table to verify they meet a proposed FK
5267  * constraint.
5268  *
5269  * Caller must have opened and locked both relations.
5270  */
5271 static void
5272 validateForeignKeyConstraint(Constraint *fkconstraint,
5273                                                          Relation rel,
5274                                                          Relation pkrel,
5275                                                          Oid pkindOid,
5276                                                          Oid constraintOid)
5277 {
5278         HeapScanDesc scan;
5279         HeapTuple       tuple;
5280         Trigger         trig;
5281
5282         /*
5283          * Build a trigger call structure; we'll need it either way.
5284          */
5285         MemSet(&trig, 0, sizeof(trig));
5286         trig.tgoid = InvalidOid;
5287         trig.tgname = fkconstraint->conname;
5288         trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
5289         trig.tgisconstraint = TRUE;
5290         trig.tgconstrrelid = RelationGetRelid(pkrel);
5291         trig.tgconstrindid = pkindOid;
5292         trig.tgconstraint = constraintOid;
5293         trig.tgdeferrable = FALSE;
5294         trig.tginitdeferred = FALSE;
5295         /* we needn't fill in tgargs */
5296
5297         /*
5298          * See if we can do it with a single LEFT JOIN query.  A FALSE result
5299          * indicates we must proceed with the fire-the-trigger method.
5300          */
5301         if (RI_Initial_Check(&trig, rel, pkrel))
5302                 return;
5303
5304         /*
5305          * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
5306          * if that tuple had just been inserted.  If any of those fail, it should
5307          * ereport(ERROR) and that's that.
5308          */
5309         scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
5310
5311         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
5312         {
5313                 FunctionCallInfoData fcinfo;
5314                 TriggerData trigdata;
5315
5316                 /*
5317                  * Make a call to the trigger function
5318                  *
5319                  * No parameters are passed, but we do set a context
5320                  */
5321                 MemSet(&fcinfo, 0, sizeof(fcinfo));
5322
5323                 /*
5324                  * We assume RI_FKey_check_ins won't look at flinfo...
5325                  */
5326                 trigdata.type = T_TriggerData;
5327                 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
5328                 trigdata.tg_relation = rel;
5329                 trigdata.tg_trigtuple = tuple;
5330                 trigdata.tg_newtuple = NULL;
5331                 trigdata.tg_trigger = &trig;
5332                 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
5333                 trigdata.tg_newtuplebuf = InvalidBuffer;
5334
5335                 fcinfo.context = (Node *) &trigdata;
5336
5337                 RI_FKey_check_ins(&fcinfo);
5338         }
5339
5340         heap_endscan(scan);
5341 }
5342
5343 static void
5344 CreateFKCheckTrigger(RangeVar *myRel, Constraint *fkconstraint,
5345                                          Oid constraintOid, Oid indexOid, bool on_insert)
5346 {
5347         CreateTrigStmt *fk_trigger;
5348
5349         fk_trigger = makeNode(CreateTrigStmt);
5350         fk_trigger->trigname = fkconstraint->conname;
5351         fk_trigger->relation = myRel;
5352         fk_trigger->before = false;
5353         fk_trigger->row = true;
5354
5355         /* Either ON INSERT or ON UPDATE */
5356         if (on_insert)
5357         {
5358                 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
5359                 fk_trigger->events = TRIGGER_TYPE_INSERT;
5360         }
5361         else
5362         {
5363                 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
5364                 fk_trigger->events = TRIGGER_TYPE_UPDATE;
5365         }
5366
5367         fk_trigger->isconstraint = true;
5368         fk_trigger->deferrable = fkconstraint->deferrable;
5369         fk_trigger->initdeferred = fkconstraint->initdeferred;
5370         fk_trigger->constrrel = fkconstraint->pktable;
5371         fk_trigger->args = NIL;
5372
5373         (void) CreateTrigger(fk_trigger, constraintOid, indexOid,
5374                                                  "RI_ConstraintTrigger", false);
5375
5376         /* Make changes-so-far visible */
5377         CommandCounterIncrement();
5378 }
5379
5380 /*
5381  * Create the triggers that implement an FK constraint.
5382  */
5383 static void
5384 createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
5385                                                  Oid constraintOid, Oid indexOid)
5386 {
5387         RangeVar   *myRel;
5388         CreateTrigStmt *fk_trigger;
5389
5390         /*
5391          * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
5392          */
5393         myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5394                                                  pstrdup(RelationGetRelationName(rel)),
5395                                                  -1);
5396
5397         /* Make changes-so-far visible */
5398         CommandCounterIncrement();
5399
5400         /*
5401          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
5402          * action for both INSERTs and UPDATEs on the referencing table.
5403          */
5404         CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, true);
5405         CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, false);
5406
5407         /*
5408          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5409          * DELETE action on the referenced table.
5410          */
5411         fk_trigger = makeNode(CreateTrigStmt);
5412         fk_trigger->trigname = fkconstraint->conname;
5413         fk_trigger->relation = fkconstraint->pktable;
5414         fk_trigger->before = false;
5415         fk_trigger->row = true;
5416         fk_trigger->events = TRIGGER_TYPE_DELETE;
5417         fk_trigger->isconstraint = true;
5418         fk_trigger->constrrel = myRel;
5419         switch (fkconstraint->fk_del_action)
5420         {
5421                 case FKCONSTR_ACTION_NOACTION:
5422                         fk_trigger->deferrable = fkconstraint->deferrable;
5423                         fk_trigger->initdeferred = fkconstraint->initdeferred;
5424                         fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
5425                         break;
5426                 case FKCONSTR_ACTION_RESTRICT:
5427                         fk_trigger->deferrable = false;
5428                         fk_trigger->initdeferred = false;
5429                         fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
5430                         break;
5431                 case FKCONSTR_ACTION_CASCADE:
5432                         fk_trigger->deferrable = false;
5433                         fk_trigger->initdeferred = false;
5434                         fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
5435                         break;
5436                 case FKCONSTR_ACTION_SETNULL:
5437                         fk_trigger->deferrable = false;
5438                         fk_trigger->initdeferred = false;
5439                         fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
5440                         break;
5441                 case FKCONSTR_ACTION_SETDEFAULT:
5442                         fk_trigger->deferrable = false;
5443                         fk_trigger->initdeferred = false;
5444                         fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
5445                         break;
5446                 default:
5447                         elog(ERROR, "unrecognized FK action type: %d",
5448                                  (int) fkconstraint->fk_del_action);
5449                         break;
5450         }
5451         fk_trigger->args = NIL;
5452
5453         (void) CreateTrigger(fk_trigger, constraintOid, indexOid,
5454                                                  "RI_ConstraintTrigger", false);
5455
5456         /* Make changes-so-far visible */
5457         CommandCounterIncrement();
5458
5459         /*
5460          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5461          * UPDATE action on the referenced table.
5462          */
5463         fk_trigger = makeNode(CreateTrigStmt);
5464         fk_trigger->trigname = fkconstraint->conname;
5465         fk_trigger->relation = fkconstraint->pktable;
5466         fk_trigger->before = false;
5467         fk_trigger->row = true;
5468         fk_trigger->events = TRIGGER_TYPE_UPDATE;
5469         fk_trigger->isconstraint = true;
5470         fk_trigger->constrrel = myRel;
5471         switch (fkconstraint->fk_upd_action)
5472         {
5473                 case FKCONSTR_ACTION_NOACTION:
5474                         fk_trigger->deferrable = fkconstraint->deferrable;
5475                         fk_trigger->initdeferred = fkconstraint->initdeferred;
5476                         fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
5477                         break;
5478                 case FKCONSTR_ACTION_RESTRICT:
5479                         fk_trigger->deferrable = false;
5480                         fk_trigger->initdeferred = false;
5481                         fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
5482                         break;
5483                 case FKCONSTR_ACTION_CASCADE:
5484                         fk_trigger->deferrable = false;
5485                         fk_trigger->initdeferred = false;
5486                         fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
5487                         break;
5488                 case FKCONSTR_ACTION_SETNULL:
5489                         fk_trigger->deferrable = false;
5490                         fk_trigger->initdeferred = false;
5491                         fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
5492                         break;
5493                 case FKCONSTR_ACTION_SETDEFAULT:
5494                         fk_trigger->deferrable = false;
5495                         fk_trigger->initdeferred = false;
5496                         fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
5497                         break;
5498                 default:
5499                         elog(ERROR, "unrecognized FK action type: %d",
5500                                  (int) fkconstraint->fk_upd_action);
5501                         break;
5502         }
5503         fk_trigger->args = NIL;
5504
5505         (void) CreateTrigger(fk_trigger, constraintOid, indexOid,
5506                                                  "RI_ConstraintTrigger", false);
5507 }
5508
5509 /*
5510  * ALTER TABLE DROP CONSTRAINT
5511  *
5512  * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
5513  */
5514 static void
5515 ATExecDropConstraint(Relation rel, const char *constrName,
5516                                          DropBehavior behavior,
5517                                          bool recurse, bool recursing,
5518                                          bool missing_ok)
5519 {
5520         List       *children;
5521         ListCell   *child;
5522         Relation        conrel;
5523         Form_pg_constraint con;
5524         SysScanDesc scan;
5525         ScanKeyData key;
5526         HeapTuple       tuple;
5527         bool            found = false;
5528         bool            is_check_constraint = false;
5529
5530         /* At top level, permission check was done in ATPrepCmd, else do it */
5531         if (recursing)
5532                 ATSimplePermissions(rel, false);
5533
5534         conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5535
5536         /*
5537          * Find and drop the target constraint
5538          */
5539         ScanKeyInit(&key,
5540                                 Anum_pg_constraint_conrelid,
5541                                 BTEqualStrategyNumber, F_OIDEQ,
5542                                 ObjectIdGetDatum(RelationGetRelid(rel)));
5543         scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5544                                                           true, SnapshotNow, 1, &key);
5545
5546         while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5547         {
5548                 ObjectAddress conobj;
5549
5550                 con = (Form_pg_constraint) GETSTRUCT(tuple);
5551
5552                 if (strcmp(NameStr(con->conname), constrName) != 0)
5553                         continue;
5554
5555                 /* Don't drop inherited constraints */
5556                 if (con->coninhcount > 0 && !recursing)
5557                         ereport(ERROR,
5558                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5559                                          errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5560                                                         constrName, RelationGetRelationName(rel))));
5561
5562                 /* Right now only CHECK constraints can be inherited */
5563                 if (con->contype == CONSTRAINT_CHECK)
5564                         is_check_constraint = true;
5565
5566                 /*
5567                  * Perform the actual constraint deletion
5568                  */
5569                 conobj.classId = ConstraintRelationId;
5570                 conobj.objectId = HeapTupleGetOid(tuple);
5571                 conobj.objectSubId = 0;
5572
5573                 performDeletion(&conobj, behavior);
5574
5575                 found = true;
5576         }
5577
5578         systable_endscan(scan);
5579
5580         if (!found){
5581                 if (!missing_ok){
5582                         ereport(ERROR,
5583                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
5584                                          errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5585                                                         constrName, RelationGetRelationName(rel))));
5586                 }
5587                 else
5588                 {
5589                         ereport(NOTICE,
5590                                         (errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
5591                                                         constrName, RelationGetRelationName(rel))));
5592                         heap_close(conrel, RowExclusiveLock);
5593                         return;
5594                 }
5595         }
5596         /*
5597          * Propagate to children as appropriate.  Unlike most other ALTER
5598          * routines, we have to do this one level of recursion at a time; we can't
5599          * use find_all_inheritors to do it in one pass.
5600          */
5601         if (is_check_constraint)
5602                 children = find_inheritance_children(RelationGetRelid(rel),
5603                                                                                          AccessExclusiveLock);
5604         else
5605                 children = NIL;
5606
5607         foreach(child, children)
5608         {
5609                 Oid                     childrelid = lfirst_oid(child);
5610                 Relation        childrel;
5611
5612                 /* find_inheritance_children already got lock */
5613                 childrel = heap_open(childrelid, NoLock);
5614                 CheckTableNotInUse(childrel, "ALTER TABLE");
5615
5616                 ScanKeyInit(&key,
5617                                         Anum_pg_constraint_conrelid,
5618                                         BTEqualStrategyNumber, F_OIDEQ,
5619                                         ObjectIdGetDatum(childrelid));
5620                 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5621                                                                   true, SnapshotNow, 1, &key);
5622
5623                 found = false;
5624
5625                 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5626                 {
5627                         HeapTuple       copy_tuple;
5628
5629                         con = (Form_pg_constraint) GETSTRUCT(tuple);
5630
5631                         /* Right now only CHECK constraints can be inherited */
5632                         if (con->contype != CONSTRAINT_CHECK)
5633                                 continue;
5634
5635                         if (strcmp(NameStr(con->conname), constrName) != 0)
5636                                 continue;
5637
5638                         found = true;
5639
5640                         if (con->coninhcount <= 0)      /* shouldn't happen */
5641                                 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
5642                                          childrelid, constrName);
5643
5644                         copy_tuple = heap_copytuple(tuple);
5645                         con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
5646
5647                         if (recurse)
5648                         {
5649                                 /*
5650                                  * If the child constraint has other definition sources, just
5651                                  * decrement its inheritance count; if not, recurse to delete
5652                                  * it.
5653                                  */
5654                                 if (con->coninhcount == 1 && !con->conislocal)
5655                                 {
5656                                         /* Time to delete this child constraint, too */
5657                                         ATExecDropConstraint(childrel, constrName, behavior,
5658                                                                                  true, true,
5659                                                                                  false);
5660                                 }
5661                                 else
5662                                 {
5663                                         /* Child constraint must survive my deletion */
5664                                         con->coninhcount--;
5665                                         simple_heap_update(conrel, &copy_tuple->t_self, copy_tuple);
5666                                         CatalogUpdateIndexes(conrel, copy_tuple);
5667
5668                                         /* Make update visible */
5669                                         CommandCounterIncrement();
5670                                 }
5671                         }
5672                         else
5673                         {
5674                                 /*
5675                                  * If we were told to drop ONLY in this table (no recursion),
5676                                  * we need to mark the inheritors' constraints as locally
5677                                  * defined rather than inherited.
5678                                  */
5679                                 con->coninhcount--;
5680                                 con->conislocal = true;
5681
5682                                 simple_heap_update(conrel, &copy_tuple->t_self, copy_tuple);
5683                                 CatalogUpdateIndexes(conrel, copy_tuple);
5684
5685                                 /* Make update visible */
5686                                 CommandCounterIncrement();
5687                         }
5688
5689                         heap_freetuple(copy_tuple);
5690                 }
5691
5692                 systable_endscan(scan);
5693
5694                 if (!found)
5695                         ereport(ERROR,
5696                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
5697                                 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5698                                            constrName,
5699                                            RelationGetRelationName(childrel))));
5700
5701                 heap_close(childrel, NoLock);
5702         }
5703
5704         heap_close(conrel, RowExclusiveLock);
5705 }
5706
5707 /*
5708  * ALTER COLUMN TYPE
5709  */
5710 static void
5711 ATPrepAlterColumnType(List **wqueue,
5712                                           AlteredTableInfo *tab, Relation rel,
5713                                           bool recurse, bool recursing,
5714                                           AlterTableCmd *cmd)
5715 {
5716         char       *colName = cmd->name;
5717         TypeName   *typeName = (TypeName *) cmd->def;
5718         HeapTuple       tuple;
5719         Form_pg_attribute attTup;
5720         AttrNumber      attnum;
5721         Oid                     targettype;
5722         int32           targettypmod;
5723         Node       *transform;
5724         NewColumnValue *newval;
5725         ParseState *pstate = make_parsestate(NULL);
5726
5727         /* lookup the attribute so we can check inheritance status */
5728         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5729         if (!HeapTupleIsValid(tuple))
5730                 ereport(ERROR,
5731                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5732                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5733                                                 colName, RelationGetRelationName(rel))));
5734         attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5735         attnum = attTup->attnum;
5736
5737         /* Can't alter a system attribute */
5738         if (attnum <= 0)
5739                 ereport(ERROR,
5740                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5741                                  errmsg("cannot alter system column \"%s\"",
5742                                                 colName)));
5743
5744         /* Don't alter inherited columns */
5745         if (attTup->attinhcount > 0 && !recursing)
5746                 ereport(ERROR,
5747                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5748                                  errmsg("cannot alter inherited column \"%s\"",
5749                                                 colName)));
5750
5751         /* Look up the target type */
5752         targettype = typenameTypeId(NULL, typeName, &targettypmod);
5753
5754         /* make sure datatype is legal for a column */
5755         CheckAttributeType(colName, targettype);
5756
5757         /*
5758          * Set up an expression to transform the old data value to the new type.
5759          * If a USING option was given, transform and use that expression, else
5760          * just take the old value and try to coerce it.  We do this first so that
5761          * type incompatibility can be detected before we waste effort, and
5762          * because we need the expression to be parsed against the original table
5763          * rowtype.
5764          */
5765         if (cmd->transform)
5766         {
5767                 RangeTblEntry *rte;
5768
5769                 /* Expression must be able to access vars of old table */
5770                 rte = addRangeTableEntryForRelation(pstate,
5771                                                                                         rel,
5772                                                                                         NULL,
5773                                                                                         false,
5774                                                                                         true);
5775                 addRTEtoQuery(pstate, rte, false, true, true);
5776
5777                 transform = transformExpr(pstate, cmd->transform);
5778
5779                 /* It can't return a set */
5780                 if (expression_returns_set(transform))
5781                         ereport(ERROR,
5782                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
5783                                          errmsg("transform expression must not return a set")));
5784
5785                 /* No subplans or aggregates, either... */
5786                 if (pstate->p_hasSubLinks)
5787                         ereport(ERROR,
5788                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5789                                          errmsg("cannot use subquery in transform expression")));
5790                 if (pstate->p_hasAggs)
5791                         ereport(ERROR,
5792                                         (errcode(ERRCODE_GROUPING_ERROR),
5793                         errmsg("cannot use aggregate function in transform expression")));
5794                 if (pstate->p_hasWindowFuncs)
5795                         ereport(ERROR,
5796                                         (errcode(ERRCODE_WINDOWING_ERROR),
5797                           errmsg("cannot use window function in transform expression")));
5798         }
5799         else
5800         {
5801                 transform = (Node *) makeVar(1, attnum,
5802                                                                          attTup->atttypid, attTup->atttypmod,
5803                                                                          0);
5804         }
5805
5806         transform = coerce_to_target_type(pstate,
5807                                                                           transform, exprType(transform),
5808                                                                           targettype, targettypmod,
5809                                                                           COERCION_ASSIGNMENT,
5810                                                                           COERCE_IMPLICIT_CAST,
5811                                                                           -1);
5812         if (transform == NULL)
5813                 ereport(ERROR,
5814                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
5815                                  errmsg("column \"%s\" cannot be cast to type %s",
5816                                                 colName, format_type_be(targettype))));
5817
5818         /*
5819          * Add a work queue item to make ATRewriteTable update the column
5820          * contents.
5821          */
5822         newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5823         newval->attnum = attnum;
5824         newval->expr = (Expr *) transform;
5825
5826         tab->newvals = lappend(tab->newvals, newval);
5827
5828         ReleaseSysCache(tuple);
5829
5830         /*
5831          * The recursion case is handled by ATSimpleRecursion.  However, if we are
5832          * told not to recurse, there had better not be any child tables; else the
5833          * alter would put them out of step.
5834          */
5835         if (recurse)
5836                 ATSimpleRecursion(wqueue, rel, cmd, recurse);
5837         else if (!recursing &&
5838                          find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
5839                 ereport(ERROR,
5840                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5841                                  errmsg("type of inherited column \"%s\" must be changed in child tables too",
5842                                                 colName)));
5843 }
5844
5845 static void
5846 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
5847                                           const char *colName, TypeName *typeName)
5848 {
5849         HeapTuple       heapTup;
5850         Form_pg_attribute attTup;
5851         AttrNumber      attnum;
5852         HeapTuple       typeTuple;
5853         Form_pg_type tform;
5854         Oid                     targettype;
5855         int32           targettypmod;
5856         Node       *defaultexpr;
5857         Relation        attrelation;
5858         Relation        depRel;
5859         ScanKeyData key[3];
5860         SysScanDesc scan;
5861         HeapTuple       depTup;
5862
5863         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5864
5865         /* Look up the target column */
5866         heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5867         if (!HeapTupleIsValid(heapTup))         /* shouldn't happen */
5868                 ereport(ERROR,
5869                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5870                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5871                                                 colName, RelationGetRelationName(rel))));
5872         attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5873         attnum = attTup->attnum;
5874
5875         /* Check for multiple ALTER TYPE on same column --- can't cope */
5876         if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5877                 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5878                 ereport(ERROR,
5879                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5880                                  errmsg("cannot alter type of column \"%s\" twice",
5881                                                 colName)));
5882
5883         /* Look up the target type (should not fail, since prep found it) */
5884         typeTuple = typenameType(NULL, typeName, &targettypmod);
5885         tform = (Form_pg_type) GETSTRUCT(typeTuple);
5886         targettype = HeapTupleGetOid(typeTuple);
5887
5888         /*
5889          * If there is a default expression for the column, get it and ensure we
5890          * can coerce it to the new datatype.  (We must do this before changing
5891          * the column type, because build_column_default itself will try to
5892          * coerce, and will not issue the error message we want if it fails.)
5893          *
5894          * We remove any implicit coercion steps at the top level of the old
5895          * default expression; this has been agreed to satisfy the principle of
5896          * least surprise.      (The conversion to the new column type should act like
5897          * it started from what the user sees as the stored expression, and the
5898          * implicit coercions aren't going to be shown.)
5899          */
5900         if (attTup->atthasdef)
5901         {
5902                 defaultexpr = build_column_default(rel, attnum);
5903                 Assert(defaultexpr);
5904                 defaultexpr = strip_implicit_coercions(defaultexpr);
5905                 defaultexpr = coerce_to_target_type(NULL,               /* no UNKNOWN params */
5906                                                                                   defaultexpr, exprType(defaultexpr),
5907                                                                                         targettype, targettypmod,
5908                                                                                         COERCION_ASSIGNMENT,
5909                                                                                         COERCE_IMPLICIT_CAST,
5910                                                                                         -1);
5911                 if (defaultexpr == NULL)
5912                         ereport(ERROR,
5913                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
5914                                 errmsg("default for column \"%s\" cannot be cast to type %s",
5915                                            colName, format_type_be(targettype))));
5916         }
5917         else
5918                 defaultexpr = NULL;
5919
5920         /*
5921          * Find everything that depends on the column (constraints, indexes, etc),
5922          * and record enough information to let us recreate the objects.
5923          *
5924          * The actual recreation does not happen here, but only after we have
5925          * performed all the individual ALTER TYPE operations.  We have to save
5926          * the info before executing ALTER TYPE, though, else the deparser will
5927          * get confused.
5928          *
5929          * There could be multiple entries for the same object, so we must check
5930          * to ensure we process each one only once.  Note: we assume that an index
5931          * that implements a constraint will not show a direct dependency on the
5932          * column.
5933          */
5934         depRel = heap_open(DependRelationId, RowExclusiveLock);
5935
5936         ScanKeyInit(&key[0],
5937                                 Anum_pg_depend_refclassid,
5938                                 BTEqualStrategyNumber, F_OIDEQ,
5939                                 ObjectIdGetDatum(RelationRelationId));
5940         ScanKeyInit(&key[1],
5941                                 Anum_pg_depend_refobjid,
5942                                 BTEqualStrategyNumber, F_OIDEQ,
5943                                 ObjectIdGetDatum(RelationGetRelid(rel)));
5944         ScanKeyInit(&key[2],
5945                                 Anum_pg_depend_refobjsubid,
5946                                 BTEqualStrategyNumber, F_INT4EQ,
5947                                 Int32GetDatum((int32) attnum));
5948
5949         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5950                                                           SnapshotNow, 3, key);
5951
5952         while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5953         {
5954                 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5955                 ObjectAddress foundObject;
5956
5957                 /* We don't expect any PIN dependencies on columns */
5958                 if (foundDep->deptype == DEPENDENCY_PIN)
5959                         elog(ERROR, "cannot alter type of a pinned column");
5960
5961                 foundObject.classId = foundDep->classid;
5962                 foundObject.objectId = foundDep->objid;
5963                 foundObject.objectSubId = foundDep->objsubid;
5964
5965                 switch (getObjectClass(&foundObject))
5966                 {
5967                         case OCLASS_CLASS:
5968                                 {
5969                                         char            relKind = get_rel_relkind(foundObject.objectId);
5970
5971                                         if (relKind == RELKIND_INDEX)
5972                                         {
5973                                                 Assert(foundObject.objectSubId == 0);
5974                                                 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5975                                                 {
5976                                                         tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5977                                                                                                            foundObject.objectId);
5978                                                         tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5979                                                            pg_get_indexdef_string(foundObject.objectId));
5980                                                 }
5981                                         }
5982                                         else if (relKind == RELKIND_SEQUENCE)
5983                                         {
5984                                                 /*
5985                                                  * This must be a SERIAL column's sequence.  We need
5986                                                  * not do anything to it.
5987                                                  */
5988                                                 Assert(foundObject.objectSubId == 0);
5989                                         }
5990                                         else
5991                                         {
5992                                                 /* Not expecting any other direct dependencies... */
5993                                                 elog(ERROR, "unexpected object depending on column: %s",
5994                                                          getObjectDescription(&foundObject));
5995                                         }
5996                                         break;
5997                                 }
5998
5999                         case OCLASS_CONSTRAINT:
6000                                 Assert(foundObject.objectSubId == 0);
6001                                 if (!list_member_oid(tab->changedConstraintOids,
6002                                                                          foundObject.objectId))
6003                                 {
6004                                         char       *defstring = pg_get_constraintdef_string(foundObject.objectId);
6005
6006                                         /*
6007                                          * Put NORMAL dependencies at the front of the list and
6008                                          * AUTO dependencies at the back.  This makes sure that
6009                                          * foreign-key constraints depending on this column will
6010                                          * be dropped before unique or primary-key constraints of
6011                                          * the column; which we must have because the FK
6012                                          * constraints depend on the indexes belonging to the
6013                                          * unique constraints.
6014                                          */
6015                                         if (foundDep->deptype == DEPENDENCY_NORMAL)
6016                                         {
6017                                                 tab->changedConstraintOids =
6018                                                         lcons_oid(foundObject.objectId,
6019                                                                           tab->changedConstraintOids);
6020                                                 tab->changedConstraintDefs =
6021                                                         lcons(defstring,
6022                                                                   tab->changedConstraintDefs);
6023                                         }
6024                                         else
6025                                         {
6026                                                 tab->changedConstraintOids =
6027                                                         lappend_oid(tab->changedConstraintOids,
6028                                                                                 foundObject.objectId);
6029                                                 tab->changedConstraintDefs =
6030                                                         lappend(tab->changedConstraintDefs,
6031                                                                         defstring);
6032                                         }
6033                                 }
6034                                 break;
6035
6036                         case OCLASS_REWRITE:
6037                                 /* XXX someday see if we can cope with revising views */
6038                                 ereport(ERROR,
6039                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6040                                                  errmsg("cannot alter type of a column used by a view or rule"),
6041                                                  errdetail("%s depends on column \"%s\"",
6042                                                                    getObjectDescription(&foundObject),
6043                                                                    colName)));
6044                                 break;
6045
6046                         case OCLASS_DEFAULT:
6047
6048                                 /*
6049                                  * Ignore the column's default expression, since we will fix
6050                                  * it below.
6051                                  */
6052                                 Assert(defaultexpr);
6053                                 break;
6054
6055                         case OCLASS_PROC:
6056                         case OCLASS_TYPE:
6057                         case OCLASS_CAST:
6058                         case OCLASS_CONVERSION:
6059                         case OCLASS_LANGUAGE:
6060                         case OCLASS_OPERATOR:
6061                         case OCLASS_OPCLASS:
6062                         case OCLASS_OPFAMILY:
6063                         case OCLASS_AMOP:
6064                         case OCLASS_AMPROC:
6065                         case OCLASS_TRIGGER:
6066                         case OCLASS_SCHEMA:
6067                         case OCLASS_TSPARSER:
6068                         case OCLASS_TSDICT:
6069                         case OCLASS_TSTEMPLATE:
6070                         case OCLASS_TSCONFIG:
6071                         case OCLASS_ROLE:
6072                         case OCLASS_DATABASE:
6073                         case OCLASS_TBLSPACE:
6074                         case OCLASS_FDW:
6075                         case OCLASS_FOREIGN_SERVER:
6076                         case OCLASS_USER_MAPPING:
6077
6078                                 /*
6079                                  * We don't expect any of these sorts of objects to depend on
6080                                  * a column.
6081                                  */
6082                                 elog(ERROR, "unexpected object depending on column: %s",
6083                                          getObjectDescription(&foundObject));
6084                                 break;
6085
6086                         default:
6087                                 elog(ERROR, "unrecognized object class: %u",
6088                                          foundObject.classId);
6089                 }
6090         }
6091
6092         systable_endscan(scan);
6093
6094         /*
6095          * Now scan for dependencies of this column on other things.  The only
6096          * thing we should find is the dependency on the column datatype, which we
6097          * want to remove.
6098          */
6099         ScanKeyInit(&key[0],
6100                                 Anum_pg_depend_classid,
6101                                 BTEqualStrategyNumber, F_OIDEQ,
6102                                 ObjectIdGetDatum(RelationRelationId));
6103         ScanKeyInit(&key[1],
6104                                 Anum_pg_depend_objid,
6105                                 BTEqualStrategyNumber, F_OIDEQ,
6106                                 ObjectIdGetDatum(RelationGetRelid(rel)));
6107         ScanKeyInit(&key[2],
6108                                 Anum_pg_depend_objsubid,
6109                                 BTEqualStrategyNumber, F_INT4EQ,
6110                                 Int32GetDatum((int32) attnum));
6111
6112         scan = systable_beginscan(depRel, DependDependerIndexId, true,
6113                                                           SnapshotNow, 3, key);
6114
6115         while (HeapTupleIsValid(depTup = systable_getnext(scan)))
6116         {
6117                 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
6118
6119                 if (foundDep->deptype != DEPENDENCY_NORMAL)
6120                         elog(ERROR, "found unexpected dependency type '%c'",
6121                                  foundDep->deptype);
6122                 if (foundDep->refclassid != TypeRelationId ||
6123                         foundDep->refobjid != attTup->atttypid)
6124                         elog(ERROR, "found unexpected dependency for column");
6125
6126                 simple_heap_delete(depRel, &depTup->t_self);
6127         }
6128
6129         systable_endscan(scan);
6130
6131         heap_close(depRel, RowExclusiveLock);
6132
6133         /*
6134          * Here we go --- change the recorded column type.      (Note heapTup is a
6135          * copy of the syscache entry, so okay to scribble on.)
6136          */
6137         attTup->atttypid = targettype;
6138         attTup->atttypmod = targettypmod;
6139         attTup->attndims = list_length(typeName->arrayBounds);
6140         attTup->attlen = tform->typlen;
6141         attTup->attbyval = tform->typbyval;
6142         attTup->attalign = tform->typalign;
6143         attTup->attstorage = tform->typstorage;
6144
6145         ReleaseSysCache(typeTuple);
6146
6147         simple_heap_update(attrelation, &heapTup->t_self, heapTup);
6148
6149         /* keep system catalog indexes current */
6150         CatalogUpdateIndexes(attrelation, heapTup);
6151
6152         heap_close(attrelation, RowExclusiveLock);
6153
6154         /* Install dependency on new datatype */
6155         add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
6156
6157         /*
6158          * Drop any pg_statistic entry for the column, since it's now wrong type
6159          */
6160         RemoveStatistics(RelationGetRelid(rel), attnum);
6161
6162         /*
6163          * Update the default, if present, by brute force --- remove and re-add
6164          * the default.  Probably unsafe to take shortcuts, since the new version
6165          * may well have additional dependencies.  (It's okay to do this now,
6166          * rather than after other ALTER TYPE commands, since the default won't
6167          * depend on other column types.)
6168          */
6169         if (defaultexpr)
6170         {
6171                 /* Must make new row visible since it will be updated again */
6172                 CommandCounterIncrement();
6173
6174                 /*
6175                  * We use RESTRICT here for safety, but at present we do not expect
6176                  * anything to depend on the default.
6177                  */
6178                 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
6179
6180                 StoreAttrDefault(rel, attnum, defaultexpr);
6181         }
6182
6183         /* Cleanup */
6184         heap_freetuple(heapTup);
6185 }
6186
6187 /*
6188  * Cleanup after we've finished all the ALTER TYPE operations for a
6189  * particular relation.  We have to drop and recreate all the indexes
6190  * and constraints that depend on the altered columns.
6191  */
6192 static void
6193 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
6194 {
6195         ObjectAddress obj;
6196         ListCell   *l;
6197
6198         /*
6199          * Re-parse the index and constraint definitions, and attach them to the
6200          * appropriate work queue entries.      We do this before dropping because in
6201          * the case of a FOREIGN KEY constraint, we might not yet have exclusive
6202          * lock on the table the constraint is attached to, and we need to get
6203          * that before dropping.  It's safe because the parser won't actually look
6204          * at the catalogs to detect the existing entry.
6205          */
6206         foreach(l, tab->changedIndexDefs)
6207                 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
6208         foreach(l, tab->changedConstraintDefs)
6209                 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
6210
6211         /*
6212          * Now we can drop the existing constraints and indexes --- constraints
6213          * first, since some of them might depend on the indexes.  In fact, we
6214          * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
6215          * we already ordered the constraint list to ensure that would happen. It
6216          * should be okay to use DROP_RESTRICT here, since nothing else should be
6217          * depending on these objects.
6218          */
6219         foreach(l, tab->changedConstraintOids)
6220         {
6221                 obj.classId = ConstraintRelationId;
6222                 obj.objectId = lfirst_oid(l);
6223                 obj.objectSubId = 0;
6224                 performDeletion(&obj, DROP_RESTRICT);
6225         }
6226
6227         foreach(l, tab->changedIndexOids)
6228         {
6229                 obj.classId = RelationRelationId;
6230                 obj.objectId = lfirst_oid(l);
6231                 obj.objectSubId = 0;
6232                 performDeletion(&obj, DROP_RESTRICT);
6233         }
6234
6235         /*
6236          * The objects will get recreated during subsequent passes over the work
6237          * queue.
6238          */
6239 }
6240
6241 static void
6242 ATPostAlterTypeParse(char *cmd, List **wqueue)
6243 {
6244         List       *raw_parsetree_list;
6245         List       *querytree_list;
6246         ListCell   *list_item;
6247
6248         /*
6249          * We expect that we will get only ALTER TABLE and CREATE INDEX
6250          * statements. Hence, there is no need to pass them through
6251          * parse_analyze() or the rewriter, but instead we need to pass them
6252          * through parse_utilcmd.c to make them ready for execution.
6253          */
6254         raw_parsetree_list = raw_parser(cmd);
6255         querytree_list = NIL;
6256         foreach(list_item, raw_parsetree_list)
6257         {
6258                 Node       *stmt = (Node *) lfirst(list_item);
6259
6260                 if (IsA(stmt, IndexStmt))
6261                         querytree_list = lappend(querytree_list,
6262                                                                          transformIndexStmt((IndexStmt *) stmt,
6263                                                                                                                 cmd));
6264                 else if (IsA(stmt, AlterTableStmt))
6265                         querytree_list = list_concat(querytree_list,
6266                                                          transformAlterTableStmt((AlterTableStmt *) stmt,
6267                                                                                                          cmd));
6268                 else
6269                         querytree_list = lappend(querytree_list, stmt);
6270         }
6271
6272         /*
6273          * Attach each generated command to the proper place in the work queue.
6274          * Note this could result in creation of entirely new work-queue entries.
6275          */
6276         foreach(list_item, querytree_list)
6277         {
6278                 Node       *stm = (Node *) lfirst(list_item);
6279                 Relation        rel;
6280                 AlteredTableInfo *tab;
6281
6282                 switch (nodeTag(stm))
6283                 {
6284                         case T_IndexStmt:
6285                                 {
6286                                         IndexStmt  *stmt = (IndexStmt *) stm;
6287                                         AlterTableCmd *newcmd;
6288
6289                                         rel = relation_openrv(stmt->relation, AccessExclusiveLock);
6290                                         tab = ATGetQueueEntry(wqueue, rel);
6291                                         newcmd = makeNode(AlterTableCmd);
6292                                         newcmd->subtype = AT_ReAddIndex;
6293                                         newcmd->def = (Node *) stmt;
6294                                         tab->subcmds[AT_PASS_OLD_INDEX] =
6295                                                 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
6296                                         relation_close(rel, NoLock);
6297                                         break;
6298                                 }
6299                         case T_AlterTableStmt:
6300                                 {
6301                                         AlterTableStmt *stmt = (AlterTableStmt *) stm;
6302                                         ListCell   *lcmd;
6303
6304                                         rel = relation_openrv(stmt->relation, AccessExclusiveLock);
6305                                         tab = ATGetQueueEntry(wqueue, rel);
6306                                         foreach(lcmd, stmt->cmds)
6307                                         {
6308                                                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
6309
6310                                                 switch (cmd->subtype)
6311                                                 {
6312                                                         case AT_AddIndex:
6313                                                                 cmd->subtype = AT_ReAddIndex;
6314                                                                 tab->subcmds[AT_PASS_OLD_INDEX] =
6315                                                                         lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
6316                                                                 break;
6317                                                         case AT_AddConstraint:
6318                                                                 tab->subcmds[AT_PASS_OLD_CONSTR] =
6319                                                                         lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
6320                                                                 break;
6321                                                         default:
6322                                                                 elog(ERROR, "unexpected statement type: %d",
6323                                                                          (int) cmd->subtype);
6324                                                 }
6325                                         }
6326                                         relation_close(rel, NoLock);
6327                                         break;
6328                                 }
6329                         default:
6330                                 elog(ERROR, "unexpected statement type: %d",
6331                                          (int) nodeTag(stm));
6332                 }
6333         }
6334 }
6335
6336
6337 /*
6338  * ALTER TABLE OWNER
6339  *
6340  * recursing is true if we are recursing from a table to its indexes,
6341  * sequences, or toast table.  We don't allow the ownership of those things to
6342  * be changed separately from the parent table.  Also, we can skip permission
6343  * checks (this is necessary not just an optimization, else we'd fail to
6344  * handle toast tables properly).
6345  *
6346  * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
6347  * free-standing composite type.
6348  */
6349 void
6350 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
6351 {
6352         Relation        target_rel;
6353         Relation        class_rel;
6354         HeapTuple       tuple;
6355         Form_pg_class tuple_class;
6356
6357         /*
6358          * Get exclusive lock till end of transaction on the target table. Use
6359          * relation_open so that we can work on indexes and sequences.
6360          */
6361         target_rel = relation_open(relationOid, AccessExclusiveLock);
6362
6363         /* Get its pg_class tuple, too */
6364         class_rel = heap_open(RelationRelationId, RowExclusiveLock);
6365
6366         tuple = SearchSysCache(RELOID,
6367                                                    ObjectIdGetDatum(relationOid),
6368                                                    0, 0, 0);
6369         if (!HeapTupleIsValid(tuple))
6370                 elog(ERROR, "cache lookup failed for relation %u", relationOid);
6371         tuple_class = (Form_pg_class) GETSTRUCT(tuple);
6372
6373         /* Can we change the ownership of this tuple? */
6374         switch (tuple_class->relkind)
6375         {
6376                 case RELKIND_RELATION:
6377                 case RELKIND_VIEW:
6378                         /* ok to change owner */
6379                         break;
6380                 case RELKIND_INDEX:
6381                         if (!recursing)
6382                         {
6383                                 /*
6384                                  * Because ALTER INDEX OWNER used to be allowed, and in fact
6385                                  * is generated by old versions of pg_dump, we give a warning
6386                                  * and do nothing rather than erroring out.  Also, to avoid
6387                                  * unnecessary chatter while restoring those old dumps, say
6388                                  * nothing at all if the command would be a no-op anyway.
6389                                  */
6390                                 if (tuple_class->relowner != newOwnerId)
6391                                         ereport(WARNING,
6392                                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6393                                                          errmsg("cannot change owner of index \"%s\"",
6394                                                                         NameStr(tuple_class->relname)),
6395                                                          errhint("Change the ownership of the index's table, instead.")));
6396                                 /* quick hack to exit via the no-op path */
6397                                 newOwnerId = tuple_class->relowner;
6398                         }
6399                         break;
6400                 case RELKIND_SEQUENCE:
6401                         if (!recursing &&
6402                                 tuple_class->relowner != newOwnerId)
6403                         {
6404                                 /* if it's an owned sequence, disallow changing it by itself */
6405                                 Oid                     tableId;
6406                                 int32           colId;
6407
6408                                 if (sequenceIsOwned(relationOid, &tableId, &colId))
6409                                         ereport(ERROR,
6410                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6411                                                          errmsg("cannot change owner of sequence \"%s\"",
6412                                                                         NameStr(tuple_class->relname)),
6413                                           errdetail("Sequence \"%s\" is linked to table \"%s\".",
6414                                                                 NameStr(tuple_class->relname),
6415                                                                 get_rel_name(tableId))));
6416                         }
6417                         break;
6418                 case RELKIND_COMPOSITE_TYPE:
6419                         if (recursing)
6420                                 break;
6421                         ereport(ERROR,
6422                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6423                                          errmsg("\"%s\" is a composite type",
6424                                                         NameStr(tuple_class->relname)),
6425                                          errhint("Use ALTER TYPE instead.")));
6426                         break;
6427                 case RELKIND_TOASTVALUE:
6428                         if (recursing)
6429                                 break;
6430                         /* FALL THRU */
6431                 default:
6432                         ereport(ERROR,
6433                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6434                                          errmsg("\"%s\" is not a table, view, or sequence",
6435                                                         NameStr(tuple_class->relname))));
6436         }
6437
6438         /*
6439          * If the new owner is the same as the existing owner, consider the
6440          * command to have succeeded.  This is for dump restoration purposes.
6441          */
6442         if (tuple_class->relowner != newOwnerId)
6443         {
6444                 Datum           repl_val[Natts_pg_class];
6445                 bool            repl_null[Natts_pg_class];
6446                 bool            repl_repl[Natts_pg_class];
6447                 Acl                *newAcl;
6448                 Datum           aclDatum;
6449                 bool            isNull;
6450                 HeapTuple       newtuple;
6451
6452                 /* skip permission checks when recursing to index or toast table */
6453                 if (!recursing)
6454                 {
6455                         /* Superusers can always do it */
6456                         if (!superuser())
6457                         {
6458                                 Oid                     namespaceOid = tuple_class->relnamespace;
6459                                 AclResult       aclresult;
6460
6461                                 /* Otherwise, must be owner of the existing object */
6462                                 if (!pg_class_ownercheck(relationOid, GetUserId()))
6463                                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
6464                                                                    RelationGetRelationName(target_rel));
6465
6466                                 /* Must be able to become new owner */
6467                                 check_is_member_of_role(GetUserId(), newOwnerId);
6468
6469                                 /* New owner must have CREATE privilege on namespace */
6470                                 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
6471                                                                                                   ACL_CREATE);
6472                                 if (aclresult != ACLCHECK_OK)
6473                                         aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
6474                                                                    get_namespace_name(namespaceOid));
6475                         }
6476                 }
6477
6478                 memset(repl_null, false, sizeof(repl_null));
6479                 memset(repl_repl, false, sizeof(repl_repl));
6480
6481                 repl_repl[Anum_pg_class_relowner - 1] = true;
6482                 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
6483
6484                 /*
6485                  * Determine the modified ACL for the new owner.  This is only
6486                  * necessary when the ACL is non-null.
6487                  */
6488                 aclDatum = SysCacheGetAttr(RELOID, tuple,
6489                                                                    Anum_pg_class_relacl,
6490                                                                    &isNull);
6491                 if (!isNull)
6492                 {
6493                         newAcl = aclnewowner(DatumGetAclP(aclDatum),
6494                                                                  tuple_class->relowner, newOwnerId);
6495                         repl_repl[Anum_pg_class_relacl - 1] = true;
6496                         repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
6497                 }
6498
6499                 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
6500
6501                 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
6502                 CatalogUpdateIndexes(class_rel, newtuple);
6503
6504                 heap_freetuple(newtuple);
6505
6506                 /*
6507                  * Update owner dependency reference, if any.  A composite type has
6508                  * none, because it's tracked for the pg_type entry instead of here;
6509                  * indexes and TOAST tables don't have their own entries either.
6510                  */
6511                 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
6512                         tuple_class->relkind != RELKIND_INDEX &&
6513                         tuple_class->relkind != RELKIND_TOASTVALUE)
6514                         changeDependencyOnOwner(RelationRelationId, relationOid,
6515                                                                         newOwnerId);
6516
6517                 /*
6518                  * Also change the ownership of the table's rowtype, if it has one
6519                  */
6520                 if (tuple_class->relkind != RELKIND_INDEX)
6521                         AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
6522                                                          tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
6523
6524                 /*
6525                  * If we are operating on a table, also change the ownership of any
6526                  * indexes and sequences that belong to the table, as well as the
6527                  * table's toast table (if it has one)
6528                  */
6529                 if (tuple_class->relkind == RELKIND_RELATION ||
6530                         tuple_class->relkind == RELKIND_TOASTVALUE)
6531                 {
6532                         List       *index_oid_list;
6533                         ListCell   *i;
6534
6535                         /* Find all the indexes belonging to this relation */
6536                         index_oid_list = RelationGetIndexList(target_rel);
6537
6538                         /* For each index, recursively change its ownership */
6539                         foreach(i, index_oid_list)
6540                                 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
6541
6542                         list_free(index_oid_list);
6543                 }
6544
6545                 if (tuple_class->relkind == RELKIND_RELATION)
6546                 {
6547                         /* If it has a toast table, recurse to change its ownership */
6548                         if (tuple_class->reltoastrelid != InvalidOid)
6549                                 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
6550                                                                   true);
6551
6552                         /* If it has dependent sequences, recurse to change them too */
6553                         change_owner_recurse_to_sequences(relationOid, newOwnerId);
6554                 }
6555         }
6556
6557         ReleaseSysCache(tuple);
6558         heap_close(class_rel, RowExclusiveLock);
6559         relation_close(target_rel, NoLock);
6560 }
6561
6562 /*
6563  * change_owner_recurse_to_sequences
6564  *
6565  * Helper function for ATExecChangeOwner.  Examines pg_depend searching
6566  * for sequences that are dependent on serial columns, and changes their
6567  * ownership.
6568  */
6569 static void
6570 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
6571 {
6572         Relation        depRel;
6573         SysScanDesc scan;
6574         ScanKeyData key[2];
6575         HeapTuple       tup;
6576
6577         /*
6578          * SERIAL sequences are those having an auto dependency on one of the
6579          * table's columns (we don't care *which* column, exactly).
6580          */
6581         depRel = heap_open(DependRelationId, AccessShareLock);
6582
6583         ScanKeyInit(&key[0],
6584                                 Anum_pg_depend_refclassid,
6585                                 BTEqualStrategyNumber, F_OIDEQ,
6586                                 ObjectIdGetDatum(RelationRelationId));
6587         ScanKeyInit(&key[1],
6588                                 Anum_pg_depend_refobjid,
6589                                 BTEqualStrategyNumber, F_OIDEQ,
6590                                 ObjectIdGetDatum(relationOid));
6591         /* we leave refobjsubid unspecified */
6592
6593         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6594                                                           SnapshotNow, 2, key);
6595
6596         while (HeapTupleIsValid(tup = systable_getnext(scan)))
6597         {
6598                 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6599                 Relation        seqRel;
6600
6601                 /* skip dependencies other than auto dependencies on columns */
6602                 if (depForm->refobjsubid == 0 ||
6603                         depForm->classid != RelationRelationId ||
6604                         depForm->objsubid != 0 ||
6605                         depForm->deptype != DEPENDENCY_AUTO)
6606                         continue;
6607
6608                 /* Use relation_open just in case it's an index */
6609                 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6610
6611                 /* skip non-sequence relations */
6612                 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6613                 {
6614                         /* No need to keep the lock */
6615                         relation_close(seqRel, AccessExclusiveLock);
6616                         continue;
6617                 }
6618
6619                 /* We don't need to close the sequence while we alter it. */
6620                 ATExecChangeOwner(depForm->objid, newOwnerId, true);
6621
6622                 /* Now we can close it.  Keep the lock till end of transaction. */
6623                 relation_close(seqRel, NoLock);
6624         }
6625
6626         systable_endscan(scan);
6627
6628         relation_close(depRel, AccessShareLock);
6629 }
6630
6631 /*
6632  * ALTER TABLE CLUSTER ON
6633  *
6634  * The only thing we have to do is to change the indisclustered bits.
6635  */
6636 static void
6637 ATExecClusterOn(Relation rel, const char *indexName)
6638 {
6639         Oid                     indexOid;
6640
6641         indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
6642
6643         if (!OidIsValid(indexOid))
6644                 ereport(ERROR,
6645                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6646                                  errmsg("index \"%s\" for table \"%s\" does not exist",
6647                                                 indexName, RelationGetRelationName(rel))));
6648
6649         /* Check index is valid to cluster on */
6650         check_index_is_clusterable(rel, indexOid, false);
6651
6652         /* And do the work */
6653         mark_index_clustered(rel, indexOid);
6654 }
6655
6656 /*
6657  * ALTER TABLE SET WITHOUT CLUSTER
6658  *
6659  * We have to find any indexes on the table that have indisclustered bit
6660  * set and turn it off.
6661  */
6662 static void
6663 ATExecDropCluster(Relation rel)
6664 {
6665         mark_index_clustered(rel, InvalidOid);
6666 }
6667
6668 /*
6669  * ALTER TABLE SET TABLESPACE
6670  */
6671 static void
6672 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
6673 {
6674         Oid                     tablespaceId;
6675         AclResult       aclresult;
6676
6677         /* Check that the tablespace exists */
6678         tablespaceId = get_tablespace_oid(tablespacename);
6679         if (!OidIsValid(tablespaceId))
6680                 ereport(ERROR,
6681                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6682                                  errmsg("tablespace \"%s\" does not exist", tablespacename)));
6683
6684         /* Check its permissions */
6685         aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
6686         if (aclresult != ACLCHECK_OK)
6687                 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
6688
6689         /* Save info for Phase 3 to do the real work */
6690         if (OidIsValid(tab->newTableSpace))
6691                 ereport(ERROR,
6692                                 (errcode(ERRCODE_SYNTAX_ERROR),
6693                                  errmsg("cannot have multiple SET TABLESPACE subcommands")));
6694         tab->newTableSpace = tablespaceId;
6695 }
6696
6697 /*
6698  * ALTER TABLE/INDEX SET (...) or RESET (...)
6699  */
6700 static void
6701 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
6702 {
6703         Oid                     relid;
6704         Relation        pgclass;
6705         HeapTuple       tuple;
6706         HeapTuple       newtuple;
6707         Datum           datum;
6708         bool            isnull;
6709         Datum           newOptions;
6710         Datum           repl_val[Natts_pg_class];
6711         bool            repl_null[Natts_pg_class];
6712         bool            repl_repl[Natts_pg_class];
6713         static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
6714
6715         if (defList == NIL)
6716                 return;                                 /* nothing to do */
6717
6718         pgclass = heap_open(RelationRelationId, RowExclusiveLock);
6719
6720         /* Get the old reloptions */
6721         relid = RelationGetRelid(rel);
6722         tuple = SearchSysCache(RELOID,
6723                                                    ObjectIdGetDatum(relid),
6724                                                    0, 0, 0);
6725         if (!HeapTupleIsValid(tuple))
6726                 elog(ERROR, "cache lookup failed for relation %u", relid);
6727
6728         datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6729
6730         /* Generate new proposed reloptions (text array) */
6731         newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6732                                                                    defList, NULL, validnsps, false, isReset);
6733
6734         /* Validate */
6735         switch (rel->rd_rel->relkind)
6736         {
6737                 case RELKIND_RELATION:
6738                 case RELKIND_TOASTVALUE:
6739                         (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
6740                         break;
6741                 case RELKIND_INDEX:
6742                         (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
6743                         break;
6744                 default:
6745                         ereport(ERROR,
6746                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6747                                          errmsg("\"%s\" is not a table, index, or TOAST table",
6748                                                         RelationGetRelationName(rel))));
6749                         break;
6750         }
6751
6752         /*
6753          * All we need do here is update the pg_class row; the new options will be
6754          * propagated into relcaches during post-commit cache inval.
6755          */
6756         memset(repl_val, 0, sizeof(repl_val));
6757         memset(repl_null, false, sizeof(repl_null));
6758         memset(repl_repl, false, sizeof(repl_repl));
6759
6760         if (newOptions != (Datum) 0)
6761                 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6762         else
6763                 repl_null[Anum_pg_class_reloptions - 1] = true;
6764
6765         repl_repl[Anum_pg_class_reloptions - 1] = true;
6766
6767         newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
6768                                                                  repl_val, repl_null, repl_repl);
6769
6770         simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6771
6772         CatalogUpdateIndexes(pgclass, newtuple);
6773
6774         heap_freetuple(newtuple);
6775
6776         ReleaseSysCache(tuple);
6777
6778         /* repeat the whole exercise for the toast table, if there's one */
6779         if (OidIsValid(rel->rd_rel->reltoastrelid))
6780         {
6781                 Relation        toastrel;
6782                 Oid                     toastid = rel->rd_rel->reltoastrelid;
6783
6784                 toastrel = heap_open(toastid, AccessExclusiveLock);
6785
6786                 /* Get the old reloptions */
6787                 tuple = SearchSysCache(RELOID,
6788                                                            ObjectIdGetDatum(toastid),
6789                                                            0, 0, 0);
6790                 if (!HeapTupleIsValid(tuple))
6791                         elog(ERROR, "cache lookup failed for relation %u", toastid);
6792
6793                 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6794
6795                 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6796                                                                 defList, "toast", validnsps, false, isReset);
6797
6798                 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
6799
6800                 memset(repl_val, 0, sizeof(repl_val));
6801                 memset(repl_null, false, sizeof(repl_null));
6802                 memset(repl_repl, false, sizeof(repl_repl));
6803
6804                 if (newOptions != (Datum) 0)
6805                         repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6806                 else
6807                         repl_null[Anum_pg_class_reloptions - 1] = true;
6808
6809                 repl_repl[Anum_pg_class_reloptions - 1] = true;
6810
6811                 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
6812                                                                          repl_val, repl_null, repl_repl);
6813
6814                 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6815
6816                 CatalogUpdateIndexes(pgclass, newtuple);
6817
6818                 heap_freetuple(newtuple);
6819
6820                 ReleaseSysCache(tuple);
6821
6822                 heap_close(toastrel, NoLock);
6823         }
6824
6825         heap_close(pgclass, RowExclusiveLock);
6826 }
6827
6828 /*
6829  * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6830  * rewriting to be done, so we just want to copy the data as fast as possible.
6831  */
6832 static void
6833 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
6834 {
6835         Relation        rel;
6836         Oid                     oldTableSpace;
6837         Oid                     reltoastrelid;
6838         Oid                     reltoastidxid;
6839         Oid                     newrelfilenode;
6840         RelFileNode newrnode;
6841         SMgrRelation dstrel;
6842         Relation        pg_class;
6843         HeapTuple       tuple;
6844         Form_pg_class rd_rel;
6845         ForkNumber      forkNum;
6846
6847         /*
6848          * Need lock here in case we are recursing to toast table or index
6849          */
6850         rel = relation_open(tableOid, AccessExclusiveLock);
6851
6852         /*
6853          * We can never allow moving of shared or nailed-in-cache relations,
6854          * because we can't support changing their reltablespace values.
6855          */
6856         if (rel->rd_rel->relisshared || rel->rd_isnailed)
6857                 ereport(ERROR,
6858                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6859                                  errmsg("cannot move system relation \"%s\"",
6860                                                 RelationGetRelationName(rel))));
6861
6862         /* Can't move a non-shared relation into pg_global */
6863         if (newTableSpace == GLOBALTABLESPACE_OID)
6864                 ereport(ERROR,
6865                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6866                                  errmsg("only shared relations can be placed in pg_global tablespace")));
6867
6868         /*
6869          * Don't allow moving temp tables of other backends ... their local buffer
6870          * manager is not going to cope.
6871          */
6872         if (RELATION_IS_OTHER_TEMP(rel))
6873                 ereport(ERROR,
6874                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6875                                  errmsg("cannot move temporary tables of other sessions")));
6876
6877         /*
6878          * No work if no change in tablespace.
6879          */
6880         oldTableSpace = rel->rd_rel->reltablespace;
6881         if (newTableSpace == oldTableSpace ||
6882                 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
6883         {
6884                 relation_close(rel, NoLock);
6885                 return;
6886         }
6887
6888         reltoastrelid = rel->rd_rel->reltoastrelid;
6889         reltoastidxid = rel->rd_rel->reltoastidxid;
6890
6891         /* Get a modifiable copy of the relation's pg_class row */
6892         pg_class = heap_open(RelationRelationId, RowExclusiveLock);
6893
6894         tuple = SearchSysCacheCopy(RELOID,
6895                                                            ObjectIdGetDatum(tableOid),
6896                                                            0, 0, 0);
6897         if (!HeapTupleIsValid(tuple))
6898                 elog(ERROR, "cache lookup failed for relation %u", tableOid);
6899         rd_rel = (Form_pg_class) GETSTRUCT(tuple);
6900
6901         /*
6902          * Since we copy the file directly without looking at the shared buffers,
6903          * we'd better first flush out any pages of the source relation that are
6904          * in shared buffers.  We assume no new changes will be made while we are
6905          * holding exclusive lock on the rel.
6906          */
6907         FlushRelationBuffers(rel);
6908
6909         /*
6910          * Relfilenodes are not unique across tablespaces, so we need to allocate
6911          * a new one in the new tablespace.
6912          */
6913         newrelfilenode = GetNewRelFileNode(newTableSpace,
6914                                                                            rel->rd_rel->relisshared,
6915                                                                            NULL);
6916
6917         /* Open old and new relation */
6918         newrnode = rel->rd_node;
6919         newrnode.relNode = newrelfilenode;
6920         newrnode.spcNode = newTableSpace;
6921         dstrel = smgropen(newrnode);
6922
6923         RelationOpenSmgr(rel);
6924
6925         /*
6926          * Create and copy all forks of the relation, and schedule unlinking of
6927          * old physical files.
6928          *
6929          * NOTE: any conflict in relfilenode value will be caught in
6930          * RelationCreateStorage().
6931          */
6932         RelationCreateStorage(newrnode, rel->rd_istemp);
6933
6934         /* copy main fork */
6935         copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM, rel->rd_istemp);
6936
6937         /* copy those extra forks that exist */
6938         for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
6939         {
6940                 if (smgrexists(rel->rd_smgr, forkNum))
6941                 {
6942                         smgrcreate(dstrel, forkNum, false);
6943                         copy_relation_data(rel->rd_smgr, dstrel, forkNum, rel->rd_istemp);
6944                 }
6945         }
6946
6947         /* drop old relation, and close new one */
6948         RelationDropStorage(rel);
6949         smgrclose(dstrel);
6950
6951         /* update the pg_class row */
6952         rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6953         rd_rel->relfilenode = newrelfilenode;
6954         simple_heap_update(pg_class, &tuple->t_self, tuple);
6955         CatalogUpdateIndexes(pg_class, tuple);
6956
6957         heap_freetuple(tuple);
6958
6959         heap_close(pg_class, RowExclusiveLock);
6960
6961         relation_close(rel, NoLock);
6962
6963         /* Make sure the reltablespace change is visible */
6964         CommandCounterIncrement();
6965
6966         /* Move associated toast relation and/or index, too */
6967         if (OidIsValid(reltoastrelid))
6968                 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6969         if (OidIsValid(reltoastidxid))
6970                 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6971 }
6972
6973 /*
6974  * Copy data, block by block
6975  */
6976 static void
6977 copy_relation_data(SMgrRelation src, SMgrRelation dst,
6978                                    ForkNumber forkNum, bool istemp)
6979 {
6980         bool            use_wal;
6981         BlockNumber nblocks;
6982         BlockNumber blkno;
6983         char            buf[BLCKSZ];
6984         Page            page = (Page) buf;
6985
6986         /*
6987          * We need to log the copied data in WAL iff WAL archiving is enabled AND
6988          * it's not a temp rel.
6989          */
6990         use_wal = XLogArchivingActive() && !istemp;
6991
6992         nblocks = smgrnblocks(src, forkNum);
6993
6994         for (blkno = 0; blkno < nblocks; blkno++)
6995         {
6996                 smgrread(src, forkNum, blkno, buf);
6997
6998                 /* XLOG stuff */
6999                 if (use_wal)
7000                         log_newpage(&dst->smgr_rnode, forkNum, blkno, page);
7001
7002                 /*
7003                  * Now write the page.  We say isTemp = true even if it's not a temp
7004                  * rel, because there's no need for smgr to schedule an fsync for this
7005                  * write; we'll do it ourselves below.
7006                  */
7007                 smgrextend(dst, forkNum, blkno, buf, true);
7008         }
7009
7010         /*
7011          * If the rel isn't temp, we must fsync it down to disk before it's safe
7012          * to commit the transaction.  (For a temp rel we don't care since the rel
7013          * will be uninteresting after a crash anyway.)
7014          *
7015          * It's obvious that we must do this when not WAL-logging the copy. It's
7016          * less obvious that we have to do it even if we did WAL-log the copied
7017          * pages. The reason is that since we're copying outside shared buffers, a
7018          * CHECKPOINT occurring during the copy has no way to flush the previously
7019          * written data to disk (indeed it won't know the new rel even exists).  A
7020          * crash later on would replay WAL from the checkpoint, therefore it
7021          * wouldn't replay our earlier WAL entries. If we do not fsync those pages
7022          * here, they might still not be on disk when the crash occurs.
7023          */
7024         if (!istemp)
7025                 smgrimmedsync(dst, forkNum);
7026 }
7027
7028 /*
7029  * ALTER TABLE ENABLE/DISABLE TRIGGER
7030  *
7031  * We just pass this off to trigger.c.
7032  */
7033 static void
7034 ATExecEnableDisableTrigger(Relation rel, char *trigname,
7035                                                    char fires_when, bool skip_system)
7036 {
7037         EnableDisableTrigger(rel, trigname, fires_when, skip_system);
7038 }
7039
7040 /*
7041  * ALTER TABLE ENABLE/DISABLE RULE
7042  *
7043  * We just pass this off to rewriteDefine.c.
7044  */
7045 static void
7046 ATExecEnableDisableRule(Relation rel, char *trigname,
7047                                                 char fires_when)
7048 {
7049         EnableDisableRule(rel, trigname, fires_when);
7050 }
7051
7052 /*
7053  * ALTER TABLE INHERIT
7054  *
7055  * Add a parent to the child's parents. This verifies that all the columns and
7056  * check constraints of the parent appear in the child and that they have the
7057  * same data types and expressions.
7058  */
7059 static void
7060 ATExecAddInherit(Relation child_rel, RangeVar *parent)
7061 {
7062         Relation        parent_rel,
7063                                 catalogRelation;
7064         SysScanDesc scan;
7065         ScanKeyData key;
7066         HeapTuple       inheritsTuple;
7067         int32           inhseqno;
7068         List       *children;
7069
7070         /*
7071          * AccessShareLock on the parent is what's obtained during normal CREATE
7072          * TABLE ... INHERITS ..., so should be enough here.
7073          */
7074         parent_rel = heap_openrv(parent, AccessShareLock);
7075
7076         /*
7077          * Must be owner of both parent and child -- child was checked by
7078          * ATSimplePermissions call in ATPrepCmd
7079          */
7080         ATSimplePermissions(parent_rel, false);
7081
7082         /* Permanent rels cannot inherit from temporary ones */
7083         if (parent_rel->rd_istemp && !child_rel->rd_istemp)
7084                 ereport(ERROR,
7085                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7086                                  errmsg("cannot inherit from temporary relation \"%s\"",
7087                                                 RelationGetRelationName(parent_rel))));
7088
7089         /*
7090          * Check for duplicates in the list of parents, and determine the highest
7091          * inhseqno already present; we'll use the next one for the new parent.
7092          * (Note: get RowExclusiveLock because we will write pg_inherits below.)
7093          *
7094          * Note: we do not reject the case where the child already inherits from
7095          * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
7096          */
7097         catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7098         ScanKeyInit(&key,
7099                                 Anum_pg_inherits_inhrelid,
7100                                 BTEqualStrategyNumber, F_OIDEQ,
7101                                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
7102         scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7103                                                           true, SnapshotNow, 1, &key);
7104
7105         /* inhseqno sequences start at 1 */
7106         inhseqno = 0;
7107         while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7108         {
7109                 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
7110
7111                 if (inh->inhparent == RelationGetRelid(parent_rel))
7112                         ereport(ERROR,
7113                                         (errcode(ERRCODE_DUPLICATE_TABLE),
7114                          errmsg("relation \"%s\" would be inherited from more than once",
7115                                         RelationGetRelationName(parent_rel))));
7116                 if (inh->inhseqno > inhseqno)
7117                         inhseqno = inh->inhseqno;
7118         }
7119         systable_endscan(scan);
7120
7121         /*
7122          * Prevent circularity by seeing if proposed parent inherits from child.
7123          * (In particular, this disallows making a rel inherit from itself.)
7124          *
7125          * This is not completely bulletproof because of race conditions: in
7126          * multi-level inheritance trees, someone else could concurrently be
7127          * making another inheritance link that closes the loop but does not join
7128          * either of the rels we have locked.  Preventing that seems to require
7129          * exclusive locks on the entire inheritance tree, which is a cure worse
7130          * than the disease.  find_all_inheritors() will cope with circularity
7131          * anyway, so don't sweat it too much.
7132          *
7133          * We use weakest lock we can on child's children, namely AccessShareLock.
7134          */
7135         children = find_all_inheritors(RelationGetRelid(child_rel),
7136                                                                    AccessShareLock);
7137
7138         if (list_member_oid(children, RelationGetRelid(parent_rel)))
7139                 ereport(ERROR,
7140                                 (errcode(ERRCODE_DUPLICATE_TABLE),
7141                                  errmsg("circular inheritance not allowed"),
7142                                  errdetail("\"%s\" is already a child of \"%s\".",
7143                                                    parent->relname,
7144                                                    RelationGetRelationName(child_rel))));
7145
7146         /* If parent has OIDs then child must have OIDs */
7147         if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
7148                 ereport(ERROR,
7149                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7150                                  errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
7151                                                 RelationGetRelationName(child_rel),
7152                                                 RelationGetRelationName(parent_rel))));
7153
7154         /* Match up the columns and bump attinhcount as needed */
7155         MergeAttributesIntoExisting(child_rel, parent_rel);
7156
7157         /* Match up the constraints and bump coninhcount as needed */
7158         MergeConstraintsIntoExisting(child_rel, parent_rel);
7159
7160         /*
7161          * OK, it looks valid.  Make the catalog entries that show inheritance.
7162          */
7163         StoreCatalogInheritance1(RelationGetRelid(child_rel),
7164                                                          RelationGetRelid(parent_rel),
7165                                                          inhseqno + 1,
7166                                                          catalogRelation);
7167
7168         /* Now we're done with pg_inherits */
7169         heap_close(catalogRelation, RowExclusiveLock);
7170
7171         /* keep our lock on the parent relation until commit */
7172         heap_close(parent_rel, NoLock);
7173 }
7174
7175 /*
7176  * Obtain the source-text form of the constraint expression for a check
7177  * constraint, given its pg_constraint tuple
7178  */
7179 static char *
7180 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
7181 {
7182         Form_pg_constraint con;
7183         bool            isnull;
7184         Datum           attr;
7185         Datum           expr;
7186
7187         con = (Form_pg_constraint) GETSTRUCT(contup);
7188         attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
7189         if (isnull)
7190                 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
7191
7192         expr = DirectFunctionCall2(pg_get_expr, attr,
7193                                                            ObjectIdGetDatum(con->conrelid));
7194         return TextDatumGetCString(expr);
7195 }
7196
7197 /*
7198  * Determine whether two check constraints are functionally equivalent
7199  *
7200  * The test we apply is to see whether they reverse-compile to the same
7201  * source string.  This insulates us from issues like whether attributes
7202  * have the same physical column numbers in parent and child relations.
7203  */
7204 static bool
7205 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
7206 {
7207         Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
7208         Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
7209
7210         if (acon->condeferrable != bcon->condeferrable ||
7211                 acon->condeferred != bcon->condeferred ||
7212                 strcmp(decompile_conbin(a, tupleDesc),
7213                            decompile_conbin(b, tupleDesc)) != 0)
7214                 return false;
7215         else
7216                 return true;
7217 }
7218
7219 /*
7220  * Check columns in child table match up with columns in parent, and increment
7221  * their attinhcount.
7222  *
7223  * Called by ATExecAddInherit
7224  *
7225  * Currently all parent columns must be found in child. Missing columns are an
7226  * error.  One day we might consider creating new columns like CREATE TABLE
7227  * does.  However, that is widely unpopular --- in the common use case of
7228  * partitioned tables it's a foot-gun.
7229  *
7230  * The data type must match exactly. If the parent column is NOT NULL then
7231  * the child must be as well. Defaults are not compared, however.
7232  */
7233 static void
7234 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
7235 {
7236         Relation        attrrel;
7237         AttrNumber      parent_attno;
7238         int                     parent_natts;
7239         TupleDesc       tupleDesc;
7240         TupleConstr *constr;
7241         HeapTuple       tuple;
7242
7243         attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
7244
7245         tupleDesc = RelationGetDescr(parent_rel);
7246         parent_natts = tupleDesc->natts;
7247         constr = tupleDesc->constr;
7248
7249         for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
7250         {
7251                 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
7252                 char       *attributeName = NameStr(attribute->attname);
7253
7254                 /* Ignore dropped columns in the parent. */
7255                 if (attribute->attisdropped)
7256                         continue;
7257
7258                 /* Find same column in child (matching on column name). */
7259                 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
7260                                                                                   attributeName);
7261                 if (HeapTupleIsValid(tuple))
7262                 {
7263                         /* Check they are same type and typmod */
7264                         Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
7265
7266                         if (attribute->atttypid != childatt->atttypid ||
7267                                 attribute->atttypmod != childatt->atttypmod)
7268                                 ereport(ERROR,
7269                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
7270                                                  errmsg("child table \"%s\" has different type for column \"%s\"",
7271                                                                 RelationGetRelationName(child_rel),
7272                                                                 attributeName)));
7273
7274                         if (attribute->attnotnull && !childatt->attnotnull)
7275                                 ereport(ERROR,
7276                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
7277                                 errmsg("column \"%s\" in child table must be marked NOT NULL",
7278                                            attributeName)));
7279
7280                         /*
7281                          * OK, bump the child column's inheritance count.  (If we fail
7282                          * later on, this change will just roll back.)
7283                          */
7284                         childatt->attinhcount++;
7285                         simple_heap_update(attrrel, &tuple->t_self, tuple);
7286                         CatalogUpdateIndexes(attrrel, tuple);
7287                         heap_freetuple(tuple);
7288                 }
7289                 else
7290                 {
7291                         ereport(ERROR,
7292                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
7293                                          errmsg("child table is missing column \"%s\"",
7294                                                         attributeName)));
7295                 }
7296         }
7297
7298         heap_close(attrrel, RowExclusiveLock);
7299 }
7300
7301 /*
7302  * Check constraints in child table match up with constraints in parent,
7303  * and increment their coninhcount.
7304  *
7305  * Called by ATExecAddInherit
7306  *
7307  * Currently all constraints in parent must be present in the child. One day we
7308  * may consider adding new constraints like CREATE TABLE does. We may also want
7309  * to allow an optional flag on parent table constraints indicating they are
7310  * intended to ONLY apply to the master table, not to the children. That would
7311  * make it possible to ensure no records are mistakenly inserted into the
7312  * master in partitioned tables rather than the appropriate child.
7313  *
7314  * XXX This is O(N^2) which may be an issue with tables with hundreds of
7315  * constraints. As long as tables have more like 10 constraints it shouldn't be
7316  * a problem though. Even 100 constraints ought not be the end of the world.
7317  */
7318 static void
7319 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
7320 {
7321         Relation        catalog_relation;
7322         TupleDesc       tuple_desc;
7323         SysScanDesc parent_scan;
7324         ScanKeyData parent_key;
7325         HeapTuple       parent_tuple;
7326
7327         catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
7328         tuple_desc = RelationGetDescr(catalog_relation);
7329
7330         /* Outer loop scans through the parent's constraint definitions */
7331         ScanKeyInit(&parent_key,
7332                                 Anum_pg_constraint_conrelid,
7333                                 BTEqualStrategyNumber, F_OIDEQ,
7334                                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7335         parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
7336                                                                          true, SnapshotNow, 1, &parent_key);
7337
7338         while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
7339         {
7340                 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
7341                 SysScanDesc child_scan;
7342                 ScanKeyData child_key;
7343                 HeapTuple       child_tuple;
7344                 bool            found = false;
7345
7346                 if (parent_con->contype != CONSTRAINT_CHECK)
7347                         continue;
7348
7349                 /* Search for a child constraint matching this one */
7350                 ScanKeyInit(&child_key,
7351                                         Anum_pg_constraint_conrelid,
7352                                         BTEqualStrategyNumber, F_OIDEQ,
7353                                         ObjectIdGetDatum(RelationGetRelid(child_rel)));
7354                 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
7355                                                                                 true, SnapshotNow, 1, &child_key);
7356
7357                 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
7358                 {
7359                         Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
7360                         HeapTuple       child_copy;
7361
7362                         if (child_con->contype != CONSTRAINT_CHECK)
7363                                 continue;
7364
7365                         if (strcmp(NameStr(parent_con->conname),
7366                                            NameStr(child_con->conname)) != 0)
7367                                 continue;
7368
7369                         if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
7370                                 ereport(ERROR,
7371                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
7372                                                  errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
7373                                                                 RelationGetRelationName(child_rel),
7374                                                                 NameStr(parent_con->conname))));
7375
7376                         /*
7377                          * OK, bump the child constraint's inheritance count.  (If we fail
7378                          * later on, this change will just roll back.)
7379                          */
7380                         child_copy = heap_copytuple(child_tuple);
7381                         child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
7382                         child_con->coninhcount++;
7383                         simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
7384                         CatalogUpdateIndexes(catalog_relation, child_copy);
7385                         heap_freetuple(child_copy);
7386
7387                         found = true;
7388                         break;
7389                 }
7390
7391                 systable_endscan(child_scan);
7392
7393                 if (!found)
7394                         ereport(ERROR,
7395                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
7396                                          errmsg("child table is missing constraint \"%s\"",
7397                                                         NameStr(parent_con->conname))));
7398         }
7399
7400         systable_endscan(parent_scan);
7401         heap_close(catalog_relation, RowExclusiveLock);
7402 }
7403
7404 /*
7405  * ALTER TABLE NO INHERIT
7406  *
7407  * Drop a parent from the child's parents. This just adjusts the attinhcount
7408  * and attislocal of the columns and removes the pg_inherit and pg_depend
7409  * entries.
7410  *
7411  * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
7412  * up attislocal stays true, which means if a child is ever removed from a
7413  * parent then its columns will never be automatically dropped which may
7414  * surprise. But at least we'll never surprise by dropping columns someone
7415  * isn't expecting to be dropped which would actually mean data loss.
7416  *
7417  * coninhcount and conislocal for inherited constraints are adjusted in
7418  * exactly the same way.
7419  */
7420 static void
7421 ATExecDropInherit(Relation rel, RangeVar *parent)
7422 {
7423         Relation        parent_rel;
7424         Relation        catalogRelation;
7425         SysScanDesc scan;
7426         ScanKeyData key[3];
7427         HeapTuple       inheritsTuple,
7428                                 attributeTuple,
7429                                 constraintTuple,
7430                                 depTuple;
7431         List       *connames;
7432         bool            found = false;
7433
7434         /*
7435          * AccessShareLock on the parent is probably enough, seeing that DROP
7436          * TABLE doesn't lock parent tables at all.  We need some lock since we'll
7437          * be inspecting the parent's schema.
7438          */
7439         parent_rel = heap_openrv(parent, AccessShareLock);
7440
7441         /*
7442          * We don't bother to check ownership of the parent table --- ownership of
7443          * the child is presumed enough rights.
7444          */
7445
7446         /*
7447          * Find and destroy the pg_inherits entry linking the two, or error out if
7448          * there is none.
7449          */
7450         catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7451         ScanKeyInit(&key[0],
7452                                 Anum_pg_inherits_inhrelid,
7453                                 BTEqualStrategyNumber, F_OIDEQ,
7454                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7455         scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7456                                                           true, SnapshotNow, 1, key);
7457
7458         while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7459         {
7460                 Oid                     inhparent;
7461
7462                 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
7463                 if (inhparent == RelationGetRelid(parent_rel))
7464                 {
7465                         simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
7466                         found = true;
7467                         break;
7468                 }
7469         }
7470
7471         systable_endscan(scan);
7472         heap_close(catalogRelation, RowExclusiveLock);
7473
7474         if (!found)
7475                 ereport(ERROR,
7476                                 (errcode(ERRCODE_UNDEFINED_TABLE),
7477                                  errmsg("relation \"%s\" is not a parent of relation \"%s\"",
7478                                                 RelationGetRelationName(parent_rel),
7479                                                 RelationGetRelationName(rel))));
7480
7481         /*
7482          * Search through child columns looking for ones matching parent rel
7483          */
7484         catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
7485         ScanKeyInit(&key[0],
7486                                 Anum_pg_attribute_attrelid,
7487                                 BTEqualStrategyNumber, F_OIDEQ,
7488                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7489         scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
7490                                                           true, SnapshotNow, 1, key);
7491         while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
7492         {
7493                 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
7494
7495                 /* Ignore if dropped or not inherited */
7496                 if (att->attisdropped)
7497                         continue;
7498                 if (att->attinhcount <= 0)
7499                         continue;
7500
7501                 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
7502                                                                                 NameStr(att->attname)))
7503                 {
7504                         /* Decrement inhcount and possibly set islocal to true */
7505                         HeapTuple       copyTuple = heap_copytuple(attributeTuple);
7506                         Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
7507
7508                         copy_att->attinhcount--;
7509                         if (copy_att->attinhcount == 0)
7510                                 copy_att->attislocal = true;
7511
7512                         simple_heap_update(catalogRelation, &copyTuple->t_self, copyTuple);
7513                         CatalogUpdateIndexes(catalogRelation, copyTuple);
7514                         heap_freetuple(copyTuple);
7515                 }
7516         }
7517         systable_endscan(scan);
7518         heap_close(catalogRelation, RowExclusiveLock);
7519
7520         /*
7521          * Likewise, find inherited check constraints and disinherit them. To do
7522          * this, we first need a list of the names of the parent's check
7523          * constraints.  (We cheat a bit by only checking for name matches,
7524          * assuming that the expressions will match.)
7525          */
7526         catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
7527         ScanKeyInit(&key[0],
7528                                 Anum_pg_constraint_conrelid,
7529                                 BTEqualStrategyNumber, F_OIDEQ,
7530                                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7531         scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7532                                                           true, SnapshotNow, 1, key);
7533
7534         connames = NIL;
7535
7536         while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7537         {
7538                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7539
7540                 if (con->contype == CONSTRAINT_CHECK)
7541                         connames = lappend(connames, pstrdup(NameStr(con->conname)));
7542         }
7543
7544         systable_endscan(scan);
7545
7546         /* Now scan the child's constraints */
7547         ScanKeyInit(&key[0],
7548                                 Anum_pg_constraint_conrelid,
7549                                 BTEqualStrategyNumber, F_OIDEQ,
7550                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7551         scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7552                                                           true, SnapshotNow, 1, key);
7553
7554         while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7555         {
7556                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7557                 bool            match;
7558                 ListCell   *lc;
7559
7560                 if (con->contype != CONSTRAINT_CHECK)
7561                         continue;
7562
7563                 match = false;
7564                 foreach(lc, connames)
7565                 {
7566                         if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
7567                         {
7568                                 match = true;
7569                                 break;
7570                         }
7571                 }
7572
7573                 if (match)
7574                 {
7575                         /* Decrement inhcount and possibly set islocal to true */
7576                         HeapTuple       copyTuple = heap_copytuple(constraintTuple);
7577                         Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
7578
7579                         if (copy_con->coninhcount <= 0)         /* shouldn't happen */
7580                                 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7581                                          RelationGetRelid(rel), NameStr(copy_con->conname));
7582
7583                         copy_con->coninhcount--;
7584                         if (copy_con->coninhcount == 0)
7585                                 copy_con->conislocal = true;
7586
7587                         simple_heap_update(catalogRelation, &copyTuple->t_self, copyTuple);
7588                         CatalogUpdateIndexes(catalogRelation, copyTuple);
7589                         heap_freetuple(copyTuple);
7590                 }
7591         }
7592
7593         systable_endscan(scan);
7594         heap_close(catalogRelation, RowExclusiveLock);
7595
7596         /*
7597          * Drop the dependency
7598          *
7599          * There's no convenient way to do this, so go trawling through pg_depend
7600          */
7601         catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
7602
7603         ScanKeyInit(&key[0],
7604                                 Anum_pg_depend_classid,
7605                                 BTEqualStrategyNumber, F_OIDEQ,
7606                                 ObjectIdGetDatum(RelationRelationId));
7607         ScanKeyInit(&key[1],
7608                                 Anum_pg_depend_objid,
7609                                 BTEqualStrategyNumber, F_OIDEQ,
7610                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7611         ScanKeyInit(&key[2],
7612                                 Anum_pg_depend_objsubid,
7613                                 BTEqualStrategyNumber, F_INT4EQ,
7614                                 Int32GetDatum(0));
7615
7616         scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
7617                                                           SnapshotNow, 3, key);
7618
7619         while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
7620         {
7621                 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
7622
7623                 if (dep->refclassid == RelationRelationId &&
7624                         dep->refobjid == RelationGetRelid(parent_rel) &&
7625                         dep->refobjsubid == 0 &&
7626                         dep->deptype == DEPENDENCY_NORMAL)
7627                         simple_heap_delete(catalogRelation, &depTuple->t_self);
7628         }
7629
7630         systable_endscan(scan);
7631         heap_close(catalogRelation, RowExclusiveLock);
7632
7633         /* keep our lock on the parent relation until commit */
7634         heap_close(parent_rel, NoLock);
7635 }
7636
7637
7638 /*
7639  * Execute ALTER TABLE SET SCHEMA
7640  *
7641  * Note: caller must have checked ownership of the relation already
7642  */
7643 void
7644 AlterTableNamespace(RangeVar *relation, const char *newschema,
7645                                         ObjectType stmttype)
7646 {
7647         Relation        rel;
7648         Oid                     relid;
7649         Oid                     oldNspOid;
7650         Oid                     nspOid;
7651         Relation        classRel;
7652
7653         rel = relation_openrv(relation, AccessExclusiveLock);
7654
7655         relid = RelationGetRelid(rel);
7656         oldNspOid = RelationGetNamespace(rel);
7657
7658         /* Check relation type against type specified in the ALTER command */
7659         switch (stmttype)
7660         {
7661                 case OBJECT_TABLE:
7662
7663                         /*
7664                          * For mostly-historical reasons, we allow ALTER TABLE to apply to
7665                          * all relation types.
7666                          */
7667                         break;
7668
7669                 case OBJECT_SEQUENCE:
7670                         if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
7671                                 ereport(ERROR,
7672                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7673                                                  errmsg("\"%s\" is not a sequence",
7674                                                                 RelationGetRelationName(rel))));
7675                         break;
7676
7677                 case OBJECT_VIEW:
7678                         if (rel->rd_rel->relkind != RELKIND_VIEW)
7679                                 ereport(ERROR,
7680                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7681                                                  errmsg("\"%s\" is not a view",
7682                                                                 RelationGetRelationName(rel))));
7683                         break;
7684
7685                 default:
7686                         elog(ERROR, "unrecognized object type: %d", (int) stmttype);
7687         }
7688
7689         /* Can we change the schema of this tuple? */
7690         switch (rel->rd_rel->relkind)
7691         {
7692                 case RELKIND_RELATION:
7693                 case RELKIND_VIEW:
7694                         /* ok to change schema */
7695                         break;
7696                 case RELKIND_SEQUENCE:
7697                         {
7698                                 /* if it's an owned sequence, disallow moving it by itself */
7699                                 Oid                     tableId;
7700                                 int32           colId;
7701
7702                                 if (sequenceIsOwned(relid, &tableId, &colId))
7703                                         ereport(ERROR,
7704                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7705                                                          errmsg("cannot move an owned sequence into another schema"),
7706                                           errdetail("Sequence \"%s\" is linked to table \"%s\".",
7707                                                                 RelationGetRelationName(rel),
7708                                                                 get_rel_name(tableId))));
7709                         }
7710                         break;
7711                 case RELKIND_COMPOSITE_TYPE:
7712                         ereport(ERROR,
7713                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7714                                          errmsg("\"%s\" is a composite type",
7715                                                         RelationGetRelationName(rel)),
7716                                          errhint("Use ALTER TYPE instead.")));
7717                         break;
7718                 case RELKIND_INDEX:
7719                 case RELKIND_TOASTVALUE:
7720                         /* FALL THRU */
7721                 default:
7722                         ereport(ERROR,
7723                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7724                                          errmsg("\"%s\" is not a table, view, or sequence",
7725                                                         RelationGetRelationName(rel))));
7726         }
7727
7728         /* get schema OID and check its permissions */
7729         nspOid = LookupCreationNamespace(newschema);
7730
7731         if (oldNspOid == nspOid)
7732                 ereport(ERROR,
7733                                 (errcode(ERRCODE_DUPLICATE_TABLE),
7734                                  errmsg("relation \"%s\" is already in schema \"%s\"",
7735                                                 RelationGetRelationName(rel),
7736                                                 newschema)));
7737
7738         /* disallow renaming into or out of temp schemas */
7739         if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
7740                 ereport(ERROR,
7741                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7742                         errmsg("cannot move objects into or out of temporary schemas")));
7743
7744         /* same for TOAST schema */
7745         if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
7746                 ereport(ERROR,
7747                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7748                                  errmsg("cannot move objects into or out of TOAST schema")));
7749
7750         /* OK, modify the pg_class row and pg_depend entry */
7751         classRel = heap_open(RelationRelationId, RowExclusiveLock);
7752
7753         AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
7754
7755         /* Fix the table's rowtype too */
7756         AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
7757
7758         /* Fix other dependent stuff */
7759         if (rel->rd_rel->relkind == RELKIND_RELATION)
7760         {
7761                 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
7762                 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
7763                 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
7764         }
7765
7766         heap_close(classRel, RowExclusiveLock);
7767
7768         /* close rel, but keep lock until commit */
7769         relation_close(rel, NoLock);
7770 }
7771
7772 /*
7773  * The guts of relocating a relation to another namespace: fix the pg_class
7774  * entry, and the pg_depend entry if any.  Caller must already have
7775  * opened and write-locked pg_class.
7776  */
7777 void
7778 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
7779                                                            Oid oldNspOid, Oid newNspOid,
7780                                                            bool hasDependEntry)
7781 {
7782         HeapTuple       classTup;
7783         Form_pg_class classForm;
7784
7785         classTup = SearchSysCacheCopy(RELOID,
7786                                                                   ObjectIdGetDatum(relOid),
7787                                                                   0, 0, 0);
7788         if (!HeapTupleIsValid(classTup))
7789                 elog(ERROR, "cache lookup failed for relation %u", relOid);
7790         classForm = (Form_pg_class) GETSTRUCT(classTup);
7791
7792         Assert(classForm->relnamespace == oldNspOid);
7793
7794         /* check for duplicate name (more friendly than unique-index failure) */
7795         if (get_relname_relid(NameStr(classForm->relname),
7796                                                   newNspOid) != InvalidOid)
7797                 ereport(ERROR,
7798                                 (errcode(ERRCODE_DUPLICATE_TABLE),
7799                                  errmsg("relation \"%s\" already exists in schema \"%s\"",
7800                                                 NameStr(classForm->relname),
7801                                                 get_namespace_name(newNspOid))));
7802
7803         /* classTup is a copy, so OK to scribble on */
7804         classForm->relnamespace = newNspOid;
7805
7806         simple_heap_update(classRel, &classTup->t_self, classTup);
7807         CatalogUpdateIndexes(classRel, classTup);
7808
7809         /* Update dependency on schema if caller said so */
7810         if (hasDependEntry &&
7811                 changeDependencyFor(RelationRelationId, relOid,
7812                                                         NamespaceRelationId, oldNspOid, newNspOid) != 1)
7813                 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
7814                          NameStr(classForm->relname));
7815
7816         heap_freetuple(classTup);
7817 }
7818
7819 /*
7820  * Move all indexes for the specified relation to another namespace.
7821  *
7822  * Note: we assume adequate permission checking was done by the caller,
7823  * and that the caller has a suitable lock on the owning relation.
7824  */
7825 static void
7826 AlterIndexNamespaces(Relation classRel, Relation rel,
7827                                          Oid oldNspOid, Oid newNspOid)
7828 {
7829         List       *indexList;
7830         ListCell   *l;
7831
7832         indexList = RelationGetIndexList(rel);
7833
7834         foreach(l, indexList)
7835         {
7836                 Oid                     indexOid = lfirst_oid(l);
7837
7838                 /*
7839                  * Note: currently, the index will not have its own dependency on the
7840                  * namespace, so we don't need to do changeDependencyFor(). There's no
7841                  * rowtype in pg_type, either.
7842                  */
7843                 AlterRelationNamespaceInternal(classRel, indexOid,
7844                                                                            oldNspOid, newNspOid,
7845                                                                            false);
7846         }
7847
7848         list_free(indexList);
7849 }
7850
7851 /*
7852  * Move all SERIAL-column sequences of the specified relation to another
7853  * namespace.
7854  *
7855  * Note: we assume adequate permission checking was done by the caller,
7856  * and that the caller has a suitable lock on the owning relation.
7857  */
7858 static void
7859 AlterSeqNamespaces(Relation classRel, Relation rel,
7860                                    Oid oldNspOid, Oid newNspOid, const char *newNspName)
7861 {
7862         Relation        depRel;
7863         SysScanDesc scan;
7864         ScanKeyData key[2];
7865         HeapTuple       tup;
7866
7867         /*
7868          * SERIAL sequences are those having an auto dependency on one of the
7869          * table's columns (we don't care *which* column, exactly).
7870          */
7871         depRel = heap_open(DependRelationId, AccessShareLock);
7872
7873         ScanKeyInit(&key[0],
7874                                 Anum_pg_depend_refclassid,
7875                                 BTEqualStrategyNumber, F_OIDEQ,
7876                                 ObjectIdGetDatum(RelationRelationId));
7877         ScanKeyInit(&key[1],
7878                                 Anum_pg_depend_refobjid,
7879                                 BTEqualStrategyNumber, F_OIDEQ,
7880                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7881         /* we leave refobjsubid unspecified */
7882
7883         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7884                                                           SnapshotNow, 2, key);
7885
7886         while (HeapTupleIsValid(tup = systable_getnext(scan)))
7887         {
7888                 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7889                 Relation        seqRel;
7890
7891                 /* skip dependencies other than auto dependencies on columns */
7892                 if (depForm->refobjsubid == 0 ||
7893                         depForm->classid != RelationRelationId ||
7894                         depForm->objsubid != 0 ||
7895                         depForm->deptype != DEPENDENCY_AUTO)
7896                         continue;
7897
7898                 /* Use relation_open just in case it's an index */
7899                 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
7900
7901                 /* skip non-sequence relations */
7902                 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7903                 {
7904                         /* No need to keep the lock */
7905                         relation_close(seqRel, AccessExclusiveLock);
7906                         continue;
7907                 }
7908
7909                 /* Fix the pg_class and pg_depend entries */
7910                 AlterRelationNamespaceInternal(classRel, depForm->objid,
7911                                                                            oldNspOid, newNspOid,
7912                                                                            true);
7913
7914                 /*
7915                  * Sequences have entries in pg_type. We need to be careful to move
7916                  * them to the new namespace, too.
7917                  */
7918                 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
7919                                                                    newNspOid, false, false);
7920
7921                 /* Now we can close it.  Keep the lock till end of transaction. */
7922                 relation_close(seqRel, NoLock);
7923         }
7924
7925         systable_endscan(scan);
7926
7927         relation_close(depRel, AccessShareLock);
7928 }
7929
7930
7931 /*
7932  * This code supports
7933  *      CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7934  *
7935  * Because we only support this for TEMP tables, it's sufficient to remember
7936  * the state in a backend-local data structure.
7937  */
7938
7939 /*
7940  * Register a newly-created relation's ON COMMIT action.
7941  */
7942 void
7943 register_on_commit_action(Oid relid, OnCommitAction action)
7944 {
7945         OnCommitItem *oc;
7946         MemoryContext oldcxt;
7947
7948         /*
7949          * We needn't bother registering the relation unless there is an ON COMMIT
7950          * action we need to take.
7951          */
7952         if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
7953                 return;
7954
7955         oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
7956
7957         oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
7958         oc->relid = relid;
7959         oc->oncommit = action;
7960         oc->creating_subid = GetCurrentSubTransactionId();
7961         oc->deleting_subid = InvalidSubTransactionId;
7962
7963         on_commits = lcons(oc, on_commits);
7964
7965         MemoryContextSwitchTo(oldcxt);
7966 }
7967
7968 /*
7969  * Unregister any ON COMMIT action when a relation is deleted.
7970  *
7971  * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7972  */
7973 void
7974 remove_on_commit_action(Oid relid)
7975 {
7976         ListCell   *l;
7977
7978         foreach(l, on_commits)
7979         {
7980                 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7981
7982                 if (oc->relid == relid)
7983                 {
7984                         oc->deleting_subid = GetCurrentSubTransactionId();
7985                         break;
7986                 }
7987         }
7988 }
7989
7990 /*
7991  * Perform ON COMMIT actions.
7992  *
7993  * This is invoked just before actually committing, since it's possible
7994  * to encounter errors.
7995  */
7996 void
7997 PreCommit_on_commit_actions(void)
7998 {
7999         ListCell   *l;
8000         List       *oids_to_truncate = NIL;
8001
8002         foreach(l, on_commits)
8003         {
8004                 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
8005
8006                 /* Ignore entry if already dropped in this xact */
8007                 if (oc->deleting_subid != InvalidSubTransactionId)
8008                         continue;
8009
8010                 switch (oc->oncommit)
8011                 {
8012                         case ONCOMMIT_NOOP:
8013                         case ONCOMMIT_PRESERVE_ROWS:
8014                                 /* Do nothing (there shouldn't be such entries, actually) */
8015                                 break;
8016                         case ONCOMMIT_DELETE_ROWS:
8017                                 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
8018                                 break;
8019                         case ONCOMMIT_DROP:
8020                                 {
8021                                         ObjectAddress object;
8022
8023                                         object.classId = RelationRelationId;
8024                                         object.objectId = oc->relid;
8025                                         object.objectSubId = 0;
8026                                         performDeletion(&object, DROP_CASCADE);
8027
8028                                         /*
8029                                          * Note that table deletion will call
8030                                          * remove_on_commit_action, so the entry should get marked
8031                                          * as deleted.
8032                                          */
8033                                         Assert(oc->deleting_subid != InvalidSubTransactionId);
8034                                         break;
8035                                 }
8036                 }
8037         }
8038         if (oids_to_truncate != NIL)
8039         {
8040                 heap_truncate(oids_to_truncate);
8041                 CommandCounterIncrement();              /* XXX needed? */
8042         }
8043 }
8044
8045 /*
8046  * Post-commit or post-abort cleanup for ON COMMIT management.
8047  *
8048  * All we do here is remove no-longer-needed OnCommitItem entries.
8049  *
8050  * During commit, remove entries that were deleted during this transaction;
8051  * during abort, remove those created during this transaction.
8052  */
8053 void
8054 AtEOXact_on_commit_actions(bool isCommit)
8055 {
8056         ListCell   *cur_item;
8057         ListCell   *prev_item;
8058
8059         prev_item = NULL;
8060         cur_item = list_head(on_commits);
8061
8062         while (cur_item != NULL)
8063         {
8064                 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
8065
8066                 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
8067                         oc->creating_subid != InvalidSubTransactionId)
8068                 {
8069                         /* cur_item must be removed */
8070                         on_commits = list_delete_cell(on_commits, cur_item, prev_item);
8071                         pfree(oc);
8072                         if (prev_item)
8073                                 cur_item = lnext(prev_item);
8074                         else
8075                                 cur_item = list_head(on_commits);
8076                 }
8077                 else
8078                 {
8079                         /* cur_item must be preserved */
8080                         oc->creating_subid = InvalidSubTransactionId;
8081                         oc->deleting_subid = InvalidSubTransactionId;
8082                         prev_item = cur_item;
8083                         cur_item = lnext(prev_item);
8084                 }
8085         }
8086 }
8087
8088 /*
8089  * Post-subcommit or post-subabort cleanup for ON COMMIT management.
8090  *
8091  * During subabort, we can immediately remove entries created during this
8092  * subtransaction.      During subcommit, just relabel entries marked during
8093  * this subtransaction as being the parent's responsibility.
8094  */
8095 void
8096 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
8097                                                           SubTransactionId parentSubid)
8098 {
8099         ListCell   *cur_item;
8100         ListCell   *prev_item;
8101
8102         prev_item = NULL;
8103         cur_item = list_head(on_commits);
8104
8105         while (cur_item != NULL)
8106         {
8107                 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
8108
8109                 if (!isCommit && oc->creating_subid == mySubid)
8110                 {
8111                         /* cur_item must be removed */
8112                         on_commits = list_delete_cell(on_commits, cur_item, prev_item);
8113                         pfree(oc);
8114                         if (prev_item)
8115                                 cur_item = lnext(prev_item);
8116                         else
8117                                 cur_item = list_head(on_commits);
8118                 }
8119                 else
8120                 {
8121                         /* cur_item must be preserved */
8122                         if (oc->creating_subid == mySubid)
8123                                 oc->creating_subid = parentSubid;
8124                         if (oc->deleting_subid == mySubid)
8125                                 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
8126                         prev_item = cur_item;
8127                         cur_item = lnext(prev_item);
8128                 }
8129         }
8130 }