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