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