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