]> granicus.if.org Git - postgresql/blob - src/backend/commands/tablecmds.c
Fix my brain fade in TRUNCATE triggers patch: can't release relcache refcounts
[postgresql] / src / backend / commands / tablecmds.c
1 /*-------------------------------------------------------------------------
2  *
3  * tablecmds.c
4  *        Commands for creating and altering table structures and settings
5  *
6  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.250 2008/03/31 03:34:27 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          * Add needed dependency entries for the new column.
3337          */
3338         add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3339 }
3340
3341 /*
3342  * Install a column's dependency on its datatype.
3343  */
3344 static void
3345 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3346 {
3347         ObjectAddress myself,
3348                                 referenced;
3349
3350         myself.classId = RelationRelationId;
3351         myself.objectId = relid;
3352         myself.objectSubId = attnum;
3353         referenced.classId = TypeRelationId;
3354         referenced.objectId = typid;
3355         referenced.objectSubId = 0;
3356         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3357 }
3358
3359 /*
3360  * ALTER TABLE ALTER COLUMN DROP NOT NULL
3361  */
3362 static void
3363 ATExecDropNotNull(Relation rel, const char *colName)
3364 {
3365         HeapTuple       tuple;
3366         AttrNumber      attnum;
3367         Relation        attr_rel;
3368         List       *indexoidlist;
3369         ListCell   *indexoidscan;
3370
3371         /*
3372          * lookup the attribute
3373          */
3374         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3375
3376         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3377
3378         if (!HeapTupleIsValid(tuple))
3379                 ereport(ERROR,
3380                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3381                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3382                                                 colName, RelationGetRelationName(rel))));
3383
3384         attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3385
3386         /* Prevent them from altering a system attribute */
3387         if (attnum <= 0)
3388                 ereport(ERROR,
3389                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3390                                  errmsg("cannot alter system column \"%s\"",
3391                                                 colName)));
3392
3393         /*
3394          * Check that the attribute is not in a primary key
3395          */
3396
3397         /* Loop over all indexes on the relation */
3398         indexoidlist = RelationGetIndexList(rel);
3399
3400         foreach(indexoidscan, indexoidlist)
3401         {
3402                 Oid                     indexoid = lfirst_oid(indexoidscan);
3403                 HeapTuple       indexTuple;
3404                 Form_pg_index indexStruct;
3405                 int                     i;
3406
3407                 indexTuple = SearchSysCache(INDEXRELID,
3408                                                                         ObjectIdGetDatum(indexoid),
3409                                                                         0, 0, 0);
3410                 if (!HeapTupleIsValid(indexTuple))
3411                         elog(ERROR, "cache lookup failed for index %u", indexoid);
3412                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3413
3414                 /* If the index is not a primary key, skip the check */
3415                 if (indexStruct->indisprimary)
3416                 {
3417                         /*
3418                          * Loop over each attribute in the primary key and see if it
3419                          * matches the to-be-altered attribute
3420                          */
3421                         for (i = 0; i < indexStruct->indnatts; i++)
3422                         {
3423                                 if (indexStruct->indkey.values[i] == attnum)
3424                                         ereport(ERROR,
3425                                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3426                                                          errmsg("column \"%s\" is in a primary key",
3427                                                                         colName)));
3428                         }
3429                 }
3430
3431                 ReleaseSysCache(indexTuple);
3432         }
3433
3434         list_free(indexoidlist);
3435
3436         /*
3437          * Okay, actually perform the catalog change ... if needed
3438          */
3439         if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3440         {
3441                 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3442
3443                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3444
3445                 /* keep the system catalog indexes current */
3446                 CatalogUpdateIndexes(attr_rel, tuple);
3447         }
3448
3449         heap_close(attr_rel, RowExclusiveLock);
3450 }
3451
3452 /*
3453  * ALTER TABLE ALTER COLUMN SET NOT NULL
3454  */
3455 static void
3456 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3457                                  const char *colName)
3458 {
3459         HeapTuple       tuple;
3460         AttrNumber      attnum;
3461         Relation        attr_rel;
3462
3463         /*
3464          * lookup the attribute
3465          */
3466         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3467
3468         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3469
3470         if (!HeapTupleIsValid(tuple))
3471                 ereport(ERROR,
3472                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3473                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3474                                                 colName, RelationGetRelationName(rel))));
3475
3476         attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3477
3478         /* Prevent them from altering a system attribute */
3479         if (attnum <= 0)
3480                 ereport(ERROR,
3481                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3482                                  errmsg("cannot alter system column \"%s\"",
3483                                                 colName)));
3484
3485         /*
3486          * Okay, actually perform the catalog change ... if needed
3487          */
3488         if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3489         {
3490                 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3491
3492                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3493
3494                 /* keep the system catalog indexes current */
3495                 CatalogUpdateIndexes(attr_rel, tuple);
3496
3497                 /* Tell Phase 3 it needs to test the constraint */
3498                 tab->new_notnull = true;
3499         }
3500
3501         heap_close(attr_rel, RowExclusiveLock);
3502 }
3503
3504 /*
3505  * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3506  */
3507 static void
3508 ATExecColumnDefault(Relation rel, const char *colName,
3509                                         Node *newDefault)
3510 {
3511         AttrNumber      attnum;
3512
3513         /*
3514          * get the number of the attribute
3515          */
3516         attnum = get_attnum(RelationGetRelid(rel), colName);
3517         if (attnum == InvalidAttrNumber)
3518                 ereport(ERROR,
3519                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3520                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3521                                                 colName, RelationGetRelationName(rel))));
3522
3523         /* Prevent them from altering a system attribute */
3524         if (attnum <= 0)
3525                 ereport(ERROR,
3526                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3527                                  errmsg("cannot alter system column \"%s\"",
3528                                                 colName)));
3529
3530         /*
3531          * Remove any old default for the column.  We use RESTRICT here for
3532          * safety, but at present we do not expect anything to depend on the
3533          * default.
3534          */
3535         RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3536
3537         if (newDefault)
3538         {
3539                 /* SET DEFAULT */
3540                 RawColumnDefault *rawEnt;
3541
3542                 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3543                 rawEnt->attnum = attnum;
3544                 rawEnt->raw_default = newDefault;
3545
3546                 /*
3547                  * This function is intended for CREATE TABLE, so it processes a
3548                  * _list_ of defaults, but we just do one.
3549                  */
3550                 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3551         }
3552 }
3553
3554 /*
3555  * ALTER TABLE ALTER COLUMN SET STATISTICS
3556  */
3557 static void
3558 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3559 {
3560         /*
3561          * We do our own permission checking because (a) we want to allow SET
3562          * STATISTICS on indexes (for expressional index columns), and (b) we want
3563          * to allow SET STATISTICS on system catalogs without requiring
3564          * allowSystemTableMods to be turned on.
3565          */
3566         if (rel->rd_rel->relkind != RELKIND_RELATION &&
3567                 rel->rd_rel->relkind != RELKIND_INDEX)
3568                 ereport(ERROR,
3569                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3570                                  errmsg("\"%s\" is not a table or index",
3571                                                 RelationGetRelationName(rel))));
3572
3573         /* Permissions checks */
3574         if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3575                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3576                                            RelationGetRelationName(rel));
3577 }
3578
3579 static void
3580 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3581 {
3582         int                     newtarget;
3583         Relation        attrelation;
3584         HeapTuple       tuple;
3585         Form_pg_attribute attrtuple;
3586
3587         Assert(IsA(newValue, Integer));
3588         newtarget = intVal(newValue);
3589
3590         /*
3591          * Limit target to a sane range
3592          */
3593         if (newtarget < -1)
3594         {
3595                 ereport(ERROR,
3596                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3597                                  errmsg("statistics target %d is too low",
3598                                                 newtarget)));
3599         }
3600         else if (newtarget > 1000)
3601         {
3602                 newtarget = 1000;
3603                 ereport(WARNING,
3604                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3605                                  errmsg("lowering statistics target to %d",
3606                                                 newtarget)));
3607         }
3608
3609         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3610
3611         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3612
3613         if (!HeapTupleIsValid(tuple))
3614                 ereport(ERROR,
3615                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3616                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3617                                                 colName, RelationGetRelationName(rel))));
3618         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3619
3620         if (attrtuple->attnum <= 0)
3621                 ereport(ERROR,
3622                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3623                                  errmsg("cannot alter system column \"%s\"",
3624                                                 colName)));
3625
3626         attrtuple->attstattarget = newtarget;
3627
3628         simple_heap_update(attrelation, &tuple->t_self, tuple);
3629
3630         /* keep system catalog indexes current */
3631         CatalogUpdateIndexes(attrelation, tuple);
3632
3633         heap_freetuple(tuple);
3634
3635         heap_close(attrelation, RowExclusiveLock);
3636 }
3637
3638 /*
3639  * ALTER TABLE ALTER COLUMN SET STORAGE
3640  */
3641 static void
3642 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3643 {
3644         char       *storagemode;
3645         char            newstorage;
3646         Relation        attrelation;
3647         HeapTuple       tuple;
3648         Form_pg_attribute attrtuple;
3649
3650         Assert(IsA(newValue, String));
3651         storagemode = strVal(newValue);
3652
3653         if (pg_strcasecmp(storagemode, "plain") == 0)
3654                 newstorage = 'p';
3655         else if (pg_strcasecmp(storagemode, "external") == 0)
3656                 newstorage = 'e';
3657         else if (pg_strcasecmp(storagemode, "extended") == 0)
3658                 newstorage = 'x';
3659         else if (pg_strcasecmp(storagemode, "main") == 0)
3660                 newstorage = 'm';
3661         else
3662         {
3663                 ereport(ERROR,
3664                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3665                                  errmsg("invalid storage type \"%s\"",
3666                                                 storagemode)));
3667                 newstorage = 0;                 /* keep compiler quiet */
3668         }
3669
3670         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3671
3672         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3673
3674         if (!HeapTupleIsValid(tuple))
3675                 ereport(ERROR,
3676                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3677                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3678                                                 colName, RelationGetRelationName(rel))));
3679         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3680
3681         if (attrtuple->attnum <= 0)
3682                 ereport(ERROR,
3683                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3684                                  errmsg("cannot alter system column \"%s\"",
3685                                                 colName)));
3686
3687         /*
3688          * safety check: do not allow toasted storage modes unless column datatype
3689          * is TOAST-aware.
3690          */
3691         if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
3692                 attrtuple->attstorage = newstorage;
3693         else
3694                 ereport(ERROR,
3695                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3696                                  errmsg("column data type %s can only have storage PLAIN",
3697                                                 format_type_be(attrtuple->atttypid))));
3698
3699         simple_heap_update(attrelation, &tuple->t_self, tuple);
3700
3701         /* keep system catalog indexes current */
3702         CatalogUpdateIndexes(attrelation, tuple);
3703
3704         heap_freetuple(tuple);
3705
3706         heap_close(attrelation, RowExclusiveLock);
3707 }
3708
3709
3710 /*
3711  * ALTER TABLE DROP COLUMN
3712  *
3713  * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
3714  * because we have to decide at runtime whether to recurse or not depending
3715  * on whether attinhcount goes to zero or not.  (We can't check this in a
3716  * static pre-pass because it won't handle multiple inheritance situations
3717  * correctly.)  Since DROP COLUMN doesn't need to create any work queue
3718  * entries for Phase 3, it's okay to recurse internally in this routine
3719  * without considering the work queue.
3720  */
3721 static void
3722 ATExecDropColumn(Relation rel, const char *colName,
3723                                  DropBehavior behavior,
3724                                  bool recurse, bool recursing)
3725 {
3726         HeapTuple       tuple;
3727         Form_pg_attribute targetatt;
3728         AttrNumber      attnum;
3729         List       *children;
3730         ObjectAddress object;
3731
3732         /* At top level, permission check was done in ATPrepCmd, else do it */
3733         if (recursing)
3734                 ATSimplePermissions(rel, false);
3735
3736         /*
3737          * get the number of the attribute
3738          */
3739         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
3740         if (!HeapTupleIsValid(tuple))
3741                 ereport(ERROR,
3742                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
3743                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
3744                                                 colName, RelationGetRelationName(rel))));
3745         targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
3746
3747         attnum = targetatt->attnum;
3748
3749         /* Can't drop a system attribute, except OID */
3750         if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
3751                 ereport(ERROR,
3752                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3753                                  errmsg("cannot drop system column \"%s\"",
3754                                                 colName)));
3755
3756         /* Don't drop inherited columns */
3757         if (targetatt->attinhcount > 0 && !recursing)
3758                 ereport(ERROR,
3759                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3760                                  errmsg("cannot drop inherited column \"%s\"",
3761                                                 colName)));
3762
3763         ReleaseSysCache(tuple);
3764
3765         /*
3766          * Propagate to children as appropriate.  Unlike most other ALTER
3767          * routines, we have to do this one level of recursion at a time; we can't
3768          * use find_all_inheritors to do it in one pass.
3769          */
3770         children = find_inheritance_children(RelationGetRelid(rel));
3771
3772         if (children)
3773         {
3774                 Relation        attr_rel;
3775                 ListCell   *child;
3776
3777                 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3778                 foreach(child, children)
3779                 {
3780                         Oid                     childrelid = lfirst_oid(child);
3781                         Relation        childrel;
3782                         Form_pg_attribute childatt;
3783
3784                         childrel = heap_open(childrelid, AccessExclusiveLock);
3785                         CheckTableNotInUse(childrel, "ALTER TABLE");
3786
3787                         tuple = SearchSysCacheCopyAttName(childrelid, colName);
3788                         if (!HeapTupleIsValid(tuple))           /* shouldn't happen */
3789                                 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
3790                                          colName, childrelid);
3791                         childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3792
3793                         if (childatt->attinhcount <= 0)         /* shouldn't happen */
3794                                 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
3795                                          childrelid, colName);
3796
3797                         if (recurse)
3798                         {
3799                                 /*
3800                                  * If the child column has other definition sources, just
3801                                  * decrement its inheritance count; if not, recurse to delete
3802                                  * it.
3803                                  */
3804                                 if (childatt->attinhcount == 1 && !childatt->attislocal)
3805                                 {
3806                                         /* Time to delete this child column, too */
3807                                         ATExecDropColumn(childrel, colName, behavior, true, true);
3808                                 }
3809                                 else
3810                                 {
3811                                         /* Child column must survive my deletion */
3812                                         childatt->attinhcount--;
3813
3814                                         simple_heap_update(attr_rel, &tuple->t_self, tuple);
3815
3816                                         /* keep the system catalog indexes current */
3817                                         CatalogUpdateIndexes(attr_rel, tuple);
3818
3819                                         /* Make update visible */
3820                                         CommandCounterIncrement();
3821                                 }
3822                         }
3823                         else
3824                         {
3825                                 /*
3826                                  * If we were told to drop ONLY in this table (no recursion),
3827                                  * we need to mark the inheritors' attribute as locally
3828                                  * defined rather than inherited.
3829                                  */
3830                                 childatt->attinhcount--;
3831                                 childatt->attislocal = true;
3832
3833                                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3834
3835                                 /* keep the system catalog indexes current */
3836                                 CatalogUpdateIndexes(attr_rel, tuple);
3837
3838                                 /* Make update visible */
3839                                 CommandCounterIncrement();
3840                         }
3841
3842                         heap_freetuple(tuple);
3843
3844                         heap_close(childrel, NoLock);
3845                 }
3846                 heap_close(attr_rel, RowExclusiveLock);
3847         }
3848
3849         /*
3850          * Perform the actual column deletion
3851          */
3852         object.classId = RelationRelationId;
3853         object.objectId = RelationGetRelid(rel);
3854         object.objectSubId = attnum;
3855
3856         performDeletion(&object, behavior);
3857
3858         /*
3859          * If we dropped the OID column, must adjust pg_class.relhasoids
3860          */
3861         if (attnum == ObjectIdAttributeNumber)
3862         {
3863                 Relation        class_rel;
3864                 Form_pg_class tuple_class;
3865
3866                 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
3867
3868                 tuple = SearchSysCacheCopy(RELOID,
3869                                                                    ObjectIdGetDatum(RelationGetRelid(rel)),
3870                                                                    0, 0, 0);
3871                 if (!HeapTupleIsValid(tuple))
3872                         elog(ERROR, "cache lookup failed for relation %u",
3873                                  RelationGetRelid(rel));
3874                 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
3875
3876                 tuple_class->relhasoids = false;
3877                 simple_heap_update(class_rel, &tuple->t_self, tuple);
3878
3879                 /* Keep the catalog indexes up to date */
3880                 CatalogUpdateIndexes(class_rel, tuple);
3881
3882                 heap_close(class_rel, RowExclusiveLock);
3883         }
3884 }
3885
3886 /*
3887  * ALTER TABLE ADD INDEX
3888  *
3889  * There is no such command in the grammar, but parse_utilcmd.c converts
3890  * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands.  This lets
3891  * us schedule creation of the index at the appropriate time during ALTER.
3892  */
3893 static void
3894 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
3895                            IndexStmt *stmt, bool is_rebuild)
3896 {
3897         bool            check_rights;
3898         bool            skip_build;
3899         bool            quiet;
3900
3901         Assert(IsA(stmt, IndexStmt));
3902
3903         /* suppress schema rights check when rebuilding existing index */
3904         check_rights = !is_rebuild;
3905         /* skip index build if phase 3 will have to rewrite table anyway */
3906         skip_build = (tab->newvals != NIL);
3907         /* suppress notices when rebuilding existing index */
3908         quiet = is_rebuild;
3909
3910         /* The IndexStmt has already been through transformIndexStmt */
3911
3912         DefineIndex(stmt->relation, /* relation */
3913                                 stmt->idxname,  /* index name */
3914                                 InvalidOid,             /* no predefined OID */
3915                                 stmt->accessMethod,             /* am name */
3916                                 stmt->tableSpace,
3917                                 stmt->indexParams,              /* parameters */
3918                                 (Expr *) stmt->whereClause,
3919                                 stmt->options,
3920                                 stmt->unique,
3921                                 stmt->primary,
3922                                 stmt->isconstraint,
3923                                 true,                   /* is_alter_table */
3924                                 check_rights,
3925                                 skip_build,
3926                                 quiet,
3927                                 false);
3928 }
3929
3930 /*
3931  * ALTER TABLE ADD CONSTRAINT
3932  */
3933 static void
3934 ATExecAddConstraint(AlteredTableInfo *tab, Relation rel, Node *newConstraint)
3935 {
3936         switch (nodeTag(newConstraint))
3937         {
3938                 case T_Constraint:
3939                         {
3940                                 Constraint *constr = (Constraint *) newConstraint;
3941
3942                                 /*
3943                                  * Currently, we only expect to see CONSTR_CHECK nodes
3944                                  * arriving here (see the preprocessing done in
3945                                  * parse_utilcmd.c).  Use a switch anyway to make it easier to
3946                                  * add more code later.
3947                                  */
3948                                 switch (constr->contype)
3949                                 {
3950                                         case CONSTR_CHECK:
3951                                                 {
3952                                                         List       *newcons;
3953                                                         ListCell   *lcon;
3954
3955                                                         /*
3956                                                          * Call AddRelationRawConstraints to do the work.
3957                                                          * It returns a list of cooked constraints.
3958                                                          */
3959                                                         newcons = AddRelationRawConstraints(rel, NIL,
3960                                                                                                                  list_make1(constr));
3961                                                         /* Add each constraint to Phase 3's queue */
3962                                                         foreach(lcon, newcons)
3963                                                         {
3964                                                                 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
3965                                                                 NewConstraint *newcon;
3966
3967                                                                 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
3968                                                                 newcon->name = ccon->name;
3969                                                                 newcon->contype = ccon->contype;
3970                                                                 /* ExecQual wants implicit-AND format */
3971                                                                 newcon->qual = (Node *)
3972                                                                         make_ands_implicit((Expr *) ccon->expr);
3973
3974                                                                 tab->constraints = lappend(tab->constraints,
3975                                                                                                                    newcon);
3976                                                         }
3977                                                         break;
3978                                                 }
3979                                         default:
3980                                                 elog(ERROR, "unrecognized constraint type: %d",
3981                                                          (int) constr->contype);
3982                                 }
3983                                 break;
3984                         }
3985                 case T_FkConstraint:
3986                         {
3987                                 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
3988
3989                                 /*
3990                                  * Assign or validate constraint name
3991                                  */
3992                                 if (fkconstraint->constr_name)
3993                                 {
3994                                         if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
3995                                                                                          RelationGetRelid(rel),
3996                                                                                          RelationGetNamespace(rel),
3997                                                                                          fkconstraint->constr_name))
3998                                                 ereport(ERROR,
3999                                                                 (errcode(ERRCODE_DUPLICATE_OBJECT),
4000                                                                  errmsg("constraint \"%s\" for relation \"%s\" already exists",
4001                                                                                 fkconstraint->constr_name,
4002                                                                                 RelationGetRelationName(rel))));
4003                                 }
4004                                 else
4005                                         fkconstraint->constr_name =
4006                                                 ChooseConstraintName(RelationGetRelationName(rel),
4007                                                                         strVal(linitial(fkconstraint->fk_attrs)),
4008                                                                                          "fkey",
4009                                                                                          RelationGetNamespace(rel),
4010                                                                                          NIL);
4011
4012                                 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
4013
4014                                 break;
4015                         }
4016                 default:
4017                         elog(ERROR, "unrecognized node type: %d",
4018                                  (int) nodeTag(newConstraint));
4019         }
4020 }
4021
4022 /*
4023  * Add a foreign-key constraint to a single table
4024  *
4025  * Subroutine for ATExecAddConstraint.  Must already hold exclusive
4026  * lock on the rel, and have done appropriate validity/permissions checks
4027  * for it.
4028  */
4029 static void
4030 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4031                                                   FkConstraint *fkconstraint)
4032 {
4033         Relation        pkrel;
4034         AclResult       aclresult;
4035         int16           pkattnum[INDEX_MAX_KEYS];
4036         int16           fkattnum[INDEX_MAX_KEYS];
4037         Oid                     pktypoid[INDEX_MAX_KEYS];
4038         Oid                     fktypoid[INDEX_MAX_KEYS];
4039         Oid                     opclasses[INDEX_MAX_KEYS];
4040         Oid                     pfeqoperators[INDEX_MAX_KEYS];
4041         Oid                     ppeqoperators[INDEX_MAX_KEYS];
4042         Oid                     ffeqoperators[INDEX_MAX_KEYS];
4043         int                     i;
4044         int                     numfks,
4045                                 numpks;
4046         Oid                     indexOid;
4047         Oid                     constrOid;
4048
4049         /*
4050          * Grab an exclusive lock on the pk table, so that someone doesn't delete
4051          * rows out from under us. (Although a lesser lock would do for that
4052          * purpose, we'll need exclusive lock anyway to add triggers to the pk
4053          * table; trying to start with a lesser lock will just create a risk of
4054          * deadlock.)
4055          */
4056         pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4057
4058         /*
4059          * Validity and permissions checks
4060          *
4061          * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
4062          * but we may as well error out sooner instead of later.
4063          */
4064         if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4065                 ereport(ERROR,
4066                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4067                                  errmsg("referenced relation \"%s\" is not a table",
4068                                                 RelationGetRelationName(pkrel))));
4069
4070         aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4071                                                                   ACL_REFERENCES);
4072         if (aclresult != ACLCHECK_OK)
4073                 aclcheck_error(aclresult, ACL_KIND_CLASS,
4074                                            RelationGetRelationName(pkrel));
4075
4076         if (!allowSystemTableMods && IsSystemRelation(pkrel))
4077                 ereport(ERROR,
4078                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4079                                  errmsg("permission denied: \"%s\" is a system catalog",
4080                                                 RelationGetRelationName(pkrel))));
4081
4082         aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4083                                                                   ACL_REFERENCES);
4084         if (aclresult != ACLCHECK_OK)
4085                 aclcheck_error(aclresult, ACL_KIND_CLASS,
4086                                            RelationGetRelationName(rel));
4087
4088         /*
4089          * Disallow reference from permanent table to temp table or vice versa.
4090          * (The ban on perm->temp is for fairly obvious reasons.  The ban on
4091          * temp->perm is because other backends might need to run the RI triggers
4092          * on the perm table, but they can't reliably see tuples the owning
4093          * backend has created in the temp table, because non-shared buffers are
4094          * used for temp tables.)
4095          */
4096         if (isTempNamespace(RelationGetNamespace(pkrel)))
4097         {
4098                 if (!isTempNamespace(RelationGetNamespace(rel)))
4099                         ereport(ERROR,
4100                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4101                                          errmsg("cannot reference temporary table from permanent table constraint")));
4102         }
4103         else
4104         {
4105                 if (isTempNamespace(RelationGetNamespace(rel)))
4106                         ereport(ERROR,
4107                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4108                                          errmsg("cannot reference permanent table from temporary table constraint")));
4109         }
4110
4111         /*
4112          * Look up the referencing attributes to make sure they exist, and record
4113          * their attnums and type OIDs.
4114          */
4115         MemSet(pkattnum, 0, sizeof(pkattnum));
4116         MemSet(fkattnum, 0, sizeof(fkattnum));
4117         MemSet(pktypoid, 0, sizeof(pktypoid));
4118         MemSet(fktypoid, 0, sizeof(fktypoid));
4119         MemSet(opclasses, 0, sizeof(opclasses));
4120         MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4121         MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4122         MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4123
4124         numfks = transformColumnNameList(RelationGetRelid(rel),
4125                                                                          fkconstraint->fk_attrs,
4126                                                                          fkattnum, fktypoid);
4127
4128         /*
4129          * If the attribute list for the referenced table was omitted, lookup the
4130          * definition of the primary key and use it.  Otherwise, validate the
4131          * supplied attribute list.  In either case, discover the index OID and
4132          * index opclasses, and the attnums and type OIDs of the attributes.
4133          */
4134         if (fkconstraint->pk_attrs == NIL)
4135         {
4136                 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4137                                                                                         &fkconstraint->pk_attrs,
4138                                                                                         pkattnum, pktypoid,
4139                                                                                         opclasses);
4140         }
4141         else
4142         {
4143                 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4144                                                                                  fkconstraint->pk_attrs,
4145                                                                                  pkattnum, pktypoid);
4146                 /* Look for an index matching the column list */
4147                 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4148                                                                                    opclasses);
4149         }
4150
4151         /*
4152          * Look up the equality operators to use in the constraint.
4153          *
4154          * Note that we have to be careful about the difference between the actual
4155          * PK column type and the opclass' declared input type, which might be
4156          * only binary-compatible with it.      The declared opcintype is the right
4157          * thing to probe pg_amop with.
4158          */
4159         if (numfks != numpks)
4160                 ereport(ERROR,
4161                                 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4162                                  errmsg("number of referencing and referenced columns for foreign key disagree")));
4163
4164         for (i = 0; i < numpks; i++)
4165         {
4166                 Oid                     pktype = pktypoid[i];
4167                 Oid                     fktype = fktypoid[i];
4168                 Oid                     fktyped;
4169                 HeapTuple       cla_ht;
4170                 Form_pg_opclass cla_tup;
4171                 Oid                     amid;
4172                 Oid                     opfamily;
4173                 Oid                     opcintype;
4174                 Oid                     pfeqop;
4175                 Oid                     ppeqop;
4176                 Oid                     ffeqop;
4177                 int16           eqstrategy;
4178
4179                 /* We need several fields out of the pg_opclass entry */
4180                 cla_ht = SearchSysCache(CLAOID,
4181                                                                 ObjectIdGetDatum(opclasses[i]),
4182                                                                 0, 0, 0);
4183                 if (!HeapTupleIsValid(cla_ht))
4184                         elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4185                 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4186                 amid = cla_tup->opcmethod;
4187                 opfamily = cla_tup->opcfamily;
4188                 opcintype = cla_tup->opcintype;
4189                 ReleaseSysCache(cla_ht);
4190
4191                 /*
4192                  * Check it's a btree; currently this can never fail since no other
4193                  * index AMs support unique indexes.  If we ever did have other types
4194                  * of unique indexes, we'd need a way to determine which operator
4195                  * strategy number is equality.  (Is it reasonable to insist that
4196                  * every such index AM use btree's number for equality?)
4197                  */
4198                 if (amid != BTREE_AM_OID)
4199                         elog(ERROR, "only b-tree indexes are supported for foreign keys");
4200                 eqstrategy = BTEqualStrategyNumber;
4201
4202                 /*
4203                  * There had better be a primary equality operator for the index.
4204                  * We'll use it for PK = PK comparisons.
4205                  */
4206                 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4207                                                                          eqstrategy);
4208
4209                 if (!OidIsValid(ppeqop))
4210                         elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4211                                  eqstrategy, opcintype, opcintype, opfamily);
4212
4213                 /*
4214                  * Are there equality operators that take exactly the FK type? Assume
4215                  * we should look through any domain here.
4216                  */
4217                 fktyped = getBaseType(fktype);
4218
4219                 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4220                                                                          eqstrategy);
4221                 if (OidIsValid(pfeqop))
4222                         ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4223                                                                                  eqstrategy);
4224                 else
4225                         ffeqop = InvalidOid;    /* keep compiler quiet */
4226
4227                 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4228                 {
4229                         /*
4230                          * Otherwise, look for an implicit cast from the FK type to the
4231                          * opcintype, and if found, use the primary equality operator.
4232                          * This is a bit tricky because opcintype might be a generic type
4233                          * such as ANYARRAY, and so what we have to test is whether the
4234                          * two actual column types can be concurrently cast to that type.
4235                          * (Otherwise, we'd fail to reject combinations such as int[] and
4236                          * point[].)
4237                          */
4238                         Oid                     input_typeids[2];
4239                         Oid                     target_typeids[2];
4240
4241                         input_typeids[0] = pktype;
4242                         input_typeids[1] = fktype;
4243                         target_typeids[0] = opcintype;
4244                         target_typeids[1] = opcintype;
4245                         if (can_coerce_type(2, input_typeids, target_typeids,
4246                                                                 COERCION_IMPLICIT))
4247                                 pfeqop = ffeqop = ppeqop;
4248                 }
4249
4250                 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4251                         ereport(ERROR,
4252                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
4253                                          errmsg("foreign key constraint \"%s\" "
4254                                                         "cannot be implemented",
4255                                                         fkconstraint->constr_name),
4256                                          errdetail("Key columns \"%s\" and \"%s\" "
4257                                                            "are of incompatible types: %s and %s.",
4258                                                            strVal(list_nth(fkconstraint->fk_attrs, i)),
4259                                                            strVal(list_nth(fkconstraint->pk_attrs, i)),
4260                                                            format_type_be(fktype),
4261                                                            format_type_be(pktype))));
4262
4263                 pfeqoperators[i] = pfeqop;
4264                 ppeqoperators[i] = ppeqop;
4265                 ffeqoperators[i] = ffeqop;
4266         }
4267
4268         /*
4269          * Record the FK constraint in pg_constraint.
4270          */
4271         constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4272                                                                           RelationGetNamespace(rel),
4273                                                                           CONSTRAINT_FOREIGN,
4274                                                                           fkconstraint->deferrable,
4275                                                                           fkconstraint->initdeferred,
4276                                                                           RelationGetRelid(rel),
4277                                                                           fkattnum,
4278                                                                           numfks,
4279                                                                           InvalidOid,           /* not a domain
4280                                                                                                                  * constraint */
4281                                                                           RelationGetRelid(pkrel),
4282                                                                           pkattnum,
4283                                                                           pfeqoperators,
4284                                                                           ppeqoperators,
4285                                                                           ffeqoperators,
4286                                                                           numpks,
4287                                                                           fkconstraint->fk_upd_action,
4288                                                                           fkconstraint->fk_del_action,
4289                                                                           fkconstraint->fk_matchtype,
4290                                                                           indexOid,
4291                                                                           NULL,         /* no check constraint */
4292                                                                           NULL,
4293                                                                           NULL);
4294
4295         /*
4296          * Create the triggers that will enforce the constraint.
4297          */
4298         createForeignKeyTriggers(rel, fkconstraint, constrOid);
4299
4300         /*
4301          * Tell Phase 3 to check that the constraint is satisfied by existing rows
4302          * (we can skip this during table creation).
4303          */
4304         if (!fkconstraint->skip_validation)
4305         {
4306                 NewConstraint *newcon;
4307
4308                 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4309                 newcon->name = fkconstraint->constr_name;
4310                 newcon->contype = CONSTR_FOREIGN;
4311                 newcon->refrelid = RelationGetRelid(pkrel);
4312                 newcon->conid = constrOid;
4313                 newcon->qual = (Node *) fkconstraint;
4314
4315                 tab->constraints = lappend(tab->constraints, newcon);
4316         }
4317
4318         /*
4319          * Close pk table, but keep lock until we've committed.
4320          */
4321         heap_close(pkrel, NoLock);
4322 }
4323
4324
4325 /*
4326  * transformColumnNameList - transform list of column names
4327  *
4328  * Lookup each name and return its attnum and type OID
4329  */
4330 static int
4331 transformColumnNameList(Oid relId, List *colList,
4332                                                 int16 *attnums, Oid *atttypids)
4333 {
4334         ListCell   *l;
4335         int                     attnum;
4336
4337         attnum = 0;
4338         foreach(l, colList)
4339         {
4340                 char       *attname = strVal(lfirst(l));
4341                 HeapTuple       atttuple;
4342
4343                 atttuple = SearchSysCacheAttName(relId, attname);
4344                 if (!HeapTupleIsValid(atttuple))
4345                         ereport(ERROR,
4346                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4347                                          errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4348                                                         attname)));
4349                 if (attnum >= INDEX_MAX_KEYS)
4350                         ereport(ERROR,
4351                                         (errcode(ERRCODE_TOO_MANY_COLUMNS),
4352                                          errmsg("cannot have more than %d keys in a foreign key",
4353                                                         INDEX_MAX_KEYS)));
4354                 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4355                 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4356                 ReleaseSysCache(atttuple);
4357                 attnum++;
4358         }
4359
4360         return attnum;
4361 }
4362
4363 /*
4364  * transformFkeyGetPrimaryKey -
4365  *
4366  *      Look up the names, attnums, and types of the primary key attributes
4367  *      for the pkrel.  Also return the index OID and index opclasses of the
4368  *      index supporting the primary key.
4369  *
4370  *      All parameters except pkrel are output parameters.      Also, the function
4371  *      return value is the number of attributes in the primary key.
4372  *
4373  *      Used when the column list in the REFERENCES specification is omitted.
4374  */
4375 static int
4376 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4377                                                    List **attnamelist,
4378                                                    int16 *attnums, Oid *atttypids,
4379                                                    Oid *opclasses)
4380 {
4381         List       *indexoidlist;
4382         ListCell   *indexoidscan;
4383         HeapTuple       indexTuple = NULL;
4384         Form_pg_index indexStruct = NULL;
4385         Datum           indclassDatum;
4386         bool            isnull;
4387         oidvector  *indclass;
4388         int                     i;
4389
4390         /*
4391          * Get the list of index OIDs for the table from the relcache, and look up
4392          * each one in the pg_index syscache until we find one marked primary key
4393          * (hopefully there isn't more than one such).
4394          */
4395         *indexOid = InvalidOid;
4396
4397         indexoidlist = RelationGetIndexList(pkrel);
4398
4399         foreach(indexoidscan, indexoidlist)
4400         {
4401                 Oid                     indexoid = lfirst_oid(indexoidscan);
4402
4403                 indexTuple = SearchSysCache(INDEXRELID,
4404                                                                         ObjectIdGetDatum(indexoid),
4405                                                                         0, 0, 0);
4406                 if (!HeapTupleIsValid(indexTuple))
4407                         elog(ERROR, "cache lookup failed for index %u", indexoid);
4408                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4409                 if (indexStruct->indisprimary)
4410                 {
4411                         *indexOid = indexoid;
4412                         break;
4413                 }
4414                 ReleaseSysCache(indexTuple);
4415         }
4416
4417         list_free(indexoidlist);
4418
4419         /*
4420          * Check that we found it
4421          */
4422         if (!OidIsValid(*indexOid))
4423                 ereport(ERROR,
4424                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
4425                                  errmsg("there is no primary key for referenced table \"%s\"",
4426                                                 RelationGetRelationName(pkrel))));
4427
4428         /* Must get indclass the hard way */
4429         indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4430                                                                         Anum_pg_index_indclass, &isnull);
4431         Assert(!isnull);
4432         indclass = (oidvector *) DatumGetPointer(indclassDatum);
4433
4434         /*
4435          * Now build the list of PK attributes from the indkey definition (we
4436          * assume a primary key cannot have expressional elements)
4437          */
4438         *attnamelist = NIL;
4439         for (i = 0; i < indexStruct->indnatts; i++)
4440         {
4441                 int                     pkattno = indexStruct->indkey.values[i];
4442
4443                 attnums[i] = pkattno;
4444                 atttypids[i] = attnumTypeId(pkrel, pkattno);
4445                 opclasses[i] = indclass->values[i];
4446                 *attnamelist = lappend(*attnamelist,
4447                            makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4448         }
4449
4450         ReleaseSysCache(indexTuple);
4451
4452         return i;
4453 }
4454
4455 /*
4456  * transformFkeyCheckAttrs -
4457  *
4458  *      Make sure that the attributes of a referenced table belong to a unique
4459  *      (or primary key) constraint.  Return the OID of the index supporting
4460  *      the constraint, as well as the opclasses associated with the index
4461  *      columns.
4462  */
4463 static Oid
4464 transformFkeyCheckAttrs(Relation pkrel,
4465                                                 int numattrs, int16 *attnums,
4466                                                 Oid *opclasses) /* output parameter */
4467 {
4468         Oid                     indexoid = InvalidOid;
4469         bool            found = false;
4470         List       *indexoidlist;
4471         ListCell   *indexoidscan;
4472
4473         /*
4474          * Get the list of index OIDs for the table from the relcache, and look up
4475          * each one in the pg_index syscache, and match unique indexes to the list
4476          * of attnums we are given.
4477          */
4478         indexoidlist = RelationGetIndexList(pkrel);
4479
4480         foreach(indexoidscan, indexoidlist)
4481         {
4482                 HeapTuple       indexTuple;
4483                 Form_pg_index indexStruct;
4484                 int                     i,
4485                                         j;
4486
4487                 indexoid = lfirst_oid(indexoidscan);
4488                 indexTuple = SearchSysCache(INDEXRELID,
4489                                                                         ObjectIdGetDatum(indexoid),
4490                                                                         0, 0, 0);
4491                 if (!HeapTupleIsValid(indexTuple))
4492                         elog(ERROR, "cache lookup failed for index %u", indexoid);
4493                 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4494
4495                 /*
4496                  * Must have the right number of columns; must be unique and not a
4497                  * partial index; forget it if there are any expressions, too
4498                  */
4499                 if (indexStruct->indnatts == numattrs &&
4500                         indexStruct->indisunique &&
4501                         heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4502                         heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4503                 {
4504                         /* Must get indclass the hard way */
4505                         Datum           indclassDatum;
4506                         bool            isnull;
4507                         oidvector  *indclass;
4508
4509                         indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4510                                                                                         Anum_pg_index_indclass, &isnull);
4511                         Assert(!isnull);
4512                         indclass = (oidvector *) DatumGetPointer(indclassDatum);
4513
4514                         /*
4515                          * The given attnum list may match the index columns in any order.
4516                          * Check that each list is a subset of the other.
4517                          */
4518                         for (i = 0; i < numattrs; i++)
4519                         {
4520                                 found = false;
4521                                 for (j = 0; j < numattrs; j++)
4522                                 {
4523                                         if (attnums[i] == indexStruct->indkey.values[j])
4524                                         {
4525                                                 found = true;
4526                                                 break;
4527                                         }
4528                                 }
4529                                 if (!found)
4530                                         break;
4531                         }
4532                         if (found)
4533                         {
4534                                 for (i = 0; i < numattrs; i++)
4535                                 {
4536                                         found = false;
4537                                         for (j = 0; j < numattrs; j++)
4538                                         {
4539                                                 if (attnums[j] == indexStruct->indkey.values[i])
4540                                                 {
4541                                                         opclasses[j] = indclass->values[i];
4542                                                         found = true;
4543                                                         break;
4544                                                 }
4545                                         }
4546                                         if (!found)
4547                                                 break;
4548                                 }
4549                         }
4550                 }
4551                 ReleaseSysCache(indexTuple);
4552                 if (found)
4553                         break;
4554         }
4555
4556         if (!found)
4557                 ereport(ERROR,
4558                                 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4559                                  errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4560                                                 RelationGetRelationName(pkrel))));
4561
4562         list_free(indexoidlist);
4563
4564         return indexoid;
4565 }
4566
4567 /*
4568  * Scan the existing rows in a table to verify they meet a proposed FK
4569  * constraint.
4570  *
4571  * Caller must have opened and locked both relations.
4572  */
4573 static void
4574 validateForeignKeyConstraint(FkConstraint *fkconstraint,
4575                                                          Relation rel,
4576                                                          Relation pkrel,
4577                                                          Oid constraintOid)
4578 {
4579         HeapScanDesc scan;
4580         HeapTuple       tuple;
4581         Trigger         trig;
4582
4583         /*
4584          * Build a trigger call structure; we'll need it either way.
4585          */
4586         MemSet(&trig, 0, sizeof(trig));
4587         trig.tgoid = InvalidOid;
4588         trig.tgname = fkconstraint->constr_name;
4589         trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
4590         trig.tgisconstraint = TRUE;
4591         trig.tgconstrrelid = RelationGetRelid(pkrel);
4592         trig.tgconstraint = constraintOid;
4593         trig.tgdeferrable = FALSE;
4594         trig.tginitdeferred = FALSE;
4595         /* we needn't fill in tgargs */
4596
4597         /*
4598          * See if we can do it with a single LEFT JOIN query.  A FALSE result
4599          * indicates we must proceed with the fire-the-trigger method.
4600          */
4601         if (RI_Initial_Check(&trig, rel, pkrel))
4602                 return;
4603
4604         /*
4605          * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
4606          * if that tuple had just been inserted.  If any of those fail, it should
4607          * ereport(ERROR) and that's that.
4608          */
4609         scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
4610
4611         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4612         {
4613                 FunctionCallInfoData fcinfo;
4614                 TriggerData trigdata;
4615
4616                 /*
4617                  * Make a call to the trigger function
4618                  *
4619                  * No parameters are passed, but we do set a context
4620                  */
4621                 MemSet(&fcinfo, 0, sizeof(fcinfo));
4622
4623                 /*
4624                  * We assume RI_FKey_check_ins won't look at flinfo...
4625                  */
4626                 trigdata.type = T_TriggerData;
4627                 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
4628                 trigdata.tg_relation = rel;
4629                 trigdata.tg_trigtuple = tuple;
4630                 trigdata.tg_newtuple = NULL;
4631                 trigdata.tg_trigger = &trig;
4632                 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
4633                 trigdata.tg_newtuplebuf = InvalidBuffer;
4634
4635                 fcinfo.context = (Node *) &trigdata;
4636
4637                 RI_FKey_check_ins(&fcinfo);
4638         }
4639
4640         heap_endscan(scan);
4641 }
4642
4643 static void
4644 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
4645                                          Oid constraintOid, bool on_insert)
4646 {
4647         CreateTrigStmt *fk_trigger;
4648
4649         fk_trigger = makeNode(CreateTrigStmt);
4650         fk_trigger->trigname = fkconstraint->constr_name;
4651         fk_trigger->relation = myRel;
4652         fk_trigger->before = false;
4653         fk_trigger->row = true;
4654
4655         /* Either ON INSERT or ON UPDATE */
4656         if (on_insert)
4657         {
4658                 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
4659                 fk_trigger->actions[0] = 'i';
4660         }
4661         else
4662         {
4663                 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
4664                 fk_trigger->actions[0] = 'u';
4665         }
4666         fk_trigger->actions[1] = '\0';
4667
4668         fk_trigger->isconstraint = true;
4669         fk_trigger->deferrable = fkconstraint->deferrable;
4670         fk_trigger->initdeferred = fkconstraint->initdeferred;
4671         fk_trigger->constrrel = fkconstraint->pktable;
4672         fk_trigger->args = NIL;
4673
4674         (void) CreateTrigger(fk_trigger, constraintOid);
4675
4676         /* Make changes-so-far visible */
4677         CommandCounterIncrement();
4678 }
4679
4680 /*
4681  * Create the triggers that implement an FK constraint.
4682  */
4683 static void
4684 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
4685                                                  Oid constraintOid)
4686 {
4687         RangeVar   *myRel;
4688         CreateTrigStmt *fk_trigger;
4689
4690         /*
4691          * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
4692          */
4693         myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
4694                                                  pstrdup(RelationGetRelationName(rel)));
4695
4696         /* Make changes-so-far visible */
4697         CommandCounterIncrement();
4698
4699         /*
4700          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
4701          * action for both INSERTs and UPDATEs on the referencing table.
4702          */
4703         CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
4704         CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
4705
4706         /*
4707          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4708          * DELETE action on the referenced table.
4709          */
4710         fk_trigger = makeNode(CreateTrigStmt);
4711         fk_trigger->trigname = fkconstraint->constr_name;
4712         fk_trigger->relation = fkconstraint->pktable;
4713         fk_trigger->before = false;
4714         fk_trigger->row = true;
4715         fk_trigger->actions[0] = 'd';
4716         fk_trigger->actions[1] = '\0';
4717
4718         fk_trigger->isconstraint = true;
4719         fk_trigger->constrrel = myRel;
4720         switch (fkconstraint->fk_del_action)
4721         {
4722                 case FKCONSTR_ACTION_NOACTION:
4723                         fk_trigger->deferrable = fkconstraint->deferrable;
4724                         fk_trigger->initdeferred = fkconstraint->initdeferred;
4725                         fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
4726                         break;
4727                 case FKCONSTR_ACTION_RESTRICT:
4728                         fk_trigger->deferrable = false;
4729                         fk_trigger->initdeferred = false;
4730                         fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
4731                         break;
4732                 case FKCONSTR_ACTION_CASCADE:
4733                         fk_trigger->deferrable = false;
4734                         fk_trigger->initdeferred = false;
4735                         fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
4736                         break;
4737                 case FKCONSTR_ACTION_SETNULL:
4738                         fk_trigger->deferrable = false;
4739                         fk_trigger->initdeferred = false;
4740                         fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
4741                         break;
4742                 case FKCONSTR_ACTION_SETDEFAULT:
4743                         fk_trigger->deferrable = false;
4744                         fk_trigger->initdeferred = false;
4745                         fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
4746                         break;
4747                 default:
4748                         elog(ERROR, "unrecognized FK action type: %d",
4749                                  (int) fkconstraint->fk_del_action);
4750                         break;
4751         }
4752         fk_trigger->args = NIL;
4753
4754         (void) CreateTrigger(fk_trigger, constraintOid);
4755
4756         /* Make changes-so-far visible */
4757         CommandCounterIncrement();
4758
4759         /*
4760          * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4761          * UPDATE action on the referenced table.
4762          */
4763         fk_trigger = makeNode(CreateTrigStmt);
4764         fk_trigger->trigname = fkconstraint->constr_name;
4765         fk_trigger->relation = fkconstraint->pktable;
4766         fk_trigger->before = false;
4767         fk_trigger->row = true;
4768         fk_trigger->actions[0] = 'u';
4769         fk_trigger->actions[1] = '\0';
4770         fk_trigger->isconstraint = true;
4771         fk_trigger->constrrel = myRel;
4772         switch (fkconstraint->fk_upd_action)
4773         {
4774                 case FKCONSTR_ACTION_NOACTION:
4775                         fk_trigger->deferrable = fkconstraint->deferrable;
4776                         fk_trigger->initdeferred = fkconstraint->initdeferred;
4777                         fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
4778                         break;
4779                 case FKCONSTR_ACTION_RESTRICT:
4780                         fk_trigger->deferrable = false;
4781                         fk_trigger->initdeferred = false;
4782                         fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
4783                         break;
4784                 case FKCONSTR_ACTION_CASCADE:
4785                         fk_trigger->deferrable = false;
4786                         fk_trigger->initdeferred = false;
4787                         fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
4788                         break;
4789                 case FKCONSTR_ACTION_SETNULL:
4790                         fk_trigger->deferrable = false;
4791                         fk_trigger->initdeferred = false;
4792                         fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
4793                         break;
4794                 case FKCONSTR_ACTION_SETDEFAULT:
4795                         fk_trigger->deferrable = false;
4796                         fk_trigger->initdeferred = false;
4797                         fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
4798                         break;
4799                 default:
4800                         elog(ERROR, "unrecognized FK action type: %d",
4801                                  (int) fkconstraint->fk_upd_action);
4802                         break;
4803         }
4804         fk_trigger->args = NIL;
4805
4806         (void) CreateTrigger(fk_trigger, constraintOid);
4807 }
4808
4809 /*
4810  * ALTER TABLE DROP CONSTRAINT
4811  */
4812 static void
4813 ATPrepDropConstraint(List **wqueue, Relation rel,
4814                                          bool recurse, AlterTableCmd *cmd)
4815 {
4816         /*
4817          * We don't want errors or noise from child tables, so we have to pass
4818          * down a modified command.
4819          */
4820         if (recurse)
4821         {
4822                 AlterTableCmd *childCmd = copyObject(cmd);
4823
4824                 childCmd->subtype = AT_DropConstraintQuietly;
4825                 ATSimpleRecursion(wqueue, rel, childCmd, recurse);
4826         }
4827 }
4828
4829 static void
4830 ATExecDropConstraint(Relation rel, const char *constrName,
4831                                          DropBehavior behavior, bool quiet)
4832 {
4833         int                     deleted;
4834
4835         deleted = RemoveRelConstraints(rel, constrName, behavior);
4836
4837         if (!quiet)
4838         {
4839                 /* If zero constraints deleted, complain */
4840                 if (deleted == 0)
4841                         ereport(ERROR,
4842                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
4843                                          errmsg("constraint \"%s\" does not exist",
4844                                                         constrName)));
4845                 /* Otherwise if more than one constraint deleted, notify */
4846                 else if (deleted > 1)
4847                         ereport(NOTICE,
4848                                         (errmsg("multiple constraints named \"%s\" were dropped",
4849                                                         constrName)));
4850         }
4851 }
4852
4853 /*
4854  * ALTER COLUMN TYPE
4855  */
4856 static void
4857 ATPrepAlterColumnType(List **wqueue,
4858                                           AlteredTableInfo *tab, Relation rel,
4859                                           bool recurse, bool recursing,
4860                                           AlterTableCmd *cmd)
4861 {
4862         char       *colName = cmd->name;
4863         TypeName   *typename = (TypeName *) cmd->def;
4864         HeapTuple       tuple;
4865         Form_pg_attribute attTup;
4866         AttrNumber      attnum;
4867         Oid                     targettype;
4868         int32           targettypmod;
4869         Node       *transform;
4870         NewColumnValue *newval;
4871         ParseState *pstate = make_parsestate(NULL);
4872
4873         /* lookup the attribute so we can check inheritance status */
4874         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4875         if (!HeapTupleIsValid(tuple))
4876                 ereport(ERROR,
4877                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
4878                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
4879                                                 colName, RelationGetRelationName(rel))));
4880         attTup = (Form_pg_attribute) GETSTRUCT(tuple);
4881         attnum = attTup->attnum;
4882
4883         /* Can't alter a system attribute */
4884         if (attnum <= 0)
4885                 ereport(ERROR,
4886                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4887                                  errmsg("cannot alter system column \"%s\"",
4888                                                 colName)));
4889
4890         /* Don't alter inherited columns */
4891         if (attTup->attinhcount > 0 && !recursing)
4892                 ereport(ERROR,
4893                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4894                                  errmsg("cannot alter inherited column \"%s\"",
4895                                                 colName)));
4896
4897         /* Look up the target type */
4898         targettype = typenameTypeId(NULL, typename, &targettypmod);
4899
4900         /* make sure datatype is legal for a column */
4901         CheckAttributeType(colName, targettype);
4902
4903         /*
4904          * Set up an expression to transform the old data value to the new type.
4905          * If a USING option was given, transform and use that expression, else
4906          * just take the old value and try to coerce it.  We do this first so that
4907          * type incompatibility can be detected before we waste effort, and
4908          * because we need the expression to be parsed against the original table
4909          * rowtype.
4910          */
4911         if (cmd->transform)
4912         {
4913                 RangeTblEntry *rte;
4914
4915                 /* Expression must be able to access vars of old table */
4916                 rte = addRangeTableEntryForRelation(pstate,
4917                                                                                         rel,
4918                                                                                         NULL,
4919                                                                                         false,
4920                                                                                         true);
4921                 addRTEtoQuery(pstate, rte, false, true, true);
4922
4923                 transform = transformExpr(pstate, cmd->transform);
4924
4925                 /* It can't return a set */
4926                 if (expression_returns_set(transform))
4927                         ereport(ERROR,
4928                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
4929                                          errmsg("transform expression must not return a set")));
4930
4931                 /* No subplans or aggregates, either... */
4932                 if (pstate->p_hasSubLinks)
4933                         ereport(ERROR,
4934                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4935                                          errmsg("cannot use subquery in transform expression")));
4936                 if (pstate->p_hasAggs)
4937                         ereport(ERROR,
4938                                         (errcode(ERRCODE_GROUPING_ERROR),
4939                         errmsg("cannot use aggregate function in transform expression")));
4940         }
4941         else
4942         {
4943                 transform = (Node *) makeVar(1, attnum,
4944                                                                          attTup->atttypid, attTup->atttypmod,
4945                                                                          0);
4946         }
4947
4948         transform = coerce_to_target_type(pstate,
4949                                                                           transform, exprType(transform),
4950                                                                           targettype, targettypmod,
4951                                                                           COERCION_ASSIGNMENT,
4952                                                                           COERCE_IMPLICIT_CAST);
4953         if (transform == NULL)
4954                 ereport(ERROR,
4955                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
4956                                  errmsg("column \"%s\" cannot be cast to type \"%s\"",
4957                                                 colName, TypeNameToString(typename))));
4958
4959         /*
4960          * Add a work queue item to make ATRewriteTable update the column
4961          * contents.
4962          */
4963         newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4964         newval->attnum = attnum;
4965         newval->expr = (Expr *) transform;
4966
4967         tab->newvals = lappend(tab->newvals, newval);
4968
4969         ReleaseSysCache(tuple);
4970
4971         /*
4972          * The recursion case is handled by ATSimpleRecursion.  However, if we are
4973          * told not to recurse, there had better not be any child tables; else the
4974          * alter would put them out of step.
4975          */
4976         if (recurse)
4977                 ATSimpleRecursion(wqueue, rel, cmd, recurse);
4978         else if (!recursing &&
4979                          find_inheritance_children(RelationGetRelid(rel)) != NIL)
4980                 ereport(ERROR,
4981                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4982                                  errmsg("type of inherited column \"%s\" must be changed in child tables too",
4983                                                 colName)));
4984 }
4985
4986 static void
4987 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
4988                                           const char *colName, TypeName *typename)
4989 {
4990         HeapTuple       heapTup;
4991         Form_pg_attribute attTup;
4992         AttrNumber      attnum;
4993         HeapTuple       typeTuple;
4994         Form_pg_type tform;
4995         Oid                     targettype;
4996         int32           targettypmod;
4997         Node       *defaultexpr;
4998         Relation        attrelation;
4999         Relation        depRel;
5000         ScanKeyData key[3];
5001         SysScanDesc scan;
5002         HeapTuple       depTup;
5003
5004         attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5005
5006         /* Look up the target column */
5007         heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5008         if (!HeapTupleIsValid(heapTup))         /* shouldn't happen */
5009                 ereport(ERROR,
5010                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5011                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
5012                                                 colName, RelationGetRelationName(rel))));
5013         attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5014         attnum = attTup->attnum;
5015
5016         /* Check for multiple ALTER TYPE on same column --- can't cope */
5017         if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5018                 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5019                 ereport(ERROR,
5020                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5021                                  errmsg("cannot alter type of column \"%s\" twice",
5022                                                 colName)));
5023
5024         /* Look up the target type (should not fail, since prep found it) */
5025         typeTuple = typenameType(NULL, typename, &targettypmod);
5026         tform = (Form_pg_type) GETSTRUCT(typeTuple);
5027         targettype = HeapTupleGetOid(typeTuple);
5028
5029         /*
5030          * If there is a default expression for the column, get it and ensure we
5031          * can coerce it to the new datatype.  (We must do this before changing
5032          * the column type, because build_column_default itself will try to
5033          * coerce, and will not issue the error message we want if it fails.)
5034          *
5035          * We remove any implicit coercion steps at the top level of the old
5036          * default expression; this has been agreed to satisfy the principle of
5037          * least surprise.      (The conversion to the new column type should act like
5038          * it started from what the user sees as the stored expression, and the
5039          * implicit coercions aren't going to be shown.)
5040          */
5041         if (attTup->atthasdef)
5042         {
5043                 defaultexpr = build_column_default(rel, attnum);
5044                 Assert(defaultexpr);
5045                 defaultexpr = strip_implicit_coercions(defaultexpr);
5046                 defaultexpr = coerce_to_target_type(NULL,               /* no UNKNOWN params */
5047                                                                                   defaultexpr, exprType(defaultexpr),
5048                                                                                         targettype, targettypmod,
5049                                                                                         COERCION_ASSIGNMENT,
5050                                                                                         COERCE_IMPLICIT_CAST);
5051                 if (defaultexpr == NULL)
5052                         ereport(ERROR,
5053                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
5054                         errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
5055                                    colName, TypeNameToString(typename))));
5056         }
5057         else
5058                 defaultexpr = NULL;
5059
5060         /*
5061          * Find everything that depends on the column (constraints, indexes, etc),
5062          * and record enough information to let us recreate the objects.
5063          *
5064          * The actual recreation does not happen here, but only after we have
5065          * performed all the individual ALTER TYPE operations.  We have to save
5066          * the info before executing ALTER TYPE, though, else the deparser will
5067          * get confused.
5068          *
5069          * There could be multiple entries for the same object, so we must check
5070          * to ensure we process each one only once.  Note: we assume that an index
5071          * that implements a constraint will not show a direct dependency on the
5072          * column.
5073          */
5074         depRel = heap_open(DependRelationId, RowExclusiveLock);
5075
5076         ScanKeyInit(&key[0],
5077                                 Anum_pg_depend_refclassid,
5078                                 BTEqualStrategyNumber, F_OIDEQ,
5079                                 ObjectIdGetDatum(RelationRelationId));
5080         ScanKeyInit(&key[1],
5081                                 Anum_pg_depend_refobjid,
5082                                 BTEqualStrategyNumber, F_OIDEQ,
5083                                 ObjectIdGetDatum(RelationGetRelid(rel)));
5084         ScanKeyInit(&key[2],
5085                                 Anum_pg_depend_refobjsubid,
5086                                 BTEqualStrategyNumber, F_INT4EQ,
5087                                 Int32GetDatum((int32) attnum));
5088
5089         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5090                                                           SnapshotNow, 3, key);
5091
5092         while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5093         {
5094                 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5095                 ObjectAddress foundObject;
5096
5097                 /* We don't expect any PIN dependencies on columns */
5098                 if (foundDep->deptype == DEPENDENCY_PIN)
5099                         elog(ERROR, "cannot alter type of a pinned column");
5100
5101                 foundObject.classId = foundDep->classid;
5102                 foundObject.objectId = foundDep->objid;
5103                 foundObject.objectSubId = foundDep->objsubid;
5104
5105                 switch (getObjectClass(&foundObject))
5106                 {
5107                         case OCLASS_CLASS:
5108                                 {
5109                                         char            relKind = get_rel_relkind(foundObject.objectId);
5110
5111                                         if (relKind == RELKIND_INDEX)
5112                                         {
5113                                                 Assert(foundObject.objectSubId == 0);
5114                                                 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5115                                                 {
5116                                                         tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5117                                                                                                            foundObject.objectId);
5118                                                         tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5119                                                            pg_get_indexdef_string(foundObject.objectId));
5120                                                 }
5121                                         }
5122                                         else if (relKind == RELKIND_SEQUENCE)
5123                                         {
5124                                                 /*
5125                                                  * This must be a SERIAL column's sequence.  We need
5126                                                  * not do anything to it.
5127                                                  */
5128                                                 Assert(foundObject.objectSubId == 0);
5129                                         }
5130                                         else
5131                                         {
5132                                                 /* Not expecting any other direct dependencies... */
5133                                                 elog(ERROR, "unexpected object depending on column: %s",
5134                                                          getObjectDescription(&foundObject));
5135                                         }
5136                                         break;
5137                                 }
5138
5139                         case OCLASS_CONSTRAINT:
5140                                 Assert(foundObject.objectSubId == 0);
5141                                 if (!list_member_oid(tab->changedConstraintOids,
5142                                                                          foundObject.objectId))
5143                                 {
5144                                         char       *defstring = pg_get_constraintdef_string(foundObject.objectId);
5145
5146                                         /*
5147                                          * Put NORMAL dependencies at the front of the list and
5148                                          * AUTO dependencies at the back.  This makes sure that
5149                                          * foreign-key constraints depending on this column will
5150                                          * be dropped before unique or primary-key constraints of
5151                                          * the column; which we must have because the FK
5152                                          * constraints depend on the indexes belonging to the
5153                                          * unique constraints.
5154                                          */
5155                                         if (foundDep->deptype == DEPENDENCY_NORMAL)
5156                                         {
5157                                                 tab->changedConstraintOids =
5158                                                         lcons_oid(foundObject.objectId,
5159                                                                           tab->changedConstraintOids);
5160                                                 tab->changedConstraintDefs =
5161                                                         lcons(defstring,
5162                                                                   tab->changedConstraintDefs);
5163                                         }
5164                                         else
5165                                         {
5166                                                 tab->changedConstraintOids =
5167                                                         lappend_oid(tab->changedConstraintOids,
5168                                                                                 foundObject.objectId);
5169                                                 tab->changedConstraintDefs =
5170                                                         lappend(tab->changedConstraintDefs,
5171                                                                         defstring);
5172                                         }
5173                                 }
5174                                 break;
5175
5176                         case OCLASS_REWRITE:
5177                                 /* XXX someday see if we can cope with revising views */
5178                                 ereport(ERROR,
5179                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5180                                                  errmsg("cannot alter type of a column used by a view or rule"),
5181                                                  errdetail("%s depends on column \"%s\"",
5182                                                                    getObjectDescription(&foundObject),
5183                                                                    colName)));
5184                                 break;
5185
5186                         case OCLASS_DEFAULT:
5187
5188                                 /*
5189                                  * Ignore the column's default expression, since we will fix
5190                                  * it below.
5191                                  */
5192                                 Assert(defaultexpr);
5193                                 break;
5194
5195                         case OCLASS_PROC:
5196                         case OCLASS_TYPE:
5197                         case OCLASS_CAST:
5198                         case OCLASS_CONVERSION:
5199                         case OCLASS_LANGUAGE:
5200                         case OCLASS_OPERATOR:
5201                         case OCLASS_OPCLASS:
5202                         case OCLASS_OPFAMILY:
5203                         case OCLASS_TRIGGER:
5204                         case OCLASS_SCHEMA:
5205                         case OCLASS_TSPARSER:
5206                         case OCLASS_TSDICT:
5207                         case OCLASS_TSTEMPLATE:
5208                         case OCLASS_TSCONFIG:
5209
5210                                 /*
5211                                  * We don't expect any of these sorts of objects to depend on
5212                                  * a column.
5213                                  */
5214                                 elog(ERROR, "unexpected object depending on column: %s",
5215                                          getObjectDescription(&foundObject));
5216                                 break;
5217
5218                         default:
5219                                 elog(ERROR, "unrecognized object class: %u",
5220                                          foundObject.classId);
5221                 }
5222         }
5223
5224         systable_endscan(scan);
5225
5226         /*
5227          * Now scan for dependencies of this column on other things.  The only
5228          * thing we should find is the dependency on the column datatype, which we
5229          * want to remove.
5230          */
5231         ScanKeyInit(&key[0],
5232                                 Anum_pg_depend_classid,
5233                                 BTEqualStrategyNumber, F_OIDEQ,
5234                                 ObjectIdGetDatum(RelationRelationId));
5235         ScanKeyInit(&key[1],
5236                                 Anum_pg_depend_objid,
5237                                 BTEqualStrategyNumber, F_OIDEQ,
5238                                 ObjectIdGetDatum(RelationGetRelid(rel)));
5239         ScanKeyInit(&key[2],
5240                                 Anum_pg_depend_objsubid,
5241                                 BTEqualStrategyNumber, F_INT4EQ,
5242                                 Int32GetDatum((int32) attnum));
5243
5244         scan = systable_beginscan(depRel, DependDependerIndexId, true,
5245                                                           SnapshotNow, 3, key);
5246
5247         while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5248         {
5249                 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5250
5251                 if (foundDep->deptype != DEPENDENCY_NORMAL)
5252                         elog(ERROR, "found unexpected dependency type '%c'",
5253                                  foundDep->deptype);
5254                 if (foundDep->refclassid != TypeRelationId ||
5255                         foundDep->refobjid != attTup->atttypid)
5256                         elog(ERROR, "found unexpected dependency for column");
5257
5258                 simple_heap_delete(depRel, &depTup->t_self);
5259         }
5260
5261         systable_endscan(scan);
5262
5263         heap_close(depRel, RowExclusiveLock);
5264
5265         /*
5266          * Here we go --- change the recorded column type.      (Note heapTup is a
5267          * copy of the syscache entry, so okay to scribble on.)
5268          */
5269         attTup->atttypid = targettype;
5270         attTup->atttypmod = targettypmod;
5271         attTup->attndims = list_length(typename->arrayBounds);
5272         attTup->attlen = tform->typlen;
5273         attTup->attbyval = tform->typbyval;
5274         attTup->attalign = tform->typalign;
5275         attTup->attstorage = tform->typstorage;
5276
5277         ReleaseSysCache(typeTuple);
5278
5279         simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5280
5281         /* keep system catalog indexes current */
5282         CatalogUpdateIndexes(attrelation, heapTup);
5283
5284         heap_close(attrelation, RowExclusiveLock);
5285
5286         /* Install dependency on new datatype */
5287         add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5288
5289         /*
5290          * Drop any pg_statistic entry for the column, since it's now wrong type
5291          */
5292         RemoveStatistics(RelationGetRelid(rel), attnum);
5293
5294         /*
5295          * Update the default, if present, by brute force --- remove and re-add
5296          * the default.  Probably unsafe to take shortcuts, since the new version
5297          * may well have additional dependencies.  (It's okay to do this now,
5298          * rather than after other ALTER TYPE commands, since the default won't
5299          * depend on other column types.)
5300          */
5301         if (defaultexpr)
5302         {
5303                 /* Must make new row visible since it will be updated again */
5304                 CommandCounterIncrement();
5305
5306                 /*
5307                  * We use RESTRICT here for safety, but at present we do not expect
5308                  * anything to depend on the default.
5309                  */
5310                 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5311
5312                 StoreAttrDefault(rel, attnum, nodeToString(defaultexpr));
5313         }
5314
5315         /* Cleanup */
5316         heap_freetuple(heapTup);
5317 }
5318
5319 /*
5320  * Cleanup after we've finished all the ALTER TYPE operations for a
5321  * particular relation.  We have to drop and recreate all the indexes
5322  * and constraints that depend on the altered columns.
5323  */
5324 static void
5325 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5326 {
5327         ObjectAddress obj;
5328         ListCell   *l;
5329
5330         /*
5331          * Re-parse the index and constraint definitions, and attach them to the
5332          * appropriate work queue entries.      We do this before dropping because in
5333          * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5334          * lock on the table the constraint is attached to, and we need to get
5335          * that before dropping.  It's safe because the parser won't actually look
5336          * at the catalogs to detect the existing entry.
5337          */
5338         foreach(l, tab->changedIndexDefs)
5339                 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5340         foreach(l, tab->changedConstraintDefs)
5341                 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5342
5343         /*
5344          * Now we can drop the existing constraints and indexes --- constraints
5345          * first, since some of them might depend on the indexes.  In fact, we
5346          * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5347          * we already ordered the constraint list to ensure that would happen. It
5348          * should be okay to use DROP_RESTRICT here, since nothing else should be
5349          * depending on these objects.
5350          */
5351         foreach(l, tab->changedConstraintOids)
5352         {
5353                 obj.classId = ConstraintRelationId;
5354                 obj.objectId = lfirst_oid(l);
5355                 obj.objectSubId = 0;
5356                 performDeletion(&obj, DROP_RESTRICT);
5357         }
5358
5359         foreach(l, tab->changedIndexOids)
5360         {
5361                 obj.classId = RelationRelationId;
5362                 obj.objectId = lfirst_oid(l);
5363                 obj.objectSubId = 0;
5364                 performDeletion(&obj, DROP_RESTRICT);
5365         }
5366
5367         /*
5368          * The objects will get recreated during subsequent passes over the work
5369          * queue.
5370          */
5371 }
5372
5373 static void
5374 ATPostAlterTypeParse(char *cmd, List **wqueue)
5375 {
5376         List       *raw_parsetree_list;
5377         List       *querytree_list;
5378         ListCell   *list_item;
5379
5380         /*
5381          * We expect that we will get only ALTER TABLE and CREATE INDEX
5382          * statements. Hence, there is no need to pass them through
5383          * parse_analyze() or the rewriter, but instead we need to pass them
5384          * through parse_utilcmd.c to make them ready for execution.
5385          */
5386         raw_parsetree_list = raw_parser(cmd);
5387         querytree_list = NIL;
5388         foreach(list_item, raw_parsetree_list)
5389         {
5390                 Node       *stmt = (Node *) lfirst(list_item);
5391
5392                 if (IsA(stmt, IndexStmt))
5393                         querytree_list = lappend(querytree_list,
5394                                                                          transformIndexStmt((IndexStmt *) stmt,
5395                                                                                                                 cmd));
5396                 else if (IsA(stmt, AlterTableStmt))
5397                         querytree_list = list_concat(querytree_list,
5398                                                          transformAlterTableStmt((AlterTableStmt *) stmt,
5399                                                                                                          cmd));
5400                 else
5401                         querytree_list = lappend(querytree_list, stmt);
5402         }
5403
5404         /*
5405          * Attach each generated command to the proper place in the work queue.
5406          * Note this could result in creation of entirely new work-queue entries.
5407          */
5408         foreach(list_item, querytree_list)
5409         {
5410                 Node       *stm = (Node *) lfirst(list_item);
5411                 Relation        rel;
5412                 AlteredTableInfo *tab;
5413
5414                 switch (nodeTag(stm))
5415                 {
5416                         case T_IndexStmt:
5417                                 {
5418                                         IndexStmt  *stmt = (IndexStmt *) stm;
5419                                         AlterTableCmd *newcmd;
5420
5421                                         rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5422                                         tab = ATGetQueueEntry(wqueue, rel);
5423                                         newcmd = makeNode(AlterTableCmd);
5424                                         newcmd->subtype = AT_ReAddIndex;
5425                                         newcmd->def = (Node *) stmt;
5426                                         tab->subcmds[AT_PASS_OLD_INDEX] =
5427                                                 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5428                                         relation_close(rel, NoLock);
5429                                         break;
5430                                 }
5431                         case T_AlterTableStmt:
5432                                 {
5433                                         AlterTableStmt *stmt = (AlterTableStmt *) stm;
5434                                         ListCell   *lcmd;
5435
5436                                         rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5437                                         tab = ATGetQueueEntry(wqueue, rel);
5438                                         foreach(lcmd, stmt->cmds)
5439                                         {
5440                                                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
5441
5442                                                 switch (cmd->subtype)
5443                                                 {
5444                                                         case AT_AddIndex:
5445                                                                 cmd->subtype = AT_ReAddIndex;
5446                                                                 tab->subcmds[AT_PASS_OLD_INDEX] =
5447                                                                         lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
5448                                                                 break;
5449                                                         case AT_AddConstraint:
5450                                                                 tab->subcmds[AT_PASS_OLD_CONSTR] =
5451                                                                         lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
5452                                                                 break;
5453                                                         default:
5454                                                                 elog(ERROR, "unexpected statement type: %d",
5455                                                                          (int) cmd->subtype);
5456                                                 }
5457                                         }
5458                                         relation_close(rel, NoLock);
5459                                         break;
5460                                 }
5461                         default:
5462                                 elog(ERROR, "unexpected statement type: %d",
5463                                          (int) nodeTag(stm));
5464                 }
5465         }
5466 }
5467
5468
5469 /*
5470  * ALTER TABLE OWNER
5471  *
5472  * recursing is true if we are recursing from a table to its indexes,
5473  * sequences, or toast table.  We don't allow the ownership of those things to
5474  * be changed separately from the parent table.  Also, we can skip permission
5475  * checks (this is necessary not just an optimization, else we'd fail to
5476  * handle toast tables properly).
5477  *
5478  * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
5479  * free-standing composite type.
5480  */
5481 void
5482 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
5483 {
5484         Relation        target_rel;
5485         Relation        class_rel;
5486         HeapTuple       tuple;
5487         Form_pg_class tuple_class;
5488
5489         /*
5490          * Get exclusive lock till end of transaction on the target table. Use
5491          * relation_open so that we can work on indexes and sequences.
5492          */
5493         target_rel = relation_open(relationOid, AccessExclusiveLock);
5494
5495         /* Get its pg_class tuple, too */
5496         class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5497
5498         tuple = SearchSysCache(RELOID,
5499                                                    ObjectIdGetDatum(relationOid),
5500                                                    0, 0, 0);
5501         if (!HeapTupleIsValid(tuple))
5502                 elog(ERROR, "cache lookup failed for relation %u", relationOid);
5503         tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5504
5505         /* Can we change the ownership of this tuple? */
5506         switch (tuple_class->relkind)
5507         {
5508                 case RELKIND_RELATION:
5509                 case RELKIND_VIEW:
5510                         /* ok to change owner */
5511                         break;
5512                 case RELKIND_INDEX:
5513                         if (!recursing)
5514                         {
5515                                 /*
5516                                  * Because ALTER INDEX OWNER used to be allowed, and in fact
5517                                  * is generated by old versions of pg_dump, we give a warning
5518                                  * and do nothing rather than erroring out.  Also, to avoid
5519                                  * unnecessary chatter while restoring those old dumps, say
5520                                  * nothing at all if the command would be a no-op anyway.
5521                                  */
5522                                 if (tuple_class->relowner != newOwnerId)
5523                                         ereport(WARNING,
5524                                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5525                                                          errmsg("cannot change owner of index \"%s\"",
5526                                                                         NameStr(tuple_class->relname)),
5527                                                          errhint("Change the ownership of the index's table, instead.")));
5528                                 /* quick hack to exit via the no-op path */
5529                                 newOwnerId = tuple_class->relowner;
5530                         }
5531                         break;
5532                 case RELKIND_SEQUENCE:
5533                         if (!recursing &&
5534                                 tuple_class->relowner != newOwnerId)
5535                         {
5536                                 /* if it's an owned sequence, disallow changing it by itself */
5537                                 Oid                     tableId;
5538                                 int32           colId;
5539
5540                                 if (sequenceIsOwned(relationOid, &tableId, &colId))
5541                                         ereport(ERROR,
5542                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5543                                                          errmsg("cannot change owner of sequence \"%s\"",
5544                                                                         NameStr(tuple_class->relname)),
5545                                           errdetail("Sequence \"%s\" is linked to table \"%s\".",
5546                                                                 NameStr(tuple_class->relname),
5547                                                                 get_rel_name(tableId))));
5548                         }
5549                         break;
5550                 case RELKIND_COMPOSITE_TYPE:
5551                         if (recursing)
5552                                 break;
5553                         ereport(ERROR,
5554                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5555                                          errmsg("\"%s\" is a composite type",
5556                                                         NameStr(tuple_class->relname)),
5557                                          errhint("Use ALTER TYPE instead.")));
5558                         break;
5559                 case RELKIND_TOASTVALUE:
5560                         if (recursing)
5561                                 break;
5562                         /* FALL THRU */
5563                 default:
5564                         ereport(ERROR,
5565                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5566                                          errmsg("\"%s\" is not a table, view, or sequence",
5567                                                         NameStr(tuple_class->relname))));
5568         }
5569
5570         /*
5571          * If the new owner is the same as the existing owner, consider the
5572          * command to have succeeded.  This is for dump restoration purposes.
5573          */
5574         if (tuple_class->relowner != newOwnerId)
5575         {
5576                 Datum           repl_val[Natts_pg_class];
5577                 char            repl_null[Natts_pg_class];
5578                 char            repl_repl[Natts_pg_class];
5579                 Acl                *newAcl;
5580                 Datum           aclDatum;
5581                 bool            isNull;
5582                 HeapTuple       newtuple;
5583
5584                 /* skip permission checks when recursing to index or toast table */
5585                 if (!recursing)
5586                 {
5587                         /* Superusers can always do it */
5588                         if (!superuser())
5589                         {
5590                                 Oid                     namespaceOid = tuple_class->relnamespace;
5591                                 AclResult       aclresult;
5592
5593                                 /* Otherwise, must be owner of the existing object */
5594                                 if (!pg_class_ownercheck(relationOid, GetUserId()))
5595                                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5596                                                                    RelationGetRelationName(target_rel));
5597
5598                                 /* Must be able to become new owner */
5599                                 check_is_member_of_role(GetUserId(), newOwnerId);
5600
5601                                 /* New owner must have CREATE privilege on namespace */
5602                                 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
5603                                                                                                   ACL_CREATE);
5604                                 if (aclresult != ACLCHECK_OK)
5605                                         aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
5606                                                                    get_namespace_name(namespaceOid));
5607                         }
5608                 }
5609
5610                 memset(repl_null, ' ', sizeof(repl_null));
5611                 memset(repl_repl, ' ', sizeof(repl_repl));
5612
5613                 repl_repl[Anum_pg_class_relowner - 1] = 'r';
5614                 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
5615
5616                 /*
5617                  * Determine the modified ACL for the new owner.  This is only
5618                  * necessary when the ACL is non-null.
5619                  */
5620                 aclDatum = SysCacheGetAttr(RELOID, tuple,
5621                                                                    Anum_pg_class_relacl,
5622                                                                    &isNull);
5623                 if (!isNull)
5624                 {
5625                         newAcl = aclnewowner(DatumGetAclP(aclDatum),
5626                                                                  tuple_class->relowner, newOwnerId);
5627                         repl_repl[Anum_pg_class_relacl - 1] = 'r';
5628                         repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
5629                 }
5630
5631                 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
5632
5633                 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
5634                 CatalogUpdateIndexes(class_rel, newtuple);
5635
5636                 heap_freetuple(newtuple);
5637
5638                 /*
5639                  * Update owner dependency reference, if any.  A composite type has
5640                  * none, because it's tracked for the pg_type entry instead of here;
5641                  * indexes and TOAST tables don't have their own entries either.
5642                  */
5643                 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
5644                         tuple_class->relkind != RELKIND_INDEX &&
5645                         tuple_class->relkind != RELKIND_TOASTVALUE)
5646                         changeDependencyOnOwner(RelationRelationId, relationOid,
5647                                                                         newOwnerId);
5648
5649                 /*
5650                  * Also change the ownership of the table's rowtype, if it has one
5651                  */
5652                 if (tuple_class->relkind != RELKIND_INDEX)
5653                         AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
5654                                                          tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
5655
5656                 /*
5657                  * If we are operating on a table, also change the ownership of any
5658                  * indexes and sequences that belong to the table, as well as the
5659                  * table's toast table (if it has one)
5660                  */
5661                 if (tuple_class->relkind == RELKIND_RELATION ||
5662                         tuple_class->relkind == RELKIND_TOASTVALUE)
5663                 {
5664                         List       *index_oid_list;
5665                         ListCell   *i;
5666
5667                         /* Find all the indexes belonging to this relation */
5668                         index_oid_list = RelationGetIndexList(target_rel);
5669
5670                         /* For each index, recursively change its ownership */
5671                         foreach(i, index_oid_list)
5672                                 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
5673
5674                         list_free(index_oid_list);
5675                 }
5676
5677                 if (tuple_class->relkind == RELKIND_RELATION)
5678                 {
5679                         /* If it has a toast table, recurse to change its ownership */
5680                         if (tuple_class->reltoastrelid != InvalidOid)
5681                                 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
5682                                                                   true);
5683
5684                         /* If it has dependent sequences, recurse to change them too */
5685                         change_owner_recurse_to_sequences(relationOid, newOwnerId);
5686                 }
5687         }
5688
5689         ReleaseSysCache(tuple);
5690         heap_close(class_rel, RowExclusiveLock);
5691         relation_close(target_rel, NoLock);
5692 }
5693
5694 /*
5695  * change_owner_recurse_to_sequences
5696  *
5697  * Helper function for ATExecChangeOwner.  Examines pg_depend searching
5698  * for sequences that are dependent on serial columns, and changes their
5699  * ownership.
5700  */
5701 static void
5702 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
5703 {
5704         Relation        depRel;
5705         SysScanDesc scan;
5706         ScanKeyData key[2];
5707         HeapTuple       tup;
5708
5709         /*
5710          * SERIAL sequences are those having an auto dependency on one of the
5711          * table's columns (we don't care *which* column, exactly).
5712          */
5713         depRel = heap_open(DependRelationId, AccessShareLock);
5714
5715         ScanKeyInit(&key[0],
5716                                 Anum_pg_depend_refclassid,
5717                                 BTEqualStrategyNumber, F_OIDEQ,
5718                                 ObjectIdGetDatum(RelationRelationId));
5719         ScanKeyInit(&key[1],
5720                                 Anum_pg_depend_refobjid,
5721                                 BTEqualStrategyNumber, F_OIDEQ,
5722                                 ObjectIdGetDatum(relationOid));
5723         /* we leave refobjsubid unspecified */
5724
5725         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5726                                                           SnapshotNow, 2, key);
5727
5728         while (HeapTupleIsValid(tup = systable_getnext(scan)))
5729         {
5730                 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
5731                 Relation        seqRel;
5732
5733                 /* skip dependencies other than auto dependencies on columns */
5734                 if (depForm->refobjsubid == 0 ||
5735                         depForm->classid != RelationRelationId ||
5736                         depForm->objsubid != 0 ||
5737                         depForm->deptype != DEPENDENCY_AUTO)
5738                         continue;
5739
5740                 /* Use relation_open just in case it's an index */
5741                 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
5742
5743                 /* skip non-sequence relations */
5744                 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
5745                 {
5746                         /* No need to keep the lock */
5747                         relation_close(seqRel, AccessExclusiveLock);
5748                         continue;
5749                 }
5750
5751                 /* We don't need to close the sequence while we alter it. */
5752                 ATExecChangeOwner(depForm->objid, newOwnerId, true);
5753
5754                 /* Now we can close it.  Keep the lock till end of transaction. */
5755                 relation_close(seqRel, NoLock);
5756         }
5757
5758         systable_endscan(scan);
5759
5760         relation_close(depRel, AccessShareLock);
5761 }
5762
5763 /*
5764  * ALTER TABLE CLUSTER ON
5765  *
5766  * The only thing we have to do is to change the indisclustered bits.
5767  */
5768 static void
5769 ATExecClusterOn(Relation rel, const char *indexName)
5770 {
5771         Oid                     indexOid;
5772
5773         indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
5774
5775         if (!OidIsValid(indexOid))
5776                 ereport(ERROR,
5777                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5778                                  errmsg("index \"%s\" for table \"%s\" does not exist",
5779                                                 indexName, RelationGetRelationName(rel))));
5780
5781         /* Check index is valid to cluster on */
5782         check_index_is_clusterable(rel, indexOid, false);
5783
5784         /* And do the work */
5785         mark_index_clustered(rel, indexOid);
5786 }
5787
5788 /*
5789  * ALTER TABLE SET WITHOUT CLUSTER
5790  *
5791  * We have to find any indexes on the table that have indisclustered bit
5792  * set and turn it off.
5793  */
5794 static void
5795 ATExecDropCluster(Relation rel)
5796 {
5797         mark_index_clustered(rel, InvalidOid);
5798 }
5799
5800 /*
5801  * ALTER TABLE SET TABLESPACE
5802  */
5803 static void
5804 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
5805 {
5806         Oid                     tablespaceId;
5807         AclResult       aclresult;
5808
5809         /* Check that the tablespace exists */
5810         tablespaceId = get_tablespace_oid(tablespacename);
5811         if (!OidIsValid(tablespaceId))
5812                 ereport(ERROR,
5813                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5814                                  errmsg("tablespace \"%s\" does not exist", tablespacename)));
5815
5816         /* Check its permissions */
5817         aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
5818         if (aclresult != ACLCHECK_OK)
5819                 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
5820
5821         /* Save info for Phase 3 to do the real work */
5822         if (OidIsValid(tab->newTableSpace))
5823                 ereport(ERROR,
5824                                 (errcode(ERRCODE_SYNTAX_ERROR),
5825                                  errmsg("cannot have multiple SET TABLESPACE subcommands")));
5826         tab->newTableSpace = tablespaceId;
5827 }
5828
5829 /*
5830  * ALTER TABLE/INDEX SET (...) or RESET (...)
5831  */
5832 static void
5833 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
5834 {
5835         Oid                     relid;
5836         Relation        pgclass;
5837         HeapTuple       tuple;
5838         HeapTuple       newtuple;
5839         Datum           datum;
5840         bool            isnull;
5841         Datum           newOptions;
5842         Datum           repl_val[Natts_pg_class];
5843         char            repl_null[Natts_pg_class];
5844         char            repl_repl[Natts_pg_class];
5845
5846         if (defList == NIL)
5847                 return;                                 /* nothing to do */
5848
5849         pgclass = heap_open(RelationRelationId, RowExclusiveLock);
5850
5851         /* Get the old reloptions */
5852         relid = RelationGetRelid(rel);
5853         tuple = SearchSysCache(RELOID,
5854                                                    ObjectIdGetDatum(relid),
5855                                                    0, 0, 0);
5856         if (!HeapTupleIsValid(tuple))
5857                 elog(ERROR, "cache lookup failed for relation %u", relid);
5858
5859         datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
5860
5861         /* Generate new proposed reloptions (text array) */
5862         newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5863                                                                          defList, false, isReset);
5864
5865         /* Validate */
5866         switch (rel->rd_rel->relkind)
5867         {
5868                 case RELKIND_RELATION:
5869                 case RELKIND_TOASTVALUE:
5870                         (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
5871                         break;
5872                 case RELKIND_INDEX:
5873                         (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
5874                         break;
5875                 default:
5876                         ereport(ERROR,
5877                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5878                                          errmsg("\"%s\" is not a table, index, or TOAST table",
5879                                                         RelationGetRelationName(rel))));
5880                         break;
5881         }
5882
5883         /*
5884          * All we need do here is update the pg_class row; the new options will be
5885          * propagated into relcaches during post-commit cache inval.
5886          */
5887         memset(repl_val, 0, sizeof(repl_val));
5888         memset(repl_null, ' ', sizeof(repl_null));
5889         memset(repl_repl, ' ', sizeof(repl_repl));
5890
5891         if (newOptions != (Datum) 0)
5892                 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
5893         else
5894                 repl_null[Anum_pg_class_reloptions - 1] = 'n';
5895
5896         repl_repl[Anum_pg_class_reloptions - 1] = 'r';
5897
5898         newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
5899                                                                 repl_val, repl_null, repl_repl);
5900
5901         simple_heap_update(pgclass, &newtuple->t_self, newtuple);
5902
5903         CatalogUpdateIndexes(pgclass, newtuple);
5904
5905         heap_freetuple(newtuple);
5906
5907         ReleaseSysCache(tuple);
5908
5909         heap_close(pgclass, RowExclusiveLock);
5910 }
5911
5912 /*
5913  * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
5914  * rewriting to be done, so we just want to copy the data as fast as possible.
5915  */
5916 static void
5917 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
5918 {
5919         Relation        rel;
5920         Oid                     oldTableSpace;
5921         Oid                     reltoastrelid;
5922         Oid                     reltoastidxid;
5923         RelFileNode newrnode;
5924         SMgrRelation dstrel;
5925         Relation        pg_class;
5926         HeapTuple       tuple;
5927         Form_pg_class rd_rel;
5928
5929         /*
5930          * Need lock here in case we are recursing to toast table or index
5931          */
5932         rel = relation_open(tableOid, AccessExclusiveLock);
5933
5934         /*
5935          * We can never allow moving of shared or nailed-in-cache relations,
5936          * because we can't support changing their reltablespace values.
5937          */
5938         if (rel->rd_rel->relisshared || rel->rd_isnailed)
5939                 ereport(ERROR,
5940                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5941                                  errmsg("cannot move system relation \"%s\"",
5942                                                 RelationGetRelationName(rel))));
5943
5944         /* Can't move a non-shared relation into pg_global */
5945         if (newTableSpace == GLOBALTABLESPACE_OID)
5946                 ereport(ERROR,
5947                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5948                                  errmsg("only shared relations can be placed in pg_global tablespace")));
5949
5950         /*
5951          * Don't allow moving temp tables of other backends ... their local buffer
5952          * manager is not going to cope.
5953          */
5954         if (isOtherTempNamespace(RelationGetNamespace(rel)))
5955                 ereport(ERROR,
5956                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5957                                  errmsg("cannot move temporary tables of other sessions")));
5958
5959         /*
5960          * No work if no change in tablespace.
5961          */
5962         oldTableSpace = rel->rd_rel->reltablespace;
5963         if (newTableSpace == oldTableSpace ||
5964                 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
5965         {
5966                 relation_close(rel, NoLock);
5967                 return;
5968         }
5969
5970         reltoastrelid = rel->rd_rel->reltoastrelid;
5971         reltoastidxid = rel->rd_rel->reltoastidxid;
5972
5973         /* Get a modifiable copy of the relation's pg_class row */
5974         pg_class = heap_open(RelationRelationId, RowExclusiveLock);
5975
5976         tuple = SearchSysCacheCopy(RELOID,
5977                                                            ObjectIdGetDatum(tableOid),
5978                                                            0, 0, 0);
5979         if (!HeapTupleIsValid(tuple))
5980                 elog(ERROR, "cache lookup failed for relation %u", tableOid);
5981         rd_rel = (Form_pg_class) GETSTRUCT(tuple);
5982
5983         /* create another storage file. Is it a little ugly ? */
5984         /* NOTE: any conflict in relfilenode value will be caught here */
5985         newrnode = rel->rd_node;
5986         newrnode.spcNode = newTableSpace;
5987
5988         dstrel = smgropen(newrnode);
5989         smgrcreate(dstrel, rel->rd_istemp, false);
5990
5991         /* copy relation data to the new physical file */
5992         copy_relation_data(rel, dstrel);
5993
5994         /* schedule unlinking old physical file */
5995         RelationOpenSmgr(rel);
5996         smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
5997
5998         /*
5999          * Now drop smgr references.  The source was already dropped by
6000          * smgrscheduleunlink.
6001          */
6002         smgrclose(dstrel);
6003
6004         /* update the pg_class row */
6005         rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6006         simple_heap_update(pg_class, &tuple->t_self, tuple);
6007         CatalogUpdateIndexes(pg_class, tuple);
6008
6009         heap_freetuple(tuple);
6010
6011         heap_close(pg_class, RowExclusiveLock);
6012
6013         relation_close(rel, NoLock);
6014
6015         /* Make sure the reltablespace change is visible */
6016         CommandCounterIncrement();
6017
6018         /* Move associated toast relation and/or index, too */
6019         if (OidIsValid(reltoastrelid))
6020                 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6021         if (OidIsValid(reltoastidxid))
6022                 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6023 }
6024
6025 /*
6026  * Copy data, block by block
6027  */
6028 static void
6029 copy_relation_data(Relation rel, SMgrRelation dst)
6030 {
6031         SMgrRelation src;
6032         bool            use_wal;
6033         BlockNumber nblocks;
6034         BlockNumber blkno;
6035         char            buf[BLCKSZ];
6036         Page            page = (Page) buf;
6037
6038         /*
6039          * Since we copy the file directly without looking at the shared buffers,
6040          * we'd better first flush out any pages of the source relation that are
6041          * in shared buffers.  We assume no new changes will be made while we are
6042          * holding exclusive lock on the rel.
6043          */
6044         FlushRelationBuffers(rel);
6045
6046         /*
6047          * We need to log the copied data in WAL iff WAL archiving is enabled AND
6048          * it's not a temp rel.
6049          */
6050         use_wal = XLogArchivingActive() && !rel->rd_istemp;
6051
6052         nblocks = RelationGetNumberOfBlocks(rel);
6053         /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
6054         src = rel->rd_smgr;
6055
6056         for (blkno = 0; blkno < nblocks; blkno++)
6057         {
6058                 smgrread(src, blkno, buf);
6059
6060                 /* XLOG stuff */
6061                 if (use_wal)
6062                         log_newpage(&dst->smgr_rnode, blkno, page);
6063
6064                 /*
6065                  * Now write the page.  We say isTemp = true even if it's not a temp
6066                  * rel, because there's no need for smgr to schedule an fsync for this
6067                  * write; we'll do it ourselves below.
6068                  */
6069                 smgrextend(dst, blkno, buf, true);
6070         }
6071
6072         /*
6073          * If the rel isn't temp, we must fsync it down to disk before it's safe
6074          * to commit the transaction.  (For a temp rel we don't care since the rel
6075          * will be uninteresting after a crash anyway.)
6076          *
6077          * It's obvious that we must do this when not WAL-logging the copy. It's
6078          * less obvious that we have to do it even if we did WAL-log the copied
6079          * pages. The reason is that since we're copying outside shared buffers, a
6080          * CHECKPOINT occurring during the copy has no way to flush the previously
6081          * written data to disk (indeed it won't know the new rel even exists).  A
6082          * crash later on would replay WAL from the checkpoint, therefore it
6083          * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6084          * here, they might still not be on disk when the crash occurs.
6085          */
6086         if (!rel->rd_istemp)
6087                 smgrimmedsync(dst);
6088 }
6089
6090 /*
6091  * ALTER TABLE ENABLE/DISABLE TRIGGER
6092  *
6093  * We just pass this off to trigger.c.
6094  */
6095 static void
6096 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6097                                                    char fires_when, bool skip_system)
6098 {
6099         EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6100 }
6101
6102 /*
6103  * ALTER TABLE ENABLE/DISABLE RULE
6104  *
6105  * We just pass this off to rewriteDefine.c.
6106  */
6107 static void
6108 ATExecEnableDisableRule(Relation rel, char *trigname,
6109                                                 char fires_when)
6110 {
6111         EnableDisableRule(rel, trigname, fires_when);
6112 }
6113
6114 /*
6115  * ALTER TABLE INHERIT
6116  *
6117  * Add a parent to the child's parents. This verifies that all the columns and
6118  * check constraints of the parent appear in the child and that they have the
6119  * same data types and expressions.
6120  */
6121 static void
6122 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6123 {
6124         Relation        parent_rel,
6125                                 catalogRelation;
6126         SysScanDesc scan;
6127         ScanKeyData key;
6128         HeapTuple       inheritsTuple;
6129         int32           inhseqno;
6130         List       *children;
6131
6132         /*
6133          * AccessShareLock on the parent is what's obtained during normal CREATE
6134          * TABLE ... INHERITS ..., so should be enough here.
6135          */
6136         parent_rel = heap_openrv(parent, AccessShareLock);
6137
6138         /*
6139          * Must be owner of both parent and child -- child was checked by
6140          * ATSimplePermissions call in ATPrepCmd
6141          */
6142         ATSimplePermissions(parent_rel, false);
6143
6144         /* Permanent rels cannot inherit from temporary ones */
6145         if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6146                 isTempNamespace(RelationGetNamespace(parent_rel)))
6147                 ereport(ERROR,
6148                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6149                                  errmsg("cannot inherit from temporary relation \"%s\"",
6150                                                 RelationGetRelationName(parent_rel))));
6151
6152         /*
6153          * Check for duplicates in the list of parents, and determine the highest
6154          * inhseqno already present; we'll use the next one for the new parent.
6155          * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6156          *
6157          * Note: we do not reject the case where the child already inherits from
6158          * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6159          */
6160         catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6161         ScanKeyInit(&key,
6162                                 Anum_pg_inherits_inhrelid,
6163                                 BTEqualStrategyNumber, F_OIDEQ,
6164                                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6165         scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6166                                                           true, SnapshotNow, 1, &key);
6167
6168         /* inhseqno sequences start at 1 */
6169         inhseqno = 0;
6170         while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6171         {
6172                 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6173
6174                 if (inh->inhparent == RelationGetRelid(parent_rel))
6175                         ereport(ERROR,
6176                                         (errcode(ERRCODE_DUPLICATE_TABLE),
6177                          errmsg("relation \"%s\" would be inherited from more than once",
6178                                         RelationGetRelationName(parent_rel))));
6179                 if (inh->inhseqno > inhseqno)
6180                         inhseqno = inh->inhseqno;
6181         }
6182         systable_endscan(scan);
6183
6184         /*
6185          * Prevent circularity by seeing if proposed parent inherits from child.
6186          * (In particular, this disallows making a rel inherit from itself.)
6187          *
6188          * This is not completely bulletproof because of race conditions: in
6189          * multi-level inheritance trees, someone else could concurrently be
6190          * making another inheritance link that closes the loop but does not join
6191          * either of the rels we have locked.  Preventing that seems to require
6192          * exclusive locks on the entire inheritance tree, which is a cure worse
6193          * than the disease.  find_all_inheritors() will cope with circularity
6194          * anyway, so don't sweat it too much.
6195          */
6196         children = find_all_inheritors(RelationGetRelid(child_rel));
6197
6198         if (list_member_oid(children, RelationGetRelid(parent_rel)))
6199                 ereport(ERROR,
6200                                 (errcode(ERRCODE_DUPLICATE_TABLE),
6201                                  errmsg("circular inheritance not allowed"),
6202                                  errdetail("\"%s\" is already a child of \"%s\".",
6203                                                    parent->relname,
6204                                                    RelationGetRelationName(child_rel))));
6205
6206         /* If parent has OIDs then child must have OIDs */
6207         if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6208                 ereport(ERROR,
6209                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6210                                  errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6211                                                 RelationGetRelationName(child_rel),
6212                                                 RelationGetRelationName(parent_rel))));
6213
6214         /* Match up the columns and bump attinhcount and attislocal */
6215         MergeAttributesIntoExisting(child_rel, parent_rel);
6216
6217         /* Match up the constraints and make sure they're present in child */
6218         MergeConstraintsIntoExisting(child_rel, parent_rel);
6219
6220         /*
6221          * OK, it looks valid.  Make the catalog entries that show inheritance.
6222          */
6223         StoreCatalogInheritance1(RelationGetRelid(child_rel),
6224                                                          RelationGetRelid(parent_rel),
6225                                                          inhseqno + 1,
6226                                                          catalogRelation);
6227
6228         /* Now we're done with pg_inherits */
6229         heap_close(catalogRelation, RowExclusiveLock);
6230
6231         /* keep our lock on the parent relation until commit */
6232         heap_close(parent_rel, NoLock);
6233 }
6234
6235 /*
6236  * Obtain the source-text form of the constraint expression for a check
6237  * constraint, given its pg_constraint tuple
6238  */
6239 static char *
6240 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6241 {
6242         Form_pg_constraint con;
6243         bool            isnull;
6244         Datum           attr;
6245         Datum           expr;
6246
6247         con = (Form_pg_constraint) GETSTRUCT(contup);
6248         attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6249         if (isnull)
6250                 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6251
6252         expr = DirectFunctionCall2(pg_get_expr, attr,
6253                                                            ObjectIdGetDatum(con->conrelid));
6254         return TextDatumGetCString(expr);
6255 }
6256
6257 /*
6258  * Check columns in child table match up with columns in parent, and increment
6259  * their attinhcount.
6260  *
6261  * Called by ATExecAddInherit
6262  *
6263  * Currently all parent columns must be found in child. Missing columns are an
6264  * error.  One day we might consider creating new columns like CREATE TABLE
6265  * does.  However, that is widely unpopular --- in the common use case of
6266  * partitioned tables it's a foot-gun.
6267  *
6268  * The data type must match exactly. If the parent column is NOT NULL then
6269  * the child must be as well. Defaults are not compared, however.
6270  */
6271 static void
6272 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6273 {
6274         Relation        attrrel;
6275         AttrNumber      parent_attno;
6276         int                     parent_natts;
6277         TupleDesc       tupleDesc;
6278         TupleConstr *constr;
6279         HeapTuple       tuple;
6280
6281         attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6282
6283         tupleDesc = RelationGetDescr(parent_rel);
6284         parent_natts = tupleDesc->natts;
6285         constr = tupleDesc->constr;
6286
6287         for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6288         {
6289                 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6290                 char       *attributeName = NameStr(attribute->attname);
6291
6292                 /* Ignore dropped columns in the parent. */
6293                 if (attribute->attisdropped)
6294                         continue;
6295
6296                 /* Find same column in child (matching on column name). */
6297                 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6298                                                                                   attributeName);
6299                 if (HeapTupleIsValid(tuple))
6300                 {
6301                         /* Check they are same type and typmod */
6302                         Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6303
6304                         if (attribute->atttypid != childatt->atttypid ||
6305                                 attribute->atttypmod != childatt->atttypmod)
6306                                 ereport(ERROR,
6307                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
6308                                                  errmsg("child table \"%s\" has different type for column \"%s\"",
6309                                                                 RelationGetRelationName(child_rel),
6310                                                                 attributeName)));
6311
6312                         if (attribute->attnotnull && !childatt->attnotnull)
6313                                 ereport(ERROR,
6314                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
6315                                 errmsg("column \"%s\" in child table must be marked NOT NULL",
6316                                            attributeName)));
6317
6318                         /*
6319                          * OK, bump the child column's inheritance count.  (If we fail
6320                          * later on, this change will just roll back.)
6321                          */
6322                         childatt->attinhcount++;
6323                         simple_heap_update(attrrel, &tuple->t_self, tuple);
6324                         CatalogUpdateIndexes(attrrel, tuple);
6325                         heap_freetuple(tuple);
6326                 }
6327                 else
6328                 {
6329                         ereport(ERROR,
6330                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
6331                                          errmsg("child table is missing column \"%s\"",
6332                                                         attributeName)));
6333                 }
6334         }
6335
6336         heap_close(attrrel, RowExclusiveLock);
6337 }
6338
6339 /*
6340  * Check constraints in child table match up with constraints in parent
6341  *
6342  * Called by ATExecAddInherit
6343  *
6344  * Currently all constraints in parent must be present in the child. One day we
6345  * may consider adding new constraints like CREATE TABLE does. We may also want
6346  * to allow an optional flag on parent table constraints indicating they are
6347  * intended to ONLY apply to the master table, not to the children. That would
6348  * make it possible to ensure no records are mistakenly inserted into the
6349  * master in partitioned tables rather than the appropriate child.
6350  *
6351  * XXX This is O(N^2) which may be an issue with tables with hundreds of
6352  * constraints. As long as tables have more like 10 constraints it shouldn't be
6353  * a problem though. Even 100 constraints ought not be the end of the world.
6354  */
6355 static void
6356 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6357 {
6358         Relation        catalogRelation;
6359         TupleDesc       tupleDesc;
6360         SysScanDesc scan;
6361         ScanKeyData key;
6362         HeapTuple       constraintTuple;
6363         ListCell   *elem;
6364         List       *constraints;
6365
6366         /* First gather up the child's constraint definitions */
6367         catalogRelation = heap_open(ConstraintRelationId, AccessShareLock);
6368         tupleDesc = RelationGetDescr(catalogRelation);
6369
6370         ScanKeyInit(&key,
6371                                 Anum_pg_constraint_conrelid,
6372                                 BTEqualStrategyNumber, F_OIDEQ,
6373                                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6374         scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
6375                                                           true, SnapshotNow, 1, &key);
6376
6377         constraints = NIL;
6378         while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6379         {
6380                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6381
6382                 if (con->contype != CONSTRAINT_CHECK)
6383                         continue;
6384
6385                 constraints = lappend(constraints, heap_copytuple(constraintTuple));
6386         }
6387
6388         systable_endscan(scan);
6389
6390         /* Then scan through the parent's constraints looking for matches */
6391         ScanKeyInit(&key,
6392                                 Anum_pg_constraint_conrelid,
6393                                 BTEqualStrategyNumber, F_OIDEQ,
6394                                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6395         scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId, true,
6396                                                           SnapshotNow, 1, &key);
6397
6398         while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6399         {
6400                 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6401                 bool            found = false;
6402                 Form_pg_constraint child_con = NULL;
6403                 HeapTuple       child_contuple = NULL;
6404
6405                 if (parent_con->contype != CONSTRAINT_CHECK)
6406                         continue;
6407
6408                 foreach(elem, constraints)
6409                 {
6410                         child_contuple = (HeapTuple) lfirst(elem);
6411                         child_con = (Form_pg_constraint) GETSTRUCT(child_contuple);
6412                         if (strcmp(NameStr(parent_con->conname),
6413                                            NameStr(child_con->conname)) == 0)
6414                         {
6415                                 found = true;
6416                                 break;
6417                         }
6418                 }
6419
6420                 if (!found)
6421                         ereport(ERROR,
6422                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
6423                                          errmsg("child table is missing constraint \"%s\"",
6424                                                         NameStr(parent_con->conname))));
6425
6426                 if (parent_con->condeferrable != child_con->condeferrable ||
6427                         parent_con->condeferred != child_con->condeferred ||
6428                         strcmp(decompile_conbin(constraintTuple, tupleDesc),
6429                                    decompile_conbin(child_contuple, tupleDesc)) != 0)
6430                         ereport(ERROR,
6431                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
6432                                          errmsg("constraint definition for check constraint \"%s\" does not match",
6433                                                         NameStr(parent_con->conname))));
6434
6435                 /*
6436                  * TODO: add conislocal,coninhcount to constraints. This is where we
6437                  * would have to bump them just like attributes
6438                  */
6439         }
6440
6441         systable_endscan(scan);
6442         heap_close(catalogRelation, AccessShareLock);
6443 }
6444
6445 /*
6446  * ALTER TABLE NO INHERIT
6447  *
6448  * Drop a parent from the child's parents. This just adjusts the attinhcount
6449  * and attislocal of the columns and removes the pg_inherit and pg_depend
6450  * entries.
6451  *
6452  * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
6453  * up attislocal stays true, which means if a child is ever removed from a
6454  * parent then its columns will never be automatically dropped which may
6455  * surprise. But at least we'll never surprise by dropping columns someone
6456  * isn't expecting to be dropped which would actually mean data loss.
6457  */
6458 static void
6459 ATExecDropInherit(Relation rel, RangeVar *parent)
6460 {
6461         Relation        parent_rel;
6462         Relation        catalogRelation;
6463         SysScanDesc scan;
6464         ScanKeyData key[3];
6465         HeapTuple       inheritsTuple,
6466                                 attributeTuple,
6467                                 depTuple;
6468         bool            found = false;
6469
6470         /*
6471          * AccessShareLock on the parent is probably enough, seeing that DROP
6472          * TABLE doesn't lock parent tables at all.  We need some lock since we'll
6473          * be inspecting the parent's schema.
6474          */
6475         parent_rel = heap_openrv(parent, AccessShareLock);
6476
6477         /*
6478          * We don't bother to check ownership of the parent table --- ownership of
6479          * the child is presumed enough rights.
6480          */
6481
6482         /*
6483          * Find and destroy the pg_inherits entry linking the two, or error out if
6484          * there is none.
6485          */
6486         catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6487         ScanKeyInit(&key[0],
6488                                 Anum_pg_inherits_inhrelid,
6489                                 BTEqualStrategyNumber, F_OIDEQ,
6490                                 ObjectIdGetDatum(RelationGetRelid(rel)));
6491         scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6492                                                           true, SnapshotNow, 1, key);
6493
6494         while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6495         {
6496                 Oid                     inhparent;
6497
6498                 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
6499                 if (inhparent == RelationGetRelid(parent_rel))
6500                 {
6501                         simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
6502                         found = true;
6503                         break;
6504                 }
6505         }
6506
6507         systable_endscan(scan);
6508         heap_close(catalogRelation, RowExclusiveLock);
6509
6510         if (!found)
6511                 ereport(ERROR,
6512                                 (errcode(ERRCODE_UNDEFINED_TABLE),
6513                                  errmsg("relation \"%s\" is not a parent of relation \"%s\"",
6514                                                 RelationGetRelationName(parent_rel),
6515                                                 RelationGetRelationName(rel))));
6516
6517         /*
6518          * Search through child columns looking for ones matching parent rel
6519          */
6520         catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
6521         ScanKeyInit(&key[0],
6522                                 Anum_pg_attribute_attrelid,
6523                                 BTEqualStrategyNumber, F_OIDEQ,
6524                                 ObjectIdGetDatum(RelationGetRelid(rel)));
6525         scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
6526                                                           true, SnapshotNow, 1, key);
6527         while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
6528         {
6529                 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
6530
6531                 /* Ignore if dropped or not inherited */
6532                 if (att->attisdropped)
6533                         continue;
6534                 if (att->attinhcount <= 0)
6535                         continue;
6536
6537                 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
6538                                                                                 NameStr(att->attname)))
6539                 {
6540                         /* Decrement inhcount and possibly set islocal to true */
6541                         HeapTuple       copyTuple = heap_copytuple(attributeTuple);
6542                         Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
6543
6544                         copy_att->attinhcount--;
6545                         if (copy_att->attinhcount == 0)
6546                                 copy_att->attislocal = true;
6547
6548                         simple_heap_update(catalogRelation, &copyTuple->t_self, copyTuple);
6549                         CatalogUpdateIndexes(catalogRelation, copyTuple);
6550                         heap_freetuple(copyTuple);
6551                 }
6552         }
6553         systable_endscan(scan);
6554         heap_close(catalogRelation, RowExclusiveLock);
6555
6556         /*
6557          * Drop the dependency
6558          *
6559          * There's no convenient way to do this, so go trawling through pg_depend
6560          */
6561         catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
6562
6563         ScanKeyInit(&key[0],
6564                                 Anum_pg_depend_classid,
6565                                 BTEqualStrategyNumber, F_OIDEQ,
6566                                 ObjectIdGetDatum(RelationRelationId));
6567         ScanKeyInit(&key[1],
6568                                 Anum_pg_depend_objid,
6569                                 BTEqualStrategyNumber, F_OIDEQ,
6570                                 ObjectIdGetDatum(RelationGetRelid(rel)));
6571         ScanKeyInit(&key[2],
6572                                 Anum_pg_depend_objsubid,
6573                                 BTEqualStrategyNumber, F_INT4EQ,
6574                                 Int32GetDatum(0));
6575
6576         scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
6577                                                           SnapshotNow, 3, key);
6578
6579         while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
6580         {
6581                 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
6582
6583                 if (dep->refclassid == RelationRelationId &&
6584                         dep->refobjid == RelationGetRelid(parent_rel) &&
6585                         dep->refobjsubid == 0 &&
6586                         dep->deptype == DEPENDENCY_NORMAL)
6587                         simple_heap_delete(catalogRelation, &depTuple->t_self);
6588         }
6589
6590         systable_endscan(scan);
6591         heap_close(catalogRelation, RowExclusiveLock);
6592
6593         /* keep our lock on the parent relation until commit */
6594         heap_close(parent_rel, NoLock);
6595 }
6596
6597
6598 /*
6599  * Execute ALTER TABLE SET SCHEMA
6600  *
6601  * Note: caller must have checked ownership of the relation already
6602  */
6603 void
6604 AlterTableNamespace(RangeVar *relation, const char *newschema)
6605 {
6606         Relation        rel;
6607         Oid                     relid;
6608         Oid                     oldNspOid;
6609         Oid                     nspOid;
6610         Relation        classRel;
6611
6612         rel = relation_openrv(relation, AccessExclusiveLock);
6613
6614         relid = RelationGetRelid(rel);
6615         oldNspOid = RelationGetNamespace(rel);
6616
6617         /* Can we change the schema of this tuple? */
6618         switch (rel->rd_rel->relkind)
6619         {
6620                 case RELKIND_RELATION:
6621                 case RELKIND_VIEW:
6622                         /* ok to change schema */
6623                         break;
6624                 case RELKIND_SEQUENCE:
6625                         {
6626                                 /* if it's an owned sequence, disallow moving it by itself */
6627                                 Oid                     tableId;
6628                                 int32           colId;
6629
6630                                 if (sequenceIsOwned(relid, &tableId, &colId))
6631                                         ereport(ERROR,
6632                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6633                                                          errmsg("cannot move an owned sequence into another schema"),
6634                                           errdetail("Sequence \"%s\" is linked to table \"%s\".",
6635                                                                 RelationGetRelationName(rel),
6636                                                                 get_rel_name(tableId))));
6637                         }
6638                         break;
6639                 case RELKIND_COMPOSITE_TYPE:
6640                         ereport(ERROR,
6641                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6642                                          errmsg("\"%s\" is a composite type",
6643                                                         RelationGetRelationName(rel)),
6644                                          errhint("Use ALTER TYPE instead.")));
6645                         break;
6646                 case RELKIND_INDEX:
6647                 case RELKIND_TOASTVALUE:
6648                         /* FALL THRU */
6649                 default:
6650                         ereport(ERROR,
6651                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6652                                          errmsg("\"%s\" is not a table, view, or sequence",
6653                                                         RelationGetRelationName(rel))));
6654         }
6655
6656         /* get schema OID and check its permissions */
6657         nspOid = LookupCreationNamespace(newschema);
6658
6659         if (oldNspOid == nspOid)
6660                 ereport(ERROR,
6661                                 (errcode(ERRCODE_DUPLICATE_TABLE),
6662                                  errmsg("relation \"%s\" is already in schema \"%s\"",
6663                                                 RelationGetRelationName(rel),
6664                                                 newschema)));
6665
6666         /* disallow renaming into or out of temp schemas */
6667         if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
6668                 ereport(ERROR,
6669                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6670                         errmsg("cannot move objects into or out of temporary schemas")));
6671
6672         /* same for TOAST schema */
6673         if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
6674                 ereport(ERROR,
6675                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6676                                  errmsg("cannot move objects into or out of TOAST schema")));
6677
6678         /* OK, modify the pg_class row and pg_depend entry */
6679         classRel = heap_open(RelationRelationId, RowExclusiveLock);
6680
6681         AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
6682
6683         /* Fix the table's rowtype too */
6684         AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
6685
6686         /* Fix other dependent stuff */
6687         if (rel->rd_rel->relkind == RELKIND_RELATION)
6688         {
6689                 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
6690                 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
6691                 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
6692         }
6693
6694         heap_close(classRel, RowExclusiveLock);
6695
6696         /* close rel, but keep lock until commit */
6697         relation_close(rel, NoLock);
6698 }
6699
6700 /*
6701  * The guts of relocating a relation to another namespace: fix the pg_class
6702  * entry, and the pg_depend entry if any.  Caller must already have
6703  * opened and write-locked pg_class.
6704  */
6705 void
6706 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
6707                                                            Oid oldNspOid, Oid newNspOid,
6708                                                            bool hasDependEntry)
6709 {
6710         HeapTuple       classTup;
6711         Form_pg_class classForm;
6712
6713         classTup = SearchSysCacheCopy(RELOID,
6714                                                                   ObjectIdGetDatum(relOid),
6715                                                                   0, 0, 0);
6716         if (!HeapTupleIsValid(classTup))
6717                 elog(ERROR, "cache lookup failed for relation %u", relOid);
6718         classForm = (Form_pg_class) GETSTRUCT(classTup);
6719
6720         Assert(classForm->relnamespace == oldNspOid);
6721
6722         /* check for duplicate name (more friendly than unique-index failure) */
6723         if (get_relname_relid(NameStr(classForm->relname),
6724                                                   newNspOid) != InvalidOid)
6725                 ereport(ERROR,
6726                                 (errcode(ERRCODE_DUPLICATE_TABLE),
6727                                  errmsg("relation \"%s\" already exists in schema \"%s\"",
6728                                                 NameStr(classForm->relname),
6729                                                 get_namespace_name(newNspOid))));
6730
6731         /* classTup is a copy, so OK to scribble on */
6732         classForm->relnamespace = newNspOid;
6733
6734         simple_heap_update(classRel, &classTup->t_self, classTup);
6735         CatalogUpdateIndexes(classRel, classTup);
6736
6737         /* Update dependency on schema if caller said so */
6738         if (hasDependEntry &&
6739                 changeDependencyFor(RelationRelationId, relOid,
6740                                                         NamespaceRelationId, oldNspOid, newNspOid) != 1)
6741                 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
6742                          NameStr(classForm->relname));
6743
6744         heap_freetuple(classTup);
6745 }
6746
6747 /*
6748  * Move all indexes for the specified relation to another namespace.
6749  *
6750  * Note: we assume adequate permission checking was done by the caller,
6751  * and that the caller has a suitable lock on the owning relation.
6752  */
6753 static void
6754 AlterIndexNamespaces(Relation classRel, Relation rel,
6755                                          Oid oldNspOid, Oid newNspOid)
6756 {
6757         List       *indexList;
6758         ListCell   *l;
6759
6760         indexList = RelationGetIndexList(rel);
6761
6762         foreach(l, indexList)
6763         {
6764                 Oid                     indexOid = lfirst_oid(l);
6765
6766                 /*
6767                  * Note: currently, the index will not have its own dependency on the
6768                  * namespace, so we don't need to do changeDependencyFor(). There's no
6769                  * rowtype in pg_type, either.
6770                  */
6771                 AlterRelationNamespaceInternal(classRel, indexOid,
6772                                                                            oldNspOid, newNspOid,
6773                                                                            false);
6774         }
6775
6776         list_free(indexList);
6777 }
6778
6779 /*
6780  * Move all SERIAL-column sequences of the specified relation to another
6781  * namespace.
6782  *
6783  * Note: we assume adequate permission checking was done by the caller,
6784  * and that the caller has a suitable lock on the owning relation.
6785  */
6786 static void
6787 AlterSeqNamespaces(Relation classRel, Relation rel,
6788                                    Oid oldNspOid, Oid newNspOid, const char *newNspName)
6789 {
6790         Relation        depRel;
6791         SysScanDesc scan;
6792         ScanKeyData key[2];
6793         HeapTuple       tup;
6794
6795         /*
6796          * SERIAL sequences are those having an auto dependency on one of the
6797          * table's columns (we don't care *which* column, exactly).
6798          */
6799         depRel = heap_open(DependRelationId, AccessShareLock);
6800
6801         ScanKeyInit(&key[0],
6802                                 Anum_pg_depend_refclassid,
6803                                 BTEqualStrategyNumber, F_OIDEQ,
6804                                 ObjectIdGetDatum(RelationRelationId));
6805         ScanKeyInit(&key[1],
6806                                 Anum_pg_depend_refobjid,
6807                                 BTEqualStrategyNumber, F_OIDEQ,
6808                                 ObjectIdGetDatum(RelationGetRelid(rel)));
6809         /* we leave refobjsubid unspecified */
6810
6811         scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6812                                                           SnapshotNow, 2, key);
6813
6814         while (HeapTupleIsValid(tup = systable_getnext(scan)))
6815         {
6816                 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6817                 Relation        seqRel;
6818
6819                 /* skip dependencies other than auto dependencies on columns */
6820                 if (depForm->refobjsubid == 0 ||
6821                         depForm->classid != RelationRelationId ||
6822                         depForm->objsubid != 0 ||
6823                         depForm->deptype != DEPENDENCY_AUTO)
6824                         continue;
6825
6826                 /* Use relation_open just in case it's an index */
6827                 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6828
6829                 /* skip non-sequence relations */
6830                 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6831                 {
6832                         /* No need to keep the lock */
6833                         relation_close(seqRel, AccessExclusiveLock);
6834                         continue;
6835                 }
6836
6837                 /* Fix the pg_class and pg_depend entries */
6838                 AlterRelationNamespaceInternal(classRel, depForm->objid,
6839                                                                            oldNspOid, newNspOid,
6840                                                                            true);
6841
6842                 /*
6843                  * Sequences have entries in pg_type. We need to be careful to move
6844                  * them to the new namespace, too.
6845                  */
6846                 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
6847                                                                    newNspOid, false, false);
6848
6849                 /* Now we can close it.  Keep the lock till end of transaction. */
6850                 relation_close(seqRel, NoLock);
6851         }
6852
6853         systable_endscan(scan);
6854
6855         relation_close(depRel, AccessShareLock);
6856 }
6857
6858
6859 /*
6860  * This code supports
6861  *      CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
6862  *
6863  * Because we only support this for TEMP tables, it's sufficient to remember
6864  * the state in a backend-local data structure.
6865  */
6866
6867 /*
6868  * Register a newly-created relation's ON COMMIT action.
6869  */
6870 void
6871 register_on_commit_action(Oid relid, OnCommitAction action)
6872 {
6873         OnCommitItem *oc;
6874         MemoryContext oldcxt;
6875
6876         /*
6877          * We needn't bother registering the relation unless there is an ON COMMIT
6878          * action we need to take.
6879          */
6880         if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
6881                 return;
6882
6883         oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
6884
6885         oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
6886         oc->relid = relid;
6887         oc->oncommit = action;
6888         oc->creating_subid = GetCurrentSubTransactionId();
6889         oc->deleting_subid = InvalidSubTransactionId;
6890
6891         on_commits = lcons(oc, on_commits);
6892
6893         MemoryContextSwitchTo(oldcxt);
6894 }
6895
6896 /*
6897  * Unregister any ON COMMIT action when a relation is deleted.
6898  *
6899  * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
6900  */
6901 void
6902 remove_on_commit_action(Oid relid)
6903 {
6904         ListCell   *l;
6905
6906         foreach(l, on_commits)
6907         {
6908                 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6909
6910                 if (oc->relid == relid)
6911                 {
6912                         oc->deleting_subid = GetCurrentSubTransactionId();
6913                         break;
6914                 }
6915         }
6916 }
6917
6918 /*
6919  * Perform ON COMMIT actions.
6920  *
6921  * This is invoked just before actually committing, since it's possible
6922  * to encounter errors.
6923  */
6924 void
6925 PreCommit_on_commit_actions(void)
6926 {
6927         ListCell   *l;
6928         List       *oids_to_truncate = NIL;
6929
6930         foreach(l, on_commits)
6931         {
6932                 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6933
6934                 /* Ignore entry if already dropped in this xact */
6935                 if (oc->deleting_subid != InvalidSubTransactionId)
6936                         continue;
6937
6938                 switch (oc->oncommit)
6939                 {
6940                         case ONCOMMIT_NOOP:
6941                         case ONCOMMIT_PRESERVE_ROWS:
6942                                 /* Do nothing (there shouldn't be such entries, actually) */
6943                                 break;
6944                         case ONCOMMIT_DELETE_ROWS:
6945                                 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
6946                                 break;
6947                         case ONCOMMIT_DROP:
6948                                 {
6949                                         ObjectAddress object;
6950
6951                                         object.classId = RelationRelationId;
6952                                         object.objectId = oc->relid;
6953                                         object.objectSubId = 0;
6954                                         performDeletion(&object, DROP_CASCADE);
6955
6956                                         /*
6957                                          * Note that table deletion will call
6958                                          * remove_on_commit_action, so the entry should get marked
6959                                          * as deleted.
6960                                          */
6961                                         Assert(oc->deleting_subid != InvalidSubTransactionId);
6962                                         break;
6963                                 }
6964                 }
6965         }
6966         if (oids_to_truncate != NIL)
6967         {
6968                 heap_truncate(oids_to_truncate);
6969                 CommandCounterIncrement();              /* XXX needed? */
6970         }
6971 }
6972
6973 /*
6974  * Post-commit or post-abort cleanup for ON COMMIT management.
6975  *
6976  * All we do here is remove no-longer-needed OnCommitItem entries.
6977  *
6978  * During commit, remove entries that were deleted during this transaction;
6979  * during abort, remove those created during this transaction.
6980  */
6981 void
6982 AtEOXact_on_commit_actions(bool isCommit)
6983 {
6984         ListCell   *cur_item;
6985         ListCell   *prev_item;
6986
6987         prev_item = NULL;
6988         cur_item = list_head(on_commits);
6989
6990         while (cur_item != NULL)
6991         {
6992                 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6993
6994                 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
6995                         oc->creating_subid != InvalidSubTransactionId)
6996                 {
6997                         /* cur_item must be removed */
6998                         on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6999                         pfree(oc);
7000                         if (prev_item)
7001                                 cur_item = lnext(prev_item);
7002                         else
7003                                 cur_item = list_head(on_commits);
7004                 }
7005                 else
7006                 {
7007                         /* cur_item must be preserved */
7008                         oc->creating_subid = InvalidSubTransactionId;
7009                         oc->deleting_subid = InvalidSubTransactionId;
7010                         prev_item = cur_item;
7011                         cur_item = lnext(prev_item);
7012                 }
7013         }
7014 }
7015
7016 /*
7017  * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7018  *
7019  * During subabort, we can immediately remove entries created during this
7020  * subtransaction.      During subcommit, just relabel entries marked during
7021  * this subtransaction as being the parent's responsibility.
7022  */
7023 void
7024 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
7025                                                           SubTransactionId parentSubid)
7026 {
7027         ListCell   *cur_item;
7028         ListCell   *prev_item;
7029
7030         prev_item = NULL;
7031         cur_item = list_head(on_commits);
7032
7033         while (cur_item != NULL)
7034         {
7035                 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7036
7037                 if (!isCommit && oc->creating_subid == mySubid)
7038                 {
7039                         /* cur_item must be removed */
7040                         on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7041                         pfree(oc);
7042                         if (prev_item)
7043                                 cur_item = lnext(prev_item);
7044                         else
7045                                 cur_item = list_head(on_commits);
7046                 }
7047                 else
7048                 {
7049                         /* cur_item must be preserved */
7050                         if (oc->creating_subid == mySubid)
7051                                 oc->creating_subid = parentSubid;
7052                         if (oc->deleting_subid == mySubid)
7053                                 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7054                         prev_item = cur_item;
7055                         cur_item = lnext(prev_item);
7056                 }
7057         }
7058 }