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