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