OSDN Git Service

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