OSDN Git Service

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