]> granicus.if.org Git - postgresql/blob - src/backend/catalog/heap.c
Core support for "extensions", which are packages of SQL objects.
[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 /* Potentially set by contrib/pg_upgrade_support functions */
77 Oid                     binary_upgrade_next_heap_pg_class_oid = InvalidOid;
78 Oid                     binary_upgrade_next_toast_pg_class_oid = 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         values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(new_attribute->attcollation);
546
547         /* start out with empty permissions and empty options */
548         nulls[Anum_pg_attribute_attacl - 1] = true;
549         nulls[Anum_pg_attribute_attoptions - 1] = true;
550
551         tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
552
553         /* finally insert the new tuple, update the indexes, and clean up */
554         simple_heap_insert(pg_attribute_rel, tup);
555
556         if (indstate != NULL)
557                 CatalogIndexInsert(indstate, tup);
558         else
559                 CatalogUpdateIndexes(pg_attribute_rel, tup);
560
561         heap_freetuple(tup);
562 }
563
564 /* --------------------------------
565  *              AddNewAttributeTuples
566  *
567  *              this registers the new relation's schema by adding
568  *              tuples to pg_attribute.
569  * --------------------------------
570  */
571 static void
572 AddNewAttributeTuples(Oid new_rel_oid,
573                                           TupleDesc tupdesc,
574                                           char relkind,
575                                           bool oidislocal,
576                                           int oidinhcount)
577 {
578         Form_pg_attribute attr;
579         int                     i;
580         Relation        rel;
581         CatalogIndexState indstate;
582         int                     natts = tupdesc->natts;
583         ObjectAddress myself,
584                                 referenced;
585
586         /*
587          * open pg_attribute and its indexes.
588          */
589         rel = heap_open(AttributeRelationId, RowExclusiveLock);
590
591         indstate = CatalogOpenIndexes(rel);
592
593         /*
594          * First we add the user attributes.  This is also a convenient place to
595          * add dependencies on their datatypes.
596          */
597         for (i = 0; i < natts; i++)
598         {
599                 attr = tupdesc->attrs[i];
600                 /* Fill in the correct relation OID */
601                 attr->attrelid = new_rel_oid;
602                 /* Make sure these are OK, too */
603                 attr->attstattarget = -1;
604                 attr->attcacheoff = -1;
605
606                 InsertPgAttributeTuple(rel, attr, indstate);
607
608                 /* Add dependency info */
609                 myself.classId = RelationRelationId;
610                 myself.objectId = new_rel_oid;
611                 myself.objectSubId = i + 1;
612                 referenced.classId = TypeRelationId;
613                 referenced.objectId = attr->atttypid;
614                 referenced.objectSubId = 0;
615                 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
616         }
617
618         /*
619          * Next we add the system attributes.  Skip OID if rel has no OIDs. Skip
620          * all for a view or type relation.  We don't bother with making datatype
621          * dependencies here, since presumably all these types are pinned.
622          */
623         if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
624         {
625                 for (i = 0; i < (int) lengthof(SysAtt); i++)
626                 {
627                         FormData_pg_attribute attStruct;
628
629                         /* skip OID where appropriate */
630                         if (!tupdesc->tdhasoid &&
631                                 SysAtt[i]->attnum == ObjectIdAttributeNumber)
632                                 continue;
633
634                         memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
635
636                         /* Fill in the correct relation OID in the copied tuple */
637                         attStruct.attrelid = new_rel_oid;
638
639                         /* Fill in correct inheritance info for the OID column */
640                         if (attStruct.attnum == ObjectIdAttributeNumber)
641                         {
642                                 attStruct.attislocal = oidislocal;
643                                 attStruct.attinhcount = oidinhcount;
644                         }
645
646                         InsertPgAttributeTuple(rel, &attStruct, indstate);
647                 }
648         }
649
650         /*
651          * clean up
652          */
653         CatalogCloseIndexes(indstate);
654
655         heap_close(rel, RowExclusiveLock);
656 }
657
658 /* --------------------------------
659  *              InsertPgClassTuple
660  *
661  *              Construct and insert a new tuple in pg_class.
662  *
663  * Caller has already opened and locked pg_class.
664  * Tuple data is taken from new_rel_desc->rd_rel, except for the
665  * variable-width fields which are not present in a cached reldesc.
666  * relacl and reloptions are passed in Datum form (to avoid having
667  * to reference the data types in heap.h).      Pass (Datum) 0 to set them
668  * to NULL.
669  * --------------------------------
670  */
671 void
672 InsertPgClassTuple(Relation pg_class_desc,
673                                    Relation new_rel_desc,
674                                    Oid new_rel_oid,
675                                    Datum relacl,
676                                    Datum reloptions)
677 {
678         Form_pg_class rd_rel = new_rel_desc->rd_rel;
679         Datum           values[Natts_pg_class];
680         bool            nulls[Natts_pg_class];
681         HeapTuple       tup;
682
683         /* This is a tad tedious, but way cleaner than what we used to do... */
684         memset(values, 0, sizeof(values));
685         memset(nulls, false, sizeof(nulls));
686
687         values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
688         values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
689         values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
690         values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
691         values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
692         values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
693         values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
694         values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
695         values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
696         values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
697         values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
698         values[Anum_pg_class_reltoastidxid - 1] = ObjectIdGetDatum(rd_rel->reltoastidxid);
699         values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
700         values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
701         values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
702         values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
703         values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
704         values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
705         values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
706         values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
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                                    InvalidOid); /* typcollation */
865 }
866
867 /* --------------------------------
868  *              heap_create_with_catalog
869  *
870  *              creates a new cataloged relation.  see comments above.
871  *
872  * Arguments:
873  *      relname: name to give to new rel
874  *      relnamespace: OID of namespace it goes in
875  *      reltablespace: OID of tablespace it goes in
876  *      relid: OID to assign to new rel, or InvalidOid to select a new OID
877  *      reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
878  *      ownerid: OID of new rel's owner
879  *      tupdesc: tuple descriptor (source of column definitions)
880  *      cooked_constraints: list of precooked check constraints and defaults
881  *      relkind: relkind for new rel
882  *      shared_relation: TRUE if it's to be a shared relation
883  *      mapped_relation: TRUE if the relation will use the relfilenode map
884  *      oidislocal: TRUE if oid column (if any) should be marked attislocal
885  *      oidinhcount: attinhcount to assign to oid column (if any)
886  *      oncommit: ON COMMIT marking (only relevant if it's a temp table)
887  *      reloptions: reloptions in Datum form, or (Datum) 0 if none
888  *      use_user_acl: TRUE if should look for user-defined default permissions;
889  *              if FALSE, relacl is always set NULL
890  *      allow_system_table_mods: TRUE to allow creation in system namespaces
891  *
892  * Returns the OID of the new relation
893  * --------------------------------
894  */
895 Oid
896 heap_create_with_catalog(const char *relname,
897                                                  Oid relnamespace,
898                                                  Oid reltablespace,
899                                                  Oid relid,
900                                                  Oid reltypeid,
901                                                  Oid reloftypeid,
902                                                  Oid ownerid,
903                                                  TupleDesc tupdesc,
904                                                  List *cooked_constraints,
905                                                  char relkind,
906                                                  char relpersistence,
907                                                  bool shared_relation,
908                                                  bool mapped_relation,
909                                                  bool oidislocal,
910                                                  int oidinhcount,
911                                                  OnCommitAction oncommit,
912                                                  Datum reloptions,
913                                                  bool use_user_acl,
914                                                  bool allow_system_table_mods,
915                                                  bool if_not_exists)
916 {
917         Relation        pg_class_desc;
918         Relation        new_rel_desc;
919         Acl                *relacl;
920         Oid                     existing_relid;
921         Oid                     old_type_oid;
922         Oid                     new_type_oid;
923         Oid                     new_array_oid = InvalidOid;
924
925         pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
926
927         /*
928          * sanity checks
929          */
930         Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
931
932         CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
933
934         /*
935          * If the relation already exists, it's an error, unless the user specifies
936          * "IF NOT EXISTS".  In that case, we just print a notice and do nothing
937          * further.
938          */
939         existing_relid = get_relname_relid(relname, relnamespace);
940         if (existing_relid != InvalidOid)
941         {
942                 if (if_not_exists)
943                 {
944                         ereport(NOTICE,
945                                         (errcode(ERRCODE_DUPLICATE_TABLE),
946                                          errmsg("relation \"%s\" already exists, skipping",
947                                          relname)));
948                         heap_close(pg_class_desc, RowExclusiveLock);
949                         return InvalidOid;
950                 }
951                 ereport(ERROR,
952                                 (errcode(ERRCODE_DUPLICATE_TABLE),
953                                  errmsg("relation \"%s\" already exists", relname)));
954         }
955
956         /*
957          * Since we are going to create a rowtype as well, also check for
958          * collision with an existing type name.  If there is one and it's an
959          * autogenerated array, we can rename it out of the way; otherwise we can
960          * at least give a good error message.
961          */
962         old_type_oid = GetSysCacheOid2(TYPENAMENSP,
963                                                                    CStringGetDatum(relname),
964                                                                    ObjectIdGetDatum(relnamespace));
965         if (OidIsValid(old_type_oid))
966         {
967                 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
968                         ereport(ERROR,
969                                         (errcode(ERRCODE_DUPLICATE_OBJECT),
970                                          errmsg("type \"%s\" already exists", relname),
971                            errhint("A relation has an associated type of the same name, "
972                                            "so you must use a name that doesn't conflict "
973                                            "with any existing type.")));
974         }
975
976         /*
977          * Shared relations must be in pg_global (last-ditch check)
978          */
979         if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
980                 elog(ERROR, "shared relations must be placed in pg_global tablespace");
981
982         /*
983          * Allocate an OID for the relation, unless we were told what to use.
984          *
985          * The OID will be the relfilenode as well, so make sure it doesn't
986          * collide with either pg_class OIDs or existing physical files.
987          */
988         if (!OidIsValid(relid))
989         {
990                 /*
991                  *      Use binary-upgrade override for pg_class.oid/relfilenode,
992                  *      if supplied.
993                  */
994                 if (OidIsValid(binary_upgrade_next_heap_pg_class_oid) &&
995                         (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
996                          relkind == RELKIND_VIEW || relkind == RELKIND_COMPOSITE_TYPE ||
997                          relkind == RELKIND_FOREIGN_TABLE))
998                 {
999                         relid = binary_upgrade_next_heap_pg_class_oid;
1000                         binary_upgrade_next_heap_pg_class_oid = InvalidOid;
1001                 }
1002                 else if (OidIsValid(binary_upgrade_next_toast_pg_class_oid) &&
1003                                  relkind == RELKIND_TOASTVALUE)
1004                 {
1005                         relid = binary_upgrade_next_toast_pg_class_oid;
1006                         binary_upgrade_next_toast_pg_class_oid = InvalidOid;
1007                 }
1008                 else
1009                         relid = GetNewRelFileNode(reltablespace, pg_class_desc,
1010                                                                           relpersistence);
1011         }
1012
1013         /*
1014          * Determine the relation's initial permissions.
1015          */
1016         if (use_user_acl)
1017         {
1018                 switch (relkind)
1019                 {
1020                         case RELKIND_RELATION:
1021                         case RELKIND_VIEW:
1022                         case RELKIND_FOREIGN_TABLE:
1023                                 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1024                                                                                           relnamespace);
1025                                 break;
1026                         case RELKIND_SEQUENCE:
1027                                 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1028                                                                                           relnamespace);
1029                                 break;
1030                         default:
1031                                 relacl = NULL;
1032                                 break;
1033                 }
1034         }
1035         else
1036                 relacl = NULL;
1037
1038         /*
1039          * Create the relcache entry (mostly dummy at this point) and the physical
1040          * disk file.  (If we fail further down, it's the smgr's responsibility to
1041          * remove the disk file again.)
1042          */
1043         new_rel_desc = heap_create(relname,
1044                                                            relnamespace,
1045                                                            reltablespace,
1046                                                            relid,
1047                                                            tupdesc,
1048                                                            relkind,
1049                                                            relpersistence,
1050                                                            shared_relation,
1051                                                            mapped_relation,
1052                                                            allow_system_table_mods);
1053
1054         Assert(relid == RelationGetRelid(new_rel_desc));
1055
1056         /*
1057          * Decide whether to create an array type over the relation's rowtype. We
1058          * do not create any array types for system catalogs (ie, those made
1059          * during initdb).      We create array types for regular relations, views,
1060          * composite types and foreign tables ... but not, eg, for toast tables or
1061          * sequences.
1062          */
1063         if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1064                                                           relkind == RELKIND_VIEW ||
1065                                                           relkind == RELKIND_FOREIGN_TABLE ||
1066                                                           relkind == RELKIND_COMPOSITE_TYPE))
1067                 new_array_oid = AssignTypeArrayOid();
1068
1069         /*
1070          * Since defining a relation also defines a complex type, we add a new
1071          * system type corresponding to the new relation.  The OID of the type can
1072          * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1073          * generate a new OID for it.
1074          *
1075          * NOTE: we could get a unique-index failure here, in case someone else is
1076          * creating the same type name in parallel but hadn't committed yet when
1077          * we checked for a duplicate name above.
1078          */
1079         new_type_oid = AddNewRelationType(relname,
1080                                                                           relnamespace,
1081                                                                           relid,
1082                                                                           relkind,
1083                                                                           ownerid,
1084                                                                           reltypeid,
1085                                                                           new_array_oid);
1086
1087         /*
1088          * Now make the array type if wanted.
1089          */
1090         if (OidIsValid(new_array_oid))
1091         {
1092                 char       *relarrayname;
1093
1094                 relarrayname = makeArrayTypeName(relname, relnamespace);
1095
1096                 TypeCreate(new_array_oid,               /* force the type's OID to this */
1097                                    relarrayname,        /* Array type name */
1098                                    relnamespace,        /* Same namespace as parent */
1099                                    InvalidOid,  /* Not composite, no relationOid */
1100                                    0,                   /* relkind, also N/A here */
1101                                    ownerid,             /* owner's ID */
1102                                    -1,                  /* Internal size (varlena) */
1103                                    TYPTYPE_BASE,        /* Not composite - typelem is */
1104                                    TYPCATEGORY_ARRAY,   /* type-category (array) */
1105                                    false,               /* array types are never preferred */
1106                                    DEFAULT_TYPDELIM,    /* default array delimiter */
1107                                    F_ARRAY_IN,  /* array input proc */
1108                                    F_ARRAY_OUT, /* array output proc */
1109                                    F_ARRAY_RECV,        /* array recv (bin) proc */
1110                                    F_ARRAY_SEND,        /* array send (bin) proc */
1111                                    InvalidOid,  /* typmodin procedure - none */
1112                                    InvalidOid,  /* typmodout procedure - none */
1113                                    InvalidOid,  /* analyze procedure - default */
1114                                    new_type_oid,        /* array element type - the rowtype */
1115                                    true,                /* yes, this is an array type */
1116                                    InvalidOid,  /* this has no array type */
1117                                    InvalidOid,  /* domain base type - irrelevant */
1118                                    NULL,                /* default value - none */
1119                                    NULL,                /* default binary representation */
1120                                    false,               /* passed by reference */
1121                                    'd',                 /* alignment - must be the largest! */
1122                                    'x',                 /* fully TOASTable */
1123                                    -1,                  /* typmod */
1124                                    0,                   /* array dimensions for typBaseType */
1125                                    false,               /* Type NOT NULL */
1126                                    InvalidOid); /* typcollation */
1127
1128                 pfree(relarrayname);
1129         }
1130
1131         /*
1132          * now create an entry in pg_class for the relation.
1133          *
1134          * NOTE: we could get a unique-index failure here, in case someone else is
1135          * creating the same relation name in parallel but hadn't committed yet
1136          * when we checked for a duplicate name above.
1137          */
1138         AddNewRelationTuple(pg_class_desc,
1139                                                 new_rel_desc,
1140                                                 relid,
1141                                                 new_type_oid,
1142                                                 reloftypeid,
1143                                                 ownerid,
1144                                                 relkind,
1145                                                 PointerGetDatum(relacl),
1146                                                 reloptions);
1147
1148         /*
1149          * now add tuples to pg_attribute for the attributes in our new relation.
1150          */
1151         AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1152                                                   oidislocal, oidinhcount);
1153
1154         /*
1155          * Make a dependency link to force the relation to be deleted if its
1156          * namespace is.  Also make a dependency link to its owner, as well as
1157          * dependencies for any roles mentioned in the default ACL.
1158          *
1159          * For composite types, these dependencies are tracked for the pg_type
1160          * entry, so we needn't record them here.  Likewise, TOAST tables don't
1161          * need a namespace dependency (they live in a pinned namespace) nor an
1162          * owner dependency (they depend indirectly through the parent table), nor
1163          * should they have any ACL entries.  The same applies for extension
1164          * dependencies.
1165          *
1166          * Also, skip this in bootstrap mode, since we don't make dependencies
1167          * while bootstrapping.
1168          */
1169         if (relkind != RELKIND_COMPOSITE_TYPE &&
1170                 relkind != RELKIND_TOASTVALUE &&
1171                 !IsBootstrapProcessingMode())
1172         {
1173                 ObjectAddress myself,
1174                                         referenced;
1175
1176                 myself.classId = RelationRelationId;
1177                 myself.objectId = relid;
1178                 myself.objectSubId = 0;
1179                 referenced.classId = NamespaceRelationId;
1180                 referenced.objectId = relnamespace;
1181                 referenced.objectSubId = 0;
1182                 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1183
1184                 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1185
1186                 recordDependencyOnCurrentExtension(&myself);
1187
1188                 if (reloftypeid)
1189                 {
1190                         referenced.classId = TypeRelationId;
1191                         referenced.objectId = reloftypeid;
1192                         referenced.objectSubId = 0;
1193                         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1194                 }
1195
1196                 if (relacl != NULL)
1197                 {
1198                         int                     nnewmembers;
1199                         Oid                *newmembers;
1200
1201                         nnewmembers = aclmembers(relacl, &newmembers);
1202                         updateAclDependencies(RelationRelationId, relid, 0,
1203                                                                   ownerid,
1204                                                                   0, NULL,
1205                                                                   nnewmembers, newmembers);
1206                 }
1207         }
1208
1209         /* Post creation hook for new relation */
1210         InvokeObjectAccessHook(OAT_POST_CREATE, RelationRelationId, relid, 0);
1211
1212         /*
1213          * Store any supplied constraints and defaults.
1214          *
1215          * NB: this may do a CommandCounterIncrement and rebuild the relcache
1216          * entry, so the relation must be valid and self-consistent at this point.
1217          * In particular, there are not yet constraints and defaults anywhere.
1218          */
1219         StoreConstraints(new_rel_desc, cooked_constraints);
1220
1221         /*
1222          * If there's a special on-commit action, remember it
1223          */
1224         if (oncommit != ONCOMMIT_NOOP)
1225                 register_on_commit_action(relid, oncommit);
1226
1227         /*
1228          * If this is an unlogged relation, it needs an init fork so that it
1229          * can be correctly reinitialized on restart.  Since we're going to
1230          * do an immediate sync, we ony need to xlog this if archiving or
1231          * streaming is enabled.  And the immediate sync is required, because
1232          * otherwise there's no guarantee that this will hit the disk before
1233          * the next checkpoint moves the redo pointer.
1234          */
1235         if (relpersistence == RELPERSISTENCE_UNLOGGED)
1236         {
1237                 Assert(relkind == RELKIND_RELATION || relkind == RELKIND_TOASTVALUE);
1238
1239                 smgrcreate(new_rel_desc->rd_smgr, INIT_FORKNUM, false);
1240                 if (XLogIsNeeded())
1241                         log_smgrcreate(&new_rel_desc->rd_smgr->smgr_rnode.node,
1242                                                    INIT_FORKNUM);
1243                 smgrimmedsync(new_rel_desc->rd_smgr, INIT_FORKNUM);
1244         }
1245
1246         /*
1247          * ok, the relation has been cataloged, so close our relations and return
1248          * the OID of the newly created relation.
1249          */
1250         heap_close(new_rel_desc, NoLock);       /* do not unlock till end of xact */
1251         heap_close(pg_class_desc, RowExclusiveLock);
1252
1253         return relid;
1254 }
1255
1256
1257 /*
1258  *              RelationRemoveInheritance
1259  *
1260  * Formerly, this routine checked for child relations and aborted the
1261  * deletion if any were found.  Now we rely on the dependency mechanism
1262  * to check for or delete child relations.      By the time we get here,
1263  * there are no children and we need only remove any pg_inherits rows
1264  * linking this relation to its parent(s).
1265  */
1266 static void
1267 RelationRemoveInheritance(Oid relid)
1268 {
1269         Relation        catalogRelation;
1270         SysScanDesc scan;
1271         ScanKeyData key;
1272         HeapTuple       tuple;
1273
1274         catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1275
1276         ScanKeyInit(&key,
1277                                 Anum_pg_inherits_inhrelid,
1278                                 BTEqualStrategyNumber, F_OIDEQ,
1279                                 ObjectIdGetDatum(relid));
1280
1281         scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1282                                                           SnapshotNow, 1, &key);
1283
1284         while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1285                 simple_heap_delete(catalogRelation, &tuple->t_self);
1286
1287         systable_endscan(scan);
1288         heap_close(catalogRelation, RowExclusiveLock);
1289 }
1290
1291 /*
1292  *              DeleteRelationTuple
1293  *
1294  * Remove pg_class row for the given relid.
1295  *
1296  * Note: this is shared by relation deletion and index deletion.  It's
1297  * not intended for use anyplace else.
1298  */
1299 void
1300 DeleteRelationTuple(Oid relid)
1301 {
1302         Relation        pg_class_desc;
1303         HeapTuple       tup;
1304
1305         /* Grab an appropriate lock on the pg_class relation */
1306         pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1307
1308         tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1309         if (!HeapTupleIsValid(tup))
1310                 elog(ERROR, "cache lookup failed for relation %u", relid);
1311
1312         /* delete the relation tuple from pg_class, and finish up */
1313         simple_heap_delete(pg_class_desc, &tup->t_self);
1314
1315         ReleaseSysCache(tup);
1316
1317         heap_close(pg_class_desc, RowExclusiveLock);
1318 }
1319
1320 /*
1321  *              DeleteAttributeTuples
1322  *
1323  * Remove pg_attribute rows for the given relid.
1324  *
1325  * Note: this is shared by relation deletion and index deletion.  It's
1326  * not intended for use anyplace else.
1327  */
1328 void
1329 DeleteAttributeTuples(Oid relid)
1330 {
1331         Relation        attrel;
1332         SysScanDesc scan;
1333         ScanKeyData key[1];
1334         HeapTuple       atttup;
1335
1336         /* Grab an appropriate lock on the pg_attribute relation */
1337         attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1338
1339         /* Use the index to scan only attributes of the target relation */
1340         ScanKeyInit(&key[0],
1341                                 Anum_pg_attribute_attrelid,
1342                                 BTEqualStrategyNumber, F_OIDEQ,
1343                                 ObjectIdGetDatum(relid));
1344
1345         scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1346                                                           SnapshotNow, 1, key);
1347
1348         /* Delete all the matching tuples */
1349         while ((atttup = systable_getnext(scan)) != NULL)
1350                 simple_heap_delete(attrel, &atttup->t_self);
1351
1352         /* Clean up after the scan */
1353         systable_endscan(scan);
1354         heap_close(attrel, RowExclusiveLock);
1355 }
1356
1357 /*
1358  *              RemoveAttributeById
1359  *
1360  * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1361  * deleted in pg_attribute.  We also remove pg_statistic entries for it.
1362  * (Everything else needed, such as getting rid of any pg_attrdef entry,
1363  * is handled by dependency.c.)
1364  */
1365 void
1366 RemoveAttributeById(Oid relid, AttrNumber attnum)
1367 {
1368         Relation        rel;
1369         Relation        attr_rel;
1370         HeapTuple       tuple;
1371         Form_pg_attribute attStruct;
1372         char            newattname[NAMEDATALEN];
1373
1374         /*
1375          * Grab an exclusive lock on the target table, which we will NOT release
1376          * until end of transaction.  (In the simple case where we are directly
1377          * dropping this column, AlterTableDropColumn already did this ... but
1378          * when cascading from a drop of some other object, we may not have any
1379          * lock.)
1380          */
1381         rel = relation_open(relid, AccessExclusiveLock);
1382
1383         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1384
1385         tuple = SearchSysCacheCopy2(ATTNUM,
1386                                                                 ObjectIdGetDatum(relid),
1387                                                                 Int16GetDatum(attnum));
1388         if (!HeapTupleIsValid(tuple))           /* shouldn't happen */
1389                 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1390                          attnum, relid);
1391         attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1392
1393         if (attnum < 0)
1394         {
1395                 /* System attribute (probably OID) ... just delete the row */
1396
1397                 simple_heap_delete(attr_rel, &tuple->t_self);
1398         }
1399         else
1400         {
1401                 /* Dropping user attributes is lots harder */
1402
1403                 /* Mark the attribute as dropped */
1404                 attStruct->attisdropped = true;
1405
1406                 /*
1407                  * Set the type OID to invalid.  A dropped attribute's type link
1408                  * cannot be relied on (once the attribute is dropped, the type might
1409                  * be too). Fortunately we do not need the type row --- the only
1410                  * really essential information is the type's typlen and typalign,
1411                  * which are preserved in the attribute's attlen and attalign.  We set
1412                  * atttypid to zero here as a means of catching code that incorrectly
1413                  * expects it to be valid.
1414                  */
1415                 attStruct->atttypid = InvalidOid;
1416
1417                 /* Remove any NOT NULL constraint the column may have */
1418                 attStruct->attnotnull = false;
1419
1420                 /* We don't want to keep stats for it anymore */
1421                 attStruct->attstattarget = 0;
1422
1423                 /*
1424                  * Change the column name to something that isn't likely to conflict
1425                  */
1426                 snprintf(newattname, sizeof(newattname),
1427                                  "........pg.dropped.%d........", attnum);
1428                 namestrcpy(&(attStruct->attname), newattname);
1429
1430                 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1431
1432                 /* keep the system catalog indexes current */
1433                 CatalogUpdateIndexes(attr_rel, tuple);
1434         }
1435
1436         /*
1437          * Because updating the pg_attribute row will trigger a relcache flush for
1438          * the target relation, we need not do anything else to notify other
1439          * backends of the change.
1440          */
1441
1442         heap_close(attr_rel, RowExclusiveLock);
1443
1444         if (attnum > 0)
1445                 RemoveStatistics(relid, attnum);
1446
1447         relation_close(rel, NoLock);
1448 }
1449
1450 /*
1451  *              RemoveAttrDefault
1452  *
1453  * If the specified relation/attribute has a default, remove it.
1454  * (If no default, raise error if complain is true, else return quietly.)
1455  */
1456 void
1457 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1458                                   DropBehavior behavior, bool complain)
1459 {
1460         Relation        attrdef_rel;
1461         ScanKeyData scankeys[2];
1462         SysScanDesc scan;
1463         HeapTuple       tuple;
1464         bool            found = false;
1465
1466         attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1467
1468         ScanKeyInit(&scankeys[0],
1469                                 Anum_pg_attrdef_adrelid,
1470                                 BTEqualStrategyNumber, F_OIDEQ,
1471                                 ObjectIdGetDatum(relid));
1472         ScanKeyInit(&scankeys[1],
1473                                 Anum_pg_attrdef_adnum,
1474                                 BTEqualStrategyNumber, F_INT2EQ,
1475                                 Int16GetDatum(attnum));
1476
1477         scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1478                                                           SnapshotNow, 2, scankeys);
1479
1480         /* There should be at most one matching tuple, but we loop anyway */
1481         while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1482         {
1483                 ObjectAddress object;
1484
1485                 object.classId = AttrDefaultRelationId;
1486                 object.objectId = HeapTupleGetOid(tuple);
1487                 object.objectSubId = 0;
1488
1489                 performDeletion(&object, behavior);
1490
1491                 found = true;
1492         }
1493
1494         systable_endscan(scan);
1495         heap_close(attrdef_rel, RowExclusiveLock);
1496
1497         if (complain && !found)
1498                 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1499                          relid, attnum);
1500 }
1501
1502 /*
1503  *              RemoveAttrDefaultById
1504  *
1505  * Remove a pg_attrdef entry specified by OID.  This is the guts of
1506  * attribute-default removal.  Note it should be called via performDeletion,
1507  * not directly.
1508  */
1509 void
1510 RemoveAttrDefaultById(Oid attrdefId)
1511 {
1512         Relation        attrdef_rel;
1513         Relation        attr_rel;
1514         Relation        myrel;
1515         ScanKeyData scankeys[1];
1516         SysScanDesc scan;
1517         HeapTuple       tuple;
1518         Oid                     myrelid;
1519         AttrNumber      myattnum;
1520
1521         /* Grab an appropriate lock on the pg_attrdef relation */
1522         attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1523
1524         /* Find the pg_attrdef tuple */
1525         ScanKeyInit(&scankeys[0],
1526                                 ObjectIdAttributeNumber,
1527                                 BTEqualStrategyNumber, F_OIDEQ,
1528                                 ObjectIdGetDatum(attrdefId));
1529
1530         scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1531                                                           SnapshotNow, 1, scankeys);
1532
1533         tuple = systable_getnext(scan);
1534         if (!HeapTupleIsValid(tuple))
1535                 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1536
1537         myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1538         myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1539
1540         /* Get an exclusive lock on the relation owning the attribute */
1541         myrel = relation_open(myrelid, AccessExclusiveLock);
1542
1543         /* Now we can delete the pg_attrdef row */
1544         simple_heap_delete(attrdef_rel, &tuple->t_self);
1545
1546         systable_endscan(scan);
1547         heap_close(attrdef_rel, RowExclusiveLock);
1548
1549         /* Fix the pg_attribute row */
1550         attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1551
1552         tuple = SearchSysCacheCopy2(ATTNUM,
1553                                                                 ObjectIdGetDatum(myrelid),
1554                                                                 Int16GetDatum(myattnum));
1555         if (!HeapTupleIsValid(tuple))           /* shouldn't happen */
1556                 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1557                          myattnum, myrelid);
1558
1559         ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1560
1561         simple_heap_update(attr_rel, &tuple->t_self, tuple);
1562
1563         /* keep the system catalog indexes current */
1564         CatalogUpdateIndexes(attr_rel, tuple);
1565
1566         /*
1567          * Our update of the pg_attribute row will force a relcache rebuild, so
1568          * there's nothing else to do here.
1569          */
1570         heap_close(attr_rel, RowExclusiveLock);
1571
1572         /* Keep lock on attribute's rel until end of xact */
1573         relation_close(myrel, NoLock);
1574 }
1575
1576 /*
1577  * heap_drop_with_catalog       - removes specified relation from catalogs
1578  *
1579  * Note that this routine is not responsible for dropping objects that are
1580  * linked to the pg_class entry via dependencies (for example, indexes and
1581  * constraints).  Those are deleted by the dependency-tracing logic in
1582  * dependency.c before control gets here.  In general, therefore, this routine
1583  * should never be called directly; go through performDeletion() instead.
1584  */
1585 void
1586 heap_drop_with_catalog(Oid relid)
1587 {
1588         Relation        rel;
1589
1590         /*
1591          * Open and lock the relation.
1592          */
1593         rel = relation_open(relid, AccessExclusiveLock);
1594
1595         /*
1596          * There can no longer be anyone *else* touching the relation, but we
1597          * might still have open queries or cursors in our own session.
1598          */
1599         if (rel->rd_refcnt != 1)
1600                 ereport(ERROR,
1601                                 (errcode(ERRCODE_OBJECT_IN_USE),
1602                                  errmsg("cannot drop \"%s\" because "
1603                                                 "it is being used by active queries in this session",
1604                                                 RelationGetRelationName(rel))));
1605
1606         /*
1607          * Delete pg_foreign_table tuple first.
1608          */
1609         if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1610         {
1611                 Relation    rel;
1612                 HeapTuple   tuple;
1613
1614                 rel = heap_open(ForeignTableRelationId, RowExclusiveLock);
1615
1616                 tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1617                 if (!HeapTupleIsValid(tuple))
1618                         elog(ERROR, "cache lookup failed for foreign table %u", relid);
1619
1620                 simple_heap_delete(rel, &tuple->t_self);
1621
1622                 ReleaseSysCache(tuple);
1623                 heap_close(rel, RowExclusiveLock);
1624         }
1625
1626         /*
1627          * Schedule unlinking of the relation's physical files at commit.
1628          */
1629         if (rel->rd_rel->relkind != RELKIND_VIEW &&
1630                 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1631                 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1632         {
1633                 RelationDropStorage(rel);
1634         }
1635
1636         /*
1637          * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1638          * until transaction commit.  This ensures no one else will try to do
1639          * something with the doomed relation.
1640          */
1641         relation_close(rel, NoLock);
1642
1643         /*
1644          * Forget any ON COMMIT action for the rel
1645          */
1646         remove_on_commit_action(relid);
1647
1648         /*
1649          * Flush the relation from the relcache.  We want to do this before
1650          * starting to remove catalog entries, just to be certain that no relcache
1651          * entry rebuild will happen partway through.  (That should not really
1652          * matter, since we don't do CommandCounterIncrement here, but let's be
1653          * safe.)
1654          */
1655         RelationForgetRelation(relid);
1656
1657         /*
1658          * remove inheritance information
1659          */
1660         RelationRemoveInheritance(relid);
1661
1662         /*
1663          * delete statistics
1664          */
1665         RemoveStatistics(relid, 0);
1666
1667         /*
1668          * delete attribute tuples
1669          */
1670         DeleteAttributeTuples(relid);
1671
1672         /*
1673          * delete relation tuple
1674          */
1675         DeleteRelationTuple(relid);
1676 }
1677
1678
1679 /*
1680  * Store a default expression for column attnum of relation rel.
1681  */
1682 void
1683 StoreAttrDefault(Relation rel, AttrNumber attnum, Node *expr)
1684 {
1685         char       *adbin;
1686         char       *adsrc;
1687         Relation        adrel;
1688         HeapTuple       tuple;
1689         Datum           values[4];
1690         static bool nulls[4] = {false, false, false, false};
1691         Relation        attrrel;
1692         HeapTuple       atttup;
1693         Form_pg_attribute attStruct;
1694         Oid                     attrdefOid;
1695         ObjectAddress colobject,
1696                                 defobject;
1697
1698         /*
1699          * Flatten expression to string form for storage.
1700          */
1701         adbin = nodeToString(expr);
1702
1703         /*
1704          * Also deparse it to form the mostly-obsolete adsrc field.
1705          */
1706         adsrc = deparse_expression(expr,
1707                                                         deparse_context_for(RelationGetRelationName(rel),
1708                                                                                                 RelationGetRelid(rel)),
1709                                                            false, false);
1710
1711         /*
1712          * Make the pg_attrdef entry.
1713          */
1714         values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1715         values[Anum_pg_attrdef_adnum - 1] = attnum;
1716         values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1717         values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1718
1719         adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1720
1721         tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1722         attrdefOid = simple_heap_insert(adrel, tuple);
1723
1724         CatalogUpdateIndexes(adrel, tuple);
1725
1726         defobject.classId = AttrDefaultRelationId;
1727         defobject.objectId = attrdefOid;
1728         defobject.objectSubId = 0;
1729
1730         heap_close(adrel, RowExclusiveLock);
1731
1732         /* now can free some of the stuff allocated above */
1733         pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1734         pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1735         heap_freetuple(tuple);
1736         pfree(adbin);
1737         pfree(adsrc);
1738
1739         /*
1740          * Update the pg_attribute entry for the column to show that a default
1741          * exists.
1742          */
1743         attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1744         atttup = SearchSysCacheCopy2(ATTNUM,
1745                                                                  ObjectIdGetDatum(RelationGetRelid(rel)),
1746                                                                  Int16GetDatum(attnum));
1747         if (!HeapTupleIsValid(atttup))
1748                 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1749                          attnum, RelationGetRelid(rel));
1750         attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1751         if (!attStruct->atthasdef)
1752         {
1753                 attStruct->atthasdef = true;
1754                 simple_heap_update(attrrel, &atttup->t_self, atttup);
1755                 /* keep catalog indexes current */
1756                 CatalogUpdateIndexes(attrrel, atttup);
1757         }
1758         heap_close(attrrel, RowExclusiveLock);
1759         heap_freetuple(atttup);
1760
1761         /*
1762          * Make a dependency so that the pg_attrdef entry goes away if the column
1763          * (or whole table) is deleted.
1764          */
1765         colobject.classId = RelationRelationId;
1766         colobject.objectId = RelationGetRelid(rel);
1767         colobject.objectSubId = attnum;
1768
1769         recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1770
1771         /*
1772          * Record dependencies on objects used in the expression, too.
1773          */
1774         recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1775 }
1776
1777 /*
1778  * Store a check-constraint expression for the given relation.
1779  *
1780  * Caller is responsible for updating the count of constraints
1781  * in the pg_class entry for the relation.
1782  */
1783 static void
1784 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1785                           bool is_local, int inhcount)
1786 {
1787         char       *ccbin;
1788         char       *ccsrc;
1789         List       *varList;
1790         int                     keycount;
1791         int16      *attNos;
1792
1793         /*
1794          * Flatten expression to string form for storage.
1795          */
1796         ccbin = nodeToString(expr);
1797
1798         /*
1799          * Also deparse it to form the mostly-obsolete consrc field.
1800          */
1801         ccsrc = deparse_expression(expr,
1802                                                         deparse_context_for(RelationGetRelationName(rel),
1803                                                                                                 RelationGetRelid(rel)),
1804                                                            false, false);
1805
1806         /*
1807          * Find columns of rel that are used in expr
1808          *
1809          * NB: pull_var_clause is okay here only because we don't allow subselects
1810          * in check constraints; it would fail to examine the contents of
1811          * subselects.
1812          */
1813         varList = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
1814         keycount = list_length(varList);
1815
1816         if (keycount > 0)
1817         {
1818                 ListCell   *vl;
1819                 int                     i = 0;
1820
1821                 attNos = (int16 *) palloc(keycount * sizeof(int16));
1822                 foreach(vl, varList)
1823                 {
1824                         Var                *var = (Var *) lfirst(vl);
1825                         int                     j;
1826
1827                         for (j = 0; j < i; j++)
1828                                 if (attNos[j] == var->varattno)
1829                                         break;
1830                         if (j == i)
1831                                 attNos[i++] = var->varattno;
1832                 }
1833                 keycount = i;
1834         }
1835         else
1836                 attNos = NULL;
1837
1838         /*
1839          * Create the Check Constraint
1840          */
1841         CreateConstraintEntry(ccname,           /* Constraint Name */
1842                                                   RelationGetNamespace(rel),    /* namespace */
1843                                                   CONSTRAINT_CHECK,             /* Constraint Type */
1844                                                   false,        /* Is Deferrable */
1845                                                   false,        /* Is Deferred */
1846                                                   true,         /* Is Validated */
1847                                                   RelationGetRelid(rel),                /* relation */
1848                                                   attNos,               /* attrs in the constraint */
1849                                                   keycount,             /* # attrs in the constraint */
1850                                                   InvalidOid,   /* not a domain constraint */
1851                                                   InvalidOid,   /* no associated index */
1852                                                   InvalidOid,   /* Foreign key fields */
1853                                                   NULL,
1854                                                   NULL,
1855                                                   NULL,
1856                                                   NULL,
1857                                                   0,
1858                                                   ' ',
1859                                                   ' ',
1860                                                   ' ',
1861                                                   NULL, /* not an exclusion constraint */
1862                                                   expr, /* Tree form of check constraint */
1863                                                   ccbin,        /* Binary form of check constraint */
1864                                                   ccsrc,        /* Source form of check constraint */
1865                                                   is_local,             /* conislocal */
1866                                                   inhcount);    /* coninhcount */
1867
1868         pfree(ccbin);
1869         pfree(ccsrc);
1870 }
1871
1872 /*
1873  * Store defaults and constraints (passed as a list of CookedConstraint).
1874  *
1875  * NOTE: only pre-cooked expressions will be passed this way, which is to
1876  * say expressions inherited from an existing relation.  Newly parsed
1877  * expressions can be added later, by direct calls to StoreAttrDefault
1878  * and StoreRelCheck (see AddRelationNewConstraints()).
1879  */
1880 static void
1881 StoreConstraints(Relation rel, List *cooked_constraints)
1882 {
1883         int                     numchecks = 0;
1884         ListCell   *lc;
1885
1886         if (!cooked_constraints)
1887                 return;                                 /* nothing to do */
1888
1889         /*
1890          * Deparsing of constraint expressions will fail unless the just-created
1891          * pg_attribute tuples for this relation are made visible.      So, bump the
1892          * command counter.  CAUTION: this will cause a relcache entry rebuild.
1893          */
1894         CommandCounterIncrement();
1895
1896         foreach(lc, cooked_constraints)
1897         {
1898                 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
1899
1900                 switch (con->contype)
1901                 {
1902                         case CONSTR_DEFAULT:
1903                                 StoreAttrDefault(rel, con->attnum, con->expr);
1904                                 break;
1905                         case CONSTR_CHECK:
1906                                 StoreRelCheck(rel, con->name, con->expr,
1907                                                           con->is_local, con->inhcount);
1908                                 numchecks++;
1909                                 break;
1910                         default:
1911                                 elog(ERROR, "unrecognized constraint type: %d",
1912                                          (int) con->contype);
1913                 }
1914         }
1915
1916         if (numchecks > 0)
1917                 SetRelationNumChecks(rel, numchecks);
1918 }
1919
1920 /*
1921  * AddRelationNewConstraints
1922  *
1923  * Add new column default expressions and/or constraint check expressions
1924  * to an existing relation.  This is defined to do both for efficiency in
1925  * DefineRelation, but of course you can do just one or the other by passing
1926  * empty lists.
1927  *
1928  * rel: relation to be modified
1929  * newColDefaults: list of RawColumnDefault structures
1930  * newConstraints: list of Constraint nodes
1931  * allow_merge: TRUE if check constraints may be merged with existing ones
1932  * is_local: TRUE if definition is local, FALSE if it's inherited
1933  *
1934  * All entries in newColDefaults will be processed.  Entries in newConstraints
1935  * will be processed only if they are CONSTR_CHECK type.
1936  *
1937  * Returns a list of CookedConstraint nodes that shows the cooked form of
1938  * the default and constraint expressions added to the relation.
1939  *
1940  * NB: caller should have opened rel with AccessExclusiveLock, and should
1941  * hold that lock till end of transaction.      Also, we assume the caller has
1942  * done a CommandCounterIncrement if necessary to make the relation's catalog
1943  * tuples visible.
1944  */
1945 List *
1946 AddRelationNewConstraints(Relation rel,
1947                                                   List *newColDefaults,
1948                                                   List *newConstraints,
1949                                                   bool allow_merge,
1950                                                   bool is_local)
1951 {
1952         List       *cookedConstraints = NIL;
1953         TupleDesc       tupleDesc;
1954         TupleConstr *oldconstr;
1955         int                     numoldchecks;
1956         ParseState *pstate;
1957         RangeTblEntry *rte;
1958         int                     numchecks;
1959         List       *checknames;
1960         ListCell   *cell;
1961         Node       *expr;
1962         CookedConstraint *cooked;
1963
1964         /*
1965          * Get info about existing constraints.
1966          */
1967         tupleDesc = RelationGetDescr(rel);
1968         oldconstr = tupleDesc->constr;
1969         if (oldconstr)
1970                 numoldchecks = oldconstr->num_check;
1971         else
1972                 numoldchecks = 0;
1973
1974         /*
1975          * Create a dummy ParseState and insert the target relation as its sole
1976          * rangetable entry.  We need a ParseState for transformExpr.
1977          */
1978         pstate = make_parsestate(NULL);
1979         rte = addRangeTableEntryForRelation(pstate,
1980                                                                                 rel,
1981                                                                                 NULL,
1982                                                                                 false,
1983                                                                                 true);
1984         addRTEtoQuery(pstate, rte, true, true, true);
1985
1986         /*
1987          * Process column default expressions.
1988          */
1989         foreach(cell, newColDefaults)
1990         {
1991                 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1992                 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1993
1994                 expr = cookDefault(pstate, colDef->raw_default,
1995                                                    atp->atttypid, atp->atttypmod,
1996                                                    NameStr(atp->attname));
1997
1998                 /*
1999                  * If the expression is just a NULL constant, we do not bother to make
2000                  * an explicit pg_attrdef entry, since the default behavior is
2001                  * equivalent.
2002                  *
2003                  * Note a nonobvious property of this test: if the column is of a
2004                  * domain type, what we'll get is not a bare null Const but a
2005                  * CoerceToDomain expr, so we will not discard the default.  This is
2006                  * critical because the column default needs to be retained to
2007                  * override any default that the domain might have.
2008                  */
2009                 if (expr == NULL ||
2010                         (IsA(expr, Const) &&((Const *) expr)->constisnull))
2011                         continue;
2012
2013                 StoreAttrDefault(rel, colDef->attnum, expr);
2014
2015                 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2016                 cooked->contype = CONSTR_DEFAULT;
2017                 cooked->name = NULL;
2018                 cooked->attnum = colDef->attnum;
2019                 cooked->expr = expr;
2020                 cooked->is_local = is_local;
2021                 cooked->inhcount = is_local ? 0 : 1;
2022                 cookedConstraints = lappend(cookedConstraints, cooked);
2023         }
2024
2025         /*
2026          * Process constraint expressions.
2027          */
2028         numchecks = numoldchecks;
2029         checknames = NIL;
2030         foreach(cell, newConstraints)
2031         {
2032                 Constraint *cdef = (Constraint *) lfirst(cell);
2033                 char       *ccname;
2034
2035                 if (cdef->contype != CONSTR_CHECK)
2036                         continue;
2037
2038                 if (cdef->raw_expr != NULL)
2039                 {
2040                         Assert(cdef->cooked_expr == NULL);
2041
2042                         /*
2043                          * Transform raw parsetree to executable expression, and verify
2044                          * it's valid as a CHECK constraint.
2045                          */
2046                         expr = cookConstraint(pstate, cdef->raw_expr,
2047                                                                   RelationGetRelationName(rel));
2048                 }
2049                 else
2050                 {
2051                         Assert(cdef->cooked_expr != NULL);
2052
2053                         /*
2054                          * Here, we assume the parser will only pass us valid CHECK
2055                          * expressions, so we do no particular checking.
2056                          */
2057                         expr = stringToNode(cdef->cooked_expr);
2058                 }
2059
2060                 /*
2061                  * Check name uniqueness, or generate a name if none was given.
2062                  */
2063                 if (cdef->conname != NULL)
2064                 {
2065                         ListCell   *cell2;
2066
2067                         ccname = cdef->conname;
2068                         /* Check against other new constraints */
2069                         /* Needed because we don't do CommandCounterIncrement in loop */
2070                         foreach(cell2, checknames)
2071                         {
2072                                 if (strcmp((char *) lfirst(cell2), ccname) == 0)
2073                                         ereport(ERROR,
2074                                                         (errcode(ERRCODE_DUPLICATE_OBJECT),
2075                                                          errmsg("check constraint \"%s\" already exists",
2076                                                                         ccname)));
2077                         }
2078
2079                         /* save name for future checks */
2080                         checknames = lappend(checknames, ccname);
2081
2082                         /*
2083                          * Check against pre-existing constraints.      If we are allowed to
2084                          * merge with an existing constraint, there's no more to do here.
2085                          * (We omit the duplicate constraint from the result, which is
2086                          * what ATAddCheckConstraint wants.)
2087                          */
2088                         if (MergeWithExistingConstraint(rel, ccname, expr,
2089                                                                                         allow_merge, is_local))
2090                                 continue;
2091                 }
2092                 else
2093                 {
2094                         /*
2095                          * When generating a name, we want to create "tab_col_check" for a
2096                          * column constraint and "tab_check" for a table constraint.  We
2097                          * no longer have any info about the syntactic positioning of the
2098                          * constraint phrase, so we approximate this by seeing whether the
2099                          * expression references more than one column.  (If the user
2100                          * played by the rules, the result is the same...)
2101                          *
2102                          * Note: pull_var_clause() doesn't descend into sublinks, but we
2103                          * eliminated those above; and anyway this only needs to be an
2104                          * approximate answer.
2105                          */
2106                         List       *vars;
2107                         char       *colname;
2108
2109                         vars = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
2110
2111                         /* eliminate duplicates */
2112                         vars = list_union(NIL, vars);
2113
2114                         if (list_length(vars) == 1)
2115                                 colname = get_attname(RelationGetRelid(rel),
2116                                                                           ((Var *) linitial(vars))->varattno);
2117                         else
2118                                 colname = NULL;
2119
2120                         ccname = ChooseConstraintName(RelationGetRelationName(rel),
2121                                                                                   colname,
2122                                                                                   "check",
2123                                                                                   RelationGetNamespace(rel),
2124                                                                                   checknames);
2125
2126                         /* save name for future checks */
2127                         checknames = lappend(checknames, ccname);
2128                 }
2129
2130                 /*
2131                  * OK, store it.
2132                  */
2133                 StoreRelCheck(rel, ccname, expr, is_local, is_local ? 0 : 1);
2134
2135                 numchecks++;
2136
2137                 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2138                 cooked->contype = CONSTR_CHECK;
2139                 cooked->name = ccname;
2140                 cooked->attnum = 0;
2141                 cooked->expr = expr;
2142                 cooked->is_local = is_local;
2143                 cooked->inhcount = is_local ? 0 : 1;
2144                 cookedConstraints = lappend(cookedConstraints, cooked);
2145         }
2146
2147         /*
2148          * Update the count of constraints in the relation's pg_class tuple. We do
2149          * this even if there was no change, in order to ensure that an SI update
2150          * message is sent out for the pg_class tuple, which will force other
2151          * backends to rebuild their relcache entries for the rel. (This is
2152          * critical if we added defaults but not constraints.)
2153          */
2154         SetRelationNumChecks(rel, numchecks);
2155
2156         return cookedConstraints;
2157 }
2158
2159 /*
2160  * Check for a pre-existing check constraint that conflicts with a proposed
2161  * new one, and either adjust its conislocal/coninhcount settings or throw
2162  * error as needed.
2163  *
2164  * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2165  * got a so-far-unique name, or throws error if conflict.
2166  */
2167 static bool
2168 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2169                                                         bool allow_merge, bool is_local)
2170 {
2171         bool            found;
2172         Relation        conDesc;
2173         SysScanDesc conscan;
2174         ScanKeyData skey[2];
2175         HeapTuple       tup;
2176
2177         /* Search for a pg_constraint entry with same name and relation */
2178         conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2179
2180         found = false;
2181
2182         ScanKeyInit(&skey[0],
2183                                 Anum_pg_constraint_conname,
2184                                 BTEqualStrategyNumber, F_NAMEEQ,
2185                                 CStringGetDatum(ccname));
2186
2187         ScanKeyInit(&skey[1],
2188                                 Anum_pg_constraint_connamespace,
2189                                 BTEqualStrategyNumber, F_OIDEQ,
2190                                 ObjectIdGetDatum(RelationGetNamespace(rel)));
2191
2192         conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2193                                                                  SnapshotNow, 2, skey);
2194
2195         while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2196         {
2197                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2198
2199                 if (con->conrelid == RelationGetRelid(rel))
2200                 {
2201                         /* Found it.  Conflicts if not identical check constraint */
2202                         if (con->contype == CONSTRAINT_CHECK)
2203                         {
2204                                 Datum           val;
2205                                 bool            isnull;
2206
2207                                 val = fastgetattr(tup,
2208                                                                   Anum_pg_constraint_conbin,
2209                                                                   conDesc->rd_att, &isnull);
2210                                 if (isnull)
2211                                         elog(ERROR, "null conbin for rel %s",
2212                                                  RelationGetRelationName(rel));
2213                                 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2214                                         found = true;
2215                         }
2216                         if (!found || !allow_merge)
2217                                 ereport(ERROR,
2218                                                 (errcode(ERRCODE_DUPLICATE_OBJECT),
2219                                 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2220                                            ccname, RelationGetRelationName(rel))));
2221                         /* OK to update the tuple */
2222                         ereport(NOTICE,
2223                            (errmsg("merging constraint \"%s\" with inherited definition",
2224                                            ccname)));
2225                         tup = heap_copytuple(tup);
2226                         con = (Form_pg_constraint) GETSTRUCT(tup);
2227                         if (is_local)
2228                                 con->conislocal = true;
2229                         else
2230                                 con->coninhcount++;
2231                         simple_heap_update(conDesc, &tup->t_self, tup);
2232                         CatalogUpdateIndexes(conDesc, tup);
2233                         break;
2234                 }
2235         }
2236
2237         systable_endscan(conscan);
2238         heap_close(conDesc, RowExclusiveLock);
2239
2240         return found;
2241 }
2242
2243 /*
2244  * Update the count of constraints in the relation's pg_class tuple.
2245  *
2246  * Caller had better hold exclusive lock on the relation.
2247  *
2248  * An important side effect is that a SI update message will be sent out for
2249  * the pg_class tuple, which will force other backends to rebuild their
2250  * relcache entries for the rel.  Also, this backend will rebuild its
2251  * own relcache entry at the next CommandCounterIncrement.
2252  */
2253 static void
2254 SetRelationNumChecks(Relation rel, int numchecks)
2255 {
2256         Relation        relrel;
2257         HeapTuple       reltup;
2258         Form_pg_class relStruct;
2259
2260         relrel = heap_open(RelationRelationId, RowExclusiveLock);
2261         reltup = SearchSysCacheCopy1(RELOID,
2262                                                                  ObjectIdGetDatum(RelationGetRelid(rel)));
2263         if (!HeapTupleIsValid(reltup))
2264                 elog(ERROR, "cache lookup failed for relation %u",
2265                          RelationGetRelid(rel));
2266         relStruct = (Form_pg_class) GETSTRUCT(reltup);
2267
2268         if (relStruct->relchecks != numchecks)
2269         {
2270                 relStruct->relchecks = numchecks;
2271
2272                 simple_heap_update(relrel, &reltup->t_self, reltup);
2273
2274                 /* keep catalog indexes current */
2275                 CatalogUpdateIndexes(relrel, reltup);
2276         }
2277         else
2278         {
2279                 /* Skip the disk update, but force relcache inval anyway */
2280                 CacheInvalidateRelcache(rel);
2281         }
2282
2283         heap_freetuple(reltup);
2284         heap_close(relrel, RowExclusiveLock);
2285 }
2286
2287 /*
2288  * Take a raw default and convert it to a cooked format ready for
2289  * storage.
2290  *
2291  * Parse state should be set up to recognize any vars that might appear
2292  * in the expression.  (Even though we plan to reject vars, it's more
2293  * user-friendly to give the correct error message than "unknown var".)
2294  *
2295  * If atttypid is not InvalidOid, coerce the expression to the specified
2296  * type (and typmod atttypmod).   attname is only needed in this case:
2297  * it is used in the error message, if any.
2298  */
2299 Node *
2300 cookDefault(ParseState *pstate,
2301                         Node *raw_default,
2302                         Oid atttypid,
2303                         int32 atttypmod,
2304                         char *attname)
2305 {
2306         Node       *expr;
2307
2308         Assert(raw_default != NULL);
2309
2310         /*
2311          * Transform raw parsetree to executable expression.
2312          */
2313         expr = transformExpr(pstate, raw_default);
2314
2315         /*
2316          * Make sure default expr does not refer to any vars.
2317          */
2318         if (contain_var_clause(expr))
2319                 ereport(ERROR,
2320                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2321                           errmsg("cannot use column references in default expression")));
2322
2323         /*
2324          * It can't return a set either.
2325          */
2326         if (expression_returns_set(expr))
2327                 ereport(ERROR,
2328                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2329                                  errmsg("default expression must not return a set")));
2330
2331         /*
2332          * No subplans or aggregates, either...
2333          */
2334         if (pstate->p_hasSubLinks)
2335                 ereport(ERROR,
2336                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2337                                  errmsg("cannot use subquery in default expression")));
2338         if (pstate->p_hasAggs)
2339                 ereport(ERROR,
2340                                 (errcode(ERRCODE_GROUPING_ERROR),
2341                          errmsg("cannot use aggregate function in default expression")));
2342         if (pstate->p_hasWindowFuncs)
2343                 ereport(ERROR,
2344                                 (errcode(ERRCODE_WINDOWING_ERROR),
2345                                  errmsg("cannot use window function in default expression")));
2346
2347         /*
2348          * Coerce the expression to the correct type and typmod, if given. This
2349          * should match the parser's processing of non-defaulted expressions ---
2350          * see transformAssignedExpr().
2351          */
2352         if (OidIsValid(atttypid))
2353         {
2354                 Oid                     type_id = exprType(expr);
2355
2356                 expr = coerce_to_target_type(pstate, expr, type_id,
2357                                                                          atttypid, atttypmod,
2358                                                                          COERCION_ASSIGNMENT,
2359                                                                          COERCE_IMPLICIT_CAST,
2360                                                                          -1);
2361                 if (expr == NULL)
2362                         ereport(ERROR,
2363                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
2364                                          errmsg("column \"%s\" is of type %s"
2365                                                         " but default expression is of type %s",
2366                                                         attname,
2367                                                         format_type_be(atttypid),
2368                                                         format_type_be(type_id)),
2369                            errhint("You will need to rewrite or cast the expression.")));
2370         }
2371
2372         return expr;
2373 }
2374
2375 /*
2376  * Take a raw CHECK constraint expression and convert it to a cooked format
2377  * ready for storage.
2378  *
2379  * Parse state must be set up to recognize any vars that might appear
2380  * in the expression.
2381  */
2382 static Node *
2383 cookConstraint(ParseState *pstate,
2384                            Node *raw_constraint,
2385                            char *relname)
2386 {
2387         Node       *expr;
2388
2389         /*
2390          * Transform raw parsetree to executable expression.
2391          */
2392         expr = transformExpr(pstate, raw_constraint);
2393
2394         /*
2395          * Make sure it yields a boolean result.
2396          */
2397         expr = coerce_to_boolean(pstate, expr, "CHECK");
2398
2399         /*
2400          * Make sure no outside relations are referred to.
2401          */
2402         if (list_length(pstate->p_rtable) != 1)
2403                 ereport(ERROR,
2404                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2405                         errmsg("only table \"%s\" can be referenced in check constraint",
2406                                    relname)));
2407
2408         /*
2409          * No subplans or aggregates, either...
2410          */
2411         if (pstate->p_hasSubLinks)
2412                 ereport(ERROR,
2413                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2414                                  errmsg("cannot use subquery in check constraint")));
2415         if (pstate->p_hasAggs)
2416                 ereport(ERROR,
2417                                 (errcode(ERRCODE_GROUPING_ERROR),
2418                            errmsg("cannot use aggregate function in check constraint")));
2419         if (pstate->p_hasWindowFuncs)
2420                 ereport(ERROR,
2421                                 (errcode(ERRCODE_WINDOWING_ERROR),
2422                                  errmsg("cannot use window function in check constraint")));
2423
2424         return expr;
2425 }
2426
2427
2428 /*
2429  * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2430  *
2431  * If attnum is zero, remove all entries for rel; else remove only the one(s)
2432  * for that column.
2433  */
2434 void
2435 RemoveStatistics(Oid relid, AttrNumber attnum)
2436 {
2437         Relation        pgstatistic;
2438         SysScanDesc scan;
2439         ScanKeyData key[2];
2440         int                     nkeys;
2441         HeapTuple       tuple;
2442
2443         pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2444
2445         ScanKeyInit(&key[0],
2446                                 Anum_pg_statistic_starelid,
2447                                 BTEqualStrategyNumber, F_OIDEQ,
2448                                 ObjectIdGetDatum(relid));
2449
2450         if (attnum == 0)
2451                 nkeys = 1;
2452         else
2453         {
2454                 ScanKeyInit(&key[1],
2455                                         Anum_pg_statistic_staattnum,
2456                                         BTEqualStrategyNumber, F_INT2EQ,
2457                                         Int16GetDatum(attnum));
2458                 nkeys = 2;
2459         }
2460
2461         scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2462                                                           SnapshotNow, nkeys, key);
2463
2464         /* we must loop even when attnum != 0, in case of inherited stats */
2465         while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2466                 simple_heap_delete(pgstatistic, &tuple->t_self);
2467
2468         systable_endscan(scan);
2469
2470         heap_close(pgstatistic, RowExclusiveLock);
2471 }
2472
2473
2474 /*
2475  * RelationTruncateIndexes - truncate all indexes associated
2476  * with the heap relation to zero tuples.
2477  *
2478  * The routine will truncate and then reconstruct the indexes on
2479  * the specified relation.      Caller must hold exclusive lock on rel.
2480  */
2481 static void
2482 RelationTruncateIndexes(Relation heapRelation)
2483 {
2484         ListCell   *indlist;
2485
2486         /* Ask the relcache to produce a list of the indexes of the rel */
2487         foreach(indlist, RelationGetIndexList(heapRelation))
2488         {
2489                 Oid                     indexId = lfirst_oid(indlist);
2490                 Relation        currentIndex;
2491                 IndexInfo  *indexInfo;
2492
2493                 /* Open the index relation; use exclusive lock, just to be sure */
2494                 currentIndex = index_open(indexId, AccessExclusiveLock);
2495
2496                 /* Fetch info needed for index_build */
2497                 indexInfo = BuildIndexInfo(currentIndex);
2498
2499                 /*
2500                  * Now truncate the actual file (and discard buffers).
2501                  */
2502                 RelationTruncate(currentIndex, 0);
2503
2504                 /* Initialize the index and rebuild */
2505                 /* Note: we do not need to re-establish pkey setting */
2506                 index_build(heapRelation, currentIndex, indexInfo, false);
2507
2508                 /* We're done with this index */
2509                 index_close(currentIndex, NoLock);
2510         }
2511 }
2512
2513 /*
2514  *       heap_truncate
2515  *
2516  *       This routine deletes all data within all the specified relations.
2517  *
2518  * This is not transaction-safe!  There is another, transaction-safe
2519  * implementation in commands/tablecmds.c.      We now use this only for
2520  * ON COMMIT truncation of temporary tables, where it doesn't matter.
2521  */
2522 void
2523 heap_truncate(List *relids)
2524 {
2525         List       *relations = NIL;
2526         ListCell   *cell;
2527
2528         /* Open relations for processing, and grab exclusive access on each */
2529         foreach(cell, relids)
2530         {
2531                 Oid                     rid = lfirst_oid(cell);
2532                 Relation        rel;
2533
2534                 rel = heap_open(rid, AccessExclusiveLock);
2535                 relations = lappend(relations, rel);
2536         }
2537
2538         /* Don't allow truncate on tables that are referenced by foreign keys */
2539         heap_truncate_check_FKs(relations, true);
2540
2541         /* OK to do it */
2542         foreach(cell, relations)
2543         {
2544                 Relation        rel = lfirst(cell);
2545
2546                 /* Truncate the relation */
2547                 heap_truncate_one_rel(rel);
2548
2549                 /* Close the relation, but keep exclusive lock on it until commit */
2550                 heap_close(rel, NoLock);
2551         }
2552 }
2553
2554 /*
2555  *       heap_truncate_one_rel
2556  *
2557  *       This routine deletes all data within the specified relation.
2558  *
2559  * This is not transaction-safe, because the truncation is done immediately
2560  * and cannot be rolled back later.  Caller is responsible for having
2561  * checked permissions etc, and must have obtained AccessExclusiveLock.
2562  */
2563 void
2564 heap_truncate_one_rel(Relation rel)
2565 {
2566         Oid                     toastrelid;
2567
2568         /* Truncate the actual file (and discard buffers) */
2569         RelationTruncate(rel, 0);
2570
2571         /* If the relation has indexes, truncate the indexes too */
2572         RelationTruncateIndexes(rel);
2573
2574         /* If there is a toast table, truncate that too */
2575         toastrelid = rel->rd_rel->reltoastrelid;
2576         if (OidIsValid(toastrelid))
2577         {
2578                 Relation        toastrel = heap_open(toastrelid, AccessExclusiveLock);
2579
2580                 RelationTruncate(toastrel, 0);
2581                 RelationTruncateIndexes(toastrel);
2582                 /* keep the lock... */
2583                 heap_close(toastrel, NoLock);
2584         }
2585 }
2586
2587 /*
2588  * heap_truncate_check_FKs
2589  *              Check for foreign keys referencing a list of relations that
2590  *              are to be truncated, and raise error if there are any
2591  *
2592  * We disallow such FKs (except self-referential ones) since the whole point
2593  * of TRUNCATE is to not scan the individual rows to be thrown away.
2594  *
2595  * This is split out so it can be shared by both implementations of truncate.
2596  * Caller should already hold a suitable lock on the relations.
2597  *
2598  * tempTables is only used to select an appropriate error message.
2599  */
2600 void
2601 heap_truncate_check_FKs(List *relations, bool tempTables)
2602 {
2603         List       *oids = NIL;
2604         List       *dependents;
2605         ListCell   *cell;
2606
2607         /*
2608          * Build a list of OIDs of the interesting relations.
2609          *
2610          * If a relation has no triggers, then it can neither have FKs nor be
2611          * referenced by a FK from another table, so we can ignore it.
2612          */
2613         foreach(cell, relations)
2614         {
2615                 Relation        rel = lfirst(cell);
2616
2617                 if (rel->rd_rel->relhastriggers)
2618                         oids = lappend_oid(oids, RelationGetRelid(rel));
2619         }
2620
2621         /*
2622          * Fast path: if no relation has triggers, none has FKs either.
2623          */
2624         if (oids == NIL)
2625                 return;
2626
2627         /*
2628          * Otherwise, must scan pg_constraint.  We make one pass with all the
2629          * relations considered; if this finds nothing, then all is well.
2630          */
2631         dependents = heap_truncate_find_FKs(oids);
2632         if (dependents == NIL)
2633                 return;
2634
2635         /*
2636          * Otherwise we repeat the scan once per relation to identify a particular
2637          * pair of relations to complain about.  This is pretty slow, but
2638          * performance shouldn't matter much in a failure path.  The reason for
2639          * doing things this way is to ensure that the message produced is not
2640          * dependent on chance row locations within pg_constraint.
2641          */
2642         foreach(cell, oids)
2643         {
2644                 Oid                     relid = lfirst_oid(cell);
2645                 ListCell   *cell2;
2646
2647                 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2648
2649                 foreach(cell2, dependents)
2650                 {
2651                         Oid                     relid2 = lfirst_oid(cell2);
2652
2653                         if (!list_member_oid(oids, relid2))
2654                         {
2655                                 char       *relname = get_rel_name(relid);
2656                                 char       *relname2 = get_rel_name(relid2);
2657
2658                                 if (tempTables)
2659                                         ereport(ERROR,
2660                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2661                                                          errmsg("unsupported ON COMMIT and foreign key combination"),
2662                                                          errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2663                                                                            relname2, relname)));
2664                                 else
2665                                         ereport(ERROR,
2666                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2667                                                          errmsg("cannot truncate a table referenced in a foreign key constraint"),
2668                                                          errdetail("Table \"%s\" references \"%s\".",
2669                                                                            relname2, relname),
2670                                                    errhint("Truncate table \"%s\" at the same time, "
2671                                                                    "or use TRUNCATE ... CASCADE.",
2672                                                                    relname2)));
2673                         }
2674                 }
2675         }
2676 }
2677
2678 /*
2679  * heap_truncate_find_FKs
2680  *              Find relations having foreign keys referencing any of the given rels
2681  *
2682  * Input and result are both lists of relation OIDs.  The result contains
2683  * no duplicates, does *not* include any rels that were already in the input
2684  * list, and is sorted in OID order.  (The last property is enforced mainly
2685  * to guarantee consistent behavior in the regression tests; we don't want
2686  * behavior to change depending on chance locations of rows in pg_constraint.)
2687  *
2688  * Note: caller should already have appropriate lock on all rels mentioned
2689  * in relationIds.      Since adding or dropping an FK requires exclusive lock
2690  * on both rels, this ensures that the answer will be stable.
2691  */
2692 List *
2693 heap_truncate_find_FKs(List *relationIds)
2694 {
2695         List       *result = NIL;
2696         Relation        fkeyRel;
2697         SysScanDesc fkeyScan;
2698         HeapTuple       tuple;
2699
2700         /*
2701          * Must scan pg_constraint.  Right now, it is a seqscan because there is
2702          * no available index on confrelid.
2703          */
2704         fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2705
2706         fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2707                                                                   SnapshotNow, 0, NULL);
2708
2709         while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2710         {
2711                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2712
2713                 /* Not a foreign key */
2714                 if (con->contype != CONSTRAINT_FOREIGN)
2715                         continue;
2716
2717                 /* Not referencing one of our list of tables */
2718                 if (!list_member_oid(relationIds, con->confrelid))
2719                         continue;
2720
2721                 /* Add referencer unless already in input or result list */
2722                 if (!list_member_oid(relationIds, con->conrelid))
2723                         result = insert_ordered_unique_oid(result, con->conrelid);
2724         }
2725
2726         systable_endscan(fkeyScan);
2727         heap_close(fkeyRel, AccessShareLock);
2728
2729         return result;
2730 }
2731
2732 /*
2733  * insert_ordered_unique_oid
2734  *              Insert a new Oid into a sorted list of Oids, preserving ordering,
2735  *              and eliminating duplicates
2736  *
2737  * Building the ordered list this way is O(N^2), but with a pretty small
2738  * constant, so for the number of entries we expect it will probably be
2739  * faster than trying to apply qsort().  It seems unlikely someone would be
2740  * trying to truncate a table with thousands of dependent tables ...
2741  */
2742 static List *
2743 insert_ordered_unique_oid(List *list, Oid datum)
2744 {
2745         ListCell   *prev;
2746
2747         /* Does the datum belong at the front? */
2748         if (list == NIL || datum < linitial_oid(list))
2749                 return lcons_oid(datum, list);
2750         /* Does it match the first entry? */
2751         if (datum == linitial_oid(list))
2752                 return list;                    /* duplicate, so don't insert */
2753         /* No, so find the entry it belongs after */
2754         prev = list_head(list);
2755         for (;;)
2756         {
2757                 ListCell   *curr = lnext(prev);
2758
2759                 if (curr == NULL || datum < lfirst_oid(curr))
2760                         break;                          /* it belongs after 'prev', before 'curr' */
2761
2762                 if (datum == lfirst_oid(curr))
2763                         return list;            /* duplicate, so don't insert */
2764
2765                 prev = curr;
2766         }
2767         /* Insert datum into list after 'prev' */
2768         lappend_cell_oid(list, prev, datum);
2769         return list;
2770 }