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