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