OSDN Git Service

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