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