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