LCOV - code coverage report
Current view: top level - src/backend/catalog - heap.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 866 910 95.2 %
Date: 2024-09-16 13:12:04 Functions: 37 38 97.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14