OSDN Git Service

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