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