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