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