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