]> granicus.if.org Git - postgresql/blob - src/backend/commands/tablecmds.c
f22e7be5d88eab5b6ff1e698dc19a15e320870fc
[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.288 2009/06/18 01:27:02 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/relscan.h"
21 #include "access/sysattr.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/dependency.h"
25 #include "catalog/heap.h"
26 #include "catalog/index.h"
27 #include "catalog/indexing.h"
28 #include "catalog/namespace.h"
29 #include "catalog/pg_constraint.h"
30 #include "catalog/pg_depend.h"
31 #include "catalog/pg_inherits.h"
32 #include "catalog/pg_inherits_fn.h"
33 #include "catalog/pg_namespace.h"
34 #include "catalog/pg_opclass.h"
35 #include "catalog/pg_tablespace.h"
36 #include "catalog/pg_trigger.h"
37 #include "catalog/pg_type.h"
38 #include "catalog/pg_type_fn.h"
39 #include "catalog/storage.h"
40 #include "catalog/toasting.h"
41 #include "commands/cluster.h"
42 #include "commands/defrem.h"
43 #include "commands/sequence.h"
44 #include "commands/tablecmds.h"
45 #include "commands/tablespace.h"
46 #include "commands/trigger.h"
47 #include "commands/typecmds.h"
48 #include "executor/executor.h"
49 #include "miscadmin.h"
50 #include "nodes/makefuncs.h"
51 #include "nodes/nodeFuncs.h"
52 #include "nodes/parsenodes.h"
53 #include "optimizer/clauses.h"
54 #include "parser/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 will
452          * be processed by AddRelationNewConstraints.  (We can't deal with raw
453          * 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 in
499          * for immediate handling --- since they don't need parsing, they can be
500          * 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 DROP
626          * 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, lock them
866          * (we only need AccessShareLock because that's all that ALTER SEQUENCE
867          * takes), and check permissions.  We want to do this early since it's
868          * pointless to do all the truncation work only to fail on sequence
869          * 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 for
903          * 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). Also, if
926          * we were to allow them to prevent statement execution, that would need
927          * 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 we
1000          * 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. We want people to use ALTER
2056          * 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 view,
2093          * 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                         /*
2249                          * For mostly-historical reasons, we allow ALTER TABLE to apply to
2250                          * all relation types.
2251                          */
2252                         break;
2253
2254                 case OBJECT_INDEX:
2255                         if (rel->rd_rel->relkind != RELKIND_INDEX)
2256                                 ereport(ERROR,
2257                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2258                                                  errmsg("\"%s\" is not an index",
2259                                                                 RelationGetRelationName(rel))));
2260                         break;
2261
2262                 case OBJECT_SEQUENCE:
2263                         if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2264                                 ereport(ERROR,
2265                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2266                                                  errmsg("\"%s\" is not a sequence",
2267                                                                 RelationGetRelationName(rel))));
2268                         break;
2269
2270                 case OBJECT_VIEW:
2271                         if (rel->rd_rel->relkind != RELKIND_VIEW)
2272                                 ereport(ERROR,
2273                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2274                                                  errmsg("\"%s\" is not a view",
2275                                                                 RelationGetRelationName(rel))));
2276                         break;
2277
2278                 default:
2279                         elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2280         }
2281
2282         ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
2283 }
2284
2285 /*
2286  * AlterTableInternal
2287  *
2288  * ALTER TABLE with target specified by OID
2289  *
2290  * We do not reject if the relation is already open, because it's quite
2291  * likely that one or more layers of caller have it open.  That means it
2292  * is unsafe to use this entry point for alterations that could break
2293  * existing query plans.  On the assumption it's not used for such, we
2294  * don't have to reject pending AFTER triggers, either.
2295  */
2296 void
2297 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2298 {
2299         Relation        rel = relation_open(relid, AccessExclusiveLock);
2300
2301         ATController(rel, cmds, recurse);
2302 }
2303
2304 static void
2305 ATController(Relation rel, List *cmds, bool recurse)
2306 {
2307         List       *wqueue = NIL;
2308         ListCell   *lcmd;
2309
2310         /* Phase 1: preliminary examination of commands, create work queue */
2311         foreach(lcmd, cmds)
2312         {
2313                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2314
2315                 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
2316         }
2317
2318         /* Close the relation, but keep lock until commit */
2319         relation_close(rel, NoLock);
2320
2321         /* Phase 2: update system catalogs */
2322         ATRewriteCatalogs(&wqueue);
2323
2324         /* Phase 3: scan/rewrite tables as needed */
2325         ATRewriteTables(&wqueue);
2326 }
2327
2328 /*
2329  * ATPrepCmd
2330  *
2331  * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2332  * recursion and permission checks.
2333  *
2334  * Caller must have acquired AccessExclusiveLock on relation already.
2335  * This lock should be held until commit.
2336  */
2337 static void
2338 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2339                   bool recurse, bool recursing)
2340 {
2341         AlteredTableInfo *tab;
2342         int                     pass;
2343
2344         /* Find or create work queue entry for this table */
2345         tab = ATGetQueueEntry(wqueue, rel);
2346
2347         /*
2348          * Copy the original subcommand for each table.  This avoids conflicts
2349          * when different child tables need to make different parse
2350          * transformations (for example, the same column may have different column
2351          * numbers in different children).
2352          */
2353         cmd = copyObject(cmd);
2354
2355         /*
2356          * Do permissions checking, recursion to child tables if needed, and any
2357          * additional phase-1 processing needed.
2358          */
2359         switch (cmd->subtype)
2360         {
2361                 case AT_AddColumn:              /* ADD COLUMN */
2362                         ATSimplePermissions(rel, false);
2363                         /* Performs own recursion */
2364                         ATPrepAddColumn(wqueue, rel, recurse, cmd);
2365                         pass = AT_PASS_ADD_COL;
2366                         break;
2367                 case AT_AddColumnToView:                /* add column via CREATE OR REPLACE
2368                                                                                  * VIEW */
2369                         ATSimplePermissions(rel, true);
2370                         /* Performs own recursion */
2371                         ATPrepAddColumn(wqueue, rel, recurse, cmd);
2372                         pass = AT_PASS_ADD_COL;
2373                         break;
2374                 case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
2375
2376                         /*
2377                          * We allow defaults on views so that INSERT into a view can have
2378                          * default-ish behavior.  This works because the rewriter
2379                          * substitutes default values into INSERTs before it expands
2380                          * rules.
2381                          */
2382                         ATSimplePermissions(rel, true);
2383                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2384                         /* No command-specific prep needed */
2385                         pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2386                         break;
2387                 case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
2388                         ATSimplePermissions(rel, false);
2389                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2390                         /* No command-specific prep needed */
2391                         pass = AT_PASS_DROP;
2392                         break;
2393                 case AT_SetNotNull:             /* ALTER COLUMN SET NOT NULL */
2394                         ATSimplePermissions(rel, false);
2395                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2396                         /* No command-specific prep needed */
2397                         pass = AT_PASS_ADD_CONSTR;
2398                         break;
2399                 case AT_SetStatistics:  /* ALTER COLUMN STATISTICS */
2400                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2401                         /* Performs own permission checks */
2402                         ATPrepSetStatistics(rel, cmd->name, cmd->def);
2403                         pass = AT_PASS_COL_ATTRS;
2404                         break;
2405                 case AT_SetStorage:             /* ALTER COLUMN STORAGE */
2406                         ATSimplePermissions(rel, false);
2407                         ATSimpleRecursion(wqueue, rel, cmd, recurse);
2408                         /* No command-specific prep needed */
2409                         pass = AT_PASS_COL_ATTRS;
2410                         break;
2411                 case AT_DropColumn:             /* DROP COLUMN */
2412                         ATSimplePermissions(rel, false);
2413                         /* Recursion occurs during execution phase */
2414                         /* No command-specific prep needed except saving recurse flag */
2415                         if (recurse)
2416                                 cmd->subtype = AT_DropColumnRecurse;
2417                         pass = AT_PASS_DROP;
2418                         break;
2419                 case AT_AddIndex:               /* ADD INDEX */
2420                         ATSimplePermissions(rel, false);
2421                         /* This command never recurses */
2422                         /* No command-specific prep needed */
2423                         pass = AT_PASS_ADD_INDEX;
2424                         break;
2425                 case AT_AddConstraint:  /* ADD CONSTRAINT */
2426                         ATSimplePermissions(rel, false);
2427                         /* Recursion occurs during execution phase */
2428                         /* No command-specific prep needed except saving recurse flag */
2429                         if (recurse)
2430                                 cmd->subtype = AT_AddConstraintRecurse;
2431                         pass = AT_PASS_ADD_CONSTR;
2432                         break;
2433                 case AT_DropConstraint: /* DROP CONSTRAINT */
2434                         ATSimplePermissions(rel, false);
2435                         /* Recursion occurs during execution phase */
2436                         /* No command-specific prep needed except saving recurse flag */
2437                         if (recurse)
2438                                 cmd->subtype = AT_DropConstraintRecurse;
2439                         pass = AT_PASS_DROP;
2440                         break;
2441                 case AT_AlterColumnType:                /* ALTER COLUMN TYPE */
2442                         ATSimplePermissions(rel, false);
2443                         /* Performs own recursion */
2444                         ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2445                         pass = AT_PASS_ALTER_TYPE;
2446                         break;
2447                 case AT_ChangeOwner:    /* ALTER OWNER */
2448                         /* This command never recurses */
2449                         /* No command-specific prep needed */
2450                         pass = AT_PASS_MISC;
2451                         break;
2452                 case AT_ClusterOn:              /* CLUSTER ON */
2453                 case AT_DropCluster:    /* SET WITHOUT CLUSTER */
2454                         ATSimplePermissions(rel, false);
2455                         /* These commands never recurse */
2456                         /* No command-specific prep needed */
2457                         pass = AT_PASS_MISC;
2458                         break;
2459                 case AT_AddOids:                /* SET WITH OIDS */
2460                         ATSimplePermissions(rel, false);
2461                         /* Performs own recursion */
2462                         if (!rel->rd_rel->relhasoids || recursing)
2463                                 ATPrepAddOids(wqueue, rel, recurse, cmd);
2464                         pass = AT_PASS_ADD_COL;
2465                         break;
2466                 case AT_DropOids:               /* SET WITHOUT OIDS */
2467                         ATSimplePermissions(rel, false);
2468                         /* Performs own recursion */
2469                         if (rel->rd_rel->relhasoids)
2470                         {
2471                                 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2472
2473                                 dropCmd->subtype = AT_DropColumn;
2474                                 dropCmd->name = pstrdup("oid");
2475                                 dropCmd->behavior = cmd->behavior;
2476                                 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2477                         }
2478                         pass = AT_PASS_DROP;
2479                         break;
2480                 case AT_SetTableSpace:  /* SET TABLESPACE */
2481                         ATSimplePermissionsRelationOrIndex(rel);
2482                         /* This command never recurses */
2483                         ATPrepSetTableSpace(tab, rel, cmd->name);
2484                         pass = AT_PASS_MISC;    /* doesn't actually matter */
2485                         break;
2486                 case AT_SetRelOptions:  /* SET (...) */
2487                 case AT_ResetRelOptions:                /* RESET (...) */
2488                         ATSimplePermissionsRelationOrIndex(rel);
2489                         /* This command never recurses */
2490                         /* No command-specific prep needed */
2491                         pass = AT_PASS_MISC;
2492                         break;
2493                 case AT_EnableTrig:             /* ENABLE TRIGGER variants */
2494                 case AT_EnableAlwaysTrig:
2495                 case AT_EnableReplicaTrig:
2496                 case AT_EnableTrigAll:
2497                 case AT_EnableTrigUser:
2498                 case AT_DisableTrig:    /* DISABLE TRIGGER variants */
2499                 case AT_DisableTrigAll:
2500                 case AT_DisableTrigUser:
2501                 case AT_EnableRule:             /* ENABLE/DISABLE RULE variants */
2502                 case AT_EnableAlwaysRule:
2503                 case AT_EnableReplicaRule:
2504                 case AT_DisableRule:
2505                 case AT_AddInherit:             /* INHERIT / NO INHERIT */
2506                 case AT_DropInherit:
2507                         ATSimplePermissions(rel, false);
2508                         /* These commands never recurse */
2509                         /* No command-specific prep needed */
2510                         pass = AT_PASS_MISC;
2511                         break;
2512                 default:                                /* oops */
2513                         elog(ERROR, "unrecognized alter table type: %d",
2514                                  (int) cmd->subtype);
2515                         pass = 0;                       /* keep compiler quiet */
2516                         break;
2517         }
2518
2519         /* Add the subcommand to the appropriate list for phase 2 */
2520         tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2521 }
2522
2523 /*
2524  * ATRewriteCatalogs
2525  *
2526  * Traffic cop for ALTER TABLE Phase 2 operations.      Subcommands are
2527  * dispatched in a "safe" execution order (designed to avoid unnecessary
2528  * conflicts).
2529  */
2530 static void
2531 ATRewriteCatalogs(List **wqueue)
2532 {
2533         int                     pass;
2534         ListCell   *ltab;
2535
2536         /*
2537          * We process all the tables "in parallel", one pass at a time.  This is
2538          * needed because we may have to propagate work from one table to another
2539          * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2540          * re-adding of the foreign key constraint to the other table).  Work can
2541          * only be propagated into later passes, however.
2542          */
2543         for (pass = 0; pass < AT_NUM_PASSES; pass++)
2544         {
2545                 /* Go through each table that needs to be processed */
2546                 foreach(ltab, *wqueue)
2547                 {
2548                         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2549                         List       *subcmds = tab->subcmds[pass];
2550                         Relation        rel;
2551                         ListCell   *lcmd;
2552
2553                         if (subcmds == NIL)
2554                                 continue;
2555
2556                         /*
2557                          * Exclusive lock was obtained by phase 1, needn't get it again
2558                          */
2559                         rel = relation_open(tab->relid, NoLock);
2560
2561                         foreach(lcmd, subcmds)
2562                                 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd));
2563
2564                         /*
2565                          * After the ALTER TYPE pass, do cleanup work (this is not done in
2566                          * ATExecAlterColumnType since it should be done only once if
2567                          * multiple columns of a table are altered).
2568                          */
2569                         if (pass == AT_PASS_ALTER_TYPE)
2570                                 ATPostAlterTypeCleanup(wqueue, tab);
2571
2572                         relation_close(rel, NoLock);
2573                 }
2574         }
2575
2576         /*
2577          * Check to see if a toast table must be added, if we executed any
2578          * subcommands that might have added a column or changed column storage.
2579          */
2580         foreach(ltab, *wqueue)
2581         {
2582                 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2583
2584                 if (tab->relkind == RELKIND_RELATION &&
2585                         (tab->subcmds[AT_PASS_ADD_COL] ||
2586                          tab->subcmds[AT_PASS_ALTER_TYPE] ||
2587                          tab->subcmds[AT_PASS_COL_ATTRS]))
2588                         AlterTableCreateToastTable(tab->relid, InvalidOid,
2589                                                                            (Datum) 0, false);
2590         }
2591 }
2592
2593 /*
2594  * ATExecCmd: dispatch a subcommand to appropriate execution routine
2595  */
2596 static void
2597 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
2598                   AlterTableCmd *cmd)
2599 {
2600         switch (cmd->subtype)
2601         {
2602                 case AT_AddColumn:              /* ADD COLUMN */
2603                 case AT_AddColumnToView:                /* add column via CREATE OR REPLACE
2604                                                                                  * VIEW */
2605                         ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def, false);
2606                         break;
2607                 case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
2608                         ATExecColumnDefault(rel, cmd->name, cmd->def);
2609                         break;
2610                 case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
2611                         ATExecDropNotNull(rel, cmd->name);
2612                         break;
2613                 case AT_SetNotNull:             /* ALTER COLUMN SET NOT NULL */
2614                         ATExecSetNotNull(tab, rel, cmd->name);
2615                         break;
2616                 case AT_SetStatistics:  /* ALTER COLUMN STATISTICS */
2617                         ATExecSetStatistics(rel, cmd->name, cmd->def);
2618                         break;
2619                 case AT_SetStorage:             /* ALTER COLUMN STORAGE */
2620                         ATExecSetStorage(rel, cmd->name, cmd->def);
2621                         break;
2622                 case AT_DropColumn:             /* DROP COLUMN */
2623                         ATExecDropColumn(wqueue, rel, cmd->name,
2624                                                          cmd->behavior, false, false);
2625                         break;
2626                 case AT_DropColumnRecurse:              /* DROP COLUMN with recursion */
2627                         ATExecDropColumn(wqueue, rel, cmd->name,
2628                                                          cmd->behavior, true, false);
2629                         break;
2630                 case AT_AddIndex:               /* ADD INDEX */
2631                         ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2632                         break;
2633                 case AT_ReAddIndex:             /* ADD INDEX */
2634                         ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2635                         break;
2636                 case AT_AddConstraint:  /* ADD CONSTRAINT */
2637                         ATExecAddConstraint(wqueue, tab, rel, cmd->def, false);
2638                         break;
2639                 case AT_AddConstraintRecurse:   /* ADD CONSTRAINT with recursion */
2640                         ATExecAddConstraint(wqueue, tab, rel, cmd->def, true);
2641                         break;
2642                 case AT_DropConstraint: /* DROP CONSTRAINT */
2643                         ATExecDropConstraint(rel, cmd->name, cmd->behavior, false, false);
2644                         break;
2645                 case AT_DropConstraintRecurse:  /* DROP CONSTRAINT with recursion */
2646                         ATExecDropConstraint(rel, cmd->name, cmd->behavior, true, false);
2647                         break;
2648                 case AT_AlterColumnType:                /* ALTER COLUMN TYPE */
2649                         ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2650                         break;
2651                 case AT_ChangeOwner:    /* ALTER OWNER */
2652                         ATExecChangeOwner(RelationGetRelid(rel),
2653                                                           get_roleid_checked(cmd->name),
2654                                                           false);
2655                         break;
2656                 case AT_ClusterOn:              /* CLUSTER ON */
2657                         ATExecClusterOn(rel, cmd->name);
2658                         break;
2659                 case AT_DropCluster:    /* SET WITHOUT CLUSTER */
2660                         ATExecDropCluster(rel);
2661                         break;
2662                 case AT_AddOids:                /* SET WITH OIDS */
2663                         /* Use the ADD COLUMN code, unless prep decided to do nothing */
2664                         if (cmd->def != NULL)
2665                                 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def, true);
2666                         break;
2667                 case AT_DropOids:               /* SET WITHOUT OIDS */
2668
2669                         /*
2670                          * Nothing to do here; we'll have generated a DropColumn
2671                          * subcommand to do the real work
2672                          */
2673                         break;
2674                 case AT_SetTableSpace:  /* SET TABLESPACE */
2675
2676                         /*
2677                          * Nothing to do here; Phase 3 does the work
2678                          */
2679                         break;
2680                 case AT_SetRelOptions:  /* SET (...) */
2681                         ATExecSetRelOptions(rel, (List *) cmd->def, false);
2682                         break;
2683                 case AT_ResetRelOptions:                /* RESET (...) */
2684                         ATExecSetRelOptions(rel, (List *) cmd->def, true);
2685                         break;
2686
2687                 case AT_EnableTrig:             /* ENABLE TRIGGER name */
2688                         ATExecEnableDisableTrigger(rel, cmd->name,
2689                                                                            TRIGGER_FIRES_ON_ORIGIN, false);
2690                         break;
2691                 case AT_EnableAlwaysTrig:               /* ENABLE ALWAYS TRIGGER name */
2692                         ATExecEnableDisableTrigger(rel, cmd->name,
2693                                                                            TRIGGER_FIRES_ALWAYS, false);
2694                         break;
2695                 case AT_EnableReplicaTrig:              /* ENABLE REPLICA TRIGGER name */
2696                         ATExecEnableDisableTrigger(rel, cmd->name,
2697                                                                            TRIGGER_FIRES_ON_REPLICA, false);
2698                         break;
2699                 case AT_DisableTrig:    /* DISABLE TRIGGER name */
2700                         ATExecEnableDisableTrigger(rel, cmd->name,
2701                                                                            TRIGGER_DISABLED, false);
2702                         break;
2703                 case AT_EnableTrigAll:  /* ENABLE TRIGGER ALL */
2704                         ATExecEnableDisableTrigger(rel, NULL,
2705                                                                            TRIGGER_FIRES_ON_ORIGIN, false);
2706                         break;
2707                 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2708                         ATExecEnableDisableTrigger(rel, NULL,
2709                                                                            TRIGGER_DISABLED, false);
2710                         break;
2711                 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2712                         ATExecEnableDisableTrigger(rel, NULL,
2713                                                                            TRIGGER_FIRES_ON_ORIGIN, true);
2714                         break;
2715                 case AT_DisableTrigUser:                /* DISABLE TRIGGER USER */
2716                         ATExecEnableDisableTrigger(rel, NULL,
2717                                                                            TRIGGER_DISABLED, true);
2718                         break;
2719
2720                 case AT_EnableRule:             /* ENABLE RULE name */
2721                         ATExecEnableDisableRule(rel, cmd->name,
2722                                                                         RULE_FIRES_ON_ORIGIN);
2723                         break;
2724                 case AT_EnableAlwaysRule:               /* ENABLE ALWAYS RULE name */
2725                         ATExecEnableDisableRule(rel, cmd->name,
2726                                                                         RULE_FIRES_ALWAYS);
2727                         break;
2728                 case AT_EnableReplicaRule:              /* ENABLE REPLICA RULE name */
2729                         ATExecEnableDisableRule(rel, cmd->name,
2730                                                                         RULE_FIRES_ON_REPLICA);
2731                         break;
2732                 case AT_DisableRule:    /* DISABLE RULE name */
2733                         ATExecEnableDisableRule(rel, cmd->name,
2734                                                                         RULE_DISABLED);
2735                         break;
2736
2737                 case AT_AddInherit:
2738                         ATExecAddInherit(rel, (RangeVar *) cmd->def);
2739                         break;
2740                 case AT_DropInherit:
2741                         ATExecDropInherit(rel, (RangeVar *) cmd->def);
2742                         break;
2743                 default:                                /* oops */
2744                         elog(ERROR, "unrecognized alter table type: %d",
2745                                  (int) cmd->subtype);
2746                         break;
2747         }
2748
2749         /*
2750          * Bump the command counter to ensure the next subcommand in the sequence
2751          * can see the changes so far
2752          */
2753         CommandCounterIncrement();
2754 }
2755
2756 /*
2757  * ATRewriteTables: ALTER TABLE phase 3
2758  */
2759 static void
2760 ATRewriteTables(List **wqueue)
2761 {
2762         ListCell   *ltab;
2763
2764         /* Go through each table that needs to be checked or rewritten */
2765         foreach(ltab, *wqueue)
2766         {
2767                 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2768
2769                 /*
2770                  * We only need to rewrite the table if at least one column needs to
2771                  * be recomputed, or we are adding/removing the OID column.
2772                  */
2773                 if (tab->newvals != NIL || tab->new_changeoids)
2774                 {
2775                         /* Build a temporary relation and copy data */
2776                         Oid                     OIDNewHeap;
2777                         char            NewHeapName[NAMEDATALEN];
2778                         Oid                     NewTableSpace;
2779                         Relation        OldHeap;
2780                         ObjectAddress object;
2781
2782                         OldHeap = heap_open(tab->relid, NoLock);
2783
2784                         /*
2785                          * We can never allow rewriting of shared or nailed-in-cache
2786                          * relations, because we can't support changing their relfilenode
2787                          * values.
2788                          */
2789                         if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2790                                 ereport(ERROR,
2791                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2792                                                  errmsg("cannot rewrite system relation \"%s\"",
2793                                                                 RelationGetRelationName(OldHeap))));
2794
2795                         /*
2796                          * Don't allow rewrite on temp tables of other backends ... their
2797                          * local buffer manager is not going to cope.
2798                          */
2799                         if (RELATION_IS_OTHER_TEMP(OldHeap))
2800                                 ereport(ERROR,
2801                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2802                                 errmsg("cannot rewrite temporary tables of other sessions")));
2803
2804                         /*
2805                          * Select destination tablespace (same as original unless user
2806                          * requested a change)
2807                          */
2808                         if (tab->newTableSpace)
2809                                 NewTableSpace = tab->newTableSpace;
2810                         else
2811                                 NewTableSpace = OldHeap->rd_rel->reltablespace;
2812
2813                         heap_close(OldHeap, NoLock);
2814
2815                         /*
2816                          * Create the new heap, using a temporary name in the same
2817                          * namespace as the existing table.  NOTE: there is some risk of
2818                          * collision with user relnames.  Working around this seems more
2819                          * trouble than it's worth; in particular, we can't create the new
2820                          * heap in a different namespace from the old, or we will have
2821                          * problems with the TEMP status of temp tables.
2822                          */
2823                         snprintf(NewHeapName, sizeof(NewHeapName),
2824                                          "pg_temp_%u", tab->relid);
2825
2826                         OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2827
2828                         /*
2829                          * Copy the heap data into the new table with the desired
2830                          * modifications, and test the current data within the table
2831                          * against new constraints generated by ALTER TABLE commands.
2832                          */
2833                         ATRewriteTable(tab, OIDNewHeap);
2834
2835                         /*
2836                          * Swap the physical files of the old and new heaps.  Since we are
2837                          * generating a new heap, we can use RecentXmin for the table's
2838                          * new relfrozenxid because we rewrote all the tuples on
2839                          * ATRewriteTable, so no older Xid remains on the table.
2840                          */
2841                         swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2842
2843                         CommandCounterIncrement();
2844
2845                         /* Destroy new heap with old filenode */
2846                         object.classId = RelationRelationId;
2847                         object.objectId = OIDNewHeap;
2848                         object.objectSubId = 0;
2849
2850                         /*
2851                          * The new relation is local to our transaction and we know
2852                          * nothing depends on it, so DROP_RESTRICT should be OK.
2853                          */
2854                         performDeletion(&object, DROP_RESTRICT);
2855                         /* performDeletion does CommandCounterIncrement at end */
2856
2857                         /*
2858                          * Rebuild each index on the relation (but not the toast table,
2859                          * which is all-new anyway).  We do not need
2860                          * CommandCounterIncrement() because reindex_relation does it.
2861                          */
2862                         reindex_relation(tab->relid, false);
2863                 }
2864                 else
2865                 {
2866                         /*
2867                          * Test the current data within the table against new constraints
2868                          * generated by ALTER TABLE commands, but don't rebuild data.
2869                          */
2870                         if (tab->constraints != NIL || tab->new_notnull)
2871                                 ATRewriteTable(tab, InvalidOid);
2872
2873                         /*
2874                          * If we had SET TABLESPACE but no reason to reconstruct tuples,
2875                          * just do a block-by-block copy.
2876                          */
2877                         if (tab->newTableSpace)
2878                                 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2879                 }
2880         }
2881
2882         /*
2883          * Foreign key constraints are checked in a final pass, since (a) it's
2884          * generally best to examine each one separately, and (b) it's at least
2885          * theoretically possible that we have changed both relations of the
2886          * foreign key, and we'd better have finished both rewrites before we try
2887          * to read the tables.
2888          */
2889         foreach(ltab, *wqueue)
2890         {
2891                 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2892                 Relation        rel = NULL;
2893                 ListCell   *lcon;
2894
2895                 foreach(lcon, tab->constraints)
2896                 {
2897                         NewConstraint *con = lfirst(lcon);
2898
2899                         if (con->contype == CONSTR_FOREIGN)
2900                         {
2901                                 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2902                                 Relation        refrel;
2903
2904                                 if (rel == NULL)
2905                                 {
2906                                         /* Long since locked, no need for another */
2907                                         rel = heap_open(tab->relid, NoLock);
2908                                 }
2909
2910                                 refrel = heap_open(con->refrelid, RowShareLock);
2911
2912                                 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2913                                                                                          con->conid);
2914
2915                                 heap_close(refrel, NoLock);
2916                         }
2917                 }
2918
2919                 if (rel)
2920                         heap_close(rel, NoLock);
2921         }
2922 }
2923
2924 /*
2925  * ATRewriteTable: scan or rewrite one table
2926  *
2927  * OIDNewHeap is InvalidOid if we don't need to rewrite
2928  */
2929 static void
2930 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2931 {
2932         Relation        oldrel;
2933         Relation        newrel;
2934         TupleDesc       oldTupDesc;
2935         TupleDesc       newTupDesc;
2936         bool            needscan = false;
2937         List       *notnull_attrs;
2938         int                     i;
2939         ListCell   *l;
2940         EState     *estate;
2941
2942         /*
2943          * Open the relation(s).  We have surely already locked the existing
2944          * table.
2945          */
2946         oldrel = heap_open(tab->relid, NoLock);
2947         oldTupDesc = tab->oldDesc;
2948         newTupDesc = RelationGetDescr(oldrel);          /* includes all mods */
2949
2950         if (OidIsValid(OIDNewHeap))
2951                 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2952         else
2953                 newrel = NULL;
2954
2955         /*
2956          * If we need to rewrite the table, the operation has to be propagated to
2957          * tables that use this table's rowtype as a column type.
2958          *
2959          * (Eventually this will probably become true for scans as well, but at
2960          * the moment a composite type does not enforce any constraints, so it's
2961          * not necessary/appropriate to enforce them just during ALTER.)
2962          */
2963         if (newrel)
2964                 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2965                                                                                  RelationGetRelationName(oldrel),
2966                                                                                  NULL);
2967
2968         /*
2969          * Generate the constraint and default execution states
2970          */
2971
2972         estate = CreateExecutorState();
2973
2974         /* Build the needed expression execution states */
2975         foreach(l, tab->constraints)
2976         {
2977                 NewConstraint *con = lfirst(l);
2978
2979                 switch (con->contype)
2980                 {
2981                         case CONSTR_CHECK:
2982                                 needscan = true;
2983                                 con->qualstate = (List *)
2984                                         ExecPrepareExpr((Expr *) con->qual, estate);
2985                                 break;
2986                         case CONSTR_FOREIGN:
2987                                 /* Nothing to do here */
2988                                 break;
2989                         default:
2990                                 elog(ERROR, "unrecognized constraint type: %d",
2991                                          (int) con->contype);
2992                 }
2993         }
2994
2995         foreach(l, tab->newvals)
2996         {
2997                 NewColumnValue *ex = lfirst(l);
2998
2999                 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
3000         }
3001
3002         notnull_attrs = NIL;
3003         if (newrel || tab->new_notnull)
3004         {
3005                 /*
3006                  * If we are rebuilding the tuples OR if we added any new NOT NULL
3007                  * constraints, check all not-null constraints.  This is a bit of
3008                  * overkill but it minimizes risk of bugs, and heap_attisnull is a
3009                  * pretty cheap test anyway.
3010                  */
3011                 for (i = 0; i < newTupDesc->natts; i++)
3012                 {
3013                         if (newTupDesc->attrs[i]->attnotnull &&
3014                                 !newTupDesc->attrs[i]->attisdropped)
3015                                 notnull_attrs = lappend_int(notnull_attrs, i);
3016                 }
3017                 if (notnull_attrs)
3018                         needscan = true;
3019         }
3020
3021         if (newrel || needscan)
3022         {
3023                 ExprContext *econtext;
3024                 Datum      *values;
3025                 bool       *isnull;
3026                 TupleTableSlot *oldslot;
3027                 TupleTableSlot *newslot;
3028                 HeapScanDesc scan;
3029                 HeapTuple       tuple;
3030                 MemoryContext oldCxt;
3031                 List       *dropped_attrs = NIL;
3032                 ListCell   *lc;
3033
3034                 econtext = GetPerTupleExprContext(estate);
3035
3036                 /*
3037                  * Make tuple slots for old and new tuples.  Note that even when the
3038                  * tuples are the same, the tupDescs might not be (consider ADD COLUMN
3039                  * without a default).
3040                  */
3041                 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
3042                 newslot = MakeSingleTupleTableSlot(newTupDesc);
3043
3044                 /* Preallocate values/isnull arrays */
3045                 i = Max(newTupDesc->natts, oldTupDesc->natts);
3046                 values = (Datum *) palloc(i * sizeof(Datum));
3047                 isnull = (bool *) palloc(i * sizeof(bool));
3048                 memset(values, 0, i * sizeof(Datum));
3049                 memset(isnull, true, i * sizeof(bool));
3050
3051                 /*
3052                  * Any attributes that are dropped according to the new tuple
3053                  * descriptor can be set to NULL. We precompute the list of dropped
3054                  * attributes to avoid needing to do so in the per-tuple loop.
3055                  */
3056                 for (i = 0; i < newTupDesc->natts; i++)
3057                 {
3058                         if (newTupDesc->attrs[i]->attisdropped)
3059                                 dropped_attrs = lappend_int(dropped_attrs, i);
3060                 }
3061
3062                 /*
3063                  * Scan through the rows, generating a new row if needed and then
3064                  * checking all the constraints.
3065                  */
3066                 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3067
3068                 /*
3069                  * Switch to per-tuple memory context and reset it for each tuple
3070                  * produced, so we don't leak memory.
3071                  */
3072                 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3073
3074                 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3075                 {
3076                         if (newrel)
3077                         {
3078                                 Oid                     tupOid = InvalidOid;
3079
3080                                 /* Extract data from old tuple */
3081                                 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3082                                 if (oldTupDesc->tdhasoid)
3083                                         tupOid = HeapTupleGetOid(tuple);
3084
3085                                 /* Set dropped attributes to null in new tuple */
3086                                 foreach(lc, dropped_attrs)
3087                                         isnull[lfirst_int(lc)] = true;
3088
3089                                 /*
3090                                  * Process supplied expressions to replace selected columns.
3091                                  * Expression inputs come from the old tuple.
3092                                  */
3093                                 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3094                                 econtext->ecxt_scantuple = oldslot;
3095
3096                                 foreach(l, tab->newvals)
3097                                 {
3098                                         NewColumnValue *ex = lfirst(l);
3099
3100                                         values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3101                                                                                                                   econtext,
3102                                                                                                          &isnull[ex->attnum - 1],
3103                                                                                                                   NULL);
3104                                 }
3105
3106                                 /*
3107                                  * Form the new tuple. Note that we don't explicitly pfree it,
3108                                  * since the per-tuple memory context will be reset shortly.
3109                                  */
3110                                 tuple = heap_form_tuple(newTupDesc, values, isnull);
3111
3112                                 /* Preserve OID, if any */
3113                                 if (newTupDesc->tdhasoid)
3114                                         HeapTupleSetOid(tuple, tupOid);
3115                         }
3116
3117                         /* Now check any constraints on the possibly-changed tuple */
3118                         ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3119                         econtext->ecxt_scantuple = newslot;
3120
3121                         foreach(l, notnull_attrs)
3122                         {
3123                                 int                     attn = lfirst_int(l);
3124
3125                                 if (heap_attisnull(tuple, attn + 1))
3126                                         ereport(ERROR,
3127                                                         (errcode(ERRCODE_NOT_NULL_VIOLATION),
3128                                                          errmsg("column \"%s\" contains null values",
3129                                                                 NameStr(newTupDesc->attrs[attn]->attname))));
3130                         }
3131
3132                         foreach(l, tab->constraints)
3133                         {
3134                                 NewConstraint *con = lfirst(l);
3135
3136                                 switch (con->contype)
3137                                 {
3138                                         case CONSTR_CHECK:
3139                                                 if (!ExecQual(con->qualstate, econtext, true))
3140                                                         ereport(ERROR,
3141                                                                         (errcode(ERRCODE_CHECK_VIOLATION),
3142                                                                          errmsg("check constraint \"%s\" is violated by some row",
3143                                                                                         con->name)));
3144                                                 break;
3145                                         case CONSTR_FOREIGN:
3146                                                 /* Nothing to do here */
3147                                                 break;
3148                                         default:
3149                                                 elog(ERROR, "unrecognized constraint type: %d",
3150                                                          (int) con->contype);
3151                                 }
3152                         }
3153
3154                         /* Write the tuple out to the new relation */
3155                         if (newrel)
3156                                 simple_heap_insert(newrel, tuple);
3157
3158                         ResetExprContext(econtext);
3159
3160                         CHECK_FOR_INTERRUPTS();
3161                 }
3162
3163                 MemoryContextSwitchTo(oldCxt);
3164                 heap_endscan(scan);
3165
3166                 ExecDropSingleTupleTableSlot(oldslot);
3167                 ExecDropSingleTupleTableSlot(newslot);
3168         }
3169
3170         FreeExecutorState(estate);
3171
3172         heap_close(oldrel, NoLock);
3173         if (newrel)
3174                 heap_close(newrel, NoLock);
3175 }
3176
3177 /*
3178  * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3179  */
3180 static AlteredTableInfo *
3181 ATGetQueueEntry(List **wqueue, Relation rel)
3182 {
3183         Oid                     relid = RelationGetRelid(rel);
3184         AlteredTableInfo *tab;
3185         ListCell   *ltab;
3186
3187         foreach(ltab, *wqueue)
3188         {
3189                 tab = (AlteredTableInfo *) lfirst(ltab);
3190                 if (tab->relid == relid)
3191                         return tab;
3192         }
3193
3194         /*
3195          * Not there, so add it.  Note that we make a copy of the relation's
3196          * existing descriptor before anything interesting can happen to it.
3197          */
3198         tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3199         tab->relid = relid;
3200         tab->relkind = rel->rd_rel->relkind;
3201         tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3202
3203         *wqueue = lappend(*wqueue, tab);
3204
3205         return tab;
3206 }
3207
3208 /*
3209  * ATSimplePermissions
3210  *
3211  * - Ensure that it is a relation (or possibly a view)
3212  * - Ensure this user is the owner
3213  * - Ensure that it is not a system table
3214  */
3215 static void
3216 ATSimplePermissions(Relation rel, bool allowView)
3217 {
3218         if (rel->rd_rel->relkind != RELKIND_RELATION)
3219         {
3220                 if (allowView)
3221                 {
3222                         if (rel->rd_rel->relkind != RELKIND_VIEW)
3223                                 ereport(ERROR,
3224                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3225                                                  errmsg("\"%s\" is not a table or view",
3226                                                                 RelationGetRelationName(rel))));
3227                 }
3228                 else
3229                         ereport(ERROR,
3230                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3231                                          errmsg("\"%s\" is not a table",
3232                                                         RelationGetRelationName(rel))));
3233         }
3234
3235         /* Permissions checks */
3236         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3237                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3238                                            RelationGetRelationName(rel));
3239
3240         if (!allowSystemTableMods && IsSystemRelation(rel))
3241                 ereport(ERROR,
3242                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3243                                  errmsg("permission denied: \"%s\" is a system catalog",
3244                                                 RelationGetRelationName(rel))));
3245 }
3246
3247 /*
3248  * ATSimplePermissionsRelationOrIndex
3249  *
3250  * - Ensure that it is a relation or an index
3251  * - Ensure this user is the owner
3252  * - Ensure that it is not a system table
3253  */
3254 static void
3255 ATSimplePermissionsRelationOrIndex(Relation rel)
3256 {
3257         if (rel->rd_rel->relkind != RELKIND_RELATION &&
3258                 rel->rd_rel->relkind != RELKIND_INDEX)
3259                 ereport(ERROR,
3260                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3261                                  errmsg("\"%s\" is not a table or index",
3262                                                 RelationGetRelationName(rel))));
3263
3264         /* Permissions checks */
3265         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3266                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3267                                            RelationGetRelationName(rel));
3268
3269         if (!allowSystemTableMods && IsSystemRelation(rel))
3270                 ereport(ERROR,
3271                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3272                                  errmsg("permission denied: \"%s\" is a system catalog",
3273                                                 RelationGetRelationName(rel))));
3274 }
3275
3276 /*
3277  * ATSimpleRecursion
3278  *
3279  * Simple table recursion sufficient for most ALTER TABLE operations.
3280  * All direct and indirect children are processed in an unspecified order.
3281  * Note that if a child inherits from the original table via multiple
3282  * inheritance paths, it will be visited just once.
3283  */
3284 static void
3285 ATSimpleRecursion(List **wqueue, Relation rel,
3286                                   AlterTableCmd *cmd, bool recurse)
3287 {
3288         /*
3289          * Propagate to children if desired.  Non-table relations never have
3290          * children, so no need to search in that case.
3291          */
3292         if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3293         {
3294                 Oid                     relid = RelationGetRelid(rel);
3295                 ListCell   *child;
3296                 List       *children;
3297
3298                 children = find_all_inheritors(relid, AccessExclusiveLock);
3299
3300                 /*
3301                  * find_all_inheritors does the recursive search of the inheritance
3302                  * hierarchy, so all we have to do is process all of the relids in the
3303                  * list that it returns.
3304                  */
3305                 foreach(child, children)
3306                 {
3307                         Oid                     childrelid = lfirst_oid(child);
3308                         Relation        childrel;
3309
3310                         if (childrelid == relid)
3311                                 continue;
3312                         /* find_all_inheritors already got lock */
3313                         childrel = relation_open(childrelid, NoLock);
3314                         CheckTableNotInUse(childrel, "ALTER TABLE");
3315                         ATPrepCmd(wqueue, childrel, cmd, false, true);
3316                         relation_close(childrel, NoLock);
3317                 }
3318         }
3319 }
3320
3321 /*
3322  * ATOneLevelRecursion
3323  *
3324  * Here, we visit only direct inheritance children.  It is expected that
3325  * the command's prep routine will recurse again to find indirect children.
3326  * When using this technique, a multiply-inheriting child will be visited
3327  * multiple times.
3328  */
3329 static void
3330 ATOneLevelRecursion(List **wqueue, Relation rel,
3331                                         AlterTableCmd *cmd)
3332 {
3333         Oid                     relid = RelationGetRelid(rel);
3334         ListCell   *child;
3335         List       *children;
3336
3337         children = find_inheritance_children(relid, AccessExclusiveLock);
3338
3339         foreach(child, children)
3340         {
3341                 Oid                     childrelid = lfirst_oid(child);
3342                 Relation        childrel;
3343
3344                 /* find_inheritance_children already got lock */
3345                 childrel = relation_open(childrelid, NoLock);
3346                 CheckTableNotInUse(childrel, "ALTER TABLE");
3347                 ATPrepCmd(wqueue, childrel, cmd, true, true);
3348                 relation_close(childrel, NoLock);
3349         }
3350 }
3351
3352
3353 /*
3354  * find_composite_type_dependencies
3355  *
3356  * Check to see if a composite type is being used as a column in some
3357  * other table (possibly nested several levels deep in composite types!).
3358  * Eventually, we'd like to propagate the check or rewrite operation
3359  * into other such tables, but for now, just error out if we find any.
3360  *
3361  * Caller should provide either a table name or a type name (not both) to
3362  * report in the error message, if any.
3363  *
3364  * We assume that functions and views depending on the type are not reasons
3365  * to reject the ALTER.  (How safe is this really?)
3366  */
3367 void
3368 find_composite_type_dependencies(Oid typeOid,
3369                                                                  const char *origTblName,
3370                                                                  const char *origTypeName)
3371 {
3372         Relation        depRel;
3373         ScanKeyData key[2];
3374         SysScanDesc depScan;
3375         HeapTuple       depTup;
3376         Oid                     arrayOid;
3377
3378         /*
3379          * We scan pg_depend to find those things that depend on the rowtype. (We
3380          * assume we can ignore refobjsubid for a rowtype.)
3381          */
3382         depRel = heap_open(DependRelationId, AccessShareLock);
3383
3384         ScanKeyInit(&key[0],
3385                                 Anum_pg_depend_refclassid,
3386                                 BTEqualStrategyNumber, F_OIDEQ,
3387                                 ObjectIdGetDatum(TypeRelationId));
3388         ScanKeyInit(&key[1],
3389                                 Anum_pg_depend_refobjid,
3390                                 BTEqualStrategyNumber, F_OIDEQ,
3391                                 ObjectIdGetDatum(typeOid));
3392
3393         depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3394                                                                  SnapshotNow, 2, key);
3395
3396         while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3397         {
3398                 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3399                 Relation        rel;
3400                 Form_pg_attribute att;
3401
3402                 /* Ignore dependees that aren't user columns of relations */
3403                 /* (we assume system columns are never of rowtypes) */
3404                 if (pg_depend->classid != RelationRelationId ||
3405                         pg_depend->objsubid <= 0)
3406                         continue;
3407
3408                 rel = relation_open(pg_depend->objid, AccessShareLock);
3409                 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3410
3411                 if (rel->rd_rel->relkind == RELKIND_RELATION)
3412                 {
3413                         if (origTblName)
3414                                 ereport(ERROR,
3415                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3416                                                  errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3417                                                                 origTblName,
3418                                                                 RelationGetRelationName(rel),
3419                                                                 NameStr(att->attname))));
3420                         else
3421                                 ereport(ERROR,
3422                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3423                                                  errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3424                                                                 origTypeName,
3425                                                                 RelationGetRelationName(rel),
3426                                                                 NameStr(att->attname))));
3427                 }
3428                 else if (OidIsValid(rel->rd_rel->reltype))
3429                 {
3430                         /*
3431                          * A view or composite type itself isn't a problem, but we must
3432                          * recursively check for indirect dependencies via its rowtype.
3433                          */
3434                         find_composite_type_dependencies(rel->rd_rel->reltype,
3435                                                                                          origTblName, origTypeName);
3436                 }
3437
3438                 relation_close(rel, AccessShareLock);
3439         }
3440
3441         systable_endscan(depScan);
3442
3443         relation_close(depRel, AccessShareLock);
3444
3445         /*
3446          * If there's an array type for the rowtype, must check for uses of it,
3447          * too.
3448          */
3449         arrayOid = get_array_type(typeOid);
3450         if (OidIsValid(arrayOid))
3451                 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3452 }
3453
3454
3455 /*
3456  * ALTER TABLE ADD COLUMN
3457  *
3458  * Adds an additional attribute to a relation making the assumption that
3459  * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3460  * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3461  * AlterTableCmd's.
3462  */
3463 static void
3464 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3465                                 AlterTableCmd *cmd)
3466 {
3467         /*
3468          * Recurse to add the column to child classes, if requested.
3469          *
3470          * We must recurse one level at a time, so that multiply-inheriting
3471          * children are visited the right number of times and end up with the
3472          * right attinhcount.
3473          */
3474         if (recurse)
3475         {
3476                 AlterTableCmd *childCmd = copyObject(cmd);
3477                 ColumnDef  *colDefChild = (ColumnDef *) childCmd->def;
3478
3479                 /* Child should see column as singly inherited */
3480                 colDefChild->inhcount = 1;
3481                 colDefChild->is_local = false;
3482
3483                 ATOneLevelRecursion(wqueue, rel, childCmd);
3484         }
3485         else
3486         {
3487                 /*
3488                  * If we are told not to recurse, there had better not be any child
3489                  * tables; else the addition would put them out of step.
3490                  */
3491                 if (find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
3492                         ereport(ERROR,
3493                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3494                                          errmsg("column must be added to child tables too")));
3495         }
3496 }
3497
3498 static void
3499 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3500                                 ColumnDef *colDef, bool isOid)
3501 {
3502         Oid                     myrelid = RelationGetRelid(rel);
3503         Relation        pgclass,
3504                                 attrdesc;
3505         HeapTuple       reltup;
3506         FormData_pg_attribute attribute;
3507         int                     newattnum;
3508         char            relkind;
3509         HeapTuple       typeTuple;
3510         Oid                     typeOid;
3511         int32           typmod;
3512         Form_pg_type tform;
3513         Expr       *defval;
3514
3515         attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3516
3517         /*
3518          * Are we adding the column to a recursion child?  If so, check whether to
3519          * merge with an existing definition for the column.
3520          */
3521         if (colDef->inhcount > 0)
3522         {
3523                 HeapTuple       tuple;
3524
3525                 /* Does child already have a column by this name? */
3526                 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3527                 if (HeapTupleIsValid(tuple))
3528                 {
3529                         Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3530                         Oid                     ctypeId;
3531                         int32           ctypmod;
3532
3533                         /* Child column must match by type */
3534                         ctypeId = typenameTypeId(NULL, colDef->typename, &ctypmod);
3535                         if (ctypeId != childatt->atttypid ||
3536                                 ctypmod != childatt->atttypmod)
3537                                 ereport(ERROR,
3538                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3539                                                  errmsg("child table \"%s\" has different type for column \"%s\"",
3540                                                         RelationGetRelationName(rel), colDef->colname)));
3541
3542                         /* If it's OID, child column must actually be OID */
3543                         if (isOid && childatt->attnum != ObjectIdAttributeNumber)
3544                                 ereport(ERROR,
3545                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3546                                  errmsg("child table \"%s\" has a conflicting \"%s\" column",
3547                                                 RelationGetRelationName(rel), colDef->colname)));
3548
3549                         /* Bump the existing child att's inhcount */
3550                         childatt->attinhcount++;
3551                         simple_heap_update(attrdesc, &tuple->t_self, tuple);
3552                         CatalogUpdateIndexes(attrdesc, tuple);
3553
3554                         heap_freetuple(tuple);
3555
3556                         /* Inform the user about the merge */
3557                         ereport(NOTICE,
3558                           (errmsg("merging definition of column \"%s\" for child \"%s\"",
3559                                           colDef->colname, RelationGetRelationName(rel))));
3560
3561                         heap_close(attrdesc, RowExclusiveLock);
3562                         return;
3563                 }
3564         }
3565
3566         pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3567
3568         reltup = SearchSysCacheCopy(RELOID,
3569                                                                 ObjectIdGetDatum(myrelid),
3570                                                                 0, 0, 0);
3571         if (!HeapTupleIsValid(reltup))
3572                 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3573         relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
3574
3575         /*
3576          * this test is deliberately not attisdropped-aware, since if one tries to
3577          * add a column matching a dropped column name, it's gonna fail anyway.
3578          */
3579         if (SearchSysCacheExists(ATTNAME,
3580                                                          ObjectIdGetDatum(myrelid),
3581                                                          PointerGetDatum(colDef->colname),
3582                                                          0, 0))
3583                 ereport(ERROR,
3584                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
3585                                  errmsg("column \"%s\" of relation \"%s\" already exists",
3586                                                 colDef->colname, RelationGetRelationName(rel))));
3587
3588         /* Determine the new attribute's number */
3589         if (isOid)
3590                 newattnum = ObjectIdAttributeNumber;
3591         else
3592         {
3593                 newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
3594                 if (newattnum > MaxHeapAttributeNumber)
3595                         ereport(ERROR,
3596                                         (errcode(ERRCODE_TOO_MANY_COLUMNS),
3597                                          errmsg("tables can have at most %d columns",
3598                                                         MaxHeapAttributeNumber)));
3599         }
3600
3601         typeTuple = typenameType(NULL, colDef->typename, &typmod);
3602         tform = (Form_pg_type) GETSTRUCT(typeTuple);
3603         typeOid = HeapTupleGetOid(typeTuple);
3604
3605         /* make sure datatype is legal for a column */
3606         CheckAttributeType(colDef->colname, typeOid);
3607
3608         /* construct new attribute's pg_attribute entry */
3609         attribute.attrelid = myrelid;
3610         namestrcpy(&(attribute.attname), colDef->colname);
3611         attribute.atttypid = typeOid;
3612         attribute.attstattarget = (newattnum > 0) ? -1 : 0;
3613         attribute.attlen = tform->typlen;
3614         attribute.attcacheoff = -1;
3615         attribute.atttypmod = typmod;
3616         attribute.attnum = newattnum;
3617         attribute.attbyval = tform->typbyval;
3618         attribute.attndims = list_length(colDef->typename->arrayBounds);
3619         attribute.attstorage = tform->typstorage;
3620         attribute.attalign = tform->typalign;
3621         attribute.attnotnull = colDef->is_not_null;
3622         attribute.atthasdef = false;
3623         attribute.attisdropped = false;
3624         attribute.attislocal = colDef->is_local;
3625         attribute.attinhcount = colDef->inhcount;
3626         /* attribute.attacl is handled by InsertPgAttributeTuple */
3627
3628         ReleaseSysCache(typeTuple);
3629
3630         InsertPgAttributeTuple(attrdesc, &attribute, NULL);
3631
3632         heap_close(attrdesc, RowExclusiveLock);
3633
3634         /*
3635          * Update pg_class tuple as appropriate
3636          */
3637         if (isOid)
3638                 ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
3639         else
3640                 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
3641
3642         simple_heap_update(pgclass, &reltup->t_self, reltup);
3643
3644         /* keep catalog indexes current */
3645         CatalogUpdateIndexes(pgclass, reltup);
3646
3647         heap_freetuple(reltup);
3648
3649         heap_close(pgclass, RowExclusiveLock);
3650
3651         /* Make the attribute's catalog entry visible */
3652         CommandCounterIncrement();
3653
3654         /*
3655          * Store the DEFAULT, if any, in the catalogs
3656          */
3657         if (colDef->raw_default)
3658         {
3659                 RawColumnDefault *rawEnt;
3660
3661                 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3662                 rawEnt->attnum = attribute.attnum;
3663                 rawEnt->raw_default = copyObject(colDef->raw_default);
3664
3665                 /*
3666                  * This function is intended for CREATE TABLE, so it processes a
3667                  * _list_ of defaults, but we just do one.
3668                  */
3669                 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3670
3671                 /* Make the additional catalog changes visible */
3672                 CommandCounterIncrement();
3673         }
3674
3675         /*
3676          * Tell Phase 3 to fill in the default expression, if there is one.
3677          *
3678          * If there is no default, Phase 3 doesn't have to do anything, because
3679          * that effectively means that the default is NULL.  The heap tuple access
3680          * routines always check for attnum > # of attributes in tuple, and return
3681          * NULL if so, so without any modification of the tuple data we will get
3682          * the effect of NULL values in the new column.
3683          *
3684          * An exception occurs when the new column is of a domain type: the domain
3685          * might have a NOT NULL constraint, or a check constraint that indirectly
3686          * rejects nulls.  If there are any domain constraints then we construct
3687          * an explicit NULL default value that will be passed through
3688          * CoerceToDomain processing.  (This is a tad inefficient, since it causes
3689          * rewriting the table which we really don't have to do, but the present
3690          * design of domain processing doesn't offer any simple way of checking
3691          * the constraints more directly.)
3692          *
3693          * Note: we use build_column_default, and not just the cooked default
3694          * returned by AddRelationNewConstraints, so that the right thing happens
3695          * when a datatype's default applies.
3696          *
3697          * We skip this step completely for views.      For a view, we can only get
3698          * here from CREATE OR REPLACE VIEW, which historically doesn't set up
3699          * defaults, not even for domain-typed columns.  And in any case we
3700          * mustn't invoke Phase 3 on a view, since it has no storage.
3701          */
3702         if (relkind != RELKIND_VIEW && attribute.attnum > 0)
3703         {
3704                 defval = (Expr *) build_column_default(rel, attribute.attnum);
3705
3706                 if (!defval && GetDomainConstraints(typeOid) != NIL)
3707                 {
3708                         Oid                     baseTypeId;
3709                         int32           baseTypeMod;
3710
3711                         baseTypeMod = typmod;
3712                         baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3713                         defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3714                         defval = (Expr *) coerce_to_target_type(NULL,
3715                                                                                                         (Node *) defval,
3716                                                                                                         baseTypeId,
3717                                                                                                         typeOid,
3718                                                                                                         typmod,
3719                                                                                                         COERCION_ASSIGNMENT,
3720                                                                                                         COERCE_IMPLICIT_CAST,
3721                                                                                                         -1);
3722                         if (defval == NULL) /* should not happen */
3723                                 elog(ERROR, "failed to coerce base type to domain");
3724                 }
3725
3726                 if (defval)
3727                 {
3728                         NewColumnValue *newval;
3729
3730                         newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3731                         newval->attnum = attribute.attnum;
3732                         newval->expr = defval;
3733
3734                         tab->newvals = lappend(tab->newvals, newval);
3735                 }
3736
3737                 /*
3738                  * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3739                  * (Note we don't do this for an OID column.  OID will be marked not
3740                  * null, but since it's filled specially, there's no need to test
3741                  * anything.)
3742                  */
3743                 tab->new_notnull |= colDef->is_not_null;
3744         }
3745
3746         /*
3747          * If we are adding an OID column, we have to tell Phase 3 to rewrite the
3748          * table to fix that.
3749          */
3750         if (isOid)
3751                 tab->new_changeoids = true;
3752
3753         /*
3754          * Add needed dependency entries for the new column.
3755          */
3756         add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
3757 }
3758
3759 /*
3760  * Install a column's dependency on its datatype.
3761  */
3762 static void
3763 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3764 {
3765         ObjectAddress myself,
3766                                 referenced;
3767
3768         myself.classId = RelationRelationId;
3769         myself.objectId = relid;
3770         myself.objectSubId = attnum;
3771         referenced.classId = TypeRelationId;
3772         referenced.objectId = typid;
3773         referenced.objectSubId = 0;
3774         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3775 }
3776
3777 /*
3778  * ALTER TABLE SET WITH OIDS
3779  *
3780  * Basically this is an ADD COLUMN for the special OID column.  We have
3781  * to cons up a ColumnDef node because the ADD COLUMN code needs one.
3782  */
3783 static void
3784 ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd)
3785 {
3786         /* If we're recursing to a child table, the ColumnDef is already set up */
3787         if (cmd->def == NULL)
3788         {
3789                 ColumnDef  *cdef = makeNode(ColumnDef);
3790
3791                 cdef->colname = pstrdup("oid");
3792                 cdef->typename = makeTypeNameFromOid(OIDOID, -1);
3793                 cdef->inhcount = 0;
3794                 cdef->is_local = true;
3795                 cdef->is_not_null = true;
3796                 cmd->def = (Node *) cdef;
3797         }
3798         ATPrepAddColumn(wqueue, rel, recurse, cmd);
3799 }
3800
3801 /*
3802  * ALTER TABLE ALTER COLUMN DROP NOT NULL
3803  */
3804 static void
3805 ATExecDropNotNull(Relation rel, const char *colName)
3806 {
3807         HeapTuple       tuple;
3808         AttrNumber      attnum;
3809         Relation        attr_rel;
3810         List       *indexoidlist;
3811         ListCell   *indexoidscan;
3812
3813         /*
3814          * lookup the attribute
3815          */
3816         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3817
3818         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3819
3820         if (!HeapTupleIsValid(tuple))
3821                 ereport(ERROR,
3822                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3823                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3824                                                 colName, RelationGetRelationName(rel))));
3825
3826         attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3827
3828         /* Prevent them from altering a system attribute */
3829         if (attnum <= 0)
3830                 ereport(ERROR,
3831                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3832                                  errmsg("cannot alter system column \"%s\"",
3833                                                 colName)));
3834
3835         /*
3836          * Check that the attribute is not in a primary key
3837          */
3838
3839         /* Loop over all indexes on the relation */
3840         indexoidlist = RelationGetIndexList(rel);
3841
3842         foreach(indexoidscan, indexoidlist)
3843         {
3844                 Oid                     indexoid = lfirst_oid(indexoidscan);
3845                 HeapTuple       indexTuple;
3846                 Form_pg_index indexStruct;
3847                 int                     i;
3848
3849                 indexTuple = SearchSysCache(INDEXRELID,
3850                                                                         ObjectIdGetDatum(indexoid),
3851                                                                         0, 0, 0);
3852                 if (!HeapTupleIsValid(indexTuple))
3853                         elog(ERROR, "cache lookup failed for index %u", indexoid);
3854                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3855
3856                 /* If the index is not a primary key, skip the check */
3857                 if (indexStruct->indisprimary)
3858                 {
3859                         /*
3860                          * Loop over each attribute in the primary key and see if it
3861                          * matches the to-be-altered attribute
3862                          */
3863                         for (i = 0; i < indexStruct->indnatts; i++)
3864                         {
3865                                 if (indexStruct->indkey.values[i] == attnum)
3866                                         ereport(ERROR,
3867                                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3868                                                          errmsg("column \"%s\" is in a primary key",
3869                                                                         colName)));
3870                         }
3871                 }
3872
3873                 ReleaseSysCache(indexTuple);
3874         }
3875
3876         list_free(indexoidlist);
3877
3878         /*
3879          * Okay, actually perform the catalog change ... if needed
3880          */
3881         if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3882         {
3883                 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3884
3885                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3886
3887                 /* keep the system catalog indexes current */
3888                 CatalogUpdateIndexes(attr_rel, tuple);
3889         }
3890
3891         heap_close(attr_rel, RowExclusiveLock);
3892 }
3893
3894 /*
3895  * ALTER TABLE ALTER COLUMN SET NOT NULL
3896  */
3897 static void
3898 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3899                                  const char *colName)
3900 {
3901         HeapTuple       tuple;
3902         AttrNumber      attnum;
3903         Relation        attr_rel;
3904
3905         /*
3906          * lookup the attribute
3907          */
3908         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3909
3910         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3911
3912         if (!HeapTupleIsValid(tuple))
3913                 ereport(ERROR,
3914                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3915                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3916                                                 colName, RelationGetRelationName(rel))));
3917
3918         attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3919
3920         /* Prevent them from altering a system attribute */
3921         if (attnum <= 0)
3922                 ereport(ERROR,
3923                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3924                                  errmsg("cannot alter system column \"%s\"",
3925                                                 colName)));
3926
3927         /*
3928          * Okay, actually perform the catalog change ... if needed
3929          */
3930         if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3931         {
3932                 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3933
3934                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3935
3936                 /* keep the system catalog indexes current */
3937                 CatalogUpdateIndexes(attr_rel, tuple);
3938
3939                 /* Tell Phase 3 it needs to test the constraint */
3940                 tab->new_notnull = true;
3941         }
3942
3943         heap_close(attr_rel, RowExclusiveLock);
3944 }
3945
3946 /*
3947  * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3948  */
3949 static void
3950 ATExecColumnDefault(Relation rel, const char *colName,
3951                                         Node *newDefault)
3952 {
3953         AttrNumber      attnum;
3954
3955         /*
3956          * get the number of the attribute
3957          */
3958         attnum = get_attnum(RelationGetRelid(rel), colName);
3959         if (attnum == InvalidAttrNumber)
3960                 ereport(ERROR,
3961                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3962                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3963                                                 colName, RelationGetRelationName(rel))));
3964
3965         /* Prevent them from altering a system attribute */
3966         if (attnum <= 0)
3967                 ereport(ERROR,
3968                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3969                                  errmsg("cannot alter system column \"%s\"",
3970                                                 colName)));
3971
3972         /*
3973          * Remove any old default for the column.  We use RESTRICT here for
3974          * safety, but at present we do not expect anything to depend on the
3975          * default.
3976          */
3977         RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3978
3979         if (newDefault)
3980         {
3981                 /* SET DEFAULT */
3982                 RawColumnDefault *rawEnt;
3983
3984                 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3985                 rawEnt->attnum = attnum;
3986                 rawEnt->raw_default = newDefault;
3987
3988                 /*
3989                  * This function is intended for CREATE TABLE, so it processes a
3990                  * _list_ of defaults, but we just do one.
3991                  */
3992                 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3993         }
3994 }
3995
3996 /*
3997  * ALTER TABLE ALTER COLUMN SET STATISTICS
3998  */
3999 static void
4000 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
4001 {
4002         /*
4003          * We do our own permission checking because (a) we want to allow SET
4004          * STATISTICS on indexes (for expressional index columns), and (b) we want
4005          * to allow SET STATISTICS on system catalogs without requiring
4006          * allowSystemTableMods to be turned on.
4007          */
4008         if (rel->rd_rel->relkind != RELKIND_RELATION &&
4009                 rel->rd_rel->relkind != RELKIND_INDEX)
4010                 ereport(ERROR,
4011                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4012                                  errmsg("\"%s\" is not a table or index",
4013                                                 RelationGetRelationName(rel))));
4014
4015         /* Permissions checks */
4016         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4017                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4018                                            RelationGetRelationName(rel));
4019 }
4020
4021 static void
4022 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
4023 {
4024         int                     newtarget;
4025         Relation        attrelation;
4026         HeapTuple       tuple;
4027         Form_pg_attribute attrtuple;
4028
4029         Assert(IsA(newValue, Integer));
4030         newtarget = intVal(newValue);
4031
4032         /*
4033          * Limit target to a sane range
4034          */
4035         if (newtarget < -1)
4036         {
4037                 ereport(ERROR,
4038                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4039                                  errmsg("statistics target %d is too low",
4040                                                 newtarget)));
4041         }
4042         else if (newtarget > 10000)
4043         {
4044                 newtarget = 10000;
4045                 ereport(WARNING,
4046                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4047                                  errmsg("lowering statistics target to %d",
4048                                                 newtarget)));
4049         }
4050
4051         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4052
4053         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4054
4055         if (!HeapTupleIsValid(tuple))
4056                 ereport(ERROR,
4057                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
4058                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
4059                                                 colName, RelationGetRelationName(rel))));
4060         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4061
4062         if (attrtuple->attnum <= 0)
4063                 ereport(ERROR,
4064                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4065                                  errmsg("cannot alter system column \"%s\"",
4066                                                 colName)));
4067
4068         attrtuple->attstattarget = newtarget;
4069
4070         simple_heap_update(attrelation, &tuple->t_self, tuple);
4071
4072         /* keep system catalog indexes current */
4073         CatalogUpdateIndexes(attrelation, tuple);
4074
4075         heap_freetuple(tuple);
4076
4077         heap_close(attrelation, RowExclusiveLock);
4078 }
4079
4080 /*
4081  * ALTER TABLE ALTER COLUMN SET STORAGE
4082  */
4083 static void
4084 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
4085 {
4086         char       *storagemode;
4087         char            newstorage;
4088         Relation        attrelation;
4089         HeapTuple       tuple;
4090         Form_pg_attribute attrtuple;
4091
4092         Assert(IsA(newValue, String));
4093         storagemode = strVal(newValue);
4094
4095         if (pg_strcasecmp(storagemode, "plain") == 0)
4096                 newstorage = 'p';
4097         else if (pg_strcasecmp(storagemode, "external") == 0)
4098                 newstorage = 'e';
4099         else if (pg_strcasecmp(storagemode, "extended") == 0)
4100                 newstorage = 'x';
4101         else if (pg_strcasecmp(storagemode, "main") == 0)
4102                 newstorage = 'm';
4103         else
4104         {
4105                 ereport(ERROR,
4106                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4107                                  errmsg("invalid storage type \"%s\"",
4108                                                 storagemode)));
4109                 newstorage = 0;                 /* keep compiler quiet */
4110         }
4111
4112         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4113
4114         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4115
4116         if (!HeapTupleIsValid(tuple))
4117                 ereport(ERROR,
4118                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
4119                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
4120                                                 colName, RelationGetRelationName(rel))));
4121         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4122
4123         if (attrtuple->attnum <= 0)
4124                 ereport(ERROR,
4125                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4126                                  errmsg("cannot alter system column \"%s\"",
4127                                                 colName)));
4128
4129         /*
4130          * safety check: do not allow toasted storage modes unless column datatype
4131          * is TOAST-aware.
4132          */
4133         if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4134                 attrtuple->attstorage = newstorage;
4135         else
4136                 ereport(ERROR,
4137                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4138                                  errmsg("column data type %s can only have storage PLAIN",
4139                                                 format_type_be(attrtuple->atttypid))));
4140
4141         simple_heap_update(attrelation, &tuple->t_self, tuple);
4142
4143         /* keep system catalog indexes current */
4144         CatalogUpdateIndexes(attrelation, tuple);
4145
4146         heap_freetuple(tuple);
4147
4148         heap_close(attrelation, RowExclusiveLock);
4149 }
4150
4151
4152 /*
4153  * ALTER TABLE DROP COLUMN
4154  *
4155  * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4156  * because we have to decide at runtime whether to recurse or not depending
4157  * on whether attinhcount goes to zero or not.  (We can't check this in a
4158  * static pre-pass because it won't handle multiple inheritance situations
4159  * correctly.)
4160  */
4161 static void
4162 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
4163                                  DropBehavior behavior,
4164                                  bool recurse, bool recursing)
4165 {
4166         HeapTuple       tuple;
4167         Form_pg_attribute targetatt;
4168         AttrNumber      attnum;
4169         List       *children;
4170         ObjectAddress object;
4171
4172         /* At top level, permission check was done in ATPrepCmd, else do it */
4173         if (recursing)
4174                 ATSimplePermissions(rel, false);
4175
4176         /*
4177          * get the number of the attribute
4178          */
4179         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4180         if (!HeapTupleIsValid(tuple))
4181                 ereport(ERROR,
4182                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
4183                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
4184                                                 colName, RelationGetRelationName(rel))));
4185         targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
4186
4187         attnum = targetatt->attnum;
4188
4189         /* Can't drop a system attribute, except OID */
4190         if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
4191                 ereport(ERROR,
4192                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4193                                  errmsg("cannot drop system column \"%s\"",
4194                                                 colName)));
4195
4196         /* Don't drop inherited columns */
4197         if (targetatt->attinhcount > 0 && !recursing)
4198                 ereport(ERROR,
4199                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4200                                  errmsg("cannot drop inherited column \"%s\"",
4201                                                 colName)));
4202
4203         ReleaseSysCache(tuple);
4204
4205         /*
4206          * Propagate to children as appropriate.  Unlike most other ALTER
4207          * routines, we have to do this one level of recursion at a time; we can't
4208          * use find_all_inheritors to do it in one pass.
4209          */
4210         children = find_inheritance_children(RelationGetRelid(rel),
4211                                                                                  AccessExclusiveLock);
4212
4213         if (children)
4214         {
4215                 Relation        attr_rel;
4216                 ListCell   *child;
4217
4218                 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4219                 foreach(child, children)
4220                 {
4221                         Oid                     childrelid = lfirst_oid(child);
4222                         Relation        childrel;
4223                         Form_pg_attribute childatt;
4224
4225                         /* find_inheritance_children already got lock */
4226                         childrel = heap_open(childrelid, NoLock);
4227                         CheckTableNotInUse(childrel, "ALTER TABLE");
4228
4229                         tuple = SearchSysCacheCopyAttName(childrelid, colName);
4230                         if (!HeapTupleIsValid(tuple))           /* shouldn't happen */
4231                                 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
4232                                          colName, childrelid);
4233                         childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4234
4235                         if (childatt->attinhcount <= 0)         /* shouldn't happen */
4236                                 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
4237                                          childrelid, colName);
4238
4239                         if (recurse)
4240                         {
4241                                 /*
4242                                  * If the child column has other definition sources, just
4243                                  * decrement its inheritance count; if not, recurse to delete
4244                                  * it.
4245                                  */
4246                                 if (childatt->attinhcount == 1 && !childatt->attislocal)
4247                                 {
4248                                         /* Time to delete this child column, too */
4249                                         ATExecDropColumn(wqueue, childrel, colName,
4250                                                                          behavior, true, true);
4251                                 }
4252                                 else
4253                                 {
4254                                         /* Child column must survive my deletion */
4255                                         childatt->attinhcount--;
4256
4257                                         simple_heap_update(attr_rel, &tuple->t_self, tuple);
4258
4259                                         /* keep the system catalog indexes current */
4260                                         CatalogUpdateIndexes(attr_rel, tuple);
4261
4262                                         /* Make update visible */
4263                                         CommandCounterIncrement();
4264                                 }
4265                         }
4266                         else
4267                         {
4268                                 /*
4269                                  * If we were told to drop ONLY in this table (no recursion),
4270                                  * we need to mark the inheritors' attributes as locally
4271                                  * defined rather than inherited.
4272                                  */
4273                                 childatt->attinhcount--;
4274                                 childatt->attislocal = true;
4275
4276                                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4277
4278                                 /* keep the system catalog indexes current */
4279                                 CatalogUpdateIndexes(attr_rel, tuple);
4280
4281                                 /* Make update visible */
4282                                 CommandCounterIncrement();
4283                         }
4284
4285                         heap_freetuple(tuple);
4286
4287                         heap_close(childrel, NoLock);
4288                 }
4289                 heap_close(attr_rel, RowExclusiveLock);
4290         }
4291
4292         /*
4293          * Perform the actual column deletion
4294          */
4295         object.classId = RelationRelationId;
4296         object.objectId = RelationGetRelid(rel);
4297         object.objectSubId = attnum;
4298
4299         performDeletion(&object, behavior);
4300
4301         /*
4302          * If we dropped the OID column, must adjust pg_class.relhasoids and tell
4303          * Phase 3 to physically get rid of the column.
4304          */
4305         if (attnum == ObjectIdAttributeNumber)
4306         {
4307                 Relation        class_rel;
4308                 Form_pg_class tuple_class;
4309                 AlteredTableInfo *tab;
4310
4311                 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
4312
4313                 tuple = SearchSysCacheCopy(RELOID,
4314                                                                    ObjectIdGetDatum(RelationGetRelid(rel)),
4315                                                                    0, 0, 0);
4316                 if (!HeapTupleIsValid(tuple))
4317                         elog(ERROR, "cache lookup failed for relation %u",
4318                                  RelationGetRelid(rel));
4319                 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
4320
4321                 tuple_class->relhasoids = false;
4322                 simple_heap_update(class_rel, &tuple->t_self, tuple);
4323
4324                 /* Keep the catalog indexes up to date */
4325                 CatalogUpdateIndexes(class_rel, tuple);
4326
4327                 heap_close(class_rel, RowExclusiveLock);
4328
4329                 /* Find or create work queue entry for this table */
4330                 tab = ATGetQueueEntry(wqueue, rel);
4331
4332                 /* Tell Phase 3 to physically remove the OID column */
4333                 tab->new_changeoids = true;
4334         }
4335 }
4336
4337 /*
4338  * ALTER TABLE ADD INDEX
4339  *
4340  * There is no such command in the grammar, but parse_utilcmd.c converts
4341  * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands.  This lets
4342  * us schedule creation of the index at the appropriate time during ALTER.
4343  */
4344 static void
4345 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
4346                            IndexStmt *stmt, bool is_rebuild)
4347 {
4348         bool            check_rights;
4349         bool            skip_build;
4350         bool            quiet;
4351
4352         Assert(IsA(stmt, IndexStmt));
4353
4354         /* suppress schema rights check when rebuilding existing index */
4355         check_rights = !is_rebuild;
4356         /* skip index build if phase 3 will have to rewrite table anyway */
4357         skip_build = (tab->newvals != NIL);
4358         /* suppress notices when rebuilding existing index */
4359         quiet = is_rebuild;
4360
4361         /* The IndexStmt has already been through transformIndexStmt */
4362
4363         DefineIndex(stmt->relation, /* relation */
4364                                 stmt->idxname,  /* index name */
4365                                 InvalidOid,             /* no predefined OID */
4366                                 stmt->accessMethod,             /* am name */
4367                                 stmt->tableSpace,
4368                                 stmt->indexParams,              /* parameters */
4369                                 (Expr *) stmt->whereClause,
4370                                 stmt->options,
4371                                 stmt->unique,
4372                                 stmt->primary,
4373                                 stmt->isconstraint,
4374                                 true,                   /* is_alter_table */
4375                                 check_rights,
4376                                 skip_build,
4377                                 quiet,
4378                                 false);
4379 }
4380
4381 /*
4382  * ALTER TABLE ADD CONSTRAINT
4383  */
4384 static void
4385 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4386                                         Node *newConstraint, bool recurse)
4387 {
4388         switch (nodeTag(newConstraint))
4389         {
4390                 case T_Constraint:
4391                         {
4392                                 Constraint *constr = (Constraint *) newConstraint;
4393
4394                                 /*
4395                                  * Currently, we only expect to see CONSTR_CHECK nodes
4396                                  * arriving here (see the preprocessing done in
4397                                  * parse_utilcmd.c).  Use a switch anyway to make it easier to
4398                                  * add more code later.
4399                                  */
4400                                 switch (constr->contype)
4401                                 {
4402                                         case CONSTR_CHECK:
4403                                                 ATAddCheckConstraint(wqueue, tab, rel,
4404                                                                                          constr, recurse, false);
4405                                                 break;
4406                                         default:
4407                                                 elog(ERROR, "unrecognized constraint type: %d",
4408                                                          (int) constr->contype);
4409                                 }
4410                                 break;
4411                         }
4412                 case T_FkConstraint:
4413                         {
4414                                 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
4415
4416                                 /*
4417                                  * Note that we currently never recurse for FK constraints, so
4418                                  * the "recurse" flag is silently ignored.
4419                                  *
4420                                  * Assign or validate constraint name
4421                                  */
4422                                 if (fkconstraint->constr_name)
4423                                 {
4424                                         if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4425                                                                                          RelationGetRelid(rel),
4426                                                                                          RelationGetNamespace(rel),
4427                                                                                          fkconstraint->constr_name))
4428                                                 ereport(ERROR,
4429                                                                 (errcode(ERRCODE_DUPLICATE_OBJECT),
4430                                                                  errmsg("constraint \"%s\" for relation \"%s\" already exists",
4431                                                                                 fkconstraint->constr_name,
4432                                                                                 RelationGetRelationName(rel))));
4433                                 }
4434                                 else
4435                                         fkconstraint->constr_name =
4436                                                 ChooseConstraintName(RelationGetRelationName(rel),
4437                                                                         strVal(linitial(fkconstraint->fk_attrs)),
4438                                                                                          "fkey",
4439                                                                                          RelationGetNamespace(rel),
4440                                                                                          NIL);
4441
4442                                 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
4443
4444                                 break;
4445                         }
4446                 default:
4447                         elog(ERROR, "unrecognized node type: %d",
4448                                  (int) nodeTag(newConstraint));
4449         }
4450 }
4451
4452 /*
4453  * Add a check constraint to a single table and its children
4454  *
4455  * Subroutine for ATExecAddConstraint.
4456  *
4457  * We must recurse to child tables during execution, rather than using
4458  * ALTER TABLE's normal prep-time recursion.  The reason is that all the
4459  * constraints *must* be given the same name, else they won't be seen as
4460  * related later.  If the user didn't explicitly specify a name, then
4461  * AddRelationNewConstraints would normally assign different names to the
4462  * child constraints.  To fix that, we must capture the name assigned at
4463  * the parent table and pass that down.
4464  */
4465 static void
4466 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4467                                          Constraint *constr, bool recurse, bool recursing)
4468 {
4469         List       *newcons;
4470         ListCell   *lcon;
4471         List       *children;
4472         ListCell   *child;
4473
4474         /* At top level, permission check was done in ATPrepCmd, else do it */
4475         if (recursing)
4476                 ATSimplePermissions(rel, false);
4477
4478         /*
4479          * Call AddRelationNewConstraints to do the work, making sure it works on
4480          * a copy of the Constraint so transformExpr can't modify the original. It
4481          * returns a list of cooked constraints.
4482          *
4483          * If the constraint ends up getting merged with a pre-existing one, it's
4484          * omitted from the returned list, which is what we want: we do not need
4485          * to do any validation work.  That can only happen at child tables,
4486          * though, since we disallow merging at the top level.
4487          */
4488         newcons = AddRelationNewConstraints(rel, NIL,
4489                                                                                 list_make1(copyObject(constr)),
4490                                                                                 recursing, !recursing);
4491
4492         /* Add each constraint to Phase 3's queue */
4493         foreach(lcon, newcons)
4494         {
4495                 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
4496                 NewConstraint *newcon;
4497
4498                 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4499                 newcon->name = ccon->name;
4500                 newcon->contype = ccon->contype;
4501                 /* ExecQual wants implicit-AND format */
4502                 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
4503
4504                 tab->constraints = lappend(tab->constraints, newcon);
4505
4506                 /* Save the actually assigned name if it was defaulted */
4507                 if (constr->name == NULL)
4508                         constr->name = ccon->name;
4509         }
4510
4511         /* At this point we must have a locked-down name to use */
4512         Assert(constr->name != NULL);
4513
4514         /* Advance command counter in case same table is visited multiple times */
4515         CommandCounterIncrement();
4516
4517         /*
4518          * Propagate to children as appropriate.  Unlike most other ALTER
4519          * routines, we have to do this one level of recursion at a time; we can't
4520          * use find_all_inheritors to do it in one pass.
4521          */
4522         children = find_inheritance_children(RelationGetRelid(rel),
4523                                                                                  AccessExclusiveLock);
4524
4525         /*
4526          * If we are told not to recurse, there had better not be any child
4527          * tables; else the addition would put them out of step.
4528          */
4529         if (children && !recurse)
4530                 ereport(ERROR,
4531                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4532                                  errmsg("constraint must be added to child tables too")));
4533
4534         foreach(child, children)
4535         {
4536                 Oid                     childrelid = lfirst_oid(child);
4537                 Relation        childrel;
4538                 AlteredTableInfo *childtab;
4539
4540                 /* find_inheritance_children already got lock */
4541                 childrel = heap_open(childrelid, NoLock);
4542                 CheckTableNotInUse(childrel, "ALTER TABLE");
4543
4544                 /* Find or create work queue entry for this table */
4545                 childtab = ATGetQueueEntry(wqueue, childrel);
4546
4547                 /* Recurse to child */
4548                 ATAddCheckConstraint(wqueue, childtab, childrel,
4549                                                          constr, recurse, true);
4550
4551                 heap_close(childrel, NoLock);
4552         }
4553 }
4554
4555 /*
4556  * Add a foreign-key constraint to a single table
4557  *
4558  * Subroutine for ATExecAddConstraint.  Must already hold exclusive
4559  * lock on the rel, and have done appropriate validity checks for it.
4560  * We do permissions checks here, however.
4561  */
4562 static void
4563 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4564                                                   FkConstraint *fkconstraint)
4565 {
4566         Relation        pkrel;
4567         int16           pkattnum[INDEX_MAX_KEYS];
4568         int16           fkattnum[INDEX_MAX_KEYS];
4569         Oid                     pktypoid[INDEX_MAX_KEYS];
4570         Oid                     fktypoid[INDEX_MAX_KEYS];
4571         Oid                     opclasses[INDEX_MAX_KEYS];
4572         Oid                     pfeqoperators[INDEX_MAX_KEYS];
4573         Oid                     ppeqoperators[INDEX_MAX_KEYS];
4574         Oid                     ffeqoperators[INDEX_MAX_KEYS];
4575         int                     i;
4576         int                     numfks,
4577                                 numpks;
4578         Oid                     indexOid;
4579         Oid                     constrOid;
4580
4581         /*
4582          * Grab an exclusive lock on the pk table, so that someone doesn't delete
4583          * rows out from under us. (Although a lesser lock would do for that
4584          * purpose, we'll need exclusive lock anyway to add triggers to the pk
4585          * table; trying to start with a lesser lock will just create a risk of
4586          * deadlock.)
4587          */
4588         pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4589
4590         /*
4591          * Validity checks (permission checks wait till we have the column
4592          * numbers)
4593          */
4594         if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4595                 ereport(ERROR,
4596                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4597                                  errmsg("referenced relation \"%s\" is not a table",
4598                                                 RelationGetRelationName(pkrel))));
4599
4600         if (!allowSystemTableMods && IsSystemRelation(pkrel))
4601                 ereport(ERROR,
4602                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4603                                  errmsg("permission denied: \"%s\" is a system catalog",
4604                                                 RelationGetRelationName(pkrel))));
4605
4606         /*
4607          * Disallow reference from permanent table to temp table or vice versa.
4608          * (The ban on perm->temp is for fairly obvious reasons.  The ban on
4609          * temp->perm is because other backends might need to run the RI triggers
4610          * on the perm table, but they can't reliably see tuples the owning
4611          * backend has created in the temp table, because non-shared buffers are
4612          * used for temp tables.)
4613          */
4614         if (pkrel->rd_istemp)
4615         {
4616                 if (!rel->rd_istemp)
4617                         ereport(ERROR,
4618                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4619                                          errmsg("cannot reference temporary table from permanent table constraint")));
4620         }
4621         else
4622         {
4623                 if (rel->rd_istemp)
4624                         ereport(ERROR,
4625                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4626                                          errmsg("cannot reference permanent table from temporary table constraint")));
4627         }
4628
4629         /*
4630          * Look up the referencing attributes to make sure they exist, and record
4631          * their attnums and type OIDs.
4632          */
4633         MemSet(pkattnum, 0, sizeof(pkattnum));
4634         MemSet(fkattnum, 0, sizeof(fkattnum));
4635         MemSet(pktypoid, 0, sizeof(pktypoid));
4636         MemSet(fktypoid, 0, sizeof(fktypoid));
4637         MemSet(opclasses, 0, sizeof(opclasses));
4638         MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4639         MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4640         MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4641
4642         numfks = transformColumnNameList(RelationGetRelid(rel),
4643                                                                          fkconstraint->fk_attrs,
4644                                                                          fkattnum, fktypoid);
4645
4646         /*
4647          * If the attribute list for the referenced table was omitted, lookup the
4648          * definition of the primary key and use it.  Otherwise, validate the
4649          * supplied attribute list.  In either case, discover the index OID and
4650          * index opclasses, and the attnums and type OIDs of the attributes.
4651          */
4652         if (fkconstraint->pk_attrs == NIL)
4653         {
4654                 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4655                                                                                         &fkconstraint->pk_attrs,
4656                                                                                         pkattnum, pktypoid,
4657                                                                                         opclasses);
4658         }
4659         else
4660         {
4661                 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4662                                                                                  fkconstraint->pk_attrs,
4663                                                                                  pkattnum, pktypoid);
4664                 /* Look for an index matching the column list */
4665                 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4666                                                                                    opclasses);
4667         }
4668
4669         /*
4670          * Now we can check permissions.
4671          */
4672         checkFkeyPermissions(pkrel, pkattnum, numpks);
4673         checkFkeyPermissions(rel, fkattnum, numfks);
4674
4675         /*
4676          * Look up the equality operators to use in the constraint.
4677          *
4678          * Note that we have to be careful about the difference between the actual
4679          * PK column type and the opclass' declared input type, which might be
4680          * only binary-compatible with it.      The declared opcintype is the right
4681          * thing to probe pg_amop with.
4682          */
4683         if (numfks != numpks)
4684                 ereport(ERROR,
4685                                 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4686                                  errmsg("number of referencing and referenced columns for foreign key disagree")));
4687
4688         for (i = 0; i < numpks; i++)
4689         {
4690                 Oid                     pktype = pktypoid[i];
4691                 Oid                     fktype = fktypoid[i];
4692                 Oid                     fktyped;
4693                 HeapTuple       cla_ht;
4694                 Form_pg_opclass cla_tup;
4695                 Oid                     amid;
4696                 Oid                     opfamily;
4697                 Oid                     opcintype;
4698                 Oid                     pfeqop;
4699                 Oid                     ppeqop;
4700                 Oid                     ffeqop;
4701                 int16           eqstrategy;
4702
4703                 /* We need several fields out of the pg_opclass entry */
4704                 cla_ht = SearchSysCache(CLAOID,
4705                                                                 ObjectIdGetDatum(opclasses[i]),
4706                                                                 0, 0, 0);
4707                 if (!HeapTupleIsValid(cla_ht))
4708                         elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4709                 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4710                 amid = cla_tup->opcmethod;
4711                 opfamily = cla_tup->opcfamily;
4712                 opcintype = cla_tup->opcintype;
4713                 ReleaseSysCache(cla_ht);
4714
4715                 /*
4716                  * Check it's a btree; currently this can never fail since no other
4717                  * index AMs support unique indexes.  If we ever did have other types
4718                  * of unique indexes, we'd need a way to determine which operator
4719                  * strategy number is equality.  (Is it reasonable to insist that
4720                  * every such index AM use btree's number for equality?)
4721                  */
4722                 if (amid != BTREE_AM_OID)
4723                         elog(ERROR, "only b-tree indexes are supported for foreign keys");
4724                 eqstrategy = BTEqualStrategyNumber;
4725
4726                 /*
4727                  * There had better be a primary equality operator for the index.
4728                  * We'll use it for PK = PK comparisons.
4729                  */
4730                 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4731                                                                          eqstrategy);
4732
4733                 if (!OidIsValid(ppeqop))
4734                         elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4735                                  eqstrategy, opcintype, opcintype, opfamily);
4736
4737                 /*
4738                  * Are there equality operators that take exactly the FK type? Assume
4739                  * we should look through any domain here.
4740                  */
4741                 fktyped = getBaseType(fktype);
4742
4743                 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4744                                                                          eqstrategy);
4745                 if (OidIsValid(pfeqop))
4746                         ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4747                                                                                  eqstrategy);
4748                 else
4749                         ffeqop = InvalidOid;    /* keep compiler quiet */
4750
4751                 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4752                 {
4753                         /*
4754                          * Otherwise, look for an implicit cast from the FK type to the
4755                          * opcintype, and if found, use the primary equality operator.
4756                          * This is a bit tricky because opcintype might be a polymorphic
4757                          * type such as ANYARRAY or ANYENUM; so what we have to test is
4758                          * whether the two actual column types can be concurrently cast to
4759                          * that type.  (Otherwise, we'd fail to reject combinations such
4760                          * as int[] and point[].)
4761                          */
4762                         Oid                     input_typeids[2];
4763                         Oid                     target_typeids[2];
4764
4765                         input_typeids[0] = pktype;
4766                         input_typeids[1] = fktype;
4767                         target_typeids[0] = opcintype;
4768                         target_typeids[1] = opcintype;
4769                         if (can_coerce_type(2, input_typeids, target_typeids,
4770                                                                 COERCION_IMPLICIT))
4771                                 pfeqop = ffeqop = ppeqop;
4772                 }
4773
4774                 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4775                         ereport(ERROR,
4776                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
4777                                          errmsg("foreign key constraint \"%s\" "
4778                                                         "cannot be implemented",
4779                                                         fkconstraint->constr_name),
4780                                          errdetail("Key columns \"%s\" and \"%s\" "
4781                                                            "are of incompatible types: %s and %s.",
4782                                                            strVal(list_nth(fkconstraint->fk_attrs, i)),
4783                                                            strVal(list_nth(fkconstraint->pk_attrs, i)),
4784                                                            format_type_be(fktype),
4785                                                            format_type_be(pktype))));
4786
4787                 pfeqoperators[i] = pfeqop;
4788                 ppeqoperators[i] = ppeqop;
4789                 ffeqoperators[i] = ffeqop;
4790         }
4791
4792         /*
4793          * Record the FK constraint in pg_constraint.
4794          */
4795         constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4796                                                                           RelationGetNamespace(rel),
4797                                                                           CONSTRAINT_FOREIGN,
4798                                                                           fkconstraint->deferrable,
4799                                                                           fkconstraint->initdeferred,
4800                                                                           RelationGetRelid(rel),
4801                                                                           fkattnum,
4802                                                                           numfks,
4803                                                                           InvalidOid,           /* not a domain
4804                                                                                                                  * constraint */
4805                                                                           RelationGetRelid(pkrel),
4806                                                                           pkattnum,
4807                                                                           pfeqoperators,
4808                                                                           ppeqoperators,
4809                                                                           ffeqoperators,
4810                                                                           numpks,
4811                                                                           fkconstraint->fk_upd_action,
4812                                                                           fkconstraint->fk_del_action,
4813                                                                           fkconstraint->fk_matchtype,
4814                                                                           indexOid,
4815                                                                           NULL,         /* no check constraint */
4816                                                                           NULL,
4817                                                                           NULL,
4818                                                                           true,         /* islocal */
4819                                                                           0);           /* inhcount */
4820
4821         /*
4822          * Create the triggers that will enforce the constraint.
4823          */
4824         createForeignKeyTriggers(rel, fkconstraint, constrOid);
4825
4826         /*
4827          * Tell Phase 3 to check that the constraint is satisfied by existing rows
4828          * (we can skip this during table creation).
4829          */
4830         if (!fkconstraint->skip_validation)
4831         {
4832                 NewConstraint *newcon;
4833
4834                 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4835                 newcon->name = fkconstraint->constr_name;
4836                 newcon->contype = CONSTR_FOREIGN;
4837                 newcon->refrelid = RelationGetRelid(pkrel);
4838                 newcon->conid = constrOid;
4839                 newcon->qual = (Node *) fkconstraint;
4840
4841                 tab->constraints = lappend(tab->constraints, newcon);
4842         }
4843
4844         /*
4845          * Close pk table, but keep lock until we've committed.
4846          */
4847         heap_close(pkrel, NoLock);
4848 }
4849
4850
4851 /*
4852  * transformColumnNameList - transform list of column names
4853  *
4854  * Lookup each name and return its attnum and type OID
4855  */
4856 static int
4857 transformColumnNameList(Oid relId, List *colList,
4858                                                 int16 *attnums, Oid *atttypids)
4859 {
4860         ListCell   *l;
4861         int                     attnum;
4862
4863         attnum = 0;
4864         foreach(l, colList)
4865         {
4866                 char       *attname = strVal(lfirst(l));
4867                 HeapTuple       atttuple;
4868
4869                 atttuple = SearchSysCacheAttName(relId, attname);
4870                 if (!HeapTupleIsValid(atttuple))
4871                         ereport(ERROR,
4872                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4873                                          errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4874                                                         attname)));
4875                 if (attnum >= INDEX_MAX_KEYS)
4876                         ereport(ERROR,
4877                                         (errcode(ERRCODE_TOO_MANY_COLUMNS),
4878                                          errmsg("cannot have more than %d keys in a foreign key",
4879                                                         INDEX_MAX_KEYS)));
4880                 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4881                 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4882                 ReleaseSysCache(atttuple);
4883                 attnum++;
4884         }
4885
4886         return attnum;
4887 }
4888
4889 /*
4890  * transformFkeyGetPrimaryKey -
4891  *
4892  *      Look up the names, attnums, and types of the primary key attributes
4893  *      for the pkrel.  Also return the index OID and index opclasses of the
4894  *      index supporting the primary key.
4895  *
4896  *      All parameters except pkrel are output parameters.      Also, the function
4897  *      return value is the number of attributes in the primary key.
4898  *
4899  *      Used when the column list in the REFERENCES specification is omitted.
4900  */
4901 static int
4902 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4903                                                    List **attnamelist,
4904                                                    int16 *attnums, Oid *atttypids,
4905                                                    Oid *opclasses)
4906 {
4907         List       *indexoidlist;
4908         ListCell   *indexoidscan;
4909         HeapTuple       indexTuple = NULL;
4910         Form_pg_index indexStruct = NULL;
4911         Datum           indclassDatum;
4912         bool            isnull;
4913         oidvector  *indclass;
4914         int                     i;
4915
4916         /*
4917          * Get the list of index OIDs for the table from the relcache, and look up
4918          * each one in the pg_index syscache until we find one marked primary key
4919          * (hopefully there isn't more than one such).
4920          */
4921         *indexOid = InvalidOid;
4922
4923         indexoidlist = RelationGetIndexList(pkrel);
4924
4925         foreach(indexoidscan, indexoidlist)
4926         {
4927                 Oid                     indexoid = lfirst_oid(indexoidscan);
4928
4929                 indexTuple = SearchSysCache(INDEXRELID,
4930                                                                         ObjectIdGetDatum(indexoid),
4931                                                                         0, 0, 0);
4932                 if (!HeapTupleIsValid(indexTuple))
4933                         elog(ERROR, "cache lookup failed for index %u", indexoid);
4934                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4935                 if (indexStruct->indisprimary)
4936                 {
4937                         *indexOid = indexoid;
4938                         break;
4939                 }
4940                 ReleaseSysCache(indexTuple);
4941         }
4942
4943         list_free(indexoidlist);
4944
4945         /*
4946          * Check that we found it
4947          */
4948         if (!OidIsValid(*indexOid))
4949                 ereport(ERROR,
4950                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
4951                                  errmsg("there is no primary key for referenced table \"%s\"",
4952                                                 RelationGetRelationName(pkrel))));
4953
4954         /* Must get indclass the hard way */
4955         indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4956                                                                         Anum_pg_index_indclass, &isnull);
4957         Assert(!isnull);
4958         indclass = (oidvector *) DatumGetPointer(indclassDatum);
4959
4960         /*
4961          * Now build the list of PK attributes from the indkey definition (we
4962          * assume a primary key cannot have expressional elements)
4963          */
4964         *attnamelist = NIL;
4965         for (i = 0; i < indexStruct->indnatts; i++)
4966         {
4967                 int                     pkattno = indexStruct->indkey.values[i];
4968
4969                 attnums[i] = pkattno;
4970                 atttypids[i] = attnumTypeId(pkrel, pkattno);
4971                 opclasses[i] = indclass->values[i];
4972                 *attnamelist = lappend(*attnamelist,
4973                            makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4974         }
4975
4976         ReleaseSysCache(indexTuple);
4977
4978         return i;
4979 }
4980
4981 /*
4982  * transformFkeyCheckAttrs -
4983  *
4984  *      Make sure that the attributes of a referenced table belong to a unique
4985  *      (or primary key) constraint.  Return the OID of the index supporting
4986  *      the constraint, as well as the opclasses associated with the index
4987  *      columns.
4988  */
4989 static Oid
4990 transformFkeyCheckAttrs(Relation pkrel,
4991                                                 int numattrs, int16 *attnums,
4992                                                 Oid *opclasses) /* output parameter */
4993 {
4994         Oid                     indexoid = InvalidOid;
4995         bool            found = false;
4996         List       *indexoidlist;
4997         ListCell   *indexoidscan;
4998
4999         /*
5000          * Get the list of index OIDs for the table from the relcache, and look up
5001          * each one in the pg_index syscache, and match unique indexes to the list
5002          * of attnums we are given.
5003          */
5004         indexoidlist = RelationGetIndexList(pkrel);
5005
5006         foreach(indexoidscan, indexoidlist)
5007         {
5008                 HeapTuple       indexTuple;
5009                 Form_pg_index indexStruct;
5010                 int                     i,
5011                                         j;
5012
5013                 indexoid = lfirst_oid(indexoidscan);
5014                 indexTuple = SearchSysCache(INDEXRELID,
5015                                                                         ObjectIdGetDatum(indexoid),
5016                                                                         0, 0, 0);
5017                 if (!HeapTupleIsValid(indexTuple))
5018                         elog(ERROR, "cache lookup failed for index %u", indexoid);
5019                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5020
5021                 /*
5022                  * Must have the right number of columns; must be unique and not a
5023                  * partial index; forget it if there are any expressions, too
5024                  */
5025                 if (indexStruct->indnatts == numattrs &&
5026                         indexStruct->indisunique &&
5027                         heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
5028                         heap_attisnull(indexTuple, Anum_pg_index_indexprs))
5029                 {
5030                         /* Must get indclass the hard way */
5031                         Datum           indclassDatum;
5032                         bool            isnull;
5033                         oidvector  *indclass;
5034
5035                         indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
5036                                                                                         Anum_pg_index_indclass, &isnull);
5037                         Assert(!isnull);
5038                         indclass = (oidvector *) DatumGetPointer(indclassDatum);
5039
5040                         /*
5041                          * The given attnum list may match the index columns in any order.
5042                          * Check that each list is a subset of the other.
5043                          */
5044                         for (i = 0; i < numattrs; i++)
5045                         {
5046                                 found = false;
5047                                 for (j = 0; j < numattrs; j++)
5048                                 {
5049                                         if (attnums[i] == indexStruct->indkey.values[j])
5050                                         {
5051                                                 found = true;
5052                                                 break;
5053                                         }
5054                                 }
5055                                 if (!found)
5056                                         break;
5057                         }
5058                         if (found)
5059                         {
5060                                 for (i = 0; i < numattrs; i++)
5061                                 {
5062                                         found = false;
5063                                         for (j = 0; j < numattrs; j++)
5064                                         {
5065                                                 if (attnums[j] == indexStruct->indkey.values[i])
5066                                                 {
5067                                                         opclasses[j] = indclass->values[i];
5068                                                         found = true;
5069                                                         break;
5070                                                 }
5071                                         }
5072                                         if (!found)
5073                                                 break;
5074                                 }
5075                         }
5076                 }
5077                 ReleaseSysCache(indexTuple);
5078                 if (found)
5079                         break;
5080         }
5081
5082         if (!found)
5083                 ereport(ERROR,
5084                                 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
5085                                  errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
5086                                                 RelationGetRelationName(pkrel))));
5087
5088         list_free(indexoidlist);
5089
5090         return indexoid;
5091 }
5092
5093 /* Permissions checks for ADD FOREIGN KEY */
5094 static void
5095 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
5096 {
5097         Oid                     roleid = GetUserId();
5098         AclResult       aclresult;
5099         int                     i;
5100
5101         /* Okay if we have relation-level REFERENCES permission */
5102         aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
5103                                                                   ACL_REFERENCES);
5104         if (aclresult == ACLCHECK_OK)
5105                 return;
5106         /* Else we must have REFERENCES on each column */
5107         for (i = 0; i < natts; i++)
5108         {
5109                 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
5110                                                                                   roleid, ACL_REFERENCES);
5111                 if (aclresult != ACLCHECK_OK)
5112                         aclcheck_error(aclresult, ACL_KIND_CLASS,
5113                                                    RelationGetRelationName(rel));
5114         }
5115 }
5116
5117 /*
5118  * Scan the existing rows in a table to verify they meet a proposed FK
5119  * constraint.
5120  *
5121  * Caller must have opened and locked both relations.
5122  */
5123 static void
5124 validateForeignKeyConstraint(FkConstraint *fkconstraint,
5125                                                          Relation rel,
5126                                                          Relation pkrel,
5127                                                          Oid constraintOid)
5128 {
5129         HeapScanDesc scan;
5130         HeapTuple       tuple;
5131         Trigger         trig;
5132
5133         /*
5134          * Build a trigger call structure; we'll need it either way.
5135          */
5136         MemSet(&trig, 0, sizeof(trig));
5137         trig.tgoid = InvalidOid;
5138         trig.tgname = fkconstraint->constr_name;
5139         trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
5140         trig.tgisconstraint = TRUE;
5141         trig.tgconstrrelid = RelationGetRelid(pkrel);
5142         trig.tgconstraint = constraintOid;
5143         trig.tgdeferrable = FALSE;
5144         trig.tginitdeferred = FALSE;
5145         /* we needn't fill in tgargs */
5146
5147         /*
5148          * See if we can do it with a single LEFT JOIN query.  A FALSE result
5149          * indicates we must proceed with the fire-the-trigger method.
5150          */
5151         if (RI_Initial_Check(&trig, rel, pkrel))
5152                 return;
5153
5154         /*
5155          * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
5156          * if that tuple had just been inserted.  If any of those fail, it should
5157          * ereport(ERROR) and that's that.
5158          */
5159         scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
5160
5161         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
5162         {
5163                 FunctionCallInfoData fcinfo;
5164                 TriggerData trigdata;
5165
5166                 /*
5167                  * Make a call to the trigger function
5168                  *
5169                  * No parameters are passed, but we do set a context
5170                  */
5171                 MemSet(&fcinfo, 0, sizeof(fcinfo));
5172
5173                 /*
5174                  * We assume RI_FKey_check_ins won't look at flinfo...
5175                  */
5176                 trigdata.type = T_TriggerData;
5177                 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
5178                 trigdata.tg_relation = rel;
5179                 trigdata.tg_trigtuple = tuple;
5180                 trigdata.tg_newtuple = NULL;
5181                 trigdata.tg_trigger = &trig;
5182                 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
5183                 trigdata.tg_newtuplebuf = InvalidBuffer;
5184
5185                 fcinfo.context = (Node *) &trigdata;
5186
5187                 RI_FKey_check_ins(&fcinfo);
5188         }
5189
5190         heap_endscan(scan);
5191 }
5192
5193 static void
5194 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
5195                                          Oid constraintOid, bool on_insert)
5196 {
5197         CreateTrigStmt *fk_trigger;
5198
5199         fk_trigger = makeNode(CreateTrigStmt);
5200         fk_trigger->trigname = fkconstraint->constr_name;
5201         fk_trigger->relation = myRel;
5202         fk_trigger->before = false;
5203         fk_trigger->row = true;
5204
5205         /* Either ON INSERT or ON UPDATE */
5206         if (on_insert)
5207         {
5208                 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
5209                 fk_trigger->events = TRIGGER_TYPE_INSERT;
5210         }
5211         else
5212         {
5213                 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
5214                 fk_trigger->events = TRIGGER_TYPE_UPDATE;
5215         }
5216
5217         fk_trigger->isconstraint = true;
5218         fk_trigger->deferrable = fkconstraint->deferrable;
5219         fk_trigger->initdeferred = fkconstraint->initdeferred;
5220         fk_trigger->constrrel = fkconstraint->pktable;
5221         fk_trigger->args = NIL;
5222
5223         (void) CreateTrigger(fk_trigger, constraintOid, false);
5224
5225         /* Make changes-so-far visible */
5226         CommandCounterIncrement();
5227 }
5228
5229 /*
5230  * Create the triggers that implement an FK constraint.
5231  */
5232 static void
5233 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
5234                                                  Oid constraintOid)
5235 {
5236         RangeVar   *myRel;
5237         CreateTrigStmt *fk_trigger;
5238
5239         /*
5240          * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
5241          */
5242         myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5243                                                  pstrdup(RelationGetRelationName(rel)),
5244                                                  -1);
5245
5246         /* Make changes-so-far visible */
5247         CommandCounterIncrement();
5248
5249         /*
5250          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
5251          * action for both INSERTs and UPDATEs on the referencing table.
5252          */
5253         CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
5254         CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
5255
5256         /*
5257          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5258          * DELETE action on the referenced table.
5259          */
5260         fk_trigger = makeNode(CreateTrigStmt);
5261         fk_trigger->trigname = fkconstraint->constr_name;
5262         fk_trigger->relation = fkconstraint->pktable;
5263         fk_trigger->before = false;
5264         fk_trigger->row = true;
5265         fk_trigger->events = TRIGGER_TYPE_DELETE;
5266         fk_trigger->isconstraint = true;
5267         fk_trigger->constrrel = myRel;
5268         switch (fkconstraint->fk_del_action)
5269         {
5270                 case FKCONSTR_ACTION_NOACTION:
5271                         fk_trigger->deferrable = fkconstraint->deferrable;
5272                         fk_trigger->initdeferred = fkconstraint->initdeferred;
5273                         fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
5274                         break;
5275                 case FKCONSTR_ACTION_RESTRICT:
5276                         fk_trigger->deferrable = false;
5277                         fk_trigger->initdeferred = false;
5278                         fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
5279                         break;
5280                 case FKCONSTR_ACTION_CASCADE:
5281                         fk_trigger->deferrable = false;
5282                         fk_trigger->initdeferred = false;
5283                         fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
5284                         break;
5285                 case FKCONSTR_ACTION_SETNULL:
5286                         fk_trigger->deferrable = false;
5287                         fk_trigger->initdeferred = false;
5288                         fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
5289                         break;
5290                 case FKCONSTR_ACTION_SETDEFAULT:
5291                         fk_trigger->deferrable = false;
5292                         fk_trigger->initdeferred = false;
5293                         fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
5294                         break;
5295                 default:
5296                         elog(ERROR, "unrecognized FK action type: %d",
5297                                  (int) fkconstraint->fk_del_action);
5298                         break;
5299         }
5300         fk_trigger->args = NIL;
5301
5302         (void) CreateTrigger(fk_trigger, constraintOid, false);
5303
5304         /* Make changes-so-far visible */
5305         CommandCounterIncrement();
5306
5307         /*
5308          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5309          * UPDATE action on the referenced table.
5310          */
5311         fk_trigger = makeNode(CreateTrigStmt);
5312         fk_trigger->trigname = fkconstraint->constr_name;
5313         fk_trigger->relation = fkconstraint->pktable;
5314         fk_trigger->before = false;
5315         fk_trigger->row = true;
5316         fk_trigger->events = TRIGGER_TYPE_UPDATE;
5317         fk_trigger->isconstraint = true;
5318         fk_trigger->constrrel = myRel;
5319         switch (fkconstraint->fk_upd_action)
5320         {
5321                 case FKCONSTR_ACTION_NOACTION:
5322                         fk_trigger->deferrable = fkconstraint->deferrable;
5323                         fk_trigger->initdeferred = fkconstraint->initdeferred;
5324                         fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
5325                         break;
5326                 case FKCONSTR_ACTION_RESTRICT:
5327                         fk_trigger->deferrable = false;
5328                         fk_trigger->initdeferred = false;
5329                         fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
5330                         break;
5331                 case FKCONSTR_ACTION_CASCADE:
5332                         fk_trigger->deferrable = false;
5333                         fk_trigger->initdeferred = false;
5334                         fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
5335                         break;
5336                 case FKCONSTR_ACTION_SETNULL:
5337                         fk_trigger->deferrable = false;
5338                         fk_trigger->initdeferred = false;
5339                         fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
5340                         break;
5341                 case FKCONSTR_ACTION_SETDEFAULT:
5342                         fk_trigger->deferrable = false;
5343                         fk_trigger->initdeferred = false;
5344                         fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
5345                         break;
5346                 default:
5347                         elog(ERROR, "unrecognized FK action type: %d",
5348                                  (int) fkconstraint->fk_upd_action);
5349                         break;
5350         }
5351         fk_trigger->args = NIL;
5352
5353         (void) CreateTrigger(fk_trigger, constraintOid, false);
5354 }
5355
5356 /*
5357  * ALTER TABLE DROP CONSTRAINT
5358  *
5359  * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
5360  */
5361 static void
5362 ATExecDropConstraint(Relation rel, const char *constrName,
5363                                          DropBehavior behavior,
5364                                          bool recurse, bool recursing)
5365 {
5366         List       *children;
5367         ListCell   *child;
5368         Relation        conrel;
5369         Form_pg_constraint con;
5370         SysScanDesc scan;
5371         ScanKeyData key;
5372         HeapTuple       tuple;
5373         bool            found = false;
5374         bool            is_check_constraint = false;
5375
5376         /* At top level, permission check was done in ATPrepCmd, else do it */
5377         if (recursing)
5378                 ATSimplePermissions(rel, false);
5379
5380         conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5381
5382         /*
5383          * Find and drop the target constraint
5384          */
5385         ScanKeyInit(&key,
5386                                 Anum_pg_constraint_conrelid,
5387                                 BTEqualStrategyNumber, F_OIDEQ,
5388                                 ObjectIdGetDatum(RelationGetRelid(rel)));
5389         scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5390                                                           true, SnapshotNow, 1, &key);
5391
5392         while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5393         {
5394                 ObjectAddress conobj;
5395
5396                 con = (Form_pg_constraint) GETSTRUCT(tuple);
5397
5398                 if (strcmp(NameStr(con->conname), constrName) != 0)
5399                         continue;
5400
5401                 /* Don't drop inherited constraints */
5402                 if (con->coninhcount > 0 && !recursing)
5403                         ereport(ERROR,
5404                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5405                                          errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5406                                                         constrName, RelationGetRelationName(rel))));
5407
5408                 /* Right now only CHECK constraints can be inherited */
5409                 if (con->contype == CONSTRAINT_CHECK)
5410                         is_check_constraint = true;
5411
5412                 /*
5413                  * Perform the actual constraint deletion
5414                  */
5415                 conobj.classId = ConstraintRelationId;
5416                 conobj.objectId = HeapTupleGetOid(tuple);
5417                 conobj.objectSubId = 0;
5418
5419                 performDeletion(&conobj, behavior);
5420
5421                 found = true;
5422         }
5423
5424         systable_endscan(scan);
5425
5426         if (!found)
5427                 ereport(ERROR,
5428                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5429                                  errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5430                                                 constrName, RelationGetRelationName(rel))));
5431
5432         /*
5433          * Propagate to children as appropriate.  Unlike most other ALTER
5434          * routines, we have to do this one level of recursion at a time; we can't
5435          * use find_all_inheritors to do it in one pass.
5436          */
5437         if (is_check_constraint)
5438                 children = find_inheritance_children(RelationGetRelid(rel),
5439                                                                                          AccessExclusiveLock);
5440         else
5441                 children = NIL;
5442
5443         foreach(child, children)
5444         {
5445                 Oid                     childrelid = lfirst_oid(child);
5446                 Relation        childrel;
5447
5448                 /* find_inheritance_children already got lock */
5449                 childrel = heap_open(childrelid, NoLock);
5450                 CheckTableNotInUse(childrel, "ALTER TABLE");
5451
5452                 ScanKeyInit(&key,
5453                                         Anum_pg_constraint_conrelid,
5454                                         BTEqualStrategyNumber, F_OIDEQ,
5455                                         ObjectIdGetDatum(childrelid));
5456                 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5457                                                                   true, SnapshotNow, 1, &key);
5458
5459                 found = false;
5460
5461                 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5462                 {
5463                         HeapTuple       copy_tuple;
5464
5465                         con = (Form_pg_constraint) GETSTRUCT(tuple);
5466
5467                         /* Right now only CHECK constraints can be inherited */
5468                         if (con->contype != CONSTRAINT_CHECK)
5469                                 continue;
5470
5471                         if (strcmp(NameStr(con->conname), constrName) != 0)
5472                                 continue;
5473
5474                         found = true;
5475
5476                         if (con->coninhcount <= 0)      /* shouldn't happen */
5477                                 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
5478                                          childrelid, constrName);
5479
5480                         copy_tuple = heap_copytuple(tuple);
5481                         con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
5482
5483                         if (recurse)
5484                         {
5485                                 /*
5486                                  * If the child constraint has other definition sources, just
5487                                  * decrement its inheritance count; if not, recurse to delete
5488                                  * it.
5489                                  */
5490                                 if (con->coninhcount == 1 && !con->conislocal)
5491                                 {
5492                                         /* Time to delete this child constraint, too */
5493                                         ATExecDropConstraint(childrel, constrName, behavior,
5494                                                                                  true, true);
5495                                 }
5496                                 else
5497                                 {
5498                                         /* Child constraint must survive my deletion */
5499                                         con->coninhcount--;
5500                                         simple_heap_update(conrel, &copy_tuple->t_self, copy_tuple);
5501                                         CatalogUpdateIndexes(conrel, copy_tuple);
5502
5503                                         /* Make update visible */
5504                                         CommandCounterIncrement();
5505                                 }
5506                         }
5507                         else
5508                         {
5509                                 /*
5510                                  * If we were told to drop ONLY in this table (no recursion),
5511                                  * we need to mark the inheritors' constraints as locally
5512                                  * defined rather than inherited.
5513                                  */
5514                                 con->coninhcount--;
5515                                 con->conislocal = true;
5516
5517                                 simple_heap_update(conrel, &copy_tuple->t_self, copy_tuple);
5518                                 CatalogUpdateIndexes(conrel, copy_tuple);
5519
5520                                 /* Make update visible */
5521                                 CommandCounterIncrement();
5522                         }
5523
5524                         heap_freetuple(copy_tuple);
5525                 }
5526
5527                 systable_endscan(scan);
5528
5529                 if (!found)
5530                         ereport(ERROR,
5531                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
5532                                 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5533                                            constrName,
5534                                            RelationGetRelationName(childrel))));
5535
5536                 heap_close(childrel, NoLock);
5537         }
5538
5539         heap_close(conrel, RowExclusiveLock);
5540 }
5541
5542 /*
5543  * ALTER COLUMN TYPE
5544  */
5545 static void
5546 ATPrepAlterColumnType(List **wqueue,
5547                                           AlteredTableInfo *tab, Relation rel,
5548                                           bool recurse, bool recursing,
5549                                           AlterTableCmd *cmd)
5550 {
5551         char       *colName = cmd->name;
5552         TypeName   *typename = (TypeName *) cmd->def;
5553         HeapTuple       tuple;
5554         Form_pg_attribute attTup;
5555         AttrNumber      attnum;
5556         Oid                     targettype;
5557         int32           targettypmod;
5558         Node       *transform;
5559         NewColumnValue *newval;
5560         ParseState *pstate = make_parsestate(NULL);
5561
5562         /* lookup the attribute so we can check inheritance status */
5563         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5564         if (!HeapTupleIsValid(tuple))
5565                 ereport(ERROR,
5566                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5567                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5568                                                 colName, RelationGetRelationName(rel))));
5569         attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5570         attnum = attTup->attnum;
5571
5572         /* Can't alter a system attribute */
5573         if (attnum <= 0)
5574                 ereport(ERROR,
5575                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5576                                  errmsg("cannot alter system column \"%s\"",
5577                                                 colName)));
5578
5579         /* Don't alter inherited columns */
5580         if (attTup->attinhcount > 0 && !recursing)
5581                 ereport(ERROR,
5582                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5583                                  errmsg("cannot alter inherited column \"%s\"",
5584                                                 colName)));
5585
5586         /* Look up the target type */
5587         targettype = typenameTypeId(NULL, typename, &targettypmod);
5588
5589         /* make sure datatype is legal for a column */
5590         CheckAttributeType(colName, targettype);
5591
5592         /*
5593          * Set up an expression to transform the old data value to the new type.
5594          * If a USING option was given, transform and use that expression, else
5595          * just take the old value and try to coerce it.  We do this first so that
5596          * type incompatibility can be detected before we waste effort, and
5597          * because we need the expression to be parsed against the original table
5598          * rowtype.
5599          */
5600         if (cmd->transform)
5601         {
5602                 RangeTblEntry *rte;
5603
5604                 /* Expression must be able to access vars of old table */
5605                 rte = addRangeTableEntryForRelation(pstate,
5606                                                                                         rel,
5607                                                                                         NULL,
5608                                                                                         false,
5609                                                                                         true);
5610                 addRTEtoQuery(pstate, rte, false, true, true);
5611
5612                 transform = transformExpr(pstate, cmd->transform);
5613
5614                 /* It can't return a set */
5615                 if (expression_returns_set(transform))
5616                         ereport(ERROR,
5617                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
5618                                          errmsg("transform expression must not return a set")));
5619
5620                 /* No subplans or aggregates, either... */
5621                 if (pstate->p_hasSubLinks)
5622                         ereport(ERROR,
5623                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5624                                          errmsg("cannot use subquery in transform expression")));
5625                 if (pstate->p_hasAggs)
5626                         ereport(ERROR,
5627                                         (errcode(ERRCODE_GROUPING_ERROR),
5628                         errmsg("cannot use aggregate function in transform expression")));
5629                 if (pstate->p_hasWindowFuncs)
5630                         ereport(ERROR,
5631                                         (errcode(ERRCODE_WINDOWING_ERROR),
5632                           errmsg("cannot use window function in transform expression")));
5633         }
5634         else
5635         {
5636                 transform = (Node *) makeVar(1, attnum,
5637                                                                          attTup->atttypid, attTup->atttypmod,
5638                                                                          0);
5639         }
5640
5641         transform = coerce_to_target_type(pstate,
5642                                                                           transform, exprType(transform),
5643                                                                           targettype, targettypmod,
5644                                                                           COERCION_ASSIGNMENT,
5645                                                                           COERCE_IMPLICIT_CAST,
5646                                                                           -1);
5647         if (transform == NULL)
5648                 ereport(ERROR,
5649                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
5650                                  errmsg("column \"%s\" cannot be cast to type %s",
5651                                                 colName, format_type_be(targettype))));
5652
5653         /*
5654          * Add a work queue item to make ATRewriteTable update the column
5655          * contents.
5656          */
5657         newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5658         newval->attnum = attnum;
5659         newval->expr = (Expr *) transform;
5660
5661         tab->newvals = lappend(tab->newvals, newval);
5662
5663         ReleaseSysCache(tuple);
5664
5665         /*
5666          * The recursion case is handled by ATSimpleRecursion.  However, if we are
5667          * told not to recurse, there had better not be any child tables; else the
5668          * alter would put them out of step.
5669          */
5670         if (recurse)
5671                 ATSimpleRecursion(wqueue, rel, cmd, recurse);
5672         else if (!recursing &&
5673                          find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
5674                 ereport(ERROR,
5675                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5676                                  errmsg("type of inherited column \"%s\" must be changed in child tables too",
5677                                                 colName)));
5678 }
5679
5680 static void
5681 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
5682                                           const char *colName, TypeName *typename)
5683 {
5684         HeapTuple       heapTup;
5685         Form_pg_attribute attTup;
5686         AttrNumber      attnum;
5687         HeapTuple       typeTuple;
5688         Form_pg_type tform;
5689         Oid                     targettype;
5690         int32           targettypmod;
5691         Node       *defaultexpr;
5692         Relation        attrelation;
5693         Relation        depRel;
5694         ScanKeyData key[3];
5695         SysScanDesc scan;
5696         HeapTuple       depTup;
5697
5698         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5699
5700         /* Look up the target column */
5701         heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5702         if (!HeapTupleIsValid(heapTup))         /* shouldn't happen */
5703                 ereport(ERROR,
5704                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5705                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5706                                                 colName, RelationGetRelationName(rel))));
5707         attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5708         attnum = attTup->attnum;
5709
5710         /* Check for multiple ALTER TYPE on same column --- can't cope */
5711         if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5712                 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5713                 ereport(ERROR,
5714                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5715                                  errmsg("cannot alter type of column \"%s\" twice",
5716                                                 colName)));
5717
5718         /* Look up the target type (should not fail, since prep found it) */
5719         typeTuple = typenameType(NULL, typename, &targettypmod);
5720         tform = (Form_pg_type) GETSTRUCT(typeTuple);
5721         targettype = HeapTupleGetOid(typeTuple);
5722
5723         /*
5724          * If there is a default expression for the column, get it and ensure we
5725          * can coerce it to the new datatype.  (We must do this before changing
5726          * the column type, because build_column_default itself will try to
5727          * coerce, and will not issue the error message we want if it fails.)
5728          *
5729          * We remove any implicit coercion steps at the top level of the old
5730          * default expression; this has been agreed to satisfy the principle of
5731          * least surprise.      (The conversion to the new column type should act like
5732          * it started from what the user sees as the stored expression, and the
5733          * implicit coercions aren't going to be shown.)
5734          */
5735         if (attTup->atthasdef)
5736         {
5737                 defaultexpr = build_column_default(rel, attnum);
5738                 Assert(defaultexpr);
5739                 defaultexpr = strip_implicit_coercions(defaultexpr);
5740                 defaultexpr = coerce_to_target_type(NULL,               /* no UNKNOWN params */
5741                                                                                   defaultexpr, exprType(defaultexpr),
5742                                                                                         targettype, targettypmod,
5743                                                                                         COERCION_ASSIGNMENT,
5744                                                                                         COERCE_IMPLICIT_CAST,
5745                                                                                         -1);
5746                 if (defaultexpr == NULL)
5747                         ereport(ERROR,
5748                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
5749                                 errmsg("default for column \"%s\" cannot be cast to type %s",
5750                                            colName, format_type_be(targettype))));
5751         }
5752         else
5753                 defaultexpr = NULL;
5754
5755         /*
5756          * Find everything that depends on the column (constraints, indexes, etc),
5757          * and record enough information to let us recreate the objects.
5758          *
5759          * The actual recreation does not happen here, but only after we have
5760          * performed all the individual ALTER TYPE operations.  We have to save
5761          * the info before executing ALTER TYPE, though, else the deparser will
5762          * get confused.
5763          *
5764          * There could be multiple entries for the same object, so we must check
5765          * to ensure we process each one only once.  Note: we assume that an index
5766          * that implements a constraint will not show a direct dependency on the
5767          * column.
5768          */
5769         depRel = heap_open(DependRelationId, RowExclusiveLock);
5770
5771         ScanKeyInit(&key[0],
5772                                 Anum_pg_depend_refclassid,
5773                                 BTEqualStrategyNumber, F_OIDEQ,
5774                                 ObjectIdGetDatum(RelationRelationId));
5775         ScanKeyInit(&key[1],
5776                                 Anum_pg_depend_refobjid,
5777                                 BTEqualStrategyNumber, F_OIDEQ,
5778                                 ObjectIdGetDatum(RelationGetRelid(rel)));
5779         ScanKeyInit(&key[2],
5780                                 Anum_pg_depend_refobjsubid,
5781                                 BTEqualStrategyNumber, F_INT4EQ,
5782                                 Int32GetDatum((int32) attnum));
5783
5784         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5785                                                           SnapshotNow, 3, key);
5786
5787         while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5788         {
5789                 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5790                 ObjectAddress foundObject;
5791
5792                 /* We don't expect any PIN dependencies on columns */
5793                 if (foundDep->deptype == DEPENDENCY_PIN)
5794                         elog(ERROR, "cannot alter type of a pinned column");
5795
5796                 foundObject.classId = foundDep->classid;
5797                 foundObject.objectId = foundDep->objid;
5798                 foundObject.objectSubId = foundDep->objsubid;
5799
5800                 switch (getObjectClass(&foundObject))
5801                 {
5802                         case OCLASS_CLASS:
5803                                 {
5804                                         char            relKind = get_rel_relkind(foundObject.objectId);
5805
5806                                         if (relKind == RELKIND_INDEX)
5807                                         {
5808                                                 Assert(foundObject.objectSubId == 0);
5809                                                 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5810                                                 {
5811                                                         tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5812                                                                                                            foundObject.objectId);
5813                                                         tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5814                                                            pg_get_indexdef_string(foundObject.objectId));
5815                                                 }
5816                                         }
5817                                         else if (relKind == RELKIND_SEQUENCE)
5818                                         {
5819                                                 /*
5820                                                  * This must be a SERIAL column's sequence.  We need
5821                                                  * not do anything to it.
5822                                                  */
5823                                                 Assert(foundObject.objectSubId == 0);
5824                                         }
5825                                         else
5826                                         {
5827                                                 /* Not expecting any other direct dependencies... */
5828                                                 elog(ERROR, "unexpected object depending on column: %s",
5829                                                          getObjectDescription(&foundObject));
5830                                         }
5831                                         break;
5832                                 }
5833
5834                         case OCLASS_CONSTRAINT:
5835                                 Assert(foundObject.objectSubId == 0);
5836                                 if (!list_member_oid(tab->changedConstraintOids,
5837                                                                          foundObject.objectId))
5838                                 {
5839                                         char       *defstring = pg_get_constraintdef_string(foundObject.objectId);
5840
5841                                         /*
5842                                          * Put NORMAL dependencies at the front of the list and
5843                                          * AUTO dependencies at the back.  This makes sure that
5844                                          * foreign-key constraints depending on this column will
5845                                          * be dropped before unique or primary-key constraints of
5846                                          * the column; which we must have because the FK
5847                                          * constraints depend on the indexes belonging to the
5848                                          * unique constraints.
5849                                          */
5850                                         if (foundDep->deptype == DEPENDENCY_NORMAL)
5851                                         {
5852                                                 tab->changedConstraintOids =
5853                                                         lcons_oid(foundObject.objectId,
5854                                                                           tab->changedConstraintOids);
5855                                                 tab->changedConstraintDefs =
5856                                                         lcons(defstring,
5857                                                                   tab->changedConstraintDefs);
5858                                         }
5859                                         else
5860                                         {
5861                                                 tab->changedConstraintOids =
5862                                                         lappend_oid(tab->changedConstraintOids,
5863                                                                                 foundObject.objectId);
5864                                                 tab->changedConstraintDefs =
5865                                                         lappend(tab->changedConstraintDefs,
5866                                                                         defstring);
5867                                         }
5868                                 }
5869                                 break;
5870
5871                         case OCLASS_REWRITE:
5872                                 /* XXX someday see if we can cope with revising views */
5873                                 ereport(ERROR,
5874                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5875                                                  errmsg("cannot alter type of a column used by a view or rule"),
5876                                                  errdetail("%s depends on column \"%s\"",
5877                                                                    getObjectDescription(&foundObject),
5878                                                                    colName)));
5879                                 break;
5880
5881                         case OCLASS_DEFAULT:
5882
5883                                 /*
5884                                  * Ignore the column's default expression, since we will fix
5885                                  * it below.
5886                                  */
5887                                 Assert(defaultexpr);
5888                                 break;
5889
5890                         case OCLASS_PROC:
5891                         case OCLASS_TYPE:
5892                         case OCLASS_CAST:
5893                         case OCLASS_CONVERSION:
5894                         case OCLASS_LANGUAGE:
5895                         case OCLASS_OPERATOR:
5896                         case OCLASS_OPCLASS:
5897                         case OCLASS_OPFAMILY:
5898                         case OCLASS_TRIGGER:
5899                         case OCLASS_SCHEMA:
5900                         case OCLASS_TSPARSER:
5901                         case OCLASS_TSDICT:
5902                         case OCLASS_TSTEMPLATE:
5903                         case OCLASS_TSCONFIG:
5904
5905                                 /*
5906                                  * We don't expect any of these sorts of objects to depend on
5907                                  * a column.
5908                                  */
5909                                 elog(ERROR, "unexpected object depending on column: %s",
5910                                          getObjectDescription(&foundObject));
5911                                 break;
5912
5913                         default:
5914                                 elog(ERROR, "unrecognized object class: %u",
5915                                          foundObject.classId);
5916                 }
5917         }
5918
5919         systable_endscan(scan);
5920
5921         /*
5922          * Now scan for dependencies of this column on other things.  The only
5923          * thing we should find is the dependency on the column datatype, which we
5924          * want to remove.
5925          */
5926         ScanKeyInit(&key[0],
5927                                 Anum_pg_depend_classid,
5928                                 BTEqualStrategyNumber, F_OIDEQ,
5929                                 ObjectIdGetDatum(RelationRelationId));
5930         ScanKeyInit(&key[1],
5931                                 Anum_pg_depend_objid,
5932                                 BTEqualStrategyNumber, F_OIDEQ,
5933                                 ObjectIdGetDatum(RelationGetRelid(rel)));
5934         ScanKeyInit(&key[2],
5935                                 Anum_pg_depend_objsubid,
5936                                 BTEqualStrategyNumber, F_INT4EQ,
5937                                 Int32GetDatum((int32) attnum));
5938
5939         scan = systable_beginscan(depRel, DependDependerIndexId, true,
5940                                                           SnapshotNow, 3, key);
5941
5942         while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5943         {
5944                 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5945
5946                 if (foundDep->deptype != DEPENDENCY_NORMAL)
5947                         elog(ERROR, "found unexpected dependency type '%c'",
5948                                  foundDep->deptype);
5949                 if (foundDep->refclassid != TypeRelationId ||
5950                         foundDep->refobjid != attTup->atttypid)
5951                         elog(ERROR, "found unexpected dependency for column");
5952
5953                 simple_heap_delete(depRel, &depTup->t_self);
5954         }
5955
5956         systable_endscan(scan);
5957
5958         heap_close(depRel, RowExclusiveLock);
5959
5960         /*
5961          * Here we go --- change the recorded column type.      (Note heapTup is a
5962          * copy of the syscache entry, so okay to scribble on.)
5963          */
5964         attTup->atttypid = targettype;
5965         attTup->atttypmod = targettypmod;
5966         attTup->attndims = list_length(typename->arrayBounds);
5967         attTup->attlen = tform->typlen;
5968         attTup->attbyval = tform->typbyval;
5969         attTup->attalign = tform->typalign;
5970         attTup->attstorage = tform->typstorage;
5971
5972         ReleaseSysCache(typeTuple);
5973
5974         simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5975
5976         /* keep system catalog indexes current */
5977         CatalogUpdateIndexes(attrelation, heapTup);
5978
5979         heap_close(attrelation, RowExclusiveLock);
5980
5981         /* Install dependency on new datatype */
5982         add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5983
5984         /*
5985          * Drop any pg_statistic entry for the column, since it's now wrong type
5986          */
5987         RemoveStatistics(RelationGetRelid(rel), attnum);
5988
5989         /*
5990          * Update the default, if present, by brute force --- remove and re-add
5991          * the default.  Probably unsafe to take shortcuts, since the new version
5992          * may well have additional dependencies.  (It's okay to do this now,
5993          * rather than after other ALTER TYPE commands, since the default won't
5994          * depend on other column types.)
5995          */
5996         if (defaultexpr)
5997         {
5998                 /* Must make new row visible since it will be updated again */
5999                 CommandCounterIncrement();
6000
6001                 /*
6002                  * We use RESTRICT here for safety, but at present we do not expect
6003                  * anything to depend on the default.
6004                  */
6005                 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
6006
6007                 StoreAttrDefault(rel, attnum, defaultexpr);
6008         }
6009
6010         /* Cleanup */
6011         heap_freetuple(heapTup);
6012 }
6013
6014 /*
6015  * Cleanup after we've finished all the ALTER TYPE operations for a
6016  * particular relation.  We have to drop and recreate all the indexes
6017  * and constraints that depend on the altered columns.
6018  */
6019 static void
6020 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
6021 {
6022         ObjectAddress obj;
6023         ListCell   *l;
6024
6025         /*
6026          * Re-parse the index and constraint definitions, and attach them to the
6027          * appropriate work queue entries.      We do this before dropping because in
6028          * the case of a FOREIGN KEY constraint, we might not yet have exclusive
6029          * lock on the table the constraint is attached to, and we need to get
6030          * that before dropping.  It's safe because the parser won't actually look
6031          * at the catalogs to detect the existing entry.
6032          */
6033         foreach(l, tab->changedIndexDefs)
6034                 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
6035         foreach(l, tab->changedConstraintDefs)
6036                 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
6037
6038         /*
6039          * Now we can drop the existing constraints and indexes --- constraints
6040          * first, since some of them might depend on the indexes.  In fact, we
6041          * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
6042          * we already ordered the constraint list to ensure that would happen. It
6043          * should be okay to use DROP_RESTRICT here, since nothing else should be
6044          * depending on these objects.
6045          */
6046         foreach(l, tab->changedConstraintOids)
6047         {
6048                 obj.classId = ConstraintRelationId;
6049                 obj.objectId = lfirst_oid(l);
6050                 obj.objectSubId = 0;
6051                 performDeletion(&obj, DROP_RESTRICT);
6052         }
6053
6054         foreach(l, tab->changedIndexOids)
6055         {
6056                 obj.classId = RelationRelationId;
6057                 obj.objectId = lfirst_oid(l);
6058                 obj.objectSubId = 0;
6059                 performDeletion(&obj, DROP_RESTRICT);
6060         }
6061
6062         /*
6063          * The objects will get recreated during subsequent passes over the work
6064          * queue.
6065          */
6066 }
6067
6068 static void
6069 ATPostAlterTypeParse(char *cmd, List **wqueue)
6070 {
6071         List       *raw_parsetree_list;
6072         List       *querytree_list;
6073         ListCell   *list_item;
6074
6075         /*
6076          * We expect that we will get only ALTER TABLE and CREATE INDEX
6077          * statements. Hence, there is no need to pass them through
6078          * parse_analyze() or the rewriter, but instead we need to pass them
6079          * through parse_utilcmd.c to make them ready for execution.
6080          */
6081         raw_parsetree_list = raw_parser(cmd);
6082         querytree_list = NIL;
6083         foreach(list_item, raw_parsetree_list)
6084         {
6085                 Node       *stmt = (Node *) lfirst(list_item);
6086
6087                 if (IsA(stmt, IndexStmt))
6088                         querytree_list = lappend(querytree_list,
6089                                                                          transformIndexStmt((IndexStmt *) stmt,
6090                                                                                                                 cmd));
6091                 else if (IsA(stmt, AlterTableStmt))
6092                         querytree_list = list_concat(querytree_list,
6093                                                          transformAlterTableStmt((AlterTableStmt *) stmt,
6094                                                                                                          cmd));
6095                 else
6096                         querytree_list = lappend(querytree_list, stmt);
6097         }
6098
6099         /*
6100          * Attach each generated command to the proper place in the work queue.
6101          * Note this could result in creation of entirely new work-queue entries.
6102          */
6103         foreach(list_item, querytree_list)
6104         {
6105                 Node       *stm = (Node *) lfirst(list_item);
6106                 Relation        rel;
6107                 AlteredTableInfo *tab;
6108
6109                 switch (nodeTag(stm))
6110                 {
6111                         case T_IndexStmt:
6112                                 {
6113                                         IndexStmt  *stmt = (IndexStmt *) stm;
6114                                         AlterTableCmd *newcmd;
6115
6116                                         rel = relation_openrv(stmt->relation, AccessExclusiveLock);
6117                                         tab = ATGetQueueEntry(wqueue, rel);
6118                                         newcmd = makeNode(AlterTableCmd);
6119                                         newcmd->subtype = AT_ReAddIndex;
6120                                         newcmd->def = (Node *) stmt;
6121                                         tab->subcmds[AT_PASS_OLD_INDEX] =
6122                                                 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
6123                                         relation_close(rel, NoLock);
6124                                         break;
6125                                 }
6126                         case T_AlterTableStmt:
6127                                 {
6128                                         AlterTableStmt *stmt = (AlterTableStmt *) stm;
6129                                         ListCell   *lcmd;
6130
6131                                         rel = relation_openrv(stmt->relation, AccessExclusiveLock);
6132                                         tab = ATGetQueueEntry(wqueue, rel);
6133                                         foreach(lcmd, stmt->cmds)
6134                                         {
6135                                                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
6136
6137                                                 switch (cmd->subtype)
6138                                                 {
6139                                                         case AT_AddIndex:
6140                                                                 cmd->subtype = AT_ReAddIndex;
6141                                                                 tab->subcmds[AT_PASS_OLD_INDEX] =
6142                                                                         lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
6143                                                                 break;
6144                                                         case AT_AddConstraint:
6145                                                                 tab->subcmds[AT_PASS_OLD_CONSTR] =
6146                                                                         lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
6147                                                                 break;
6148                                                         default:
6149                                                                 elog(ERROR, "unexpected statement type: %d",
6150                                                                          (int) cmd->subtype);
6151                                                 }
6152                                         }
6153                                         relation_close(rel, NoLock);
6154                                         break;
6155                                 }
6156                         default:
6157                                 elog(ERROR, "unexpected statement type: %d",
6158                                          (int) nodeTag(stm));
6159                 }
6160         }
6161 }
6162
6163
6164 /*
6165  * ALTER TABLE OWNER
6166  *
6167  * recursing is true if we are recursing from a table to its indexes,
6168  * sequences, or toast table.  We don't allow the ownership of those things to
6169  * be changed separately from the parent table.  Also, we can skip permission
6170  * checks (this is necessary not just an optimization, else we'd fail to
6171  * handle toast tables properly).
6172  *
6173  * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
6174  * free-standing composite type.
6175  */
6176 void
6177 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
6178 {
6179         Relation        target_rel;
6180         Relation        class_rel;
6181         HeapTuple       tuple;
6182         Form_pg_class tuple_class;
6183
6184         /*
6185          * Get exclusive lock till end of transaction on the target table. Use
6186          * relation_open so that we can work on indexes and sequences.
6187          */
6188         target_rel = relation_open(relationOid, AccessExclusiveLock);
6189
6190         /* Get its pg_class tuple, too */
6191         class_rel = heap_open(RelationRelationId, RowExclusiveLock);
6192
6193         tuple = SearchSysCache(RELOID,
6194                                                    ObjectIdGetDatum(relationOid),
6195                                                    0, 0, 0);
6196         if (!HeapTupleIsValid(tuple))
6197                 elog(ERROR, "cache lookup failed for relation %u", relationOid);
6198         tuple_class = (Form_pg_class) GETSTRUCT(tuple);
6199
6200         /* Can we change the ownership of this tuple? */
6201         switch (tuple_class->relkind)
6202         {
6203                 case RELKIND_RELATION:
6204                 case RELKIND_VIEW:
6205                         /* ok to change owner */
6206                         break;
6207                 case RELKIND_INDEX:
6208                         if (!recursing)
6209                         {
6210                                 /*
6211                                  * Because ALTER INDEX OWNER used to be allowed, and in fact
6212                                  * is generated by old versions of pg_dump, we give a warning
6213                                  * and do nothing rather than erroring out.  Also, to avoid
6214                                  * unnecessary chatter while restoring those old dumps, say
6215                                  * nothing at all if the command would be a no-op anyway.
6216                                  */
6217                                 if (tuple_class->relowner != newOwnerId)
6218                                         ereport(WARNING,
6219                                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6220                                                          errmsg("cannot change owner of index \"%s\"",
6221                                                                         NameStr(tuple_class->relname)),
6222                                                          errhint("Change the ownership of the index's table, instead.")));
6223                                 /* quick hack to exit via the no-op path */
6224                                 newOwnerId = tuple_class->relowner;
6225                         }
6226                         break;
6227                 case RELKIND_SEQUENCE:
6228                         if (!recursing &&
6229                                 tuple_class->relowner != newOwnerId)
6230                         {
6231                                 /* if it's an owned sequence, disallow changing it by itself */
6232                                 Oid                     tableId;
6233                                 int32           colId;
6234
6235                                 if (sequenceIsOwned(relationOid, &tableId, &colId))
6236                                         ereport(ERROR,
6237                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6238                                                          errmsg("cannot change owner of sequence \"%s\"",
6239                                                                         NameStr(tuple_class->relname)),
6240                                           errdetail("Sequence \"%s\" is linked to table \"%s\".",
6241                                                                 NameStr(tuple_class->relname),
6242                                                                 get_rel_name(tableId))));
6243                         }
6244                         break;
6245                 case RELKIND_COMPOSITE_TYPE:
6246                         if (recursing)
6247                                 break;
6248                         ereport(ERROR,
6249                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6250                                          errmsg("\"%s\" is a composite type",
6251                                                         NameStr(tuple_class->relname)),
6252                                          errhint("Use ALTER TYPE instead.")));
6253                         break;
6254                 case RELKIND_TOASTVALUE:
6255                         if (recursing)
6256                                 break;
6257                         /* FALL THRU */
6258                 default:
6259                         ereport(ERROR,
6260                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6261                                          errmsg("\"%s\" is not a table, view, or sequence",
6262                                                         NameStr(tuple_class->relname))));
6263         }
6264
6265         /*
6266          * If the new owner is the same as the existing owner, consider the
6267          * command to have succeeded.  This is for dump restoration purposes.
6268          */
6269         if (tuple_class->relowner != newOwnerId)
6270         {
6271                 Datum           repl_val[Natts_pg_class];
6272                 bool            repl_null[Natts_pg_class];
6273                 bool            repl_repl[Natts_pg_class];
6274                 Acl                *newAcl;
6275                 Datum           aclDatum;
6276                 bool            isNull;
6277                 HeapTuple       newtuple;
6278
6279                 /* skip permission checks when recursing to index or toast table */
6280                 if (!recursing)
6281                 {
6282                         /* Superusers can always do it */
6283                         if (!superuser())
6284                         {
6285                                 Oid                     namespaceOid = tuple_class->relnamespace;
6286                                 AclResult       aclresult;
6287
6288                                 /* Otherwise, must be owner of the existing object */
6289                                 if (!pg_class_ownercheck(relationOid, GetUserId()))
6290                                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
6291                                                                    RelationGetRelationName(target_rel));
6292
6293                                 /* Must be able to become new owner */
6294                                 check_is_member_of_role(GetUserId(), newOwnerId);
6295
6296                                 /* New owner must have CREATE privilege on namespace */
6297                                 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
6298                                                                                                   ACL_CREATE);
6299                                 if (aclresult != ACLCHECK_OK)
6300                                         aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
6301                                                                    get_namespace_name(namespaceOid));
6302                         }
6303                 }
6304
6305                 memset(repl_null, false, sizeof(repl_null));
6306                 memset(repl_repl, false, sizeof(repl_repl));
6307
6308                 repl_repl[Anum_pg_class_relowner - 1] = true;
6309                 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
6310
6311                 /*
6312                  * Determine the modified ACL for the new owner.  This is only
6313                  * necessary when the ACL is non-null.
6314                  */
6315                 aclDatum = SysCacheGetAttr(RELOID, tuple,
6316                                                                    Anum_pg_class_relacl,
6317                                                                    &isNull);
6318                 if (!isNull)
6319                 {
6320                         newAcl = aclnewowner(DatumGetAclP(aclDatum),
6321                                                                  tuple_class->relowner, newOwnerId);
6322                         repl_repl[Anum_pg_class_relacl - 1] = true;
6323                         repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
6324                 }
6325
6326                 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
6327
6328                 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
6329                 CatalogUpdateIndexes(class_rel, newtuple);
6330
6331                 heap_freetuple(newtuple);
6332
6333                 /*
6334                  * Update owner dependency reference, if any.  A composite type has
6335                  * none, because it's tracked for the pg_type entry instead of here;
6336                  * indexes and TOAST tables don't have their own entries either.
6337                  */
6338                 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
6339                         tuple_class->relkind != RELKIND_INDEX &&
6340                         tuple_class->relkind != RELKIND_TOASTVALUE)
6341                         changeDependencyOnOwner(RelationRelationId, relationOid,
6342                                                                         newOwnerId);
6343
6344                 /*
6345                  * Also change the ownership of the table's rowtype, if it has one
6346                  */
6347                 if (tuple_class->relkind != RELKIND_INDEX)
6348                         AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
6349                                                          tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
6350
6351                 /*
6352                  * If we are operating on a table, also change the ownership of any
6353                  * indexes and sequences that belong to the table, as well as the
6354                  * table's toast table (if it has one)
6355                  */
6356                 if (tuple_class->relkind == RELKIND_RELATION ||
6357                         tuple_class->relkind == RELKIND_TOASTVALUE)
6358                 {
6359                         List       *index_oid_list;
6360                         ListCell   *i;
6361
6362                         /* Find all the indexes belonging to this relation */
6363                         index_oid_list = RelationGetIndexList(target_rel);
6364
6365                         /* For each index, recursively change its ownership */
6366                         foreach(i, index_oid_list)
6367                                 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
6368
6369                         list_free(index_oid_list);
6370                 }
6371
6372                 if (tuple_class->relkind == RELKIND_RELATION)
6373                 {
6374                         /* If it has a toast table, recurse to change its ownership */
6375                         if (tuple_class->reltoastrelid != InvalidOid)
6376                                 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
6377                                                                   true);
6378
6379                         /* If it has dependent sequences, recurse to change them too */
6380                         change_owner_recurse_to_sequences(relationOid, newOwnerId);
6381                 }
6382         }
6383
6384         ReleaseSysCache(tuple);
6385         heap_close(class_rel, RowExclusiveLock);
6386         relation_close(target_rel, NoLock);
6387 }
6388
6389 /*
6390  * change_owner_recurse_to_sequences
6391  *
6392  * Helper function for ATExecChangeOwner.  Examines pg_depend searching
6393  * for sequences that are dependent on serial columns, and changes their
6394  * ownership.
6395  */
6396 static void
6397 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
6398 {
6399         Relation        depRel;
6400         SysScanDesc scan;
6401         ScanKeyData key[2];
6402         HeapTuple       tup;
6403
6404         /*
6405          * SERIAL sequences are those having an auto dependency on one of the
6406          * table's columns (we don't care *which* column, exactly).
6407          */
6408         depRel = heap_open(DependRelationId, AccessShareLock);
6409
6410         ScanKeyInit(&key[0],
6411                                 Anum_pg_depend_refclassid,
6412                                 BTEqualStrategyNumber, F_OIDEQ,
6413                                 ObjectIdGetDatum(RelationRelationId));
6414         ScanKeyInit(&key[1],
6415                                 Anum_pg_depend_refobjid,
6416                                 BTEqualStrategyNumber, F_OIDEQ,
6417                                 ObjectIdGetDatum(relationOid));
6418         /* we leave refobjsubid unspecified */
6419
6420         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6421                                                           SnapshotNow, 2, key);
6422
6423         while (HeapTupleIsValid(tup = systable_getnext(scan)))
6424         {
6425                 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6426                 Relation        seqRel;
6427
6428                 /* skip dependencies other than auto dependencies on columns */
6429                 if (depForm->refobjsubid == 0 ||
6430                         depForm->classid != RelationRelationId ||
6431                         depForm->objsubid != 0 ||
6432                         depForm->deptype != DEPENDENCY_AUTO)
6433                         continue;
6434
6435                 /* Use relation_open just in case it's an index */
6436                 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6437
6438                 /* skip non-sequence relations */
6439                 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6440                 {
6441                         /* No need to keep the lock */
6442                         relation_close(seqRel, AccessExclusiveLock);
6443                         continue;
6444                 }
6445
6446                 /* We don't need to close the sequence while we alter it. */
6447                 ATExecChangeOwner(depForm->objid, newOwnerId, true);
6448
6449                 /* Now we can close it.  Keep the lock till end of transaction. */
6450                 relation_close(seqRel, NoLock);
6451         }
6452
6453         systable_endscan(scan);
6454
6455         relation_close(depRel, AccessShareLock);
6456 }
6457
6458 /*
6459  * ALTER TABLE CLUSTER ON
6460  *
6461  * The only thing we have to do is to change the indisclustered bits.
6462  */
6463 static void
6464 ATExecClusterOn(Relation rel, const char *indexName)
6465 {
6466         Oid                     indexOid;
6467
6468         indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
6469
6470         if (!OidIsValid(indexOid))
6471                 ereport(ERROR,
6472                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6473                                  errmsg("index \"%s\" for table \"%s\" does not exist",
6474                                                 indexName, RelationGetRelationName(rel))));
6475
6476         /* Check index is valid to cluster on */
6477         check_index_is_clusterable(rel, indexOid, false);
6478
6479         /* And do the work */
6480         mark_index_clustered(rel, indexOid);
6481 }
6482
6483 /*
6484  * ALTER TABLE SET WITHOUT CLUSTER
6485  *
6486  * We have to find any indexes on the table that have indisclustered bit
6487  * set and turn it off.
6488  */
6489 static void
6490 ATExecDropCluster(Relation rel)
6491 {
6492         mark_index_clustered(rel, InvalidOid);
6493 }
6494
6495 /*
6496  * ALTER TABLE SET TABLESPACE
6497  */
6498 static void
6499 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
6500 {
6501         Oid                     tablespaceId;
6502         AclResult       aclresult;
6503
6504         /* Check that the tablespace exists */
6505         tablespaceId = get_tablespace_oid(tablespacename);
6506         if (!OidIsValid(tablespaceId))
6507                 ereport(ERROR,
6508                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6509                                  errmsg("tablespace \"%s\" does not exist", tablespacename)));
6510
6511         /* Check its permissions */
6512         aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
6513         if (aclresult != ACLCHECK_OK)
6514                 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
6515
6516         /* Save info for Phase 3 to do the real work */
6517         if (OidIsValid(tab->newTableSpace))
6518                 ereport(ERROR,
6519                                 (errcode(ERRCODE_SYNTAX_ERROR),
6520                                  errmsg("cannot have multiple SET TABLESPACE subcommands")));
6521         tab->newTableSpace = tablespaceId;
6522 }
6523
6524 /*
6525  * ALTER TABLE/INDEX SET (...) or RESET (...)
6526  */
6527 static void
6528 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
6529 {
6530         Oid                     relid;
6531         Relation        pgclass;
6532         HeapTuple       tuple;
6533         HeapTuple       newtuple;
6534         Datum           datum;
6535         bool            isnull;
6536         Datum           newOptions;
6537         Datum           repl_val[Natts_pg_class];
6538         bool            repl_null[Natts_pg_class];
6539         bool            repl_repl[Natts_pg_class];
6540         static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
6541
6542         if (defList == NIL)
6543                 return;                                 /* nothing to do */
6544
6545         pgclass = heap_open(RelationRelationId, RowExclusiveLock);
6546
6547         /* Get the old reloptions */
6548         relid = RelationGetRelid(rel);
6549         tuple = SearchSysCache(RELOID,
6550                                                    ObjectIdGetDatum(relid),
6551                                                    0, 0, 0);
6552         if (!HeapTupleIsValid(tuple))
6553                 elog(ERROR, "cache lookup failed for relation %u", relid);
6554
6555         datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6556
6557         /* Generate new proposed reloptions (text array) */
6558         newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6559                                                                    defList, NULL, validnsps, false, isReset);
6560
6561         /* Validate */
6562         switch (rel->rd_rel->relkind)
6563         {
6564                 case RELKIND_RELATION:
6565                 case RELKIND_TOASTVALUE:
6566                         (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
6567                         break;
6568                 case RELKIND_INDEX:
6569                         (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
6570                         break;
6571                 default:
6572                         ereport(ERROR,
6573                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6574                                          errmsg("\"%s\" is not a table, index, or TOAST table",
6575                                                         RelationGetRelationName(rel))));
6576                         break;
6577         }
6578
6579         /*
6580          * All we need do here is update the pg_class row; the new options will be
6581          * propagated into relcaches during post-commit cache inval.
6582          */
6583         memset(repl_val, 0, sizeof(repl_val));
6584         memset(repl_null, false, sizeof(repl_null));
6585         memset(repl_repl, false, sizeof(repl_repl));
6586
6587         if (newOptions != (Datum) 0)
6588                 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6589         else
6590                 repl_null[Anum_pg_class_reloptions - 1] = true;
6591
6592         repl_repl[Anum_pg_class_reloptions - 1] = true;
6593
6594         newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
6595                                                                  repl_val, repl_null, repl_repl);
6596
6597         simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6598
6599         CatalogUpdateIndexes(pgclass, newtuple);
6600
6601         heap_freetuple(newtuple);
6602
6603         ReleaseSysCache(tuple);
6604
6605         /* repeat the whole exercise for the toast table, if there's one */
6606         if (OidIsValid(rel->rd_rel->reltoastrelid))
6607         {
6608                 Relation        toastrel;
6609                 Oid                     toastid = rel->rd_rel->reltoastrelid;
6610
6611                 toastrel = heap_open(toastid, AccessExclusiveLock);
6612
6613                 /* Get the old reloptions */
6614                 tuple = SearchSysCache(RELOID,
6615                                                            ObjectIdGetDatum(toastid),
6616                                                            0, 0, 0);
6617                 if (!HeapTupleIsValid(tuple))
6618                         elog(ERROR, "cache lookup failed for relation %u", toastid);
6619
6620                 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6621
6622                 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6623                                                                 defList, "toast", validnsps, false, isReset);
6624
6625                 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
6626
6627                 memset(repl_val, 0, sizeof(repl_val));
6628                 memset(repl_null, false, sizeof(repl_null));
6629                 memset(repl_repl, false, sizeof(repl_repl));
6630
6631                 if (newOptions != (Datum) 0)
6632                         repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6633                 else
6634                         repl_null[Anum_pg_class_reloptions - 1] = true;
6635
6636                 repl_repl[Anum_pg_class_reloptions - 1] = true;
6637
6638                 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
6639                                                                          repl_val, repl_null, repl_repl);
6640
6641                 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6642
6643                 CatalogUpdateIndexes(pgclass, newtuple);
6644
6645                 heap_freetuple(newtuple);
6646
6647                 ReleaseSysCache(tuple);
6648
6649                 heap_close(toastrel, NoLock);
6650         }
6651
6652         heap_close(pgclass, RowExclusiveLock);
6653 }
6654
6655 /*
6656  * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6657  * rewriting to be done, so we just want to copy the data as fast as possible.
6658  */
6659 static void
6660 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
6661 {
6662         Relation        rel;
6663         Oid                     oldTableSpace;
6664         Oid                     reltoastrelid;
6665         Oid                     reltoastidxid;
6666         Oid                     newrelfilenode;
6667         RelFileNode newrnode;
6668         SMgrRelation dstrel;
6669         Relation        pg_class;
6670         HeapTuple       tuple;
6671         Form_pg_class rd_rel;
6672         ForkNumber      forkNum;
6673
6674         /*
6675          * Need lock here in case we are recursing to toast table or index
6676          */
6677         rel = relation_open(tableOid, AccessExclusiveLock);
6678
6679         /*
6680          * We can never allow moving of shared or nailed-in-cache relations,
6681          * because we can't support changing their reltablespace values.
6682          */
6683         if (rel->rd_rel->relisshared || rel->rd_isnailed)
6684                 ereport(ERROR,
6685                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6686                                  errmsg("cannot move system relation \"%s\"",
6687                                                 RelationGetRelationName(rel))));
6688
6689         /* Can't move a non-shared relation into pg_global */
6690         if (newTableSpace == GLOBALTABLESPACE_OID)
6691                 ereport(ERROR,
6692                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6693                                  errmsg("only shared relations can be placed in pg_global tablespace")));
6694
6695         /*
6696          * Don't allow moving temp tables of other backends ... their local buffer
6697          * manager is not going to cope.
6698          */
6699         if (RELATION_IS_OTHER_TEMP(rel))
6700                 ereport(ERROR,
6701                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6702                                  errmsg("cannot move temporary tables of other sessions")));
6703
6704         /*
6705          * No work if no change in tablespace.
6706          */
6707         oldTableSpace = rel->rd_rel->reltablespace;
6708         if (newTableSpace == oldTableSpace ||
6709                 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
6710         {
6711                 relation_close(rel, NoLock);
6712                 return;
6713         }
6714
6715         reltoastrelid = rel->rd_rel->reltoastrelid;
6716         reltoastidxid = rel->rd_rel->reltoastidxid;
6717
6718         /* Get a modifiable copy of the relation's pg_class row */
6719         pg_class = heap_open(RelationRelationId, RowExclusiveLock);
6720
6721         tuple = SearchSysCacheCopy(RELOID,
6722                                                            ObjectIdGetDatum(tableOid),
6723                                                            0, 0, 0);
6724         if (!HeapTupleIsValid(tuple))
6725                 elog(ERROR, "cache lookup failed for relation %u", tableOid);
6726         rd_rel = (Form_pg_class) GETSTRUCT(tuple);
6727
6728         /*
6729          * Since we copy the file directly without looking at the shared buffers,
6730          * we'd better first flush out any pages of the source relation that are
6731          * in shared buffers.  We assume no new changes will be made while we are
6732          * holding exclusive lock on the rel.
6733          */
6734         FlushRelationBuffers(rel);
6735
6736         /*
6737          * Relfilenodes are not unique across tablespaces, so we need to allocate
6738          * a new one in the new tablespace.
6739          */
6740         newrelfilenode = GetNewRelFileNode(newTableSpace,
6741                                                                            rel->rd_rel->relisshared,
6742                                                                            NULL);
6743
6744         /* Open old and new relation */
6745         newrnode = rel->rd_node;
6746         newrnode.relNode = newrelfilenode;
6747         newrnode.spcNode = newTableSpace;
6748         dstrel = smgropen(newrnode);
6749
6750         RelationOpenSmgr(rel);
6751
6752         /*
6753          * Create and copy all forks of the relation, and schedule unlinking of
6754          * old physical files.
6755          *
6756          * NOTE: any conflict in relfilenode value will be caught in
6757          * RelationCreateStorage().
6758          */
6759         RelationCreateStorage(newrnode, rel->rd_istemp);
6760
6761         /* copy main fork */
6762         copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM, rel->rd_istemp);
6763
6764         /* copy those extra forks that exist */
6765         for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
6766         {
6767                 if (smgrexists(rel->rd_smgr, forkNum))
6768                 {
6769                         smgrcreate(dstrel, forkNum, false);
6770                         copy_relation_data(rel->rd_smgr, dstrel, forkNum, rel->rd_istemp);
6771                 }
6772         }
6773
6774         /* drop old relation, and close new one */
6775         RelationDropStorage(rel);
6776         smgrclose(dstrel);
6777
6778         /* update the pg_class row */
6779         rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6780         rd_rel->relfilenode = newrelfilenode;
6781         simple_heap_update(pg_class, &tuple->t_self, tuple);
6782         CatalogUpdateIndexes(pg_class, tuple);
6783
6784         heap_freetuple(tuple);
6785
6786         heap_close(pg_class, RowExclusiveLock);
6787
6788         relation_close(rel, NoLock);
6789
6790         /* Make sure the reltablespace change is visible */
6791         CommandCounterIncrement();
6792
6793         /* Move associated toast relation and/or index, too */
6794         if (OidIsValid(reltoastrelid))
6795                 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6796         if (OidIsValid(reltoastidxid))
6797                 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6798 }
6799
6800 /*
6801  * Copy data, block by block
6802  */
6803 static void
6804 copy_relation_data(SMgrRelation src, SMgrRelation dst,
6805                                    ForkNumber forkNum, bool istemp)
6806 {
6807         bool            use_wal;
6808         BlockNumber nblocks;
6809         BlockNumber blkno;
6810         char            buf[BLCKSZ];
6811         Page            page = (Page) buf;
6812
6813         /*
6814          * We need to log the copied data in WAL iff WAL archiving is enabled AND
6815          * it's not a temp rel.
6816          */
6817         use_wal = XLogArchivingActive() && !istemp;
6818
6819         nblocks = smgrnblocks(src, forkNum);
6820
6821         for (blkno = 0; blkno < nblocks; blkno++)
6822         {
6823                 smgrread(src, forkNum, blkno, buf);
6824
6825                 /* XLOG stuff */
6826                 if (use_wal)
6827                         log_newpage(&dst->smgr_rnode, forkNum, blkno, page);
6828
6829                 /*
6830                  * Now write the page.  We say isTemp = true even if it's not a temp
6831                  * rel, because there's no need for smgr to schedule an fsync for this
6832                  * write; we'll do it ourselves below.
6833                  */
6834                 smgrextend(dst, forkNum, blkno, buf, true);
6835         }
6836
6837         /*
6838          * If the rel isn't temp, we must fsync it down to disk before it's safe
6839          * to commit the transaction.  (For a temp rel we don't care since the rel
6840          * will be uninteresting after a crash anyway.)
6841          *
6842          * It's obvious that we must do this when not WAL-logging the copy. It's
6843          * less obvious that we have to do it even if we did WAL-log the copied
6844          * pages. The reason is that since we're copying outside shared buffers, a
6845          * CHECKPOINT occurring during the copy has no way to flush the previously
6846          * written data to disk (indeed it won't know the new rel even exists).  A
6847          * crash later on would replay WAL from the checkpoint, therefore it
6848          * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6849          * here, they might still not be on disk when the crash occurs.
6850          */
6851         if (!istemp)
6852                 smgrimmedsync(dst, forkNum);
6853 }
6854
6855 /*
6856  * ALTER TABLE ENABLE/DISABLE TRIGGER
6857  *
6858  * We just pass this off to trigger.c.
6859  */
6860 static void
6861 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6862                                                    char fires_when, bool skip_system)
6863 {
6864         EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6865 }
6866
6867 /*
6868  * ALTER TABLE ENABLE/DISABLE RULE
6869  *
6870  * We just pass this off to rewriteDefine.c.
6871  */
6872 static void
6873 ATExecEnableDisableRule(Relation rel, char *trigname,
6874                                                 char fires_when)
6875 {
6876         EnableDisableRule(rel, trigname, fires_when);
6877 }
6878
6879 /*
6880  * ALTER TABLE INHERIT
6881  *
6882  * Add a parent to the child's parents. This verifies that all the columns and
6883  * check constraints of the parent appear in the child and that they have the
6884  * same data types and expressions.
6885  */
6886 static void
6887 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6888 {
6889         Relation        parent_rel,
6890                                 catalogRelation;
6891         SysScanDesc scan;
6892         ScanKeyData key;
6893         HeapTuple       inheritsTuple;
6894         int32           inhseqno;
6895         List       *children;
6896
6897         /*
6898          * AccessShareLock on the parent is what's obtained during normal CREATE
6899          * TABLE ... INHERITS ..., so should be enough here.
6900          */
6901         parent_rel = heap_openrv(parent, AccessShareLock);
6902
6903         /*
6904          * Must be owner of both parent and child -- child was checked by
6905          * ATSimplePermissions call in ATPrepCmd
6906          */
6907         ATSimplePermissions(parent_rel, false);
6908
6909         /* Permanent rels cannot inherit from temporary ones */
6910         if (parent_rel->rd_istemp && !child_rel->rd_istemp)
6911                 ereport(ERROR,
6912                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6913                                  errmsg("cannot inherit from temporary relation \"%s\"",
6914                                                 RelationGetRelationName(parent_rel))));
6915
6916         /*
6917          * Check for duplicates in the list of parents, and determine the highest
6918          * inhseqno already present; we'll use the next one for the new parent.
6919          * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6920          *
6921          * Note: we do not reject the case where the child already inherits from
6922          * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6923          */
6924         catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6925         ScanKeyInit(&key,
6926                                 Anum_pg_inherits_inhrelid,
6927                                 BTEqualStrategyNumber, F_OIDEQ,
6928                                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6929         scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6930                                                           true, SnapshotNow, 1, &key);
6931
6932         /* inhseqno sequences start at 1 */
6933         inhseqno = 0;
6934         while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6935         {
6936                 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6937
6938                 if (inh->inhparent == RelationGetRelid(parent_rel))
6939                         ereport(ERROR,
6940                                         (errcode(ERRCODE_DUPLICATE_TABLE),
6941                          errmsg("relation \"%s\" would be inherited from more than once",
6942                                         RelationGetRelationName(parent_rel))));
6943                 if (inh->inhseqno > inhseqno)
6944                         inhseqno = inh->inhseqno;
6945         }
6946         systable_endscan(scan);
6947
6948         /*
6949          * Prevent circularity by seeing if proposed parent inherits from child.
6950          * (In particular, this disallows making a rel inherit from itself.)
6951          *
6952          * This is not completely bulletproof because of race conditions: in
6953          * multi-level inheritance trees, someone else could concurrently be
6954          * making another inheritance link that closes the loop but does not join
6955          * either of the rels we have locked.  Preventing that seems to require
6956          * exclusive locks on the entire inheritance tree, which is a cure worse
6957          * than the disease.  find_all_inheritors() will cope with circularity
6958          * anyway, so don't sweat it too much.
6959          *
6960          * We use weakest lock we can on child's children, namely AccessShareLock.
6961          */
6962         children = find_all_inheritors(RelationGetRelid(child_rel),
6963                                                                    AccessShareLock);
6964
6965         if (list_member_oid(children, RelationGetRelid(parent_rel)))
6966                 ereport(ERROR,
6967                                 (errcode(ERRCODE_DUPLICATE_TABLE),
6968                                  errmsg("circular inheritance not allowed"),
6969                                  errdetail("\"%s\" is already a child of \"%s\".",
6970                                                    parent->relname,
6971                                                    RelationGetRelationName(child_rel))));
6972
6973         /* If parent has OIDs then child must have OIDs */
6974         if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6975                 ereport(ERROR,
6976                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6977                                  errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6978                                                 RelationGetRelationName(child_rel),
6979                                                 RelationGetRelationName(parent_rel))));
6980
6981         /* Match up the columns and bump attinhcount as needed */
6982         MergeAttributesIntoExisting(child_rel, parent_rel);
6983
6984         /* Match up the constraints and bump coninhcount as needed */
6985         MergeConstraintsIntoExisting(child_rel, parent_rel);
6986
6987         /*
6988          * OK, it looks valid.  Make the catalog entries that show inheritance.
6989          */
6990         StoreCatalogInheritance1(RelationGetRelid(child_rel),
6991                                                          RelationGetRelid(parent_rel),
6992                                                          inhseqno + 1,
6993                                                          catalogRelation);
6994
6995         /* Now we're done with pg_inherits */
6996         heap_close(catalogRelation, RowExclusiveLock);
6997
6998         /* keep our lock on the parent relation until commit */
6999         heap_close(parent_rel, NoLock);
7000 }
7001
7002 /*
7003  * Obtain the source-text form of the constraint expression for a check
7004  * constraint, given its pg_constraint tuple
7005  */
7006 static char *
7007 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
7008 {
7009         Form_pg_constraint con;
7010         bool            isnull;
7011         Datum           attr;
7012         Datum           expr;
7013
7014         con = (Form_pg_constraint) GETSTRUCT(contup);
7015         attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
7016         if (isnull)
7017                 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
7018
7019         expr = DirectFunctionCall2(pg_get_expr, attr,
7020                                                            ObjectIdGetDatum(con->conrelid));
7021         return TextDatumGetCString(expr);
7022 }
7023
7024 /*
7025  * Determine whether two check constraints are functionally equivalent
7026  *
7027  * The test we apply is to see whether they reverse-compile to the same
7028  * source string.  This insulates us from issues like whether attributes
7029  * have the same physical column numbers in parent and child relations.
7030  */
7031 static bool
7032 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
7033 {
7034         Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
7035         Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
7036
7037         if (acon->condeferrable != bcon->condeferrable ||
7038                 acon->condeferred != bcon->condeferred ||
7039                 strcmp(decompile_conbin(a, tupleDesc),
7040                            decompile_conbin(b, tupleDesc)) != 0)
7041                 return false;
7042         else
7043                 return true;
7044 }
7045
7046 /*
7047  * Check columns in child table match up with columns in parent, and increment
7048  * their attinhcount.
7049  *
7050  * Called by ATExecAddInherit
7051  *
7052  * Currently all parent columns must be found in child. Missing columns are an
7053  * error.  One day we might consider creating new columns like CREATE TABLE
7054  * does.  However, that is widely unpopular --- in the common use case of
7055  * partitioned tables it's a foot-gun.
7056  *
7057  * The data type must match exactly. If the parent column is NOT NULL then
7058  * the child must be as well. Defaults are not compared, however.
7059  */
7060 static void
7061 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
7062 {
7063         Relation        attrrel;
7064         AttrNumber      parent_attno;
7065         int                     parent_natts;
7066         TupleDesc       tupleDesc;
7067         TupleConstr *constr;
7068         HeapTuple       tuple;
7069
7070         attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
7071
7072         tupleDesc = RelationGetDescr(parent_rel);
7073         parent_natts = tupleDesc->natts;
7074         constr = tupleDesc->constr;
7075
7076         for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
7077         {
7078                 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
7079                 char       *attributeName = NameStr(attribute->attname);
7080
7081                 /* Ignore dropped columns in the parent. */
7082                 if (attribute->attisdropped)
7083                         continue;
7084
7085                 /* Find same column in child (matching on column name). */
7086                 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
7087                                                                                   attributeName);
7088                 if (HeapTupleIsValid(tuple))
7089                 {
7090                         /* Check they are same type and typmod */
7091                         Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
7092
7093                         if (attribute->atttypid != childatt->atttypid ||
7094                                 attribute->atttypmod != childatt->atttypmod)
7095                                 ereport(ERROR,
7096                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
7097                                                  errmsg("child table \"%s\" has different type for column \"%s\"",
7098                                                                 RelationGetRelationName(child_rel),
7099                                                                 attributeName)));
7100
7101                         if (attribute->attnotnull && !childatt->attnotnull)
7102                                 ereport(ERROR,
7103                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
7104                                 errmsg("column \"%s\" in child table must be marked NOT NULL",
7105                                            attributeName)));
7106
7107                         /*
7108                          * OK, bump the child column's inheritance count.  (If we fail
7109                          * later on, this change will just roll back.)
7110                          */
7111                         childatt->attinhcount++;
7112                         simple_heap_update(attrrel, &tuple->t_self, tuple);
7113                         CatalogUpdateIndexes(attrrel, tuple);
7114                         heap_freetuple(tuple);
7115                 }
7116                 else
7117                 {
7118                         ereport(ERROR,
7119                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
7120                                          errmsg("child table is missing column \"%s\"",
7121                                                         attributeName)));
7122                 }
7123         }
7124
7125         heap_close(attrrel, RowExclusiveLock);
7126 }
7127
7128 /*
7129  * Check constraints in child table match up with constraints in parent,
7130  * and increment their coninhcount.
7131  *
7132  * Called by ATExecAddInherit
7133  *
7134  * Currently all constraints in parent must be present in the child. One day we
7135  * may consider adding new constraints like CREATE TABLE does. We may also want
7136  * to allow an optional flag on parent table constraints indicating they are
7137  * intended to ONLY apply to the master table, not to the children. That would
7138  * make it possible to ensure no records are mistakenly inserted into the
7139  * master in partitioned tables rather than the appropriate child.
7140  *
7141  * XXX This is O(N^2) which may be an issue with tables with hundreds of
7142  * constraints. As long as tables have more like 10 constraints it shouldn't be
7143  * a problem though. Even 100 constraints ought not be the end of the world.
7144  */
7145 static void
7146 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
7147 {
7148         Relation        catalog_relation;
7149         TupleDesc       tuple_desc;
7150         SysScanDesc parent_scan;
7151         ScanKeyData parent_key;
7152         HeapTuple       parent_tuple;
7153
7154         catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
7155         tuple_desc = RelationGetDescr(catalog_relation);
7156
7157         /* Outer loop scans through the parent's constraint definitions */
7158         ScanKeyInit(&parent_key,
7159                                 Anum_pg_constraint_conrelid,
7160                                 BTEqualStrategyNumber, F_OIDEQ,
7161                                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7162         parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
7163                                                                          true, SnapshotNow, 1, &parent_key);
7164
7165         while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
7166         {
7167                 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
7168                 SysScanDesc child_scan;
7169                 ScanKeyData child_key;
7170                 HeapTuple       child_tuple;
7171                 bool            found = false;
7172
7173                 if (parent_con->contype != CONSTRAINT_CHECK)
7174                         continue;
7175
7176                 /* Search for a child constraint matching this one */
7177                 ScanKeyInit(&child_key,
7178                                         Anum_pg_constraint_conrelid,
7179                                         BTEqualStrategyNumber, F_OIDEQ,
7180                                         ObjectIdGetDatum(RelationGetRelid(child_rel)));
7181                 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
7182                                                                                 true, SnapshotNow, 1, &child_key);
7183
7184                 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
7185                 {
7186                         Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
7187                         HeapTuple       child_copy;
7188
7189                         if (child_con->contype != CONSTRAINT_CHECK)
7190                                 continue;
7191
7192                         if (strcmp(NameStr(parent_con->conname),
7193                                            NameStr(child_con->conname)) != 0)
7194                                 continue;
7195
7196                         if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
7197                                 ereport(ERROR,
7198                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
7199                                                  errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
7200                                                                 RelationGetRelationName(child_rel),
7201                                                                 NameStr(parent_con->conname))));
7202
7203                         /*
7204                          * OK, bump the child constraint's inheritance count.  (If we fail
7205                          * later on, this change will just roll back.)
7206                          */
7207                         child_copy = heap_copytuple(child_tuple);
7208                         child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
7209                         child_con->coninhcount++;
7210                         simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
7211                         CatalogUpdateIndexes(catalog_relation, child_copy);
7212                         heap_freetuple(child_copy);
7213
7214                         found = true;
7215                         break;
7216                 }
7217
7218                 systable_endscan(child_scan);
7219
7220                 if (!found)
7221                         ereport(ERROR,
7222                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
7223                                          errmsg("child table is missing constraint \"%s\"",
7224                                                         NameStr(parent_con->conname))));
7225         }
7226
7227         systable_endscan(parent_scan);
7228         heap_close(catalog_relation, RowExclusiveLock);
7229 }
7230
7231 /*
7232  * ALTER TABLE NO INHERIT
7233  *
7234  * Drop a parent from the child's parents. This just adjusts the attinhcount
7235  * and attislocal of the columns and removes the pg_inherit and pg_depend
7236  * entries.
7237  *
7238  * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
7239  * up attislocal stays true, which means if a child is ever removed from a
7240  * parent then its columns will never be automatically dropped which may
7241  * surprise. But at least we'll never surprise by dropping columns someone
7242  * isn't expecting to be dropped which would actually mean data loss.
7243  *
7244  * coninhcount and conislocal for inherited constraints are adjusted in
7245  * exactly the same way.
7246  */
7247 static void
7248 ATExecDropInherit(Relation rel, RangeVar *parent)
7249 {
7250         Relation        parent_rel;
7251         Relation        catalogRelation;
7252         SysScanDesc scan;
7253         ScanKeyData key[3];
7254         HeapTuple       inheritsTuple,
7255                                 attributeTuple,
7256                                 constraintTuple,
7257                                 depTuple;
7258         List       *connames;
7259         bool            found = false;
7260
7261         /*
7262          * AccessShareLock on the parent is probably enough, seeing that DROP
7263          * TABLE doesn't lock parent tables at all.  We need some lock since we'll
7264          * be inspecting the parent's schema.
7265          */
7266         parent_rel = heap_openrv(parent, AccessShareLock);
7267
7268         /*
7269          * We don't bother to check ownership of the parent table --- ownership of
7270          * the child is presumed enough rights.
7271          */
7272
7273         /*
7274          * Find and destroy the pg_inherits entry linking the two, or error out if
7275          * there is none.
7276          */
7277         catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7278         ScanKeyInit(&key[0],
7279                                 Anum_pg_inherits_inhrelid,
7280                                 BTEqualStrategyNumber, F_OIDEQ,
7281                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7282         scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7283                                                           true, SnapshotNow, 1, key);
7284
7285         while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7286         {
7287                 Oid                     inhparent;
7288
7289                 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
7290                 if (inhparent == RelationGetRelid(parent_rel))
7291                 {
7292                         simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
7293                         found = true;
7294                         break;
7295                 }
7296         }
7297
7298         systable_endscan(scan);
7299         heap_close(catalogRelation, RowExclusiveLock);
7300
7301         if (!found)
7302                 ereport(ERROR,
7303                                 (errcode(ERRCODE_UNDEFINED_TABLE),
7304                                  errmsg("relation \"%s\" is not a parent of relation \"%s\"",
7305                                                 RelationGetRelationName(parent_rel),
7306                                                 RelationGetRelationName(rel))));
7307
7308         /*
7309          * Search through child columns looking for ones matching parent rel
7310          */
7311         catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
7312         ScanKeyInit(&key[0],
7313                                 Anum_pg_attribute_attrelid,
7314                                 BTEqualStrategyNumber, F_OIDEQ,
7315                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7316         scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
7317                                                           true, SnapshotNow, 1, key);
7318         while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
7319         {
7320                 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
7321
7322                 /* Ignore if dropped or not inherited */
7323                 if (att->attisdropped)
7324                         continue;
7325                 if (att->attinhcount <= 0)
7326                         continue;
7327
7328                 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
7329                                                                                 NameStr(att->attname)))
7330                 {
7331                         /* Decrement inhcount and possibly set islocal to true */
7332                         HeapTuple       copyTuple = heap_copytuple(attributeTuple);
7333                         Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
7334
7335                         copy_att->attinhcount--;
7336                         if (copy_att->attinhcount == 0)
7337                                 copy_att->attislocal = true;
7338
7339                         simple_heap_update(catalogRelation, &copyTuple->t_self, copyTuple);
7340                         CatalogUpdateIndexes(catalogRelation, copyTuple);
7341                         heap_freetuple(copyTuple);
7342                 }
7343         }
7344         systable_endscan(scan);
7345         heap_close(catalogRelation, RowExclusiveLock);
7346
7347         /*
7348          * Likewise, find inherited check constraints and disinherit them. To do
7349          * this, we first need a list of the names of the parent's check
7350          * constraints.  (We cheat a bit by only checking for name matches,
7351          * assuming that the expressions will match.)
7352          */
7353         catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
7354         ScanKeyInit(&key[0],
7355                                 Anum_pg_constraint_conrelid,
7356                                 BTEqualStrategyNumber, F_OIDEQ,
7357                                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7358         scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7359                                                           true, SnapshotNow, 1, key);
7360
7361         connames = NIL;
7362
7363         while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7364         {
7365                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7366
7367                 if (con->contype == CONSTRAINT_CHECK)
7368                         connames = lappend(connames, pstrdup(NameStr(con->conname)));
7369         }
7370
7371         systable_endscan(scan);
7372
7373         /* Now scan the child's constraints */
7374         ScanKeyInit(&key[0],
7375                                 Anum_pg_constraint_conrelid,
7376                                 BTEqualStrategyNumber, F_OIDEQ,
7377                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7378         scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7379                                                           true, SnapshotNow, 1, key);
7380
7381         while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7382         {
7383                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7384                 bool            match;
7385                 ListCell   *lc;
7386
7387                 if (con->contype != CONSTRAINT_CHECK)
7388                         continue;
7389
7390                 match = false;
7391                 foreach(lc, connames)
7392                 {
7393                         if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
7394                         {
7395                                 match = true;
7396                                 break;
7397                         }
7398                 }
7399
7400                 if (match)
7401                 {
7402                         /* Decrement inhcount and possibly set islocal to true */
7403                         HeapTuple       copyTuple = heap_copytuple(constraintTuple);
7404                         Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
7405
7406                         if (copy_con->coninhcount <= 0)         /* shouldn't happen */
7407                                 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7408                                          RelationGetRelid(rel), NameStr(copy_con->conname));
7409
7410                         copy_con->coninhcount--;
7411                         if (copy_con->coninhcount == 0)
7412                                 copy_con->conislocal = true;
7413
7414                         simple_heap_update(catalogRelation, &copyTuple->t_self, copyTuple);
7415                         CatalogUpdateIndexes(catalogRelation, copyTuple);
7416                         heap_freetuple(copyTuple);
7417                 }
7418         }
7419
7420         systable_endscan(scan);
7421         heap_close(catalogRelation, RowExclusiveLock);
7422
7423         /*
7424          * Drop the dependency
7425          *
7426          * There's no convenient way to do this, so go trawling through pg_depend
7427          */
7428         catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
7429
7430         ScanKeyInit(&key[0],
7431                                 Anum_pg_depend_classid,
7432                                 BTEqualStrategyNumber, F_OIDEQ,
7433                                 ObjectIdGetDatum(RelationRelationId));
7434         ScanKeyInit(&key[1],
7435                                 Anum_pg_depend_objid,
7436                                 BTEqualStrategyNumber, F_OIDEQ,
7437                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7438         ScanKeyInit(&key[2],
7439                                 Anum_pg_depend_objsubid,
7440                                 BTEqualStrategyNumber, F_INT4EQ,
7441                                 Int32GetDatum(0));
7442
7443         scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
7444                                                           SnapshotNow, 3, key);
7445
7446         while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
7447         {
7448                 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
7449
7450                 if (dep->refclassid == RelationRelationId &&
7451                         dep->refobjid == RelationGetRelid(parent_rel) &&
7452                         dep->refobjsubid == 0 &&
7453                         dep->deptype == DEPENDENCY_NORMAL)
7454                         simple_heap_delete(catalogRelation, &depTuple->t_self);
7455         }
7456
7457         systable_endscan(scan);
7458         heap_close(catalogRelation, RowExclusiveLock);
7459
7460         /* keep our lock on the parent relation until commit */
7461         heap_close(parent_rel, NoLock);
7462 }
7463
7464
7465 /*
7466  * Execute ALTER TABLE SET SCHEMA
7467  *
7468  * Note: caller must have checked ownership of the relation already
7469  */
7470 void
7471 AlterTableNamespace(RangeVar *relation, const char *newschema,
7472                                         ObjectType stmttype)
7473 {
7474         Relation        rel;
7475         Oid                     relid;
7476         Oid                     oldNspOid;
7477         Oid                     nspOid;
7478         Relation        classRel;
7479
7480         rel = relation_openrv(relation, AccessExclusiveLock);
7481
7482         relid = RelationGetRelid(rel);
7483         oldNspOid = RelationGetNamespace(rel);
7484
7485         /* Check relation type against type specified in the ALTER command */
7486         switch (stmttype)
7487         {
7488                 case OBJECT_TABLE:
7489
7490                         /*
7491                          * For mostly-historical reasons, we allow ALTER TABLE to apply to
7492                          * all relation types.
7493                          */
7494                         break;
7495
7496                 case OBJECT_SEQUENCE:
7497                         if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
7498                                 ereport(ERROR,
7499                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7500                                                  errmsg("\"%s\" is not a sequence",
7501                                                                 RelationGetRelationName(rel))));
7502                         break;
7503
7504                 case OBJECT_VIEW:
7505                         if (rel->rd_rel->relkind != RELKIND_VIEW)
7506                                 ereport(ERROR,
7507                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7508                                                  errmsg("\"%s\" is not a view",
7509                                                                 RelationGetRelationName(rel))));
7510                         break;
7511
7512                 default:
7513                         elog(ERROR, "unrecognized object type: %d", (int) stmttype);
7514         }
7515
7516         /* Can we change the schema of this tuple? */
7517         switch (rel->rd_rel->relkind)
7518         {
7519                 case RELKIND_RELATION:
7520                 case RELKIND_VIEW:
7521                         /* ok to change schema */
7522                         break;
7523                 case RELKIND_SEQUENCE:
7524                         {
7525                                 /* if it's an owned sequence, disallow moving it by itself */
7526                                 Oid                     tableId;
7527                                 int32           colId;
7528
7529                                 if (sequenceIsOwned(relid, &tableId, &colId))
7530                                         ereport(ERROR,
7531                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7532                                                          errmsg("cannot move an owned sequence into another schema"),
7533                                           errdetail("Sequence \"%s\" is linked to table \"%s\".",
7534                                                                 RelationGetRelationName(rel),
7535                                                                 get_rel_name(tableId))));
7536                         }
7537                         break;
7538                 case RELKIND_COMPOSITE_TYPE:
7539                         ereport(ERROR,
7540                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7541                                          errmsg("\"%s\" is a composite type",
7542                                                         RelationGetRelationName(rel)),
7543                                          errhint("Use ALTER TYPE instead.")));
7544                         break;
7545                 case RELKIND_INDEX:
7546                 case RELKIND_TOASTVALUE:
7547                         /* FALL THRU */
7548                 default:
7549                         ereport(ERROR,
7550                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7551                                          errmsg("\"%s\" is not a table, view, or sequence",
7552                                                         RelationGetRelationName(rel))));
7553         }
7554
7555         /* get schema OID and check its permissions */
7556         nspOid = LookupCreationNamespace(newschema);
7557
7558         if (oldNspOid == nspOid)
7559                 ereport(ERROR,
7560                                 (errcode(ERRCODE_DUPLICATE_TABLE),
7561                                  errmsg("relation \"%s\" is already in schema \"%s\"",
7562                                                 RelationGetRelationName(rel),
7563                                                 newschema)));
7564
7565         /* disallow renaming into or out of temp schemas */
7566         if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
7567                 ereport(ERROR,
7568                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7569                         errmsg("cannot move objects into or out of temporary schemas")));
7570
7571         /* same for TOAST schema */
7572         if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
7573                 ereport(ERROR,
7574                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7575                                  errmsg("cannot move objects into or out of TOAST schema")));
7576
7577         /* OK, modify the pg_class row and pg_depend entry */
7578         classRel = heap_open(RelationRelationId, RowExclusiveLock);
7579
7580         AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
7581
7582         /* Fix the table's rowtype too */
7583         AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
7584
7585         /* Fix other dependent stuff */
7586         if (rel->rd_rel->relkind == RELKIND_RELATION)
7587         {
7588                 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
7589                 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
7590                 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
7591         }
7592
7593         heap_close(classRel, RowExclusiveLock);
7594
7595         /* close rel, but keep lock until commit */
7596         relation_close(rel, NoLock);
7597 }
7598
7599 /*
7600  * The guts of relocating a relation to another namespace: fix the pg_class
7601  * entry, and the pg_depend entry if any.  Caller must already have
7602  * opened and write-locked pg_class.
7603  */
7604 void
7605 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
7606                                                            Oid oldNspOid, Oid newNspOid,
7607                                                            bool hasDependEntry)
7608 {
7609         HeapTuple       classTup;
7610         Form_pg_class classForm;
7611
7612         classTup = SearchSysCacheCopy(RELOID,
7613                                                                   ObjectIdGetDatum(relOid),
7614                                                                   0, 0, 0);
7615         if (!HeapTupleIsValid(classTup))
7616                 elog(ERROR, "cache lookup failed for relation %u", relOid);
7617         classForm = (Form_pg_class) GETSTRUCT(classTup);
7618
7619         Assert(classForm->relnamespace == oldNspOid);
7620
7621         /* check for duplicate name (more friendly than unique-index failure) */
7622         if (get_relname_relid(NameStr(classForm->relname),
7623                                                   newNspOid) != InvalidOid)
7624                 ereport(ERROR,
7625                                 (errcode(ERRCODE_DUPLICATE_TABLE),
7626                                  errmsg("relation \"%s\" already exists in schema \"%s\"",
7627                                                 NameStr(classForm->relname),
7628                                                 get_namespace_name(newNspOid))));
7629
7630         /* classTup is a copy, so OK to scribble on */
7631         classForm->relnamespace = newNspOid;
7632
7633         simple_heap_update(classRel, &classTup->t_self, classTup);
7634         CatalogUpdateIndexes(classRel, classTup);
7635
7636         /* Update dependency on schema if caller said so */
7637         if (hasDependEntry &&
7638                 changeDependencyFor(RelationRelationId, relOid,
7639                                                         NamespaceRelationId, oldNspOid, newNspOid) != 1)
7640                 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
7641                          NameStr(classForm->relname));
7642
7643         heap_freetuple(classTup);
7644 }
7645
7646 /*
7647  * Move all indexes for the specified relation to another namespace.
7648  *
7649  * Note: we assume adequate permission checking was done by the caller,
7650  * and that the caller has a suitable lock on the owning relation.
7651  */
7652 static void
7653 AlterIndexNamespaces(Relation classRel, Relation rel,
7654                                          Oid oldNspOid, Oid newNspOid)
7655 {
7656         List       *indexList;
7657         ListCell   *l;
7658
7659         indexList = RelationGetIndexList(rel);
7660
7661         foreach(l, indexList)
7662         {
7663                 Oid                     indexOid = lfirst_oid(l);
7664
7665                 /*
7666                  * Note: currently, the index will not have its own dependency on the
7667                  * namespace, so we don't need to do changeDependencyFor(). There's no
7668                  * rowtype in pg_type, either.
7669                  */
7670                 AlterRelationNamespaceInternal(classRel, indexOid,
7671                                                                            oldNspOid, newNspOid,
7672                                                                            false);
7673         }
7674
7675         list_free(indexList);
7676 }
7677
7678 /*
7679  * Move all SERIAL-column sequences of the specified relation to another
7680  * namespace.
7681  *
7682  * Note: we assume adequate permission checking was done by the caller,
7683  * and that the caller has a suitable lock on the owning relation.
7684  */
7685 static void
7686 AlterSeqNamespaces(Relation classRel, Relation rel,
7687                                    Oid oldNspOid, Oid newNspOid, const char *newNspName)
7688 {
7689         Relation        depRel;
7690         SysScanDesc scan;
7691         ScanKeyData key[2];
7692         HeapTuple       tup;
7693
7694         /*
7695          * SERIAL sequences are those having an auto dependency on one of the
7696          * table's columns (we don't care *which* column, exactly).
7697          */
7698         depRel = heap_open(DependRelationId, AccessShareLock);
7699
7700         ScanKeyInit(&key[0],
7701                                 Anum_pg_depend_refclassid,
7702                                 BTEqualStrategyNumber, F_OIDEQ,
7703                                 ObjectIdGetDatum(RelationRelationId));
7704         ScanKeyInit(&key[1],
7705                                 Anum_pg_depend_refobjid,
7706                                 BTEqualStrategyNumber, F_OIDEQ,
7707                                 ObjectIdGetDatum(RelationGetRelid(rel)));
7708         /* we leave refobjsubid unspecified */
7709
7710         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7711                                                           SnapshotNow, 2, key);
7712
7713         while (HeapTupleIsValid(tup = systable_getnext(scan)))
7714         {
7715                 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7716                 Relation        seqRel;
7717
7718                 /* skip dependencies other than auto dependencies on columns */
7719                 if (depForm->refobjsubid == 0 ||
7720                         depForm->classid != RelationRelationId ||
7721                         depForm->objsubid != 0 ||
7722                         depForm->deptype != DEPENDENCY_AUTO)
7723                         continue;
7724
7725                 /* Use relation_open just in case it's an index */
7726                 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
7727
7728                 /* skip non-sequence relations */
7729                 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7730                 {
7731                         /* No need to keep the lock */
7732                         relation_close(seqRel, AccessExclusiveLock);
7733                         continue;
7734                 }
7735
7736                 /* Fix the pg_class and pg_depend entries */
7737                 AlterRelationNamespaceInternal(classRel, depForm->objid,
7738                                                                            oldNspOid, newNspOid,
7739                                                                            true);
7740
7741                 /*
7742                  * Sequences have entries in pg_type. We need to be careful to move
7743                  * them to the new namespace, too.
7744                  */
7745                 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
7746                                                                    newNspOid, false, false);
7747
7748                 /* Now we can close it.  Keep the lock till end of transaction. */
7749                 relation_close(seqRel, NoLock);
7750         }
7751
7752         systable_endscan(scan);
7753
7754         relation_close(depRel, AccessShareLock);
7755 }
7756
7757
7758 /*
7759  * This code supports
7760  *      CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7761  *
7762  * Because we only support this for TEMP tables, it's sufficient to remember
7763  * the state in a backend-local data structure.
7764  */
7765
7766 /*
7767  * Register a newly-created relation's ON COMMIT action.
7768  */
7769 void
7770 register_on_commit_action(Oid relid, OnCommitAction action)
7771 {
7772         OnCommitItem *oc;
7773         MemoryContext oldcxt;
7774
7775         /*
7776          * We needn't bother registering the relation unless there is an ON COMMIT
7777          * action we need to take.
7778          */
7779         if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
7780                 return;
7781
7782         oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
7783
7784         oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
7785         oc->relid = relid;
7786         oc->oncommit = action;
7787         oc->creating_subid = GetCurrentSubTransactionId();
7788         oc->deleting_subid = InvalidSubTransactionId;
7789
7790         on_commits = lcons(oc, on_commits);
7791
7792         MemoryContextSwitchTo(oldcxt);
7793 }
7794
7795 /*
7796  * Unregister any ON COMMIT action when a relation is deleted.
7797  *
7798  * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7799  */
7800 void
7801 remove_on_commit_action(Oid relid)
7802 {
7803         ListCell   *l;
7804
7805         foreach(l, on_commits)
7806         {
7807                 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7808
7809                 if (oc->relid == relid)
7810                 {
7811                         oc->deleting_subid = GetCurrentSubTransactionId();
7812                         break;
7813                 }
7814         }
7815 }
7816
7817 /*
7818  * Perform ON COMMIT actions.
7819  *
7820  * This is invoked just before actually committing, since it's possible
7821  * to encounter errors.
7822  */
7823 void
7824 PreCommit_on_commit_actions(void)
7825 {
7826         ListCell   *l;
7827         List       *oids_to_truncate = NIL;
7828
7829         foreach(l, on_commits)
7830         {
7831                 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7832
7833                 /* Ignore entry if already dropped in this xact */
7834                 if (oc->deleting_subid != InvalidSubTransactionId)
7835                         continue;
7836
7837                 switch (oc->oncommit)
7838                 {
7839                         case ONCOMMIT_NOOP:
7840                         case ONCOMMIT_PRESERVE_ROWS:
7841                                 /* Do nothing (there shouldn't be such entries, actually) */
7842                                 break;
7843                         case ONCOMMIT_DELETE_ROWS:
7844                                 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
7845                                 break;
7846                         case ONCOMMIT_DROP:
7847                                 {
7848                                         ObjectAddress object;
7849
7850                                         object.classId = RelationRelationId;
7851                                         object.objectId = oc->relid;
7852                                         object.objectSubId = 0;
7853                                         performDeletion(&object, DROP_CASCADE);
7854
7855                                         /*
7856                                          * Note that table deletion will call
7857                                          * remove_on_commit_action, so the entry should get marked
7858                                          * as deleted.
7859                                          */
7860                                         Assert(oc->deleting_subid != InvalidSubTransactionId);
7861                                         break;
7862                                 }
7863                 }
7864         }
7865         if (oids_to_truncate != NIL)
7866         {
7867                 heap_truncate(oids_to_truncate);
7868                 CommandCounterIncrement();              /* XXX needed? */
7869         }
7870 }
7871
7872 /*
7873  * Post-commit or post-abort cleanup for ON COMMIT management.
7874  *
7875  * All we do here is remove no-longer-needed OnCommitItem entries.
7876  *
7877  * During commit, remove entries that were deleted during this transaction;
7878  * during abort, remove those created during this transaction.
7879  */
7880 void
7881 AtEOXact_on_commit_actions(bool isCommit)
7882 {
7883         ListCell   *cur_item;
7884         ListCell   *prev_item;
7885
7886         prev_item = NULL;
7887         cur_item = list_head(on_commits);
7888
7889         while (cur_item != NULL)
7890         {
7891                 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7892
7893                 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
7894                         oc->creating_subid != InvalidSubTransactionId)
7895                 {
7896                         /* cur_item must be removed */
7897                         on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7898                         pfree(oc);
7899                         if (prev_item)
7900                                 cur_item = lnext(prev_item);
7901                         else
7902                                 cur_item = list_head(on_commits);
7903                 }
7904                 else
7905                 {
7906                         /* cur_item must be preserved */
7907                         oc->creating_subid = InvalidSubTransactionId;
7908                         oc->deleting_subid = InvalidSubTransactionId;
7909                         prev_item = cur_item;
7910                         cur_item = lnext(prev_item);
7911                 }
7912         }
7913 }
7914
7915 /*
7916  * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7917  *
7918  * During subabort, we can immediately remove entries created during this
7919  * subtransaction.      During subcommit, just relabel entries marked during
7920  * this subtransaction as being the parent's responsibility.
7921  */
7922 void
7923 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
7924                                                           SubTransactionId parentSubid)
7925 {
7926         ListCell   *cur_item;
7927         ListCell   *prev_item;
7928
7929         prev_item = NULL;
7930         cur_item = list_head(on_commits);
7931
7932         while (cur_item != NULL)
7933         {
7934                 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7935
7936                 if (!isCommit && oc->creating_subid == mySubid)
7937                 {
7938                         /* cur_item must be removed */
7939                         on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7940                         pfree(oc);
7941                         if (prev_item)
7942                                 cur_item = lnext(prev_item);
7943                         else
7944                                 cur_item = list_head(on_commits);
7945                 }
7946                 else
7947                 {
7948                         /* cur_item must be preserved */
7949                         if (oc->creating_subid == mySubid)
7950                                 oc->creating_subid = parentSubid;
7951                         if (oc->deleting_subid == mySubid)
7952                                 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7953                         prev_item = cur_item;
7954                         cur_item = lnext(prev_item);
7955                 }
7956         }
7957 }