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