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