OSDN Git Service

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