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