1 /*-------------------------------------------------------------------------
2  *
3  * heap.c
4  *	  code to create and destroy POSTGRES heap relations
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/catalog/heap.c
12  *
13  *
14  * INTERFACE ROUTINES
15  *		heap_create()			- Create an uncataloged heap relation
16  *		heap_create_with_catalog() - Create a cataloged relation
17  *		heap_drop_with_catalog() - Removes named relation from catalogs
18  *
19  * NOTES
20  *	  this code taken from access/heap/create.c, which contains
21  *	  the old heap_create_with_catalog, amcreate, and amdestroy.
22  *	  those routines will soon call these routines using the function
23  *	  manager,
24  *	  just like the poorly named "NewXXX" routines do.  The
25  *	  "New" routines are all going to die soon, once and for all!
26  *		-cim 1/13/91
27  *
28  *-------------------------------------------------------------------------
29  */
30 #include "postgres.h"
31 
32 #include "access/htup_details.h"
33 #include "access/multixact.h"
34 #include "access/sysattr.h"
35 #include "access/transam.h"
36 #include "access/xact.h"
37 #include "access/xlog.h"
38 #include "catalog/binary_upgrade.h"
39 #include "catalog/catalog.h"
40 #include "catalog/dependency.h"
41 #include "catalog/heap.h"
42 #include "catalog/index.h"
43 #include "catalog/objectaccess.h"
44 #include "catalog/pg_attrdef.h"
45 #include "catalog/pg_collation.h"
46 #include "catalog/pg_constraint.h"
47 #include "catalog/pg_constraint_fn.h"
48 #include "catalog/pg_foreign_table.h"
49 #include "catalog/pg_inherits.h"
50 #include "catalog/pg_namespace.h"
51 #include "catalog/pg_statistic.h"
52 #include "catalog/pg_tablespace.h"
53 #include "catalog/pg_type.h"
54 #include "catalog/pg_type_fn.h"
55 #include "catalog/storage.h"
56 #include "catalog/storage_xlog.h"
57 #include "commands/tablecmds.h"
58 #include "commands/typecmds.h"
59 #include "miscadmin.h"
60 #include "nodes/nodeFuncs.h"
61 #include "optimizer/var.h"
62 #include "parser/parse_coerce.h"
63 #include "parser/parse_collate.h"
64 #include "parser/parse_expr.h"
65 #include "parser/parse_relation.h"
66 #include "storage/predicate.h"
67 #include "storage/smgr.h"
68 #include "utils/acl.h"
69 #include "utils/builtins.h"
70 #include "utils/fmgroids.h"
71 #include "utils/inval.h"
72 #include "utils/lsyscache.h"
73 #include "utils/rel.h"
74 #include "utils/ruleutils.h"
75 #include "utils/snapmgr.h"
76 #include "utils/syscache.h"
77 #include "utils/tqual.h"
78 
79 
80 /* Potentially set by pg_upgrade_support functions */
81 Oid			binary_upgrade_next_heap_pg_class_oid = InvalidOid;
82 Oid			binary_upgrade_next_toast_pg_class_oid = InvalidOid;
83 
84 static void AddNewRelationTuple(Relation pg_class_desc,
85 					Relation new_rel_desc,
86 					Oid new_rel_oid,
87 					Oid new_type_oid,
88 					Oid reloftype,
89 					Oid relowner,
90 					char relkind,
91 					Datum relacl,
92 					Datum reloptions);
93 static ObjectAddress AddNewRelationType(const char *typeName,
94 				   Oid typeNamespace,
95 				   Oid new_rel_oid,
96 				   char new_rel_kind,
97 				   Oid ownerid,
98 				   Oid new_row_type,
99 				   Oid new_array_type);
100 static void RelationRemoveInheritance(Oid relid);
101 static Oid StoreRelCheck(Relation rel, char *ccname, Node *expr,
102 			  bool is_validated, bool is_local, int inhcount,
103 			  bool is_no_inherit, bool is_internal);
104 static void StoreConstraints(Relation rel, List *cooked_constraints,
105 				 bool is_internal);
106 static bool MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
107 							bool allow_merge, bool is_local,
108 							bool is_initially_valid,
109 							bool is_no_inherit);
110 static void SetRelationNumChecks(Relation rel, int numchecks);
111 static Node *cookConstraint(ParseState *pstate,
112 			   Node *raw_constraint,
113 			   char *relname);
114 static List *insert_ordered_unique_oid(List *list, Oid datum);
115 
116 
117 /* ----------------------------------------------------------------
118  *				XXX UGLY HARD CODED BADNESS FOLLOWS XXX
119  *
120  *		these should all be moved to someplace in the lib/catalog
121  *		module, if not obliterated first.
122  * ----------------------------------------------------------------
123  */
124 
125 
126 /*
127  * Note:
128  *		Should the system special case these attributes in the future?
129  *		Advantage:	consume much less space in the ATTRIBUTE relation.
130  *		Disadvantage:  special cases will be all over the place.
131  */
132 
133 /*
134  * The initializers below do not include trailing variable length fields,
135  * but that's OK - we're never going to reference anything beyond the
136  * fixed-size portion of the structure anyway.
137  */
138 
139 static FormData_pg_attribute a1 = {
140 	0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
141 	SelfItemPointerAttributeNumber, 0, -1, -1,
142 	false, 'p', 's', true, false, false, true, 0
143 };
144 
145 static FormData_pg_attribute a2 = {
146 	0, {"oid"}, OIDOID, 0, sizeof(Oid),
147 	ObjectIdAttributeNumber, 0, -1, -1,
148 	true, 'p', 'i', true, false, false, true, 0
149 };
150 
151 static FormData_pg_attribute a3 = {
152 	0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
153 	MinTransactionIdAttributeNumber, 0, -1, -1,
154 	true, 'p', 'i', true, false, false, true, 0
155 };
156 
157 static FormData_pg_attribute a4 = {
158 	0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
159 	MinCommandIdAttributeNumber, 0, -1, -1,
160 	true, 'p', 'i', true, false, false, true, 0
161 };
162 
163 static FormData_pg_attribute a5 = {
164 	0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
165 	MaxTransactionIdAttributeNumber, 0, -1, -1,
166 	true, 'p', 'i', true, false, false, true, 0
167 };
168 
169 static FormData_pg_attribute a6 = {
170 	0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
171 	MaxCommandIdAttributeNumber, 0, -1, -1,
172 	true, 'p', 'i', true, false, false, true, 0
173 };
174 
175 /*
176  * We decided to call this attribute "tableoid" rather than say
177  * "classoid" on the basis that in the future there may be more than one
178  * table of a particular class/type. In any case table is still the word
179  * used in SQL.
180  */
181 static FormData_pg_attribute a7 = {
182 	0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
183 	TableOidAttributeNumber, 0, -1, -1,
184 	true, 'p', 'i', true, false, false, true, 0
185 };
186 
187 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
188 
189 /*
190  * This function returns a Form_pg_attribute pointer for a system attribute.
191  * Note that we elog if the presented attno is invalid, which would only
192  * happen if there's a problem upstream.
193  */
194 Form_pg_attribute
SystemAttributeDefinition(AttrNumber attno,bool relhasoids)195 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
196 {
197 	if (attno >= 0 || attno < -(int) lengthof(SysAtt))
198 		elog(ERROR, "invalid system attribute number %d", attno);
199 	if (attno == ObjectIdAttributeNumber && !relhasoids)
200 		elog(ERROR, "invalid system attribute number %d", attno);
201 	return SysAtt[-attno - 1];
202 }
203 
204 /*
205  * If the given name is a system attribute name, return a Form_pg_attribute
206  * pointer for a prototype definition.  If not, return NULL.
207  */
208 Form_pg_attribute
SystemAttributeByName(const char * attname,bool relhasoids)209 SystemAttributeByName(const char *attname, bool relhasoids)
210 {
211 	int			j;
212 
213 	for (j = 0; j < (int) lengthof(SysAtt); j++)
214 	{
215 		Form_pg_attribute att = SysAtt[j];
216 
217 		if (relhasoids || att->attnum != ObjectIdAttributeNumber)
218 		{
219 			if (strcmp(NameStr(att->attname), attname) == 0)
220 				return att;
221 		}
222 	}
223 
224 	return NULL;
225 }
226 
227 
228 /* ----------------------------------------------------------------
229  *				XXX END OF UGLY HARD CODED BADNESS XXX
230  * ---------------------------------------------------------------- */
231 
232 
233 /* ----------------------------------------------------------------
234  *		heap_create		- Create an uncataloged heap relation
235  *
236  *		Note API change: the caller must now always provide the OID
237  *		to use for the relation.  The relfilenode may (and, normally,
238  *		should) be left unspecified.
239  *
240  *		rel->rd_rel is initialized by RelationBuildLocalRelation,
241  *		and is mostly zeroes at return.
242  * ----------------------------------------------------------------
243  */
244 Relation
heap_create(const char * relname,Oid relnamespace,Oid reltablespace,Oid relid,Oid relfilenode,TupleDesc tupDesc,char relkind,char relpersistence,bool shared_relation,bool mapped_relation,bool allow_system_table_mods)245 heap_create(const char *relname,
246 			Oid relnamespace,
247 			Oid reltablespace,
248 			Oid relid,
249 			Oid relfilenode,
250 			TupleDesc tupDesc,
251 			char relkind,
252 			char relpersistence,
253 			bool shared_relation,
254 			bool mapped_relation,
255 			bool allow_system_table_mods)
256 {
257 	bool		create_storage;
258 	Relation	rel;
259 
260 	/* The caller must have provided an OID for the relation. */
261 	Assert(OidIsValid(relid));
262 
263 	/*
264 	 * Don't allow creating relations in pg_catalog directly, even though it
265 	 * is allowed to move user defined relations there. Semantics with search
266 	 * paths including pg_catalog are too confusing for now.
267 	 *
268 	 * But allow creating indexes on relations in pg_catalog even if
269 	 * allow_system_table_mods = off, upper layers already guarantee it's on a
270 	 * user defined relation, not a system one.
271 	 */
272 	if (!allow_system_table_mods &&
273 		((IsSystemNamespace(relnamespace) && relkind != RELKIND_INDEX) ||
274 		 IsToastNamespace(relnamespace)) &&
275 		IsNormalProcessingMode())
276 		ereport(ERROR,
277 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
278 				 errmsg("permission denied to create \"%s.%s\"",
279 						get_namespace_name(relnamespace), relname),
280 		errdetail("System catalog modifications are currently disallowed.")));
281 
282 	/*
283 	 * Decide if we need storage or not, and handle a couple other special
284 	 * cases for particular relkinds.
285 	 */
286 	switch (relkind)
287 	{
288 		case RELKIND_VIEW:
289 		case RELKIND_COMPOSITE_TYPE:
290 		case RELKIND_FOREIGN_TABLE:
291 			create_storage = false;
292 
293 			/*
294 			 * Force reltablespace to zero if the relation has no physical
295 			 * storage.  This is mainly just for cleanliness' sake.
296 			 */
297 			reltablespace = InvalidOid;
298 			break;
299 		case RELKIND_SEQUENCE:
300 			create_storage = true;
301 
302 			/*
303 			 * Force reltablespace to zero for sequences, since we don't
304 			 * support moving them around into different tablespaces.
305 			 */
306 			reltablespace = InvalidOid;
307 			break;
308 		default:
309 			create_storage = true;
310 			break;
311 	}
312 
313 	/*
314 	 * Unless otherwise requested, the physical ID (relfilenode) is initially
315 	 * the same as the logical ID (OID).  When the caller did specify a
316 	 * relfilenode, it already exists; do not attempt to create it.
317 	 */
318 	if (OidIsValid(relfilenode))
319 		create_storage = false;
320 	else
321 		relfilenode = relid;
322 
323 	/*
324 	 * Never allow a pg_class entry to explicitly specify the database's
325 	 * default tablespace in reltablespace; force it to zero instead. This
326 	 * ensures that if the database is cloned with a different default
327 	 * tablespace, the pg_class entry will still match where CREATE DATABASE
328 	 * will put the physically copied relation.
329 	 *
330 	 * Yes, this is a bit of a hack.
331 	 */
332 	if (reltablespace == MyDatabaseTableSpace)
333 		reltablespace = InvalidOid;
334 
335 	/*
336 	 * build the relcache entry.
337 	 */
338 	rel = RelationBuildLocalRelation(relname,
339 									 relnamespace,
340 									 tupDesc,
341 									 relid,
342 									 relfilenode,
343 									 reltablespace,
344 									 shared_relation,
345 									 mapped_relation,
346 									 relpersistence,
347 									 relkind);
348 
349 	/*
350 	 * Have the storage manager create the relation's disk file, if needed.
351 	 *
352 	 * We only create the main fork here, other forks will be created on
353 	 * demand.
354 	 */
355 	if (create_storage)
356 	{
357 		RelationOpenSmgr(rel);
358 		RelationCreateStorage(rel->rd_node, relpersistence);
359 	}
360 
361 	return rel;
362 }
363 
364 /* ----------------------------------------------------------------
365  *		heap_create_with_catalog		- Create a cataloged relation
366  *
367  *		this is done in multiple steps:
368  *
369  *		1) CheckAttributeNamesTypes() is used to make certain the tuple
370  *		   descriptor contains a valid set of attribute names and types
371  *
372  *		2) pg_class is opened and get_relname_relid()
373  *		   performs a scan to ensure that no relation with the
374  *		   same name already exists.
375  *
376  *		3) heap_create() is called to create the new relation on disk.
377  *
378  *		4) TypeCreate() is called to define a new type corresponding
379  *		   to the new relation.
380  *
381  *		5) AddNewRelationTuple() is called to register the
382  *		   relation in pg_class.
383  *
384  *		6) AddNewAttributeTuples() is called to register the
385  *		   new relation's schema in pg_attribute.
386  *
387  *		7) StoreConstraints is called ()		- vadim 08/22/97
388  *
389  *		8) the relations are closed and the new relation's oid
390  *		   is returned.
391  *
392  * ----------------------------------------------------------------
393  */
394 
395 /* --------------------------------
396  *		CheckAttributeNamesTypes
397  *
398  *		this is used to make certain the tuple descriptor contains a
399  *		valid set of attribute names and datatypes.  a problem simply
400  *		generates ereport(ERROR) which aborts the current transaction.
401  * --------------------------------
402  */
403 void
CheckAttributeNamesTypes(TupleDesc tupdesc,char relkind,bool allow_system_table_mods)404 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
405 						 bool allow_system_table_mods)
406 {
407 	int			i;
408 	int			j;
409 	int			natts = tupdesc->natts;
410 
411 	/* Sanity check on column count */
412 	if (natts < 0 || natts > MaxHeapAttributeNumber)
413 		ereport(ERROR,
414 				(errcode(ERRCODE_TOO_MANY_COLUMNS),
415 				 errmsg("tables can have at most %d columns",
416 						MaxHeapAttributeNumber)));
417 
418 	/*
419 	 * first check for collision with system attribute names
420 	 *
421 	 * Skip this for a view or type relation, since those don't have system
422 	 * attributes.
423 	 */
424 	if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
425 	{
426 		for (i = 0; i < natts; i++)
427 		{
428 			if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
429 									  tupdesc->tdhasoid) != NULL)
430 				ereport(ERROR,
431 						(errcode(ERRCODE_DUPLICATE_COLUMN),
432 						 errmsg("column name \"%s\" conflicts with a system column name",
433 								NameStr(tupdesc->attrs[i]->attname))));
434 		}
435 	}
436 
437 	/*
438 	 * next check for repeated attribute names
439 	 */
440 	for (i = 1; i < natts; i++)
441 	{
442 		for (j = 0; j < i; j++)
443 		{
444 			if (strcmp(NameStr(tupdesc->attrs[j]->attname),
445 					   NameStr(tupdesc->attrs[i]->attname)) == 0)
446 				ereport(ERROR,
447 						(errcode(ERRCODE_DUPLICATE_COLUMN),
448 						 errmsg("column name \"%s\" specified more than once",
449 								NameStr(tupdesc->attrs[j]->attname))));
450 		}
451 	}
452 
453 	/*
454 	 * next check the attribute types
455 	 */
456 	for (i = 0; i < natts; i++)
457 	{
458 		CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
459 						   tupdesc->attrs[i]->atttypid,
460 						   tupdesc->attrs[i]->attcollation,
461 						   NIL, /* assume we're creating a new rowtype */
462 						   allow_system_table_mods);
463 	}
464 }
465 
466 /* --------------------------------
467  *		CheckAttributeType
468  *
469  *		Verify that the proposed datatype of an attribute is legal.
470  *		This is needed mainly because there are types (and pseudo-types)
471  *		in the catalogs that we do not support as elements of real tuples.
472  *		We also check some other properties required of a table column.
473  *
474  * If the attribute is being proposed for addition to an existing table or
475  * composite type, pass a one-element list of the rowtype OID as
476  * containing_rowtypes.  When checking a to-be-created rowtype, it's
477  * sufficient to pass NIL, because there could not be any recursive reference
478  * to a not-yet-existing rowtype.
479  * --------------------------------
480  */
481 void
CheckAttributeType(const char * attname,Oid atttypid,Oid attcollation,List * containing_rowtypes,bool allow_system_table_mods)482 CheckAttributeType(const char *attname,
483 				   Oid atttypid, Oid attcollation,
484 				   List *containing_rowtypes,
485 				   bool allow_system_table_mods)
486 {
487 	char		att_typtype = get_typtype(atttypid);
488 	Oid			att_typelem;
489 
490 	if (atttypid == UNKNOWNOID)
491 	{
492 		/*
493 		 * Warn user, but don't fail, if column to be created has UNKNOWN type
494 		 * (usually as a result of a 'retrieve into' - jolly)
495 		 */
496 		ereport(WARNING,
497 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
498 				 errmsg("column \"%s\" has type \"unknown\"", attname),
499 				 errdetail("Proceeding with relation creation anyway.")));
500 	}
501 	else if (att_typtype == TYPTYPE_PSEUDO)
502 	{
503 		/*
504 		 * Refuse any attempt to create a pseudo-type column, except for a
505 		 * special hack for pg_statistic: allow ANYARRAY when modifying system
506 		 * catalogs (this allows creating pg_statistic and cloning it during
507 		 * VACUUM FULL)
508 		 */
509 		if (atttypid != ANYARRAYOID || !allow_system_table_mods)
510 			ereport(ERROR,
511 					(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
512 					 errmsg("column \"%s\" has pseudo-type %s",
513 							attname, format_type_be(atttypid))));
514 	}
515 	else if (att_typtype == TYPTYPE_DOMAIN)
516 	{
517 		/*
518 		 * If it's a domain, recurse to check its base type.
519 		 */
520 		CheckAttributeType(attname, getBaseType(atttypid), attcollation,
521 						   containing_rowtypes,
522 						   allow_system_table_mods);
523 	}
524 	else if (att_typtype == TYPTYPE_COMPOSITE)
525 	{
526 		/*
527 		 * For a composite type, recurse into its attributes.
528 		 */
529 		Relation	relation;
530 		TupleDesc	tupdesc;
531 		int			i;
532 
533 		/*
534 		 * Check for self-containment.  Eventually we might be able to allow
535 		 * this (just return without complaint, if so) but it's not clear how
536 		 * many other places would require anti-recursion defenses before it
537 		 * would be safe to allow tables to contain their own rowtype.
538 		 */
539 		if (list_member_oid(containing_rowtypes, atttypid))
540 			ereport(ERROR,
541 					(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
542 				errmsg("composite type %s cannot be made a member of itself",
543 					   format_type_be(atttypid))));
544 
545 		containing_rowtypes = lcons_oid(atttypid, containing_rowtypes);
546 
547 		relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
548 
549 		tupdesc = RelationGetDescr(relation);
550 
551 		for (i = 0; i < tupdesc->natts; i++)
552 		{
553 			Form_pg_attribute attr = tupdesc->attrs[i];
554 
555 			if (attr->attisdropped)
556 				continue;
557 			CheckAttributeType(NameStr(attr->attname),
558 							   attr->atttypid, attr->attcollation,
559 							   containing_rowtypes,
560 							   allow_system_table_mods);
561 		}
562 
563 		relation_close(relation, AccessShareLock);
564 
565 		containing_rowtypes = list_delete_first(containing_rowtypes);
566 	}
567 	else if (att_typtype == TYPTYPE_RANGE)
568 	{
569 		/*
570 		 * If it's a range, recurse to check its subtype.
571 		 */
572 		CheckAttributeType(attname, get_range_subtype(atttypid),
573 						   get_range_collation(atttypid),
574 						   containing_rowtypes,
575 						   allow_system_table_mods);
576 	}
577 	else if (OidIsValid((att_typelem = get_element_type(atttypid))))
578 	{
579 		/*
580 		 * Must recurse into array types, too, in case they are composite.
581 		 */
582 		CheckAttributeType(attname, att_typelem, attcollation,
583 						   containing_rowtypes,
584 						   allow_system_table_mods);
585 	}
586 
587 	/*
588 	 * This might not be strictly invalid per SQL standard, but it is pretty
589 	 * useless, and it cannot be dumped, so we must disallow it.
590 	 */
591 	if (!OidIsValid(attcollation) && type_is_collatable(atttypid))
592 		ereport(ERROR,
593 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
594 				 errmsg("no collation was derived for column \"%s\" with collatable type %s",
595 						attname, format_type_be(atttypid)),
596 		errhint("Use the COLLATE clause to set the collation explicitly.")));
597 }
598 
599 /*
600  * InsertPgAttributeTuple
601  *		Construct and insert a new tuple in pg_attribute.
602  *
603  * Caller has already opened and locked pg_attribute.  new_attribute is the
604  * attribute to insert (but we ignore attacl and attoptions, which are always
605  * initialized to NULL).
606  *
607  * indstate is the index state for CatalogIndexInsert.  It can be passed as
608  * NULL, in which case we'll fetch the necessary info.  (Don't do this when
609  * inserting multiple attributes, because it's a tad more expensive.)
610  */
611 void
InsertPgAttributeTuple(Relation pg_attribute_rel,Form_pg_attribute new_attribute,CatalogIndexState indstate)612 InsertPgAttributeTuple(Relation pg_attribute_rel,
613 					   Form_pg_attribute new_attribute,
614 					   CatalogIndexState indstate)
615 {
616 	Datum		values[Natts_pg_attribute];
617 	bool		nulls[Natts_pg_attribute];
618 	HeapTuple	tup;
619 
620 	/* This is a tad tedious, but way cleaner than what we used to do... */
621 	memset(values, 0, sizeof(values));
622 	memset(nulls, false, sizeof(nulls));
623 
624 	values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_attribute->attrelid);
625 	values[Anum_pg_attribute_attname - 1] = NameGetDatum(&new_attribute->attname);
626 	values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(new_attribute->atttypid);
627 	values[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(new_attribute->attstattarget);
628 	values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(new_attribute->attlen);
629 	values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(new_attribute->attnum);
630 	values[Anum_pg_attribute_attndims - 1] = Int32GetDatum(new_attribute->attndims);
631 	values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(new_attribute->attcacheoff);
632 	values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(new_attribute->atttypmod);
633 	values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(new_attribute->attbyval);
634 	values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(new_attribute->attstorage);
635 	values[Anum_pg_attribute_attalign - 1] = CharGetDatum(new_attribute->attalign);
636 	values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(new_attribute->attnotnull);
637 	values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(new_attribute->atthasdef);
638 	values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(new_attribute->attisdropped);
639 	values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(new_attribute->attislocal);
640 	values[Anum_pg_attribute_attinhcount - 1] = Int32GetDatum(new_attribute->attinhcount);
641 	values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(new_attribute->attcollation);
642 
643 	/* start out with empty permissions and empty options */
644 	nulls[Anum_pg_attribute_attacl - 1] = true;
645 	nulls[Anum_pg_attribute_attoptions - 1] = true;
646 	nulls[Anum_pg_attribute_attfdwoptions - 1] = true;
647 
648 	tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
649 
650 	/* finally insert the new tuple, update the indexes, and clean up */
651 	simple_heap_insert(pg_attribute_rel, tup);
652 
653 	if (indstate != NULL)
654 		CatalogIndexInsert(indstate, tup);
655 	else
656 		CatalogUpdateIndexes(pg_attribute_rel, tup);
657 
658 	heap_freetuple(tup);
659 }
660 
661 /* --------------------------------
662  *		AddNewAttributeTuples
663  *
664  *		this registers the new relation's schema by adding
665  *		tuples to pg_attribute.
666  * --------------------------------
667  */
668 static void
AddNewAttributeTuples(Oid new_rel_oid,TupleDesc tupdesc,char relkind,bool oidislocal,int oidinhcount)669 AddNewAttributeTuples(Oid new_rel_oid,
670 					  TupleDesc tupdesc,
671 					  char relkind,
672 					  bool oidislocal,
673 					  int oidinhcount)
674 {
675 	Form_pg_attribute attr;
676 	int			i;
677 	Relation	rel;
678 	CatalogIndexState indstate;
679 	int			natts = tupdesc->natts;
680 	ObjectAddress myself,
681 				referenced;
682 
683 	/*
684 	 * open pg_attribute and its indexes.
685 	 */
686 	rel = heap_open(AttributeRelationId, RowExclusiveLock);
687 
688 	indstate = CatalogOpenIndexes(rel);
689 
690 	/*
691 	 * First we add the user attributes.  This is also a convenient place to
692 	 * add dependencies on their datatypes and collations.
693 	 */
694 	for (i = 0; i < natts; i++)
695 	{
696 		attr = tupdesc->attrs[i];
697 		/* Fill in the correct relation OID */
698 		attr->attrelid = new_rel_oid;
699 		/* Make sure these are OK, too */
700 		attr->attstattarget = -1;
701 		attr->attcacheoff = -1;
702 
703 		InsertPgAttributeTuple(rel, attr, indstate);
704 
705 		/* Add dependency info */
706 		myself.classId = RelationRelationId;
707 		myself.objectId = new_rel_oid;
708 		myself.objectSubId = i + 1;
709 		referenced.classId = TypeRelationId;
710 		referenced.objectId = attr->atttypid;
711 		referenced.objectSubId = 0;
712 		recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
713 
714 		/* The default collation is pinned, so don't bother recording it */
715 		if (OidIsValid(attr->attcollation) &&
716 			attr->attcollation != DEFAULT_COLLATION_OID)
717 		{
718 			referenced.classId = CollationRelationId;
719 			referenced.objectId = attr->attcollation;
720 			referenced.objectSubId = 0;
721 			recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
722 		}
723 	}
724 
725 	/*
726 	 * Next we add the system attributes.  Skip OID if rel has no OIDs. Skip
727 	 * all for a view or type relation.  We don't bother with making datatype
728 	 * dependencies here, since presumably all these types are pinned.
729 	 */
730 	if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
731 	{
732 		for (i = 0; i < (int) lengthof(SysAtt); i++)
733 		{
734 			FormData_pg_attribute attStruct;
735 
736 			/* skip OID where appropriate */
737 			if (!tupdesc->tdhasoid &&
738 				SysAtt[i]->attnum == ObjectIdAttributeNumber)
739 				continue;
740 
741 			memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
742 
743 			/* Fill in the correct relation OID in the copied tuple */
744 			attStruct.attrelid = new_rel_oid;
745 
746 			/* Fill in correct inheritance info for the OID column */
747 			if (attStruct.attnum == ObjectIdAttributeNumber)
748 			{
749 				attStruct.attislocal = oidislocal;
750 				attStruct.attinhcount = oidinhcount;
751 			}
752 
753 			InsertPgAttributeTuple(rel, &attStruct, indstate);
754 		}
755 	}
756 
757 	/*
758 	 * clean up
759 	 */
760 	CatalogCloseIndexes(indstate);
761 
762 	heap_close(rel, RowExclusiveLock);
763 }
764 
765 /* --------------------------------
766  *		InsertPgClassTuple
767  *
768  *		Construct and insert a new tuple in pg_class.
769  *
770  * Caller has already opened and locked pg_class.
771  * Tuple data is taken from new_rel_desc->rd_rel, except for the
772  * variable-width fields which are not present in a cached reldesc.
773  * relacl and reloptions are passed in Datum form (to avoid having
774  * to reference the data types in heap.h).  Pass (Datum) 0 to set them
775  * to NULL.
776  * --------------------------------
777  */
778 void
InsertPgClassTuple(Relation pg_class_desc,Relation new_rel_desc,Oid new_rel_oid,Datum relacl,Datum reloptions)779 InsertPgClassTuple(Relation pg_class_desc,
780 				   Relation new_rel_desc,
781 				   Oid new_rel_oid,
782 				   Datum relacl,
783 				   Datum reloptions)
784 {
785 	Form_pg_class rd_rel = new_rel_desc->rd_rel;
786 	Datum		values[Natts_pg_class];
787 	bool		nulls[Natts_pg_class];
788 	HeapTuple	tup;
789 
790 	/* This is a tad tedious, but way cleaner than what we used to do... */
791 	memset(values, 0, sizeof(values));
792 	memset(nulls, false, sizeof(nulls));
793 
794 	values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
795 	values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
796 	values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
797 	values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
798 	values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
799 	values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
800 	values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
801 	values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
802 	values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
803 	values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
804 	values[Anum_pg_class_relallvisible - 1] = Int32GetDatum(rd_rel->relallvisible);
805 	values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
806 	values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
807 	values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
808 	values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
809 	values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
810 	values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
811 	values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
812 	values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
813 	values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
814 	values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
815 	values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
816 	values[Anum_pg_class_relrowsecurity - 1] = BoolGetDatum(rd_rel->relrowsecurity);
817 	values[Anum_pg_class_relforcerowsecurity - 1] = BoolGetDatum(rd_rel->relforcerowsecurity);
818 	values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
819 	values[Anum_pg_class_relispopulated - 1] = BoolGetDatum(rd_rel->relispopulated);
820 	values[Anum_pg_class_relreplident - 1] = CharGetDatum(rd_rel->relreplident);
821 	values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
822 	values[Anum_pg_class_relminmxid - 1] = MultiXactIdGetDatum(rd_rel->relminmxid);
823 	if (relacl != (Datum) 0)
824 		values[Anum_pg_class_relacl - 1] = relacl;
825 	else
826 		nulls[Anum_pg_class_relacl - 1] = true;
827 	if (reloptions != (Datum) 0)
828 		values[Anum_pg_class_reloptions - 1] = reloptions;
829 	else
830 		nulls[Anum_pg_class_reloptions - 1] = true;
831 
832 	tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
833 
834 	/*
835 	 * The new tuple must have the oid already chosen for the rel.  Sure would
836 	 * be embarrassing to do this sort of thing in polite company.
837 	 */
838 	HeapTupleSetOid(tup, new_rel_oid);
839 
840 	/* finally insert the new tuple, update the indexes, and clean up */
841 	simple_heap_insert(pg_class_desc, tup);
842 
843 	CatalogUpdateIndexes(pg_class_desc, tup);
844 
845 	heap_freetuple(tup);
846 }
847 
848 /* --------------------------------
849  *		AddNewRelationTuple
850  *
851  *		this registers the new relation in the catalogs by
852  *		adding a tuple to pg_class.
853  * --------------------------------
854  */
855 static void
AddNewRelationTuple(Relation pg_class_desc,Relation new_rel_desc,Oid new_rel_oid,Oid new_type_oid,Oid reloftype,Oid relowner,char relkind,Datum relacl,Datum reloptions)856 AddNewRelationTuple(Relation pg_class_desc,
857 					Relation new_rel_desc,
858 					Oid new_rel_oid,
859 					Oid new_type_oid,
860 					Oid reloftype,
861 					Oid relowner,
862 					char relkind,
863 					Datum relacl,
864 					Datum reloptions)
865 {
866 	Form_pg_class new_rel_reltup;
867 
868 	/*
869 	 * first we update some of the information in our uncataloged relation's
870 	 * relation descriptor.
871 	 */
872 	new_rel_reltup = new_rel_desc->rd_rel;
873 
874 	switch (relkind)
875 	{
876 		case RELKIND_RELATION:
877 		case RELKIND_MATVIEW:
878 		case RELKIND_INDEX:
879 		case RELKIND_TOASTVALUE:
880 			/* The relation is real, but as yet empty */
881 			new_rel_reltup->relpages = 0;
882 			new_rel_reltup->reltuples = 0;
883 			new_rel_reltup->relallvisible = 0;
884 			break;
885 		case RELKIND_SEQUENCE:
886 			/* Sequences always have a known size */
887 			new_rel_reltup->relpages = 1;
888 			new_rel_reltup->reltuples = 1;
889 			new_rel_reltup->relallvisible = 0;
890 			break;
891 		default:
892 			/* Views, etc, have no disk storage */
893 			new_rel_reltup->relpages = 0;
894 			new_rel_reltup->reltuples = 0;
895 			new_rel_reltup->relallvisible = 0;
896 			break;
897 	}
898 
899 	/* Initialize relfrozenxid and relminmxid */
900 	if (relkind == RELKIND_RELATION ||
901 		relkind == RELKIND_MATVIEW ||
902 		relkind == RELKIND_TOASTVALUE)
903 	{
904 		/*
905 		 * Initialize to the minimum XID that could put tuples in the table.
906 		 * We know that no xacts older than RecentXmin are still running, so
907 		 * that will do.
908 		 */
909 		new_rel_reltup->relfrozenxid = RecentXmin;
910 
911 		/*
912 		 * Similarly, initialize the minimum Multixact to the first value that
913 		 * could possibly be stored in tuples in the table.  Running
914 		 * transactions could reuse values from their local cache, so we are
915 		 * careful to consider all currently running multis.
916 		 *
917 		 * XXX this could be refined further, but is it worth the hassle?
918 		 */
919 		new_rel_reltup->relminmxid = GetOldestMultiXactId();
920 	}
921 	else
922 	{
923 		/*
924 		 * Other relation types will not contain XIDs, so set relfrozenxid to
925 		 * InvalidTransactionId.  (Note: a sequence does contain a tuple, but
926 		 * we force its xmin to be FrozenTransactionId always; see
927 		 * commands/sequence.c.)
928 		 */
929 		new_rel_reltup->relfrozenxid = InvalidTransactionId;
930 		new_rel_reltup->relminmxid = InvalidMultiXactId;
931 	}
932 
933 	new_rel_reltup->relowner = relowner;
934 	new_rel_reltup->reltype = new_type_oid;
935 	new_rel_reltup->reloftype = reloftype;
936 
937 	new_rel_desc->rd_att->tdtypeid = new_type_oid;
938 
939 	/* Now build and insert the tuple */
940 	InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
941 					   relacl, reloptions);
942 }
943 
944 
945 /* --------------------------------
946  *		AddNewRelationType -
947  *
948  *		define a composite type corresponding to the new relation
949  * --------------------------------
950  */
951 static ObjectAddress
AddNewRelationType(const char * typeName,Oid typeNamespace,Oid new_rel_oid,char new_rel_kind,Oid ownerid,Oid new_row_type,Oid new_array_type)952 AddNewRelationType(const char *typeName,
953 				   Oid typeNamespace,
954 				   Oid new_rel_oid,
955 				   char new_rel_kind,
956 				   Oid ownerid,
957 				   Oid new_row_type,
958 				   Oid new_array_type)
959 {
960 	return
961 		TypeCreate(new_row_type,	/* optional predetermined OID */
962 				   typeName,	/* type name */
963 				   typeNamespace,		/* type namespace */
964 				   new_rel_oid, /* relation oid */
965 				   new_rel_kind,	/* relation kind */
966 				   ownerid,		/* owner's ID */
967 				   -1,			/* internal size (varlena) */
968 				   TYPTYPE_COMPOSITE,	/* type-type (composite) */
969 				   TYPCATEGORY_COMPOSITE,		/* type-category (ditto) */
970 				   false,		/* composite types are never preferred */
971 				   DEFAULT_TYPDELIM,	/* default array delimiter */
972 				   F_RECORD_IN, /* input procedure */
973 				   F_RECORD_OUT,	/* output procedure */
974 				   F_RECORD_RECV,		/* receive procedure */
975 				   F_RECORD_SEND,		/* send procedure */
976 				   InvalidOid,	/* typmodin procedure - none */
977 				   InvalidOid,	/* typmodout procedure - none */
978 				   InvalidOid,	/* analyze procedure - default */
979 				   InvalidOid,	/* array element type - irrelevant */
980 				   false,		/* this is not an array type */
981 				   new_array_type,		/* array type if any */
982 				   InvalidOid,	/* domain base type - irrelevant */
983 				   NULL,		/* default value - none */
984 				   NULL,		/* default binary representation */
985 				   false,		/* passed by reference */
986 				   'd',			/* alignment - must be the largest! */
987 				   'x',			/* fully TOASTable */
988 				   -1,			/* typmod */
989 				   0,			/* array dimensions for typBaseType */
990 				   false,		/* Type NOT NULL */
991 				   InvalidOid); /* rowtypes never have a collation */
992 }
993 
994 /* --------------------------------
995  *		heap_create_with_catalog
996  *
997  *		creates a new cataloged relation.  see comments above.
998  *
999  * Arguments:
1000  *	relname: name to give to new rel
1001  *	relnamespace: OID of namespace it goes in
1002  *	reltablespace: OID of tablespace it goes in
1003  *	relid: OID to assign to new rel, or InvalidOid to select a new OID
1004  *	reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
1005  *	reloftypeid: if a typed table, OID of underlying type; else InvalidOid
1006  *	ownerid: OID of new rel's owner
1007  *	tupdesc: tuple descriptor (source of column definitions)
1008  *	cooked_constraints: list of precooked check constraints and defaults
1009  *	relkind: relkind for new rel
1010  *	relpersistence: rel's persistence status (permanent, temp, or unlogged)
1011  *	shared_relation: TRUE if it's to be a shared relation
1012  *	mapped_relation: TRUE if the relation will use the relfilenode map
1013  *	oidislocal: TRUE if oid column (if any) should be marked attislocal
1014  *	oidinhcount: attinhcount to assign to oid column (if any)
1015  *	oncommit: ON COMMIT marking (only relevant if it's a temp table)
1016  *	reloptions: reloptions in Datum form, or (Datum) 0 if none
1017  *	use_user_acl: TRUE if should look for user-defined default permissions;
1018  *		if FALSE, relacl is always set NULL
1019  *	allow_system_table_mods: TRUE to allow creation in system namespaces
1020  *	is_internal: is this a system-generated catalog?
1021  *
1022  * Output parameters:
1023  *	typaddress: if not null, gets the object address of the new pg_type entry
1024  *
1025  * Returns the OID of the new relation
1026  * --------------------------------
1027  */
1028 Oid
heap_create_with_catalog(const char * relname,Oid relnamespace,Oid reltablespace,Oid relid,Oid reltypeid,Oid reloftypeid,Oid ownerid,TupleDesc tupdesc,List * cooked_constraints,char relkind,char relpersistence,bool shared_relation,bool mapped_relation,bool oidislocal,int oidinhcount,OnCommitAction oncommit,Datum reloptions,bool use_user_acl,bool allow_system_table_mods,bool is_internal,ObjectAddress * typaddress)1029 heap_create_with_catalog(const char *relname,
1030 						 Oid relnamespace,
1031 						 Oid reltablespace,
1032 						 Oid relid,
1033 						 Oid reltypeid,
1034 						 Oid reloftypeid,
1035 						 Oid ownerid,
1036 						 TupleDesc tupdesc,
1037 						 List *cooked_constraints,
1038 						 char relkind,
1039 						 char relpersistence,
1040 						 bool shared_relation,
1041 						 bool mapped_relation,
1042 						 bool oidislocal,
1043 						 int oidinhcount,
1044 						 OnCommitAction oncommit,
1045 						 Datum reloptions,
1046 						 bool use_user_acl,
1047 						 bool allow_system_table_mods,
1048 						 bool is_internal,
1049 						 ObjectAddress *typaddress)
1050 {
1051 	Relation	pg_class_desc;
1052 	Relation	new_rel_desc;
1053 	Acl		   *relacl;
1054 	Oid			existing_relid;
1055 	Oid			old_type_oid;
1056 	Oid			new_type_oid;
1057 	ObjectAddress new_type_addr;
1058 	Oid			new_array_oid = InvalidOid;
1059 
1060 	pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1061 
1062 	/*
1063 	 * sanity checks
1064 	 */
1065 	Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
1066 
1067 	CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
1068 
1069 	/*
1070 	 * This would fail later on anyway, if the relation already exists.  But
1071 	 * by catching it here we can emit a nicer error message.
1072 	 */
1073 	existing_relid = get_relname_relid(relname, relnamespace);
1074 	if (existing_relid != InvalidOid)
1075 		ereport(ERROR,
1076 				(errcode(ERRCODE_DUPLICATE_TABLE),
1077 				 errmsg("relation \"%s\" already exists", relname)));
1078 
1079 	/*
1080 	 * Since we are going to create a rowtype as well, also check for
1081 	 * collision with an existing type name.  If there is one and it's an
1082 	 * autogenerated array, we can rename it out of the way; otherwise we can
1083 	 * at least give a good error message.
1084 	 */
1085 	old_type_oid = GetSysCacheOid2(TYPENAMENSP,
1086 								   CStringGetDatum(relname),
1087 								   ObjectIdGetDatum(relnamespace));
1088 	if (OidIsValid(old_type_oid))
1089 	{
1090 		if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
1091 			ereport(ERROR,
1092 					(errcode(ERRCODE_DUPLICATE_OBJECT),
1093 					 errmsg("type \"%s\" already exists", relname),
1094 			   errhint("A relation has an associated type of the same name, "
1095 					   "so you must use a name that doesn't conflict "
1096 					   "with any existing type.")));
1097 	}
1098 
1099 	/*
1100 	 * Shared relations must be in pg_global (last-ditch check)
1101 	 */
1102 	if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
1103 		elog(ERROR, "shared relations must be placed in pg_global tablespace");
1104 
1105 	/*
1106 	 * Allocate an OID for the relation, unless we were told what to use.
1107 	 *
1108 	 * The OID will be the relfilenode as well, so make sure it doesn't
1109 	 * collide with either pg_class OIDs or existing physical files.
1110 	 */
1111 	if (!OidIsValid(relid))
1112 	{
1113 		/* Use binary-upgrade override for pg_class.oid/relfilenode? */
1114 		if (IsBinaryUpgrade &&
1115 			(relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
1116 			 relkind == RELKIND_VIEW || relkind == RELKIND_MATVIEW ||
1117 			 relkind == RELKIND_COMPOSITE_TYPE || relkind == RELKIND_FOREIGN_TABLE))
1118 		{
1119 			if (!OidIsValid(binary_upgrade_next_heap_pg_class_oid))
1120 				ereport(ERROR,
1121 						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1122 						 errmsg("pg_class heap OID value not set when in binary upgrade mode")));
1123 
1124 			relid = binary_upgrade_next_heap_pg_class_oid;
1125 			binary_upgrade_next_heap_pg_class_oid = InvalidOid;
1126 		}
1127 		/* There might be no TOAST table, so we have to test for it. */
1128 		else if (IsBinaryUpgrade &&
1129 				 OidIsValid(binary_upgrade_next_toast_pg_class_oid) &&
1130 				 relkind == RELKIND_TOASTVALUE)
1131 		{
1132 			relid = binary_upgrade_next_toast_pg_class_oid;
1133 			binary_upgrade_next_toast_pg_class_oid = InvalidOid;
1134 		}
1135 		else
1136 			relid = GetNewRelFileNode(reltablespace, pg_class_desc,
1137 									  relpersistence);
1138 	}
1139 
1140 	/*
1141 	 * Determine the relation's initial permissions.
1142 	 */
1143 	if (use_user_acl)
1144 	{
1145 		switch (relkind)
1146 		{
1147 			case RELKIND_RELATION:
1148 			case RELKIND_VIEW:
1149 			case RELKIND_MATVIEW:
1150 			case RELKIND_FOREIGN_TABLE:
1151 				relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1152 											  relnamespace);
1153 				break;
1154 			case RELKIND_SEQUENCE:
1155 				relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1156 											  relnamespace);
1157 				break;
1158 			default:
1159 				relacl = NULL;
1160 				break;
1161 		}
1162 	}
1163 	else
1164 		relacl = NULL;
1165 
1166 	/*
1167 	 * Create the relcache entry (mostly dummy at this point) and the physical
1168 	 * disk file.  (If we fail further down, it's the smgr's responsibility to
1169 	 * remove the disk file again.)
1170 	 */
1171 	new_rel_desc = heap_create(relname,
1172 							   relnamespace,
1173 							   reltablespace,
1174 							   relid,
1175 							   InvalidOid,
1176 							   tupdesc,
1177 							   relkind,
1178 							   relpersistence,
1179 							   shared_relation,
1180 							   mapped_relation,
1181 							   allow_system_table_mods);
1182 
1183 	Assert(relid == RelationGetRelid(new_rel_desc));
1184 
1185 	/*
1186 	 * Decide whether to create an array type over the relation's rowtype. We
1187 	 * do not create any array types for system catalogs (ie, those made
1188 	 * during initdb). We do not create them where the use of a relation as
1189 	 * such is an implementation detail: toast tables, sequences and indexes.
1190 	 */
1191 	if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1192 							  relkind == RELKIND_VIEW ||
1193 							  relkind == RELKIND_MATVIEW ||
1194 							  relkind == RELKIND_FOREIGN_TABLE ||
1195 							  relkind == RELKIND_COMPOSITE_TYPE))
1196 		new_array_oid = AssignTypeArrayOid();
1197 
1198 	/*
1199 	 * Since defining a relation also defines a complex type, we add a new
1200 	 * system type corresponding to the new relation.  The OID of the type can
1201 	 * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1202 	 * generate a new OID for it.
1203 	 *
1204 	 * NOTE: we could get a unique-index failure here, in case someone else is
1205 	 * creating the same type name in parallel but hadn't committed yet when
1206 	 * we checked for a duplicate name above.
1207 	 */
1208 	new_type_addr = AddNewRelationType(relname,
1209 									   relnamespace,
1210 									   relid,
1211 									   relkind,
1212 									   ownerid,
1213 									   reltypeid,
1214 									   new_array_oid);
1215 	new_type_oid = new_type_addr.objectId;
1216 	if (typaddress)
1217 		*typaddress = new_type_addr;
1218 
1219 	/*
1220 	 * Now make the array type if wanted.
1221 	 */
1222 	if (OidIsValid(new_array_oid))
1223 	{
1224 		char	   *relarrayname;
1225 
1226 		relarrayname = makeArrayTypeName(relname, relnamespace);
1227 
1228 		TypeCreate(new_array_oid,		/* force the type's OID to this */
1229 				   relarrayname,	/* Array type name */
1230 				   relnamespace,	/* Same namespace as parent */
1231 				   InvalidOid,	/* Not composite, no relationOid */
1232 				   0,			/* relkind, also N/A here */
1233 				   ownerid,		/* owner's ID */
1234 				   -1,			/* Internal size (varlena) */
1235 				   TYPTYPE_BASE,	/* Not composite - typelem is */
1236 				   TYPCATEGORY_ARRAY,	/* type-category (array) */
1237 				   false,		/* array types are never preferred */
1238 				   DEFAULT_TYPDELIM,	/* default array delimiter */
1239 				   F_ARRAY_IN,	/* array input proc */
1240 				   F_ARRAY_OUT, /* array output proc */
1241 				   F_ARRAY_RECV,	/* array recv (bin) proc */
1242 				   F_ARRAY_SEND,	/* array send (bin) proc */
1243 				   InvalidOid,	/* typmodin procedure - none */
1244 				   InvalidOid,	/* typmodout procedure - none */
1245 				   F_ARRAY_TYPANALYZE,	/* array analyze procedure */
1246 				   new_type_oid,	/* array element type - the rowtype */
1247 				   true,		/* yes, this is an array type */
1248 				   InvalidOid,	/* this has no array type */
1249 				   InvalidOid,	/* domain base type - irrelevant */
1250 				   NULL,		/* default value - none */
1251 				   NULL,		/* default binary representation */
1252 				   false,		/* passed by reference */
1253 				   'd',			/* alignment - must be the largest! */
1254 				   'x',			/* fully TOASTable */
1255 				   -1,			/* typmod */
1256 				   0,			/* array dimensions for typBaseType */
1257 				   false,		/* Type NOT NULL */
1258 				   InvalidOid); /* rowtypes never have a collation */
1259 
1260 		pfree(relarrayname);
1261 	}
1262 
1263 	/*
1264 	 * now create an entry in pg_class for the relation.
1265 	 *
1266 	 * NOTE: we could get a unique-index failure here, in case someone else is
1267 	 * creating the same relation name in parallel but hadn't committed yet
1268 	 * when we checked for a duplicate name above.
1269 	 */
1270 	AddNewRelationTuple(pg_class_desc,
1271 						new_rel_desc,
1272 						relid,
1273 						new_type_oid,
1274 						reloftypeid,
1275 						ownerid,
1276 						relkind,
1277 						PointerGetDatum(relacl),
1278 						reloptions);
1279 
1280 	/*
1281 	 * now add tuples to pg_attribute for the attributes in our new relation.
1282 	 */
1283 	AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1284 						  oidislocal, oidinhcount);
1285 
1286 	/*
1287 	 * Make a dependency link to force the relation to be deleted if its
1288 	 * namespace is.  Also make a dependency link to its owner, as well as
1289 	 * dependencies for any roles mentioned in the default ACL.
1290 	 *
1291 	 * For composite types, these dependencies are tracked for the pg_type
1292 	 * entry, so we needn't record them here.  Likewise, TOAST tables don't
1293 	 * need a namespace dependency (they live in a pinned namespace) nor an
1294 	 * owner dependency (they depend indirectly through the parent table), nor
1295 	 * should they have any ACL entries.  The same applies for extension
1296 	 * dependencies.
1297 	 *
1298 	 * If it's a temp table, we do not make it an extension member; this
1299 	 * prevents the unintuitive result that deletion of the temp table at
1300 	 * session end would make the whole extension go away.
1301 	 *
1302 	 * Also, skip this in bootstrap mode, since we don't make dependencies
1303 	 * while bootstrapping.
1304 	 */
1305 	if (relkind != RELKIND_COMPOSITE_TYPE &&
1306 		relkind != RELKIND_TOASTVALUE &&
1307 		!IsBootstrapProcessingMode())
1308 	{
1309 		ObjectAddress myself,
1310 					referenced;
1311 
1312 		myself.classId = RelationRelationId;
1313 		myself.objectId = relid;
1314 		myself.objectSubId = 0;
1315 
1316 		referenced.classId = NamespaceRelationId;
1317 		referenced.objectId = relnamespace;
1318 		referenced.objectSubId = 0;
1319 		recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1320 
1321 		recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1322 
1323 		recordDependencyOnNewAcl(RelationRelationId, relid, 0, ownerid, relacl);
1324 
1325 		if (relpersistence != RELPERSISTENCE_TEMP)
1326 			recordDependencyOnCurrentExtension(&myself, false);
1327 
1328 		if (reloftypeid)
1329 		{
1330 			referenced.classId = TypeRelationId;
1331 			referenced.objectId = reloftypeid;
1332 			referenced.objectSubId = 0;
1333 			recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1334 		}
1335 	}
1336 
1337 	/* Post creation hook for new relation */
1338 	InvokeObjectPostCreateHookArg(RelationRelationId, relid, 0, is_internal);
1339 
1340 	/*
1341 	 * Store any supplied constraints and defaults.
1342 	 *
1343 	 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1344 	 * entry, so the relation must be valid and self-consistent at this point.
1345 	 * In particular, there are not yet constraints and defaults anywhere.
1346 	 */
1347 	StoreConstraints(new_rel_desc, cooked_constraints, is_internal);
1348 
1349 	/*
1350 	 * If there's a special on-commit action, remember it
1351 	 */
1352 	if (oncommit != ONCOMMIT_NOOP)
1353 		register_on_commit_action(relid, oncommit);
1354 
1355 	if (relpersistence == RELPERSISTENCE_UNLOGGED)
1356 	{
1357 		Assert(relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW ||
1358 			   relkind == RELKIND_TOASTVALUE);
1359 		heap_create_init_fork(new_rel_desc);
1360 	}
1361 
1362 	/*
1363 	 * ok, the relation has been cataloged, so close our relations and return
1364 	 * the OID of the newly created relation.
1365 	 */
1366 	heap_close(new_rel_desc, NoLock);	/* do not unlock till end of xact */
1367 	heap_close(pg_class_desc, RowExclusiveLock);
1368 
1369 	return relid;
1370 }
1371 
1372 /*
1373  * Set up an init fork for an unlogged table so that it can be correctly
1374  * reinitialized on restart.  An immediate sync is required even if the
1375  * page has been logged, because the write did not go through
1376  * shared_buffers and therefore a concurrent checkpoint may have moved
1377  * the redo pointer past our xlog record.  Recovery may as well remove it
1378  * while replaying, for example, XLOG_DBASE_CREATE or XLOG_TBLSPC_CREATE
1379  * record. Therefore, logging is necessary even if wal_level=minimal.
1380  */
1381 void
heap_create_init_fork(Relation rel)1382 heap_create_init_fork(Relation rel)
1383 {
1384 	RelationOpenSmgr(rel);
1385 	smgrcreate(rel->rd_smgr, INIT_FORKNUM, false);
1386 	log_smgrcreate(&rel->rd_smgr->smgr_rnode.node, INIT_FORKNUM);
1387 	smgrimmedsync(rel->rd_smgr, INIT_FORKNUM);
1388 }
1389 
1390 /*
1391  *		RelationRemoveInheritance
1392  *
1393  * Formerly, this routine checked for child relations and aborted the
1394  * deletion if any were found.  Now we rely on the dependency mechanism
1395  * to check for or delete child relations.  By the time we get here,
1396  * there are no children and we need only remove any pg_inherits rows
1397  * linking this relation to its parent(s).
1398  */
1399 static void
RelationRemoveInheritance(Oid relid)1400 RelationRemoveInheritance(Oid relid)
1401 {
1402 	Relation	catalogRelation;
1403 	SysScanDesc scan;
1404 	ScanKeyData key;
1405 	HeapTuple	tuple;
1406 
1407 	catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1408 
1409 	ScanKeyInit(&key,
1410 				Anum_pg_inherits_inhrelid,
1411 				BTEqualStrategyNumber, F_OIDEQ,
1412 				ObjectIdGetDatum(relid));
1413 
1414 	scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1415 							  NULL, 1, &key);
1416 
1417 	while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1418 		simple_heap_delete(catalogRelation, &tuple->t_self);
1419 
1420 	systable_endscan(scan);
1421 	heap_close(catalogRelation, RowExclusiveLock);
1422 }
1423 
1424 /*
1425  *		DeleteRelationTuple
1426  *
1427  * Remove pg_class row for the given relid.
1428  *
1429  * Note: this is shared by relation deletion and index deletion.  It's
1430  * not intended for use anyplace else.
1431  */
1432 void
DeleteRelationTuple(Oid relid)1433 DeleteRelationTuple(Oid relid)
1434 {
1435 	Relation	pg_class_desc;
1436 	HeapTuple	tup;
1437 
1438 	/* Grab an appropriate lock on the pg_class relation */
1439 	pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1440 
1441 	tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1442 	if (!HeapTupleIsValid(tup))
1443 		elog(ERROR, "cache lookup failed for relation %u", relid);
1444 
1445 	/* delete the relation tuple from pg_class, and finish up */
1446 	simple_heap_delete(pg_class_desc, &tup->t_self);
1447 
1448 	ReleaseSysCache(tup);
1449 
1450 	heap_close(pg_class_desc, RowExclusiveLock);
1451 }
1452 
1453 /*
1454  *		DeleteAttributeTuples
1455  *
1456  * Remove pg_attribute rows for the given relid.
1457  *
1458  * Note: this is shared by relation deletion and index deletion.  It's
1459  * not intended for use anyplace else.
1460  */
1461 void
DeleteAttributeTuples(Oid relid)1462 DeleteAttributeTuples(Oid relid)
1463 {
1464 	Relation	attrel;
1465 	SysScanDesc scan;
1466 	ScanKeyData key[1];
1467 	HeapTuple	atttup;
1468 
1469 	/* Grab an appropriate lock on the pg_attribute relation */
1470 	attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1471 
1472 	/* Use the index to scan only attributes of the target relation */
1473 	ScanKeyInit(&key[0],
1474 				Anum_pg_attribute_attrelid,
1475 				BTEqualStrategyNumber, F_OIDEQ,
1476 				ObjectIdGetDatum(relid));
1477 
1478 	scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1479 							  NULL, 1, key);
1480 
1481 	/* Delete all the matching tuples */
1482 	while ((atttup = systable_getnext(scan)) != NULL)
1483 		simple_heap_delete(attrel, &atttup->t_self);
1484 
1485 	/* Clean up after the scan */
1486 	systable_endscan(scan);
1487 	heap_close(attrel, RowExclusiveLock);
1488 }
1489 
1490 /*
1491  *		DeleteSystemAttributeTuples
1492  *
1493  * Remove pg_attribute rows for system columns of the given relid.
1494  *
1495  * Note: this is only used when converting a table to a view.  Views don't
1496  * have system columns, so we should remove them from pg_attribute.
1497  */
1498 void
DeleteSystemAttributeTuples(Oid relid)1499 DeleteSystemAttributeTuples(Oid relid)
1500 {
1501 	Relation	attrel;
1502 	SysScanDesc scan;
1503 	ScanKeyData key[2];
1504 	HeapTuple	atttup;
1505 
1506 	/* Grab an appropriate lock on the pg_attribute relation */
1507 	attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1508 
1509 	/* Use the index to scan only system attributes of the target relation */
1510 	ScanKeyInit(&key[0],
1511 				Anum_pg_attribute_attrelid,
1512 				BTEqualStrategyNumber, F_OIDEQ,
1513 				ObjectIdGetDatum(relid));
1514 	ScanKeyInit(&key[1],
1515 				Anum_pg_attribute_attnum,
1516 				BTLessEqualStrategyNumber, F_INT2LE,
1517 				Int16GetDatum(0));
1518 
1519 	scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1520 							  NULL, 2, key);
1521 
1522 	/* Delete all the matching tuples */
1523 	while ((atttup = systable_getnext(scan)) != NULL)
1524 		simple_heap_delete(attrel, &atttup->t_self);
1525 
1526 	/* Clean up after the scan */
1527 	systable_endscan(scan);
1528 	heap_close(attrel, RowExclusiveLock);
1529 }
1530 
1531 /*
1532  *		RemoveAttributeById
1533  *
1534  * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1535  * deleted in pg_attribute.  We also remove pg_statistic entries for it.
1536  * (Everything else needed, such as getting rid of any pg_attrdef entry,
1537  * is handled by dependency.c.)
1538  */
1539 void
RemoveAttributeById(Oid relid,AttrNumber attnum)1540 RemoveAttributeById(Oid relid, AttrNumber attnum)
1541 {
1542 	Relation	rel;
1543 	Relation	attr_rel;
1544 	HeapTuple	tuple;
1545 	Form_pg_attribute attStruct;
1546 	char		newattname[NAMEDATALEN];
1547 
1548 	/*
1549 	 * Grab an exclusive lock on the target table, which we will NOT release
1550 	 * until end of transaction.  (In the simple case where we are directly
1551 	 * dropping this column, AlterTableDropColumn already did this ... but
1552 	 * when cascading from a drop of some other object, we may not have any
1553 	 * lock.)
1554 	 */
1555 	rel = relation_open(relid, AccessExclusiveLock);
1556 
1557 	attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1558 
1559 	tuple = SearchSysCacheCopy2(ATTNUM,
1560 								ObjectIdGetDatum(relid),
1561 								Int16GetDatum(attnum));
1562 	if (!HeapTupleIsValid(tuple))		/* shouldn't happen */
1563 		elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1564 			 attnum, relid);
1565 	attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1566 
1567 	if (attnum < 0)
1568 	{
1569 		/* System attribute (probably OID) ... just delete the row */
1570 
1571 		simple_heap_delete(attr_rel, &tuple->t_self);
1572 	}
1573 	else
1574 	{
1575 		/* Dropping user attributes is lots harder */
1576 
1577 		/* Mark the attribute as dropped */
1578 		attStruct->attisdropped = true;
1579 
1580 		/*
1581 		 * Set the type OID to invalid.  A dropped attribute's type link
1582 		 * cannot be relied on (once the attribute is dropped, the type might
1583 		 * be too). Fortunately we do not need the type row --- the only
1584 		 * really essential information is the type's typlen and typalign,
1585 		 * which are preserved in the attribute's attlen and attalign.  We set
1586 		 * atttypid to zero here as a means of catching code that incorrectly
1587 		 * expects it to be valid.
1588 		 */
1589 		attStruct->atttypid = InvalidOid;
1590 
1591 		/* Remove any NOT NULL constraint the column may have */
1592 		attStruct->attnotnull = false;
1593 
1594 		/* We don't want to keep stats for it anymore */
1595 		attStruct->attstattarget = 0;
1596 
1597 		/*
1598 		 * Change the column name to something that isn't likely to conflict
1599 		 */
1600 		snprintf(newattname, sizeof(newattname),
1601 				 "........pg.dropped.%d........", attnum);
1602 		namestrcpy(&(attStruct->attname), newattname);
1603 
1604 		simple_heap_update(attr_rel, &tuple->t_self, tuple);
1605 
1606 		/* keep the system catalog indexes current */
1607 		CatalogUpdateIndexes(attr_rel, tuple);
1608 	}
1609 
1610 	/*
1611 	 * Because updating the pg_attribute row will trigger a relcache flush for
1612 	 * the target relation, we need not do anything else to notify other
1613 	 * backends of the change.
1614 	 */
1615 
1616 	heap_close(attr_rel, RowExclusiveLock);
1617 
1618 	if (attnum > 0)
1619 		RemoveStatistics(relid, attnum);
1620 
1621 	relation_close(rel, NoLock);
1622 }
1623 
1624 /*
1625  *		RemoveAttrDefault
1626  *
1627  * If the specified relation/attribute has a default, remove it.
1628  * (If no default, raise error if complain is true, else return quietly.)
1629  */
1630 void
RemoveAttrDefault(Oid relid,AttrNumber attnum,DropBehavior behavior,bool complain,bool internal)1631 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1632 				  DropBehavior behavior, bool complain, bool internal)
1633 {
1634 	Relation	attrdef_rel;
1635 	ScanKeyData scankeys[2];
1636 	SysScanDesc scan;
1637 	HeapTuple	tuple;
1638 	bool		found = false;
1639 
1640 	attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1641 
1642 	ScanKeyInit(&scankeys[0],
1643 				Anum_pg_attrdef_adrelid,
1644 				BTEqualStrategyNumber, F_OIDEQ,
1645 				ObjectIdGetDatum(relid));
1646 	ScanKeyInit(&scankeys[1],
1647 				Anum_pg_attrdef_adnum,
1648 				BTEqualStrategyNumber, F_INT2EQ,
1649 				Int16GetDatum(attnum));
1650 
1651 	scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1652 							  NULL, 2, scankeys);
1653 
1654 	/* There should be at most one matching tuple, but we loop anyway */
1655 	while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1656 	{
1657 		ObjectAddress object;
1658 
1659 		object.classId = AttrDefaultRelationId;
1660 		object.objectId = HeapTupleGetOid(tuple);
1661 		object.objectSubId = 0;
1662 
1663 		performDeletion(&object, behavior,
1664 						internal ? PERFORM_DELETION_INTERNAL : 0);
1665 
1666 		found = true;
1667 	}
1668 
1669 	systable_endscan(scan);
1670 	heap_close(attrdef_rel, RowExclusiveLock);
1671 
1672 	if (complain && !found)
1673 		elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1674 			 relid, attnum);
1675 }
1676 
1677 /*
1678  *		RemoveAttrDefaultById
1679  *
1680  * Remove a pg_attrdef entry specified by OID.  This is the guts of
1681  * attribute-default removal.  Note it should be called via performDeletion,
1682  * not directly.
1683  */
1684 void
RemoveAttrDefaultById(Oid attrdefId)1685 RemoveAttrDefaultById(Oid attrdefId)
1686 {
1687 	Relation	attrdef_rel;
1688 	Relation	attr_rel;
1689 	Relation	myrel;
1690 	ScanKeyData scankeys[1];
1691 	SysScanDesc scan;
1692 	HeapTuple	tuple;
1693 	Oid			myrelid;
1694 	AttrNumber	myattnum;
1695 
1696 	/* Grab an appropriate lock on the pg_attrdef relation */
1697 	attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1698 
1699 	/* Find the pg_attrdef tuple */
1700 	ScanKeyInit(&scankeys[0],
1701 				ObjectIdAttributeNumber,
1702 				BTEqualStrategyNumber, F_OIDEQ,
1703 				ObjectIdGetDatum(attrdefId));
1704 
1705 	scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1706 							  NULL, 1, scankeys);
1707 
1708 	tuple = systable_getnext(scan);
1709 	if (!HeapTupleIsValid(tuple))
1710 		elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1711 
1712 	myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1713 	myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1714 
1715 	/* Get an exclusive lock on the relation owning the attribute */
1716 	myrel = relation_open(myrelid, AccessExclusiveLock);
1717 
1718 	/* Now we can delete the pg_attrdef row */
1719 	simple_heap_delete(attrdef_rel, &tuple->t_self);
1720 
1721 	systable_endscan(scan);
1722 	heap_close(attrdef_rel, RowExclusiveLock);
1723 
1724 	/* Fix the pg_attribute row */
1725 	attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1726 
1727 	tuple = SearchSysCacheCopy2(ATTNUM,
1728 								ObjectIdGetDatum(myrelid),
1729 								Int16GetDatum(myattnum));
1730 	if (!HeapTupleIsValid(tuple))		/* shouldn't happen */
1731 		elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1732 			 myattnum, myrelid);
1733 
1734 	((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1735 
1736 	simple_heap_update(attr_rel, &tuple->t_self, tuple);
1737 
1738 	/* keep the system catalog indexes current */
1739 	CatalogUpdateIndexes(attr_rel, tuple);
1740 
1741 	/*
1742 	 * Our update of the pg_attribute row will force a relcache rebuild, so
1743 	 * there's nothing else to do here.
1744 	 */
1745 	heap_close(attr_rel, RowExclusiveLock);
1746 
1747 	/* Keep lock on attribute's rel until end of xact */
1748 	relation_close(myrel, NoLock);
1749 }
1750 
1751 /*
1752  * heap_drop_with_catalog	- removes specified relation from catalogs
1753  *
1754  * Note that this routine is not responsible for dropping objects that are
1755  * linked to the pg_class entry via dependencies (for example, indexes and
1756  * constraints).  Those are deleted by the dependency-tracing logic in
1757  * dependency.c before control gets here.  In general, therefore, this routine
1758  * should never be called directly; go through performDeletion() instead.
1759  */
1760 void
heap_drop_with_catalog(Oid relid)1761 heap_drop_with_catalog(Oid relid)
1762 {
1763 	Relation	rel;
1764 
1765 	/*
1766 	 * Open and lock the relation.
1767 	 */
1768 	rel = relation_open(relid, AccessExclusiveLock);
1769 
1770 	/*
1771 	 * There can no longer be anyone *else* touching the relation, but we
1772 	 * might still have open queries or cursors, or pending trigger events, in
1773 	 * our own session.
1774 	 */
1775 	CheckTableNotInUse(rel, "DROP TABLE");
1776 
1777 	/*
1778 	 * This effectively deletes all rows in the table, and may be done in a
1779 	 * serializable transaction.  In that case we must record a rw-conflict in
1780 	 * to this transaction from each transaction holding a predicate lock on
1781 	 * the table.
1782 	 */
1783 	CheckTableForSerializableConflictIn(rel);
1784 
1785 	/*
1786 	 * Delete pg_foreign_table tuple first.
1787 	 */
1788 	if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1789 	{
1790 		Relation	rel;
1791 		HeapTuple	tuple;
1792 
1793 		rel = heap_open(ForeignTableRelationId, RowExclusiveLock);
1794 
1795 		tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1796 		if (!HeapTupleIsValid(tuple))
1797 			elog(ERROR, "cache lookup failed for foreign table %u", relid);
1798 
1799 		simple_heap_delete(rel, &tuple->t_self);
1800 
1801 		ReleaseSysCache(tuple);
1802 		heap_close(rel, RowExclusiveLock);
1803 	}
1804 
1805 	/*
1806 	 * Schedule unlinking of the relation's physical files at commit.
1807 	 */
1808 	if (rel->rd_rel->relkind != RELKIND_VIEW &&
1809 		rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1810 		rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1811 	{
1812 		RelationDropStorage(rel);
1813 	}
1814 
1815 	/*
1816 	 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1817 	 * until transaction commit.  This ensures no one else will try to do
1818 	 * something with the doomed relation.
1819 	 */
1820 	relation_close(rel, NoLock);
1821 
1822 	/*
1823 	 * Forget any ON COMMIT action for the rel
1824 	 */
1825 	remove_on_commit_action(relid);
1826 
1827 	/*
1828 	 * Flush the relation from the relcache.  We want to do this before
1829 	 * starting to remove catalog entries, just to be certain that no relcache
1830 	 * entry rebuild will happen partway through.  (That should not really
1831 	 * matter, since we don't do CommandCounterIncrement here, but let's be
1832 	 * safe.)
1833 	 */
1834 	RelationForgetRelation(relid);
1835 
1836 	/*
1837 	 * remove inheritance information
1838 	 */
1839 	RelationRemoveInheritance(relid);
1840 
1841 	/*
1842 	 * delete statistics
1843 	 */
1844 	RemoveStatistics(relid, 0);
1845 
1846 	/*
1847 	 * delete attribute tuples
1848 	 */
1849 	DeleteAttributeTuples(relid);
1850 
1851 	/*
1852 	 * delete relation tuple
1853 	 */
1854 	DeleteRelationTuple(relid);
1855 }
1856 
1857 
1858 /*
1859  * Store a default expression for column attnum of relation rel.
1860  *
1861  * Returns the OID of the new pg_attrdef tuple.
1862  */
1863 Oid
StoreAttrDefault(Relation rel,AttrNumber attnum,Node * expr,bool is_internal)1864 StoreAttrDefault(Relation rel, AttrNumber attnum,
1865 				 Node *expr, bool is_internal)
1866 {
1867 	char	   *adbin;
1868 	char	   *adsrc;
1869 	Relation	adrel;
1870 	HeapTuple	tuple;
1871 	Datum		values[4];
1872 	static bool nulls[4] = {false, false, false, false};
1873 	Relation	attrrel;
1874 	HeapTuple	atttup;
1875 	Form_pg_attribute attStruct;
1876 	Oid			attrdefOid;
1877 	ObjectAddress colobject,
1878 				defobject;
1879 
1880 	/*
1881 	 * Flatten expression to string form for storage.
1882 	 */
1883 	adbin = nodeToString(expr);
1884 
1885 	/*
1886 	 * Also deparse it to form the mostly-obsolete adsrc field.
1887 	 */
1888 	adsrc = deparse_expression(expr,
1889 							deparse_context_for(RelationGetRelationName(rel),
1890 												RelationGetRelid(rel)),
1891 							   false, false);
1892 
1893 	/*
1894 	 * Make the pg_attrdef entry.
1895 	 */
1896 	values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1897 	values[Anum_pg_attrdef_adnum - 1] = attnum;
1898 	values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1899 	values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1900 
1901 	adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1902 
1903 	tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1904 	attrdefOid = simple_heap_insert(adrel, tuple);
1905 
1906 	CatalogUpdateIndexes(adrel, tuple);
1907 
1908 	defobject.classId = AttrDefaultRelationId;
1909 	defobject.objectId = attrdefOid;
1910 	defobject.objectSubId = 0;
1911 
1912 	heap_close(adrel, RowExclusiveLock);
1913 
1914 	/* now can free some of the stuff allocated above */
1915 	pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1916 	pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1917 	heap_freetuple(tuple);
1918 	pfree(adbin);
1919 	pfree(adsrc);
1920 
1921 	/*
1922 	 * Update the pg_attribute entry for the column to show that a default
1923 	 * exists.
1924 	 */
1925 	attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1926 	atttup = SearchSysCacheCopy2(ATTNUM,
1927 								 ObjectIdGetDatum(RelationGetRelid(rel)),
1928 								 Int16GetDatum(attnum));
1929 	if (!HeapTupleIsValid(atttup))
1930 		elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1931 			 attnum, RelationGetRelid(rel));
1932 	attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1933 	if (!attStruct->atthasdef)
1934 	{
1935 		attStruct->atthasdef = true;
1936 		simple_heap_update(attrrel, &atttup->t_self, atttup);
1937 		/* keep catalog indexes current */
1938 		CatalogUpdateIndexes(attrrel, atttup);
1939 	}
1940 	heap_close(attrrel, RowExclusiveLock);
1941 	heap_freetuple(atttup);
1942 
1943 	/*
1944 	 * Make a dependency so that the pg_attrdef entry goes away if the column
1945 	 * (or whole table) is deleted.
1946 	 */
1947 	colobject.classId = RelationRelationId;
1948 	colobject.objectId = RelationGetRelid(rel);
1949 	colobject.objectSubId = attnum;
1950 
1951 	recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1952 
1953 	/*
1954 	 * Record dependencies on objects used in the expression, too.
1955 	 */
1956 	recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1957 
1958 	/*
1959 	 * Post creation hook for attribute defaults.
1960 	 *
1961 	 * XXX. ALTER TABLE ALTER COLUMN SET/DROP DEFAULT is implemented with a
1962 	 * couple of deletion/creation of the attribute's default entry, so the
1963 	 * callee should check existence of an older version of this entry if it
1964 	 * needs to distinguish.
1965 	 */
1966 	InvokeObjectPostCreateHookArg(AttrDefaultRelationId,
1967 								  RelationGetRelid(rel), attnum, is_internal);
1968 
1969 	return attrdefOid;
1970 }
1971 
1972 /*
1973  * Store a check-constraint expression for the given relation.
1974  *
1975  * Caller is responsible for updating the count of constraints
1976  * in the pg_class entry for the relation.
1977  *
1978  * The OID of the new constraint is returned.
1979  */
1980 static Oid
StoreRelCheck(Relation rel,char * ccname,Node * expr,bool is_validated,bool is_local,int inhcount,bool is_no_inherit,bool is_internal)1981 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1982 			  bool is_validated, bool is_local, int inhcount,
1983 			  bool is_no_inherit, bool is_internal)
1984 {
1985 	char	   *ccbin;
1986 	char	   *ccsrc;
1987 	List	   *varList;
1988 	int			keycount;
1989 	int16	   *attNos;
1990 	Oid			constrOid;
1991 
1992 	/*
1993 	 * Flatten expression to string form for storage.
1994 	 */
1995 	ccbin = nodeToString(expr);
1996 
1997 	/*
1998 	 * Also deparse it to form the mostly-obsolete consrc field.
1999 	 */
2000 	ccsrc = deparse_expression(expr,
2001 							deparse_context_for(RelationGetRelationName(rel),
2002 												RelationGetRelid(rel)),
2003 							   false, false);
2004 
2005 	/*
2006 	 * Find columns of rel that are used in expr
2007 	 *
2008 	 * NB: pull_var_clause is okay here only because we don't allow subselects
2009 	 * in check constraints; it would fail to examine the contents of
2010 	 * subselects.
2011 	 */
2012 	varList = pull_var_clause(expr, 0);
2013 	keycount = list_length(varList);
2014 
2015 	if (keycount > 0)
2016 	{
2017 		ListCell   *vl;
2018 		int			i = 0;
2019 
2020 		attNos = (int16 *) palloc(keycount * sizeof(int16));
2021 		foreach(vl, varList)
2022 		{
2023 			Var		   *var = (Var *) lfirst(vl);
2024 			int			j;
2025 
2026 			for (j = 0; j < i; j++)
2027 				if (attNos[j] == var->varattno)
2028 					break;
2029 			if (j == i)
2030 				attNos[i++] = var->varattno;
2031 		}
2032 		keycount = i;
2033 	}
2034 	else
2035 		attNos = NULL;
2036 
2037 	/*
2038 	 * Create the Check Constraint
2039 	 */
2040 	constrOid =
2041 		CreateConstraintEntry(ccname,	/* Constraint Name */
2042 							  RelationGetNamespace(rel),		/* namespace */
2043 							  CONSTRAINT_CHECK, /* Constraint Type */
2044 							  false,	/* Is Deferrable */
2045 							  false,	/* Is Deferred */
2046 							  is_validated,
2047 							  RelationGetRelid(rel),	/* relation */
2048 							  attNos,	/* attrs in the constraint */
2049 							  keycount, /* # attrs in the constraint */
2050 							  InvalidOid,		/* not a domain constraint */
2051 							  InvalidOid,		/* no associated index */
2052 							  InvalidOid,		/* Foreign key fields */
2053 							  NULL,
2054 							  NULL,
2055 							  NULL,
2056 							  NULL,
2057 							  0,
2058 							  ' ',
2059 							  ' ',
2060 							  ' ',
2061 							  NULL,		/* not an exclusion constraint */
2062 							  expr,		/* Tree form of check constraint */
2063 							  ccbin,	/* Binary form of check constraint */
2064 							  ccsrc,	/* Source form of check constraint */
2065 							  is_local, /* conislocal */
2066 							  inhcount, /* coninhcount */
2067 							  is_no_inherit,	/* connoinherit */
2068 							  is_internal);		/* internally constructed? */
2069 
2070 	pfree(ccbin);
2071 	pfree(ccsrc);
2072 
2073 	return constrOid;
2074 }
2075 
2076 /*
2077  * Store defaults and constraints (passed as a list of CookedConstraint).
2078  *
2079  * Each CookedConstraint struct is modified to store the new catalog tuple OID.
2080  *
2081  * NOTE: only pre-cooked expressions will be passed this way, which is to
2082  * say expressions inherited from an existing relation.  Newly parsed
2083  * expressions can be added later, by direct calls to StoreAttrDefault
2084  * and StoreRelCheck (see AddRelationNewConstraints()).
2085  */
2086 static void
StoreConstraints(Relation rel,List * cooked_constraints,bool is_internal)2087 StoreConstraints(Relation rel, List *cooked_constraints, bool is_internal)
2088 {
2089 	int			numchecks = 0;
2090 	ListCell   *lc;
2091 
2092 	if (cooked_constraints == NIL)
2093 		return;					/* nothing to do */
2094 
2095 	/*
2096 	 * Deparsing of constraint expressions will fail unless the just-created
2097 	 * pg_attribute tuples for this relation are made visible.  So, bump the
2098 	 * command counter.  CAUTION: this will cause a relcache entry rebuild.
2099 	 */
2100 	CommandCounterIncrement();
2101 
2102 	foreach(lc, cooked_constraints)
2103 	{
2104 		CookedConstraint *con = (CookedConstraint *) lfirst(lc);
2105 
2106 		switch (con->contype)
2107 		{
2108 			case CONSTR_DEFAULT:
2109 				con->conoid = StoreAttrDefault(rel, con->attnum, con->expr,
2110 											   is_internal);
2111 				break;
2112 			case CONSTR_CHECK:
2113 				con->conoid =
2114 					StoreRelCheck(rel, con->name, con->expr,
2115 								  !con->skip_validation, con->is_local,
2116 								  con->inhcount, con->is_no_inherit,
2117 								  is_internal);
2118 				numchecks++;
2119 				break;
2120 			default:
2121 				elog(ERROR, "unrecognized constraint type: %d",
2122 					 (int) con->contype);
2123 		}
2124 	}
2125 
2126 	if (numchecks > 0)
2127 		SetRelationNumChecks(rel, numchecks);
2128 }
2129 
2130 /*
2131  * AddRelationNewConstraints
2132  *
2133  * Add new column default expressions and/or constraint check expressions
2134  * to an existing relation.  This is defined to do both for efficiency in
2135  * DefineRelation, but of course you can do just one or the other by passing
2136  * empty lists.
2137  *
2138  * rel: relation to be modified
2139  * newColDefaults: list of RawColumnDefault structures
2140  * newConstraints: list of Constraint nodes
2141  * allow_merge: TRUE if check constraints may be merged with existing ones
2142  * is_local: TRUE if definition is local, FALSE if it's inherited
2143  * is_internal: TRUE if result of some internal process, not a user request
2144  *
2145  * All entries in newColDefaults will be processed.  Entries in newConstraints
2146  * will be processed only if they are CONSTR_CHECK type.
2147  *
2148  * Returns a list of CookedConstraint nodes that shows the cooked form of
2149  * the default and constraint expressions added to the relation.
2150  *
2151  * NB: caller should have opened rel with AccessExclusiveLock, and should
2152  * hold that lock till end of transaction.  Also, we assume the caller has
2153  * done a CommandCounterIncrement if necessary to make the relation's catalog
2154  * tuples visible.
2155  */
2156 List *
AddRelationNewConstraints(Relation rel,List * newColDefaults,List * newConstraints,bool allow_merge,bool is_local,bool is_internal)2157 AddRelationNewConstraints(Relation rel,
2158 						  List *newColDefaults,
2159 						  List *newConstraints,
2160 						  bool allow_merge,
2161 						  bool is_local,
2162 						  bool is_internal)
2163 {
2164 	List	   *cookedConstraints = NIL;
2165 	TupleDesc	tupleDesc;
2166 	TupleConstr *oldconstr;
2167 	int			numoldchecks;
2168 	ParseState *pstate;
2169 	RangeTblEntry *rte;
2170 	int			numchecks;
2171 	List	   *checknames;
2172 	ListCell   *cell;
2173 	Node	   *expr;
2174 	CookedConstraint *cooked;
2175 
2176 	/*
2177 	 * Get info about existing constraints.
2178 	 */
2179 	tupleDesc = RelationGetDescr(rel);
2180 	oldconstr = tupleDesc->constr;
2181 	if (oldconstr)
2182 		numoldchecks = oldconstr->num_check;
2183 	else
2184 		numoldchecks = 0;
2185 
2186 	/*
2187 	 * Create a dummy ParseState and insert the target relation as its sole
2188 	 * rangetable entry.  We need a ParseState for transformExpr.
2189 	 */
2190 	pstate = make_parsestate(NULL);
2191 	rte = addRangeTableEntryForRelation(pstate,
2192 										rel,
2193 										NULL,
2194 										false,
2195 										true);
2196 	addRTEtoQuery(pstate, rte, true, true, true);
2197 
2198 	/*
2199 	 * Process column default expressions.
2200 	 */
2201 	foreach(cell, newColDefaults)
2202 	{
2203 		RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
2204 		Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
2205 		Oid			defOid;
2206 
2207 		expr = cookDefault(pstate, colDef->raw_default,
2208 						   atp->atttypid, atp->atttypmod,
2209 						   NameStr(atp->attname));
2210 
2211 		/*
2212 		 * If the expression is just a NULL constant, we do not bother to make
2213 		 * an explicit pg_attrdef entry, since the default behavior is
2214 		 * equivalent.
2215 		 *
2216 		 * Note a nonobvious property of this test: if the column is of a
2217 		 * domain type, what we'll get is not a bare null Const but a
2218 		 * CoerceToDomain expr, so we will not discard the default.  This is
2219 		 * critical because the column default needs to be retained to
2220 		 * override any default that the domain might have.
2221 		 */
2222 		if (expr == NULL ||
2223 			(IsA(expr, Const) &&((Const *) expr)->constisnull))
2224 			continue;
2225 
2226 		defOid = StoreAttrDefault(rel, colDef->attnum, expr, is_internal);
2227 
2228 		cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2229 		cooked->contype = CONSTR_DEFAULT;
2230 		cooked->conoid = defOid;
2231 		cooked->name = NULL;
2232 		cooked->attnum = colDef->attnum;
2233 		cooked->expr = expr;
2234 		cooked->skip_validation = false;
2235 		cooked->is_local = is_local;
2236 		cooked->inhcount = is_local ? 0 : 1;
2237 		cooked->is_no_inherit = false;
2238 		cookedConstraints = lappend(cookedConstraints, cooked);
2239 	}
2240 
2241 	/*
2242 	 * Process constraint expressions.
2243 	 */
2244 	numchecks = numoldchecks;
2245 	checknames = NIL;
2246 	foreach(cell, newConstraints)
2247 	{
2248 		Constraint *cdef = (Constraint *) lfirst(cell);
2249 		char	   *ccname;
2250 		Oid			constrOid;
2251 
2252 		if (cdef->contype != CONSTR_CHECK)
2253 			continue;
2254 
2255 		if (cdef->raw_expr != NULL)
2256 		{
2257 			Assert(cdef->cooked_expr == NULL);
2258 
2259 			/*
2260 			 * Transform raw parsetree to executable expression, and verify
2261 			 * it's valid as a CHECK constraint.
2262 			 */
2263 			expr = cookConstraint(pstate, cdef->raw_expr,
2264 								  RelationGetRelationName(rel));
2265 		}
2266 		else
2267 		{
2268 			Assert(cdef->cooked_expr != NULL);
2269 
2270 			/*
2271 			 * Here, we assume the parser will only pass us valid CHECK
2272 			 * expressions, so we do no particular checking.
2273 			 */
2274 			expr = stringToNode(cdef->cooked_expr);
2275 		}
2276 
2277 		/*
2278 		 * Check name uniqueness, or generate a name if none was given.
2279 		 */
2280 		if (cdef->conname != NULL)
2281 		{
2282 			ListCell   *cell2;
2283 
2284 			ccname = cdef->conname;
2285 			/* Check against other new constraints */
2286 			/* Needed because we don't do CommandCounterIncrement in loop */
2287 			foreach(cell2, checknames)
2288 			{
2289 				if (strcmp((char *) lfirst(cell2), ccname) == 0)
2290 					ereport(ERROR,
2291 							(errcode(ERRCODE_DUPLICATE_OBJECT),
2292 							 errmsg("check constraint \"%s\" already exists",
2293 									ccname)));
2294 			}
2295 
2296 			/* save name for future checks */
2297 			checknames = lappend(checknames, ccname);
2298 
2299 			/*
2300 			 * Check against pre-existing constraints.  If we are allowed to
2301 			 * merge with an existing constraint, there's no more to do here.
2302 			 * (We omit the duplicate constraint from the result, which is
2303 			 * what ATAddCheckConstraint wants.)
2304 			 */
2305 			if (MergeWithExistingConstraint(rel, ccname, expr,
2306 											allow_merge, is_local,
2307 											cdef->initially_valid,
2308 											cdef->is_no_inherit))
2309 				continue;
2310 		}
2311 		else
2312 		{
2313 			/*
2314 			 * When generating a name, we want to create "tab_col_check" for a
2315 			 * column constraint and "tab_check" for a table constraint.  We
2316 			 * no longer have any info about the syntactic positioning of the
2317 			 * constraint phrase, so we approximate this by seeing whether the
2318 			 * expression references more than one column.  (If the user
2319 			 * played by the rules, the result is the same...)
2320 			 *
2321 			 * Note: pull_var_clause() doesn't descend into sublinks, but we
2322 			 * eliminated those above; and anyway this only needs to be an
2323 			 * approximate answer.
2324 			 */
2325 			List	   *vars;
2326 			char	   *colname;
2327 
2328 			vars = pull_var_clause(expr, 0);
2329 
2330 			/* eliminate duplicates */
2331 			vars = list_union(NIL, vars);
2332 
2333 			if (list_length(vars) == 1)
2334 				colname = get_attname(RelationGetRelid(rel),
2335 									  ((Var *) linitial(vars))->varattno);
2336 			else
2337 				colname = NULL;
2338 
2339 			ccname = ChooseConstraintName(RelationGetRelationName(rel),
2340 										  colname,
2341 										  "check",
2342 										  RelationGetNamespace(rel),
2343 										  checknames);
2344 
2345 			/* save name for future checks */
2346 			checknames = lappend(checknames, ccname);
2347 		}
2348 
2349 		/*
2350 		 * OK, store it.
2351 		 */
2352 		constrOid =
2353 			StoreRelCheck(rel, ccname, expr, cdef->initially_valid, is_local,
2354 						  is_local ? 0 : 1, cdef->is_no_inherit, is_internal);
2355 
2356 		numchecks++;
2357 
2358 		cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2359 		cooked->contype = CONSTR_CHECK;
2360 		cooked->conoid = constrOid;
2361 		cooked->name = ccname;
2362 		cooked->attnum = 0;
2363 		cooked->expr = expr;
2364 		cooked->skip_validation = cdef->skip_validation;
2365 		cooked->is_local = is_local;
2366 		cooked->inhcount = is_local ? 0 : 1;
2367 		cooked->is_no_inherit = cdef->is_no_inherit;
2368 		cookedConstraints = lappend(cookedConstraints, cooked);
2369 	}
2370 
2371 	/*
2372 	 * Update the count of constraints in the relation's pg_class tuple. We do
2373 	 * this even if there was no change, in order to ensure that an SI update
2374 	 * message is sent out for the pg_class tuple, which will force other
2375 	 * backends to rebuild their relcache entries for the rel. (This is
2376 	 * critical if we added defaults but not constraints.)
2377 	 */
2378 	SetRelationNumChecks(rel, numchecks);
2379 
2380 	return cookedConstraints;
2381 }
2382 
2383 /*
2384  * Check for a pre-existing check constraint that conflicts with a proposed
2385  * new one, and either adjust its conislocal/coninhcount settings or throw
2386  * error as needed.
2387  *
2388  * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2389  * got a so-far-unique name, or throws error if conflict.
2390  *
2391  * XXX See MergeConstraintsIntoExisting too if you change this code.
2392  */
2393 static bool
MergeWithExistingConstraint(Relation rel,char * ccname,Node * expr,bool allow_merge,bool is_local,bool is_initially_valid,bool is_no_inherit)2394 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2395 							bool allow_merge, bool is_local,
2396 							bool is_initially_valid,
2397 							bool is_no_inherit)
2398 {
2399 	bool		found;
2400 	Relation	conDesc;
2401 	SysScanDesc conscan;
2402 	ScanKeyData skey[2];
2403 	HeapTuple	tup;
2404 
2405 	/* Search for a pg_constraint entry with same name and relation */
2406 	conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2407 
2408 	found = false;
2409 
2410 	ScanKeyInit(&skey[0],
2411 				Anum_pg_constraint_conname,
2412 				BTEqualStrategyNumber, F_NAMEEQ,
2413 				CStringGetDatum(ccname));
2414 
2415 	ScanKeyInit(&skey[1],
2416 				Anum_pg_constraint_connamespace,
2417 				BTEqualStrategyNumber, F_OIDEQ,
2418 				ObjectIdGetDatum(RelationGetNamespace(rel)));
2419 
2420 	conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2421 								 NULL, 2, skey);
2422 
2423 	while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2424 	{
2425 		Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2426 
2427 		if (con->conrelid == RelationGetRelid(rel))
2428 		{
2429 			/* Found it.  Conflicts if not identical check constraint */
2430 			if (con->contype == CONSTRAINT_CHECK)
2431 			{
2432 				Datum		val;
2433 				bool		isnull;
2434 
2435 				val = fastgetattr(tup,
2436 								  Anum_pg_constraint_conbin,
2437 								  conDesc->rd_att, &isnull);
2438 				if (isnull)
2439 					elog(ERROR, "null conbin for rel %s",
2440 						 RelationGetRelationName(rel));
2441 				if (equal(expr, stringToNode(TextDatumGetCString(val))))
2442 					found = true;
2443 			}
2444 
2445 			/*
2446 			 * If the existing constraint is purely inherited (no local
2447 			 * definition) then interpret addition of a local constraint as a
2448 			 * legal merge.  This allows ALTER ADD CONSTRAINT on parent and
2449 			 * child tables to be given in either order with same end state.
2450 			 */
2451 			if (is_local && !con->conislocal)
2452 				allow_merge = true;
2453 
2454 			if (!found || !allow_merge)
2455 				ereport(ERROR,
2456 						(errcode(ERRCODE_DUPLICATE_OBJECT),
2457 				errmsg("constraint \"%s\" for relation \"%s\" already exists",
2458 					   ccname, RelationGetRelationName(rel))));
2459 
2460 			/* If the child constraint is "no inherit" then cannot merge */
2461 			if (con->connoinherit)
2462 				ereport(ERROR,
2463 						(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2464 						 errmsg("constraint \"%s\" conflicts with non-inherited constraint on relation \"%s\"",
2465 								ccname, RelationGetRelationName(rel))));
2466 
2467 			/*
2468 			 * Must not change an existing inherited constraint to "no
2469 			 * inherit" status.  That's because inherited constraints should
2470 			 * be able to propagate to lower-level children.
2471 			 */
2472 			if (con->coninhcount > 0 && is_no_inherit)
2473 				ereport(ERROR,
2474 						(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2475 						 errmsg("constraint \"%s\" conflicts with inherited constraint on relation \"%s\"",
2476 								ccname, RelationGetRelationName(rel))));
2477 
2478 			/*
2479 			 * If the child constraint is "not valid" then cannot merge with a
2480 			 * valid parent constraint
2481 			 */
2482 			if (is_initially_valid && !con->convalidated)
2483 				ereport(ERROR,
2484 						(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2485 						 errmsg("constraint \"%s\" conflicts with NOT VALID constraint on relation \"%s\"",
2486 								ccname, RelationGetRelationName(rel))));
2487 
2488 			/* OK to update the tuple */
2489 			ereport(NOTICE,
2490 			   (errmsg("merging constraint \"%s\" with inherited definition",
2491 					   ccname)));
2492 
2493 			tup = heap_copytuple(tup);
2494 			con = (Form_pg_constraint) GETSTRUCT(tup);
2495 
2496 			if (is_local)
2497 				con->conislocal = true;
2498 			else
2499 				con->coninhcount++;
2500 			if (is_no_inherit)
2501 			{
2502 				Assert(is_local);
2503 				con->connoinherit = true;
2504 			}
2505 			simple_heap_update(conDesc, &tup->t_self, tup);
2506 			CatalogUpdateIndexes(conDesc, tup);
2507 			break;
2508 		}
2509 	}
2510 
2511 	systable_endscan(conscan);
2512 	heap_close(conDesc, RowExclusiveLock);
2513 
2514 	return found;
2515 }
2516 
2517 /*
2518  * Update the count of constraints in the relation's pg_class tuple.
2519  *
2520  * Caller had better hold exclusive lock on the relation.
2521  *
2522  * An important side effect is that a SI update message will be sent out for
2523  * the pg_class tuple, which will force other backends to rebuild their
2524  * relcache entries for the rel.  Also, this backend will rebuild its
2525  * own relcache entry at the next CommandCounterIncrement.
2526  */
2527 static void
SetRelationNumChecks(Relation rel,int numchecks)2528 SetRelationNumChecks(Relation rel, int numchecks)
2529 {
2530 	Relation	relrel;
2531 	HeapTuple	reltup;
2532 	Form_pg_class relStruct;
2533 
2534 	relrel = heap_open(RelationRelationId, RowExclusiveLock);
2535 	reltup = SearchSysCacheCopy1(RELOID,
2536 								 ObjectIdGetDatum(RelationGetRelid(rel)));
2537 	if (!HeapTupleIsValid(reltup))
2538 		elog(ERROR, "cache lookup failed for relation %u",
2539 			 RelationGetRelid(rel));
2540 	relStruct = (Form_pg_class) GETSTRUCT(reltup);
2541 
2542 	if (relStruct->relchecks != numchecks)
2543 	{
2544 		relStruct->relchecks = numchecks;
2545 
2546 		simple_heap_update(relrel, &reltup->t_self, reltup);
2547 
2548 		/* keep catalog indexes current */
2549 		CatalogUpdateIndexes(relrel, reltup);
2550 	}
2551 	else
2552 	{
2553 		/* Skip the disk update, but force relcache inval anyway */
2554 		CacheInvalidateRelcache(rel);
2555 	}
2556 
2557 	heap_freetuple(reltup);
2558 	heap_close(relrel, RowExclusiveLock);
2559 }
2560 
2561 /*
2562  * Take a raw default and convert it to a cooked format ready for
2563  * storage.
2564  *
2565  * Parse state should be set up to recognize any vars that might appear
2566  * in the expression.  (Even though we plan to reject vars, it's more
2567  * user-friendly to give the correct error message than "unknown var".)
2568  *
2569  * If atttypid is not InvalidOid, coerce the expression to the specified
2570  * type (and typmod atttypmod).   attname is only needed in this case:
2571  * it is used in the error message, if any.
2572  */
2573 Node *
cookDefault(ParseState * pstate,Node * raw_default,Oid atttypid,int32 atttypmod,char * attname)2574 cookDefault(ParseState *pstate,
2575 			Node *raw_default,
2576 			Oid atttypid,
2577 			int32 atttypmod,
2578 			char *attname)
2579 {
2580 	Node	   *expr;
2581 
2582 	Assert(raw_default != NULL);
2583 
2584 	/*
2585 	 * Transform raw parsetree to executable expression.
2586 	 */
2587 	expr = transformExpr(pstate, raw_default, EXPR_KIND_COLUMN_DEFAULT);
2588 
2589 	/*
2590 	 * Make sure default expr does not refer to any vars (we need this check
2591 	 * since the pstate includes the target table).
2592 	 */
2593 	if (contain_var_clause(expr))
2594 		ereport(ERROR,
2595 				(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2596 			  errmsg("cannot use column references in default expression")));
2597 
2598 	/*
2599 	 * transformExpr() should have already rejected subqueries, aggregates,
2600 	 * and window functions, based on the EXPR_KIND_ for a default expression.
2601 	 *
2602 	 * It can't return a set either.
2603 	 */
2604 	if (expression_returns_set(expr))
2605 		ereport(ERROR,
2606 				(errcode(ERRCODE_DATATYPE_MISMATCH),
2607 				 errmsg("default expression must not return a set")));
2608 
2609 	/*
2610 	 * Coerce the expression to the correct type and typmod, if given. This
2611 	 * should match the parser's processing of non-defaulted expressions ---
2612 	 * see transformAssignedExpr().
2613 	 */
2614 	if (OidIsValid(atttypid))
2615 	{
2616 		Oid			type_id = exprType(expr);
2617 
2618 		expr = coerce_to_target_type(pstate, expr, type_id,
2619 									 atttypid, atttypmod,
2620 									 COERCION_ASSIGNMENT,
2621 									 COERCE_IMPLICIT_CAST,
2622 									 -1);
2623 		if (expr == NULL)
2624 			ereport(ERROR,
2625 					(errcode(ERRCODE_DATATYPE_MISMATCH),
2626 					 errmsg("column \"%s\" is of type %s"
2627 							" but default expression is of type %s",
2628 							attname,
2629 							format_type_be(atttypid),
2630 							format_type_be(type_id)),
2631 			   errhint("You will need to rewrite or cast the expression.")));
2632 	}
2633 
2634 	/*
2635 	 * Finally, take care of collations in the finished expression.
2636 	 */
2637 	assign_expr_collations(pstate, expr);
2638 
2639 	return expr;
2640 }
2641 
2642 /*
2643  * Take a raw CHECK constraint expression and convert it to a cooked format
2644  * ready for storage.
2645  *
2646  * Parse state must be set up to recognize any vars that might appear
2647  * in the expression.
2648  */
2649 static Node *
cookConstraint(ParseState * pstate,Node * raw_constraint,char * relname)2650 cookConstraint(ParseState *pstate,
2651 			   Node *raw_constraint,
2652 			   char *relname)
2653 {
2654 	Node	   *expr;
2655 
2656 	/*
2657 	 * Transform raw parsetree to executable expression.
2658 	 */
2659 	expr = transformExpr(pstate, raw_constraint, EXPR_KIND_CHECK_CONSTRAINT);
2660 
2661 	/*
2662 	 * Make sure it yields a boolean result.
2663 	 */
2664 	expr = coerce_to_boolean(pstate, expr, "CHECK");
2665 
2666 	/*
2667 	 * Take care of collations.
2668 	 */
2669 	assign_expr_collations(pstate, expr);
2670 
2671 	/*
2672 	 * Make sure no outside relations are referred to (this is probably dead
2673 	 * code now that add_missing_from is history).
2674 	 */
2675 	if (list_length(pstate->p_rtable) != 1)
2676 		ereport(ERROR,
2677 				(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2678 			errmsg("only table \"%s\" can be referenced in check constraint",
2679 				   relname)));
2680 
2681 	return expr;
2682 }
2683 
2684 
2685 /*
2686  * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2687  *
2688  * If attnum is zero, remove all entries for rel; else remove only the one(s)
2689  * for that column.
2690  */
2691 void
RemoveStatistics(Oid relid,AttrNumber attnum)2692 RemoveStatistics(Oid relid, AttrNumber attnum)
2693 {
2694 	Relation	pgstatistic;
2695 	SysScanDesc scan;
2696 	ScanKeyData key[2];
2697 	int			nkeys;
2698 	HeapTuple	tuple;
2699 
2700 	pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2701 
2702 	ScanKeyInit(&key[0],
2703 				Anum_pg_statistic_starelid,
2704 				BTEqualStrategyNumber, F_OIDEQ,
2705 				ObjectIdGetDatum(relid));
2706 
2707 	if (attnum == 0)
2708 		nkeys = 1;
2709 	else
2710 	{
2711 		ScanKeyInit(&key[1],
2712 					Anum_pg_statistic_staattnum,
2713 					BTEqualStrategyNumber, F_INT2EQ,
2714 					Int16GetDatum(attnum));
2715 		nkeys = 2;
2716 	}
2717 
2718 	scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2719 							  NULL, nkeys, key);
2720 
2721 	/* we must loop even when attnum != 0, in case of inherited stats */
2722 	while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2723 		simple_heap_delete(pgstatistic, &tuple->t_self);
2724 
2725 	systable_endscan(scan);
2726 
2727 	heap_close(pgstatistic, RowExclusiveLock);
2728 }
2729 
2730 
2731 /*
2732  * RelationTruncateIndexes - truncate all indexes associated
2733  * with the heap relation to zero tuples.
2734  *
2735  * The routine will truncate and then reconstruct the indexes on
2736  * the specified relation.  Caller must hold exclusive lock on rel.
2737  */
2738 static void
RelationTruncateIndexes(Relation heapRelation)2739 RelationTruncateIndexes(Relation heapRelation)
2740 {
2741 	ListCell   *indlist;
2742 
2743 	/* Ask the relcache to produce a list of the indexes of the rel */
2744 	foreach(indlist, RelationGetIndexList(heapRelation))
2745 	{
2746 		Oid			indexId = lfirst_oid(indlist);
2747 		Relation	currentIndex;
2748 		IndexInfo  *indexInfo;
2749 
2750 		/* Open the index relation; use exclusive lock, just to be sure */
2751 		currentIndex = index_open(indexId, AccessExclusiveLock);
2752 
2753 		/*
2754 		 * Fetch info needed for index_build.  Since we know there are no
2755 		 * tuples that actually need indexing, we can use a dummy IndexInfo.
2756 		 * This is slightly cheaper to build, but the real point is to avoid
2757 		 * possibly running user-defined code in index expressions or
2758 		 * predicates.  We might be getting invoked during ON COMMIT
2759 		 * processing, and we don't want to run any such code then.
2760 		 */
2761 		indexInfo = BuildDummyIndexInfo(currentIndex);
2762 
2763 		/*
2764 		 * Now truncate the actual file (and discard buffers).
2765 		 */
2766 		RelationTruncate(currentIndex, 0);
2767 
2768 		/* Initialize the index and rebuild */
2769 		/* Note: we do not need to re-establish pkey setting */
2770 		index_build(heapRelation, currentIndex, indexInfo, false, true);
2771 
2772 		/* We're done with this index */
2773 		index_close(currentIndex, NoLock);
2774 	}
2775 }
2776 
2777 /*
2778  *	 heap_truncate
2779  *
2780  *	 This routine deletes all data within all the specified relations.
2781  *
2782  * This is not transaction-safe!  There is another, transaction-safe
2783  * implementation in commands/tablecmds.c.  We now use this only for
2784  * ON COMMIT truncation of temporary tables, where it doesn't matter.
2785  */
2786 void
heap_truncate(List * relids)2787 heap_truncate(List *relids)
2788 {
2789 	List	   *relations = NIL;
2790 	ListCell   *cell;
2791 
2792 	/* Open relations for processing, and grab exclusive access on each */
2793 	foreach(cell, relids)
2794 	{
2795 		Oid			rid = lfirst_oid(cell);
2796 		Relation	rel;
2797 
2798 		rel = heap_open(rid, AccessExclusiveLock);
2799 		relations = lappend(relations, rel);
2800 	}
2801 
2802 	/* Don't allow truncate on tables that are referenced by foreign keys */
2803 	heap_truncate_check_FKs(relations, true);
2804 
2805 	/* OK to do it */
2806 	foreach(cell, relations)
2807 	{
2808 		Relation	rel = lfirst(cell);
2809 
2810 		/* Truncate the relation */
2811 		heap_truncate_one_rel(rel);
2812 
2813 		/* Close the relation, but keep exclusive lock on it until commit */
2814 		heap_close(rel, NoLock);
2815 	}
2816 }
2817 
2818 /*
2819  *	 heap_truncate_one_rel
2820  *
2821  *	 This routine deletes all data within the specified relation.
2822  *
2823  * This is not transaction-safe, because the truncation is done immediately
2824  * and cannot be rolled back later.  Caller is responsible for having
2825  * checked permissions etc, and must have obtained AccessExclusiveLock.
2826  */
2827 void
heap_truncate_one_rel(Relation rel)2828 heap_truncate_one_rel(Relation rel)
2829 {
2830 	Oid			toastrelid;
2831 
2832 	/* Truncate the actual file (and discard buffers) */
2833 	RelationTruncate(rel, 0);
2834 
2835 	/* If the relation has indexes, truncate the indexes too */
2836 	RelationTruncateIndexes(rel);
2837 
2838 	/* If there is a toast table, truncate that too */
2839 	toastrelid = rel->rd_rel->reltoastrelid;
2840 	if (OidIsValid(toastrelid))
2841 	{
2842 		Relation	toastrel = heap_open(toastrelid, AccessExclusiveLock);
2843 
2844 		RelationTruncate(toastrel, 0);
2845 		RelationTruncateIndexes(toastrel);
2846 		/* keep the lock... */
2847 		heap_close(toastrel, NoLock);
2848 	}
2849 }
2850 
2851 /*
2852  * heap_truncate_check_FKs
2853  *		Check for foreign keys referencing a list of relations that
2854  *		are to be truncated, and raise error if there are any
2855  *
2856  * We disallow such FKs (except self-referential ones) since the whole point
2857  * of TRUNCATE is to not scan the individual rows to be thrown away.
2858  *
2859  * This is split out so it can be shared by both implementations of truncate.
2860  * Caller should already hold a suitable lock on the relations.
2861  *
2862  * tempTables is only used to select an appropriate error message.
2863  */
2864 void
heap_truncate_check_FKs(List * relations,bool tempTables)2865 heap_truncate_check_FKs(List *relations, bool tempTables)
2866 {
2867 	List	   *oids = NIL;
2868 	List	   *dependents;
2869 	ListCell   *cell;
2870 
2871 	/*
2872 	 * Build a list of OIDs of the interesting relations.
2873 	 *
2874 	 * If a relation has no triggers, then it can neither have FKs nor be
2875 	 * referenced by a FK from another table, so we can ignore it.
2876 	 */
2877 	foreach(cell, relations)
2878 	{
2879 		Relation	rel = lfirst(cell);
2880 
2881 		if (rel->rd_rel->relhastriggers)
2882 			oids = lappend_oid(oids, RelationGetRelid(rel));
2883 	}
2884 
2885 	/*
2886 	 * Fast path: if no relation has triggers, none has FKs either.
2887 	 */
2888 	if (oids == NIL)
2889 		return;
2890 
2891 	/*
2892 	 * Otherwise, must scan pg_constraint.  We make one pass with all the
2893 	 * relations considered; if this finds nothing, then all is well.
2894 	 */
2895 	dependents = heap_truncate_find_FKs(oids);
2896 	if (dependents == NIL)
2897 		return;
2898 
2899 	/*
2900 	 * Otherwise we repeat the scan once per relation to identify a particular
2901 	 * pair of relations to complain about.  This is pretty slow, but
2902 	 * performance shouldn't matter much in a failure path.  The reason for
2903 	 * doing things this way is to ensure that the message produced is not
2904 	 * dependent on chance row locations within pg_constraint.
2905 	 */
2906 	foreach(cell, oids)
2907 	{
2908 		Oid			relid = lfirst_oid(cell);
2909 		ListCell   *cell2;
2910 
2911 		dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2912 
2913 		foreach(cell2, dependents)
2914 		{
2915 			Oid			relid2 = lfirst_oid(cell2);
2916 
2917 			if (!list_member_oid(oids, relid2))
2918 			{
2919 				char	   *relname = get_rel_name(relid);
2920 				char	   *relname2 = get_rel_name(relid2);
2921 
2922 				if (tempTables)
2923 					ereport(ERROR,
2924 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2925 							 errmsg("unsupported ON COMMIT and foreign key combination"),
2926 							 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2927 									   relname2, relname)));
2928 				else
2929 					ereport(ERROR,
2930 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2931 							 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2932 							 errdetail("Table \"%s\" references \"%s\".",
2933 									   relname2, relname),
2934 						   errhint("Truncate table \"%s\" at the same time, "
2935 								   "or use TRUNCATE ... CASCADE.",
2936 								   relname2)));
2937 			}
2938 		}
2939 	}
2940 }
2941 
2942 /*
2943  * heap_truncate_find_FKs
2944  *		Find relations having foreign keys referencing any of the given rels
2945  *
2946  * Input and result are both lists of relation OIDs.  The result contains
2947  * no duplicates, does *not* include any rels that were already in the input
2948  * list, and is sorted in OID order.  (The last property is enforced mainly
2949  * to guarantee consistent behavior in the regression tests; we don't want
2950  * behavior to change depending on chance locations of rows in pg_constraint.)
2951  *
2952  * Note: caller should already have appropriate lock on all rels mentioned
2953  * in relationIds.  Since adding or dropping an FK requires exclusive lock
2954  * on both rels, this ensures that the answer will be stable.
2955  */
2956 List *
heap_truncate_find_FKs(List * relationIds)2957 heap_truncate_find_FKs(List *relationIds)
2958 {
2959 	List	   *result = NIL;
2960 	Relation	fkeyRel;
2961 	SysScanDesc fkeyScan;
2962 	HeapTuple	tuple;
2963 
2964 	/*
2965 	 * Must scan pg_constraint.  Right now, it is a seqscan because there is
2966 	 * no available index on confrelid.
2967 	 */
2968 	fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2969 
2970 	fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2971 								  NULL, 0, NULL);
2972 
2973 	while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2974 	{
2975 		Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2976 
2977 		/* Not a foreign key */
2978 		if (con->contype != CONSTRAINT_FOREIGN)
2979 			continue;
2980 
2981 		/* Not referencing one of our list of tables */
2982 		if (!list_member_oid(relationIds, con->confrelid))
2983 			continue;
2984 
2985 		/* Add referencer unless already in input or result list */
2986 		if (!list_member_oid(relationIds, con->conrelid))
2987 			result = insert_ordered_unique_oid(result, con->conrelid);
2988 	}
2989 
2990 	systable_endscan(fkeyScan);
2991 	heap_close(fkeyRel, AccessShareLock);
2992 
2993 	return result;
2994 }
2995 
2996 /*
2997  * insert_ordered_unique_oid
2998  *		Insert a new Oid into a sorted list of Oids, preserving ordering,
2999  *		and eliminating duplicates
3000  *
3001  * Building the ordered list this way is O(N^2), but with a pretty small
3002  * constant, so for the number of entries we expect it will probably be
3003  * faster than trying to apply qsort().  It seems unlikely someone would be
3004  * trying to truncate a table with thousands of dependent tables ...
3005  */
3006 static List *
insert_ordered_unique_oid(List * list,Oid datum)3007 insert_ordered_unique_oid(List *list, Oid datum)
3008 {
3009 	ListCell   *prev;
3010 
3011 	/* Does the datum belong at the front? */
3012 	if (list == NIL || datum < linitial_oid(list))
3013 		return lcons_oid(datum, list);
3014 	/* Does it match the first entry? */
3015 	if (datum == linitial_oid(list))
3016 		return list;			/* duplicate, so don't insert */
3017 	/* No, so find the entry it belongs after */
3018 	prev = list_head(list);
3019 	for (;;)
3020 	{
3021 		ListCell   *curr = lnext(prev);
3022 
3023 		if (curr == NULL || datum < lfirst_oid(curr))
3024 			break;				/* it belongs after 'prev', before 'curr' */
3025 
3026 		if (datum == lfirst_oid(curr))
3027 			return list;		/* duplicate, so don't insert */
3028 
3029 		prev = curr;
3030 	}
3031 	/* Insert datum into list after 'prev' */
3032 	lappend_cell_oid(list, prev, datum);
3033 	return list;
3034 }
3035