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