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