LCOV - code coverage report
Current view: top level - src/backend/catalog - heap.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 973 1027 94.7 %
Date: 2024-11-21 08:14:44 Functions: 39 40 97.5 %
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, int16 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       27196 : SystemAttributeDefinition(AttrNumber attno)
     241             : {
     242       27196 :     if (attno >= 0 || attno < -(int) lengthof(SysAtt))
     243           0 :         elog(ERROR, "invalid system attribute number %d", attno);
     244       27196 :     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      323490 : SystemAttributeByName(const char *attname)
     253             : {
     254             :     int         j;
     255             : 
     256     2169406 :     for (j = 0; j < (int) lengthof(SysAtt); j++)
     257             :     {
     258     1873152 :         const FormData_pg_attribute *att = SysAtt[j];
     259             : 
     260     1873152 :         if (strcmp(NameStr(att->attname), attname) == 0)
     261       27236 :             return att;
     262             :     }
     263             : 
     264      296254 :     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      125732 : 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      197082 :     if (!allow_system_table_mods &&
     320      153866 :         ((IsCatalogNamespace(relnamespace) && relkind != RELKIND_INDEX) ||
     321       71342 :          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      125724 :     *relfrozenxid = InvalidTransactionId;
     330      125724 :     *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      125724 :     if (!RELKIND_HAS_TABLESPACE(relkind))
     337       20466 :         reltablespace = InvalidOid;
     338             : 
     339             :     /* Don't create storage for relkinds without physical storage. */
     340      125724 :     if (!RELKIND_HAS_STORAGE(relkind))
     341       25404 :         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      100320 :         if (!RelFileNumberIsValid(relfilenumber))
     349       97470 :             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      125724 :     if (reltablespace == MyDatabaseTableSpace)
     362           6 :         reltablespace = InvalidOid;
     363             : 
     364             :     /*
     365             :      * build the relcache entry.
     366             :      */
     367      125724 :     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      125724 :     if (create_storage)
     387             :     {
     388      100246 :         if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
     389       55742 :             table_relation_set_new_filelocator(rel, &rel->rd_locator,
     390             :                                                relpersistence,
     391             :                                                relfrozenxid, relminmxid);
     392       44504 :         else if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
     393       44504 :             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      125724 :     if (!create_storage && reltablespace != InvalidOid)
     404         106 :         recordDependencyOnTablespace(RelationRelationId, relid,
     405             :                                      reltablespace);
     406             : 
     407             :     /* ensure that stats are dropped if transaction aborts */
     408      125724 :     pgstat_create_relation(rel);
     409             : 
     410      125724 :     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       81410 : CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
     457             :                          int flags)
     458             : {
     459             :     int         i;
     460             :     int         j;
     461       81410 :     int         natts = tupdesc->natts;
     462             : 
     463             :     /* Sanity check on column count */
     464       81410 :     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       81410 :     if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
     477             :     {
     478      253390 :         for (i = 0; i < natts; i++)
     479             :         {
     480      191104 :             Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
     481             : 
     482      191104 :             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      333358 :     for (i = 1; i < natts; i++)
     494             :     {
     495     6728032 :         for (j = 0; j < i; j++)
     496             :         {
     497     6476084 :             if (strcmp(NameStr(TupleDescAttr(tupdesc, j)->attname),
     498     6476084 :                        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      411576 :     for (i = 0; i < natts; i++)
     510             :     {
     511      330180 :         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       81396 : }
     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      409570 : CheckAttributeType(const char *attname,
     549             :                    Oid atttypid, Oid attcollation,
     550             :                    List *containing_rowtypes,
     551             :                    int flags)
     552             : {
     553      409570 :     char        att_typtype = get_typtype(atttypid);
     554             :     Oid         att_typelem;
     555             : 
     556             :     /* since this function recurses, it could be driven to stack overflow */
     557      409570 :     check_stack_depth();
     558             : 
     559      409570 :     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        1674 :         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      407908 :     else if (att_typtype == TYPTYPE_DOMAIN)
     589             :     {
     590             :         /*
     591             :          * If it's a domain, recurse to check its base type.
     592             :          */
     593       59382 :         CheckAttributeType(attname, getBaseType(atttypid), attcollation,
     594             :                            containing_rowtypes,
     595             :                            flags);
     596             :     }
     597      348526 :     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         710 :         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         674 :         containing_rowtypes = lappend_oid(containing_rowtypes, atttypid);
     619             : 
     620         674 :         relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
     621             : 
     622         674 :         tupdesc = RelationGetDescr(relation);
     623             : 
     624        4864 :         for (i = 0; i < tupdesc->natts; i++)
     625             :         {
     626        4202 :             Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
     627             : 
     628        4202 :             if (attr->attisdropped)
     629           2 :                 continue;
     630        4200 :             CheckAttributeType(NameStr(attr->attname),
     631             :                                attr->atttypid, attr->attcollation,
     632             :                                containing_rowtypes,
     633             :                                flags & ~CHKATYPE_IS_PARTKEY);
     634             :         }
     635             : 
     636         662 :         relation_close(relation, AccessShareLock);
     637             : 
     638         662 :         containing_rowtypes = list_delete_last(containing_rowtypes);
     639             :     }
     640      347816 :     else if (att_typtype == TYPTYPE_RANGE)
     641             :     {
     642             :         /*
     643             :          * If it's a range, recurse to check its subtype.
     644             :          */
     645        1796 :         CheckAttributeType(attname, get_range_subtype(atttypid),
     646             :                            get_range_collation(atttypid),
     647             :                            containing_rowtypes,
     648             :                            flags);
     649             :     }
     650      346020 :     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        9274 :         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      409466 :     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      409466 : }
     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      190060 : 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      190060 :     int         natts = 0;
     712      190060 :     int         slotCount = 0;
     713      190060 :     bool        close_index = false;
     714             : 
     715      190060 :     td = RelationGetDescr(pg_attribute_rel);
     716             : 
     717             :     /* Initialize the number of slots to use */
     718      190060 :     nslots = Min(tupdesc->natts,
     719             :                  (MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_attribute)));
     720      190060 :     slot = palloc(sizeof(TupleTableSlot *) * nslots);
     721      963712 :     for (int i = 0; i < nslots; i++)
     722      773652 :         slot[i] = MakeSingleTupleTableSlot(td, &TTSOpsHeapTuple);
     723             : 
     724      967488 :     while (natts < tupdesc->natts)
     725             :     {
     726      777428 :         Form_pg_attribute attrs = TupleDescAttr(tupdesc, natts);
     727      777428 :         const FormExtraData_pg_attribute *attrs_extra = tupdesc_extra ? &tupdesc_extra[natts] : NULL;
     728             : 
     729      777428 :         ExecClearTuple(slot[slotCount]);
     730             : 
     731      777428 :         memset(slot[slotCount]->tts_isnull, false,
     732      777428 :                slot[slotCount]->tts_tupleDescriptor->natts * sizeof(bool));
     733             : 
     734      777428 :         if (new_rel_oid != InvalidOid)
     735      704310 :             slot[slotCount]->tts_values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_rel_oid);
     736             :         else
     737       73118 :             slot[slotCount]->tts_values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(attrs->attrelid);
     738             : 
     739      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attname - 1] = NameGetDatum(&attrs->attname);
     740      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(attrs->atttypid);
     741      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(attrs->attlen);
     742      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(attrs->attnum);
     743      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(-1);
     744      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(attrs->atttypmod);
     745      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attndims - 1] = Int16GetDatum(attrs->attndims);
     746      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(attrs->attbyval);
     747      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attalign - 1] = CharGetDatum(attrs->attalign);
     748      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(attrs->attstorage);
     749      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attcompression - 1] = CharGetDatum(attrs->attcompression);
     750      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(attrs->attnotnull);
     751      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(attrs->atthasdef);
     752      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_atthasmissing - 1] = BoolGetDatum(attrs->atthasmissing);
     753      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attidentity - 1] = CharGetDatum(attrs->attidentity);
     754      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attgenerated - 1] = CharGetDatum(attrs->attgenerated);
     755      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(attrs->attisdropped);
     756      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(attrs->attislocal);
     757      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attinhcount - 1] = Int16GetDatum(attrs->attinhcount);
     758      777428 :         slot[slotCount]->tts_values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(attrs->attcollation);
     759      777428 :         if (attrs_extra)
     760             :         {
     761       39914 :             slot[slotCount]->tts_values[Anum_pg_attribute_attstattarget - 1] = attrs_extra->attstattarget.value;
     762       39914 :             slot[slotCount]->tts_isnull[Anum_pg_attribute_attstattarget - 1] = attrs_extra->attstattarget.isnull;
     763             : 
     764       39914 :             slot[slotCount]->tts_values[Anum_pg_attribute_attoptions - 1] = attrs_extra->attoptions.value;
     765       39914 :             slot[slotCount]->tts_isnull[Anum_pg_attribute_attoptions - 1] = attrs_extra->attoptions.isnull;
     766             :         }
     767             :         else
     768             :         {
     769      737514 :             slot[slotCount]->tts_isnull[Anum_pg_attribute_attstattarget - 1] = true;
     770      737514 :             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      777428 :         slot[slotCount]->tts_isnull[Anum_pg_attribute_attacl - 1] = true;
     777      777428 :         slot[slotCount]->tts_isnull[Anum_pg_attribute_attfdwoptions - 1] = true;
     778      777428 :         slot[slotCount]->tts_isnull[Anum_pg_attribute_attmissingval - 1] = true;
     779             : 
     780      777428 :         ExecStoreVirtualTuple(slot[slotCount]);
     781      777428 :         slotCount++;
     782             : 
     783             :         /*
     784             :          * If slots are full or the end of processing has been reached, insert
     785             :          * a batch of tuples.
     786             :          */
     787      777428 :         if (slotCount == nslots || natts == tupdesc->natts - 1)
     788             :         {
     789             :             /* fetch index info only when we know we need it */
     790      186896 :             if (!indstate)
     791             :             {
     792        2428 :                 indstate = CatalogOpenIndexes(pg_attribute_rel);
     793        2428 :                 close_index = true;
     794             :             }
     795             : 
     796             :             /* insert the new tuples and update the indexes */
     797      186896 :             CatalogTuplesMultiInsertWithInfo(pg_attribute_rel, slot, slotCount,
     798             :                                              indstate);
     799      186896 :             slotCount = 0;
     800             :         }
     801             : 
     802      777428 :         natts++;
     803             :     }
     804             : 
     805      190060 :     if (close_index)
     806        2428 :         CatalogCloseIndexes(indstate);
     807      963712 :     for (int i = 0; i < nslots; i++)
     808      773652 :         ExecDropSingleTupleTableSlot(slot[i]);
     809      190060 :     pfree(slot);
     810      190060 : }
     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       80602 : AddNewAttributeTuples(Oid new_rel_oid,
     821             :                       TupleDesc tupdesc,
     822             :                       char relkind)
     823             : {
     824             :     Relation    rel;
     825             :     CatalogIndexState indstate;
     826       80602 :     int         natts = tupdesc->natts;
     827             :     ObjectAddress myself,
     828             :                 referenced;
     829             : 
     830             :     /*
     831             :      * open pg_attribute and its indexes.
     832             :      */
     833       80602 :     rel = table_open(AttributeRelationId, RowExclusiveLock);
     834             : 
     835       80602 :     indstate = CatalogOpenIndexes(rel);
     836             : 
     837       80602 :     InsertPgAttributeTuples(rel, tupdesc, new_rel_oid, NULL, indstate);
     838             : 
     839             :     /* add dependencies on their datatypes and collations */
     840      408876 :     for (int i = 0; i < natts; i++)
     841             :     {
     842      328274 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
     843             : 
     844             :         /* Add dependency info */
     845      328274 :         ObjectAddressSubSet(myself, RelationRelationId, new_rel_oid, i + 1);
     846      328274 :         ObjectAddressSet(referenced, TypeRelationId, attr->atttypid);
     847      328274 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     848             : 
     849             :         /* The default collation is pinned, so don't bother recording it */
     850      328274 :         if (OidIsValid(attr->attcollation) &&
     851      100744 :             attr->attcollation != DEFAULT_COLLATION_OID)
     852             :         {
     853       73242 :             ObjectAddressSet(referenced, CollationRelationId,
     854             :                              attr->attcollation);
     855       73242 :             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       80602 :     if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
     865             :     {
     866             :         TupleDesc   td;
     867             : 
     868       62268 :         td = CreateTupleDesc(lengthof(SysAtt), (FormData_pg_attribute **) &SysAtt);
     869             : 
     870       62268 :         InsertPgAttributeTuples(rel, td, new_rel_oid, NULL, indstate);
     871       62268 :         FreeTupleDesc(td);
     872             :     }
     873             : 
     874             :     /*
     875             :      * clean up
     876             :      */
     877       80602 :     CatalogCloseIndexes(indstate);
     878             : 
     879       80602 :     table_close(rel, RowExclusiveLock);
     880       80602 : }
     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      125364 : InsertPgClassTuple(Relation pg_class_desc,
     897             :                    Relation new_rel_desc,
     898             :                    Oid new_rel_oid,
     899             :                    Datum relacl,
     900             :                    Datum reloptions)
     901             : {
     902      125364 :     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      125364 :     memset(values, 0, sizeof(values));
     909      125364 :     memset(nulls, false, sizeof(nulls));
     910             : 
     911      125364 :     values[Anum_pg_class_oid - 1] = ObjectIdGetDatum(new_rel_oid);
     912      125364 :     values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
     913      125364 :     values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
     914      125364 :     values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
     915      125364 :     values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
     916      125364 :     values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
     917      125364 :     values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
     918      125364 :     values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
     919      125364 :     values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
     920      125364 :     values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
     921      125364 :     values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
     922      125364 :     values[Anum_pg_class_relallvisible - 1] = Int32GetDatum(rd_rel->relallvisible);
     923      125364 :     values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
     924      125364 :     values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
     925      125364 :     values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
     926      125364 :     values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
     927      125364 :     values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
     928      125364 :     values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
     929      125364 :     values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
     930      125364 :     values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
     931      125364 :     values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
     932      125364 :     values[Anum_pg_class_relrowsecurity - 1] = BoolGetDatum(rd_rel->relrowsecurity);
     933      125364 :     values[Anum_pg_class_relforcerowsecurity - 1] = BoolGetDatum(rd_rel->relforcerowsecurity);
     934      125364 :     values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
     935      125364 :     values[Anum_pg_class_relispopulated - 1] = BoolGetDatum(rd_rel->relispopulated);
     936      125364 :     values[Anum_pg_class_relreplident - 1] = CharGetDatum(rd_rel->relreplident);
     937      125364 :     values[Anum_pg_class_relispartition - 1] = BoolGetDatum(rd_rel->relispartition);
     938      125364 :     values[Anum_pg_class_relrewrite - 1] = ObjectIdGetDatum(rd_rel->relrewrite);
     939      125364 :     values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
     940      125364 :     values[Anum_pg_class_relminmxid - 1] = MultiXactIdGetDatum(rd_rel->relminmxid);
     941      125364 :     if (relacl != (Datum) 0)
     942         132 :         values[Anum_pg_class_relacl - 1] = relacl;
     943             :     else
     944      125232 :         nulls[Anum_pg_class_relacl - 1] = true;
     945      125364 :     if (reloptions != (Datum) 0)
     946        1472 :         values[Anum_pg_class_reloptions - 1] = reloptions;
     947             :     else
     948      123892 :         nulls[Anum_pg_class_reloptions - 1] = true;
     949             : 
     950             :     /* relpartbound is set by updating this tuple, if necessary */
     951      125364 :     nulls[Anum_pg_class_relpartbound - 1] = true;
     952             : 
     953      125364 :     tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
     954             : 
     955             :     /* finally insert the new tuple, update the indexes, and clean up */
     956      125364 :     CatalogTupleInsert(pg_class_desc, tup);
     957             : 
     958      125364 :     heap_freetuple(tup);
     959      125364 : }
     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       80602 : 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       80602 :     new_rel_reltup = new_rel_desc->rd_rel;
     988             : 
     989             :     /* The relation is empty */
     990       80602 :     new_rel_reltup->relpages = 0;
     991       80602 :     new_rel_reltup->reltuples = -1;
     992       80602 :     new_rel_reltup->relallvisible = 0;
     993             : 
     994             :     /* Sequences always have a known size */
     995       80602 :     if (relkind == RELKIND_SEQUENCE)
     996             :     {
     997        1710 :         new_rel_reltup->relpages = 1;
     998        1710 :         new_rel_reltup->reltuples = 1;
     999             :     }
    1000             : 
    1001       80602 :     new_rel_reltup->relfrozenxid = relfrozenxid;
    1002       80602 :     new_rel_reltup->relminmxid = relminmxid;
    1003       80602 :     new_rel_reltup->relowner = relowner;
    1004       80602 :     new_rel_reltup->reltype = new_type_oid;
    1005       80602 :     new_rel_reltup->reloftype = reloftype;
    1006             : 
    1007             :     /* relispartition is always set by updating this tuple later */
    1008       80602 :     new_rel_reltup->relispartition = false;
    1009             : 
    1010             :     /* fill rd_att's type ID with something sane even if reltype is zero */
    1011       80602 :     new_rel_desc->rd_att->tdtypeid = new_type_oid ? new_type_oid : RECORDOID;
    1012       80602 :     new_rel_desc->rd_att->tdtypmod = -1;
    1013             : 
    1014             :     /* Now build and insert the tuple */
    1015       80602 :     InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
    1016             :                        relacl, reloptions);
    1017       80602 : }
    1018             : 
    1019             : 
    1020             : /* --------------------------------
    1021             :  *      AddNewRelationType -
    1022             :  *
    1023             :  *      define a composite type corresponding to the new relation
    1024             :  * --------------------------------
    1025             :  */
    1026             : static ObjectAddress
    1027       62290 : 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       62290 :         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       80626 : 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       80626 :     RelFileNumber relfilenumber = InvalidRelFileNumber;
    1136             :     TransactionId relfrozenxid;
    1137             :     MultiXactId relminmxid;
    1138             : 
    1139       80626 :     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       80626 :     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       80612 :     existing_relid = get_relname_relid(relname, relnamespace);
    1159       80612 :     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       80610 :     old_type_oid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
    1171             :                                    CStringGetDatum(relname),
    1172             :                                    ObjectIdGetDatum(relnamespace));
    1173       80610 :     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       80610 :     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       80610 :     if (!OidIsValid(relid))
    1197             :     {
    1198             :         /* Use binary-upgrade override for pg_class.oid and relfilenumber */
    1199       71970 :         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        2078 :             if (relkind == RELKIND_TOASTVALUE)
    1209             :             {
    1210             :                 /* There might be no TOAST table, so we have to test for it. */
    1211         528 :                 if (OidIsValid(binary_upgrade_next_toast_pg_class_oid))
    1212             :                 {
    1213         528 :                     relid = binary_upgrade_next_toast_pg_class_oid;
    1214         528 :                     binary_upgrade_next_toast_pg_class_oid = InvalidOid;
    1215             : 
    1216         528 :                     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         528 :                     relfilenumber = binary_upgrade_next_toast_pg_class_relfilenumber;
    1222         528 :                     binary_upgrade_next_toast_pg_class_relfilenumber = InvalidRelFileNumber;
    1223             :                 }
    1224             :             }
    1225             :             else
    1226             :             {
    1227        1550 :                 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        1550 :                 relid = binary_upgrade_next_heap_pg_class_oid;
    1233        1550 :                 binary_upgrade_next_heap_pg_class_oid = InvalidOid;
    1234             : 
    1235        1550 :                 if (RELKIND_HAS_STORAGE(relkind))
    1236             :                 {
    1237        1256 :                     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        1256 :                     relfilenumber = binary_upgrade_next_heap_pg_class_relfilenumber;
    1243        1256 :                     binary_upgrade_next_heap_pg_class_relfilenumber = InvalidRelFileNumber;
    1244             :                 }
    1245             :             }
    1246             :         }
    1247             : 
    1248       71970 :         if (!OidIsValid(relid))
    1249       69892 :             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       80610 :     LockRelationOid(relid, AccessExclusiveLock);
    1259             : 
    1260             :     /*
    1261             :      * Determine the relation's initial permissions.
    1262             :      */
    1263       80610 :     if (use_user_acl)
    1264             :     {
    1265       56572 :         switch (relkind)
    1266             :         {
    1267       51388 :             case RELKIND_RELATION:
    1268             :             case RELKIND_VIEW:
    1269             :             case RELKIND_MATVIEW:
    1270             :             case RELKIND_FOREIGN_TABLE:
    1271             :             case RELKIND_PARTITIONED_TABLE:
    1272       51388 :                 relacl = get_user_default_acl(OBJECT_TABLE, ownerid,
    1273             :                                               relnamespace);
    1274       51388 :                 break;
    1275        1710 :             case RELKIND_SEQUENCE:
    1276        1710 :                 relacl = get_user_default_acl(OBJECT_SEQUENCE, ownerid,
    1277             :                                               relnamespace);
    1278        1710 :                 break;
    1279        3474 :             default:
    1280        3474 :                 relacl = NULL;
    1281        3474 :                 break;
    1282             :         }
    1283             :     }
    1284             :     else
    1285       24038 :         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       80610 :     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       80602 :     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      142892 :     if (!(relkind == RELKIND_SEQUENCE ||
    1322       62290 :           relkind == RELKIND_TOASTVALUE ||
    1323             :           relkind == RELKIND_INDEX ||
    1324             :           relkind == RELKIND_PARTITIONED_INDEX))
    1325       62290 :     {
    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       62290 :         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       62290 :         new_type_addr = AddNewRelationType(relname,
    1346             :                                            relnamespace,
    1347             :                                            relid,
    1348             :                                            relkind,
    1349             :                                            ownerid,
    1350             :                                            reltypeid,
    1351             :                                            new_array_oid);
    1352       62290 :         new_type_oid = new_type_addr.objectId;
    1353       62290 :         if (typaddress)
    1354        3474 :             *typaddress = new_type_addr;
    1355             : 
    1356             :         /* Now create the array type. */
    1357       62290 :         relarrayname = makeArrayTypeName(relname, relnamespace);
    1358             : 
    1359       62290 :         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       62290 :         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       18312 :         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       80602 :     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       80602 :     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       80602 :     if (relkind != RELKIND_COMPOSITE_TYPE &&
    1443       60526 :         relkind != RELKIND_TOASTVALUE &&
    1444       60526 :         !IsBootstrapProcessingMode())
    1445             :     {
    1446             :         ObjectAddress myself,
    1447             :                     referenced;
    1448             :         ObjectAddresses *addrs;
    1449             : 
    1450       55126 :         ObjectAddressSet(myself, RelationRelationId, relid);
    1451             : 
    1452       55126 :         recordDependencyOnOwner(RelationRelationId, relid, ownerid);
    1453             : 
    1454       55126 :         recordDependencyOnNewAcl(RelationRelationId, relid, 0, ownerid, relacl);
    1455             : 
    1456       55126 :         recordDependencyOnCurrentExtension(&myself, false);
    1457             : 
    1458       55126 :         addrs = new_object_addresses();
    1459             : 
    1460       55126 :         ObjectAddressSet(referenced, NamespaceRelationId, relnamespace);
    1461       55126 :         add_exact_object_address(&referenced, addrs);
    1462             : 
    1463       55126 :         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.  Partitioned tables may not have an
    1475             :          * access method set.
    1476             :          */
    1477       55126 :         if ((RELKIND_HAS_TABLE_AM(relkind) && relkind != RELKIND_TOASTVALUE) ||
    1478        4754 :             (relkind == RELKIND_PARTITIONED_TABLE && OidIsValid(accessmtd)))
    1479             :         {
    1480       33398 :             ObjectAddressSet(referenced, AccessMethodRelationId, accessmtd);
    1481       33398 :             add_exact_object_address(&referenced, addrs);
    1482             :         }
    1483             : 
    1484       55126 :         record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
    1485       55126 :         free_object_addresses(addrs);
    1486             :     }
    1487             : 
    1488             :     /* Post creation hook for new relation */
    1489       80602 :     InvokeObjectPostCreateHookArg(RelationRelationId, relid, 0, is_internal);
    1490             : 
    1491             :     /*
    1492             :      * Store any supplied constraints and defaults.
    1493             :      *
    1494             :      * NB: this may do a CommandCounterIncrement and rebuild the relcache
    1495             :      * entry, so the relation must be valid and self-consistent at this point.
    1496             :      * In particular, there are not yet constraints and defaults anywhere.
    1497             :      */
    1498       80602 :     StoreConstraints(new_rel_desc, cooked_constraints, is_internal);
    1499             : 
    1500             :     /*
    1501             :      * If there's a special on-commit action, remember it
    1502             :      */
    1503       80602 :     if (oncommit != ONCOMMIT_NOOP)
    1504         166 :         register_on_commit_action(relid, oncommit);
    1505             : 
    1506             :     /*
    1507             :      * ok, the relation has been cataloged, so close our relations and return
    1508             :      * the OID of the newly created relation.
    1509             :      */
    1510       80602 :     table_close(new_rel_desc, NoLock);  /* do not unlock till end of xact */
    1511       80602 :     table_close(pg_class_desc, RowExclusiveLock);
    1512             : 
    1513       80602 :     return relid;
    1514             : }
    1515             : 
    1516             : /*
    1517             :  *      RelationRemoveInheritance
    1518             :  *
    1519             :  * Formerly, this routine checked for child relations and aborted the
    1520             :  * deletion if any were found.  Now we rely on the dependency mechanism
    1521             :  * to check for or delete child relations.  By the time we get here,
    1522             :  * there are no children and we need only remove any pg_inherits rows
    1523             :  * linking this relation to its parent(s).
    1524             :  */
    1525             : static void
    1526       45070 : RelationRemoveInheritance(Oid relid)
    1527             : {
    1528             :     Relation    catalogRelation;
    1529             :     SysScanDesc scan;
    1530             :     ScanKeyData key;
    1531             :     HeapTuple   tuple;
    1532             : 
    1533       45070 :     catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
    1534             : 
    1535       45070 :     ScanKeyInit(&key,
    1536             :                 Anum_pg_inherits_inhrelid,
    1537             :                 BTEqualStrategyNumber, F_OIDEQ,
    1538             :                 ObjectIdGetDatum(relid));
    1539             : 
    1540       45070 :     scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
    1541             :                               NULL, 1, &key);
    1542             : 
    1543       53560 :     while (HeapTupleIsValid(tuple = systable_getnext(scan)))
    1544        8490 :         CatalogTupleDelete(catalogRelation, &tuple->t_self);
    1545             : 
    1546       45070 :     systable_endscan(scan);
    1547       45070 :     table_close(catalogRelation, RowExclusiveLock);
    1548       45070 : }
    1549             : 
    1550             : /*
    1551             :  *      DeleteRelationTuple
    1552             :  *
    1553             :  * Remove pg_class row for the given relid.
    1554             :  *
    1555             :  * Note: this is shared by relation deletion and index deletion.  It's
    1556             :  * not intended for use anyplace else.
    1557             :  */
    1558             : void
    1559       67834 : DeleteRelationTuple(Oid relid)
    1560             : {
    1561             :     Relation    pg_class_desc;
    1562             :     HeapTuple   tup;
    1563             : 
    1564             :     /* Grab an appropriate lock on the pg_class relation */
    1565       67834 :     pg_class_desc = table_open(RelationRelationId, RowExclusiveLock);
    1566             : 
    1567       67834 :     tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    1568       67834 :     if (!HeapTupleIsValid(tup))
    1569           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
    1570             : 
    1571             :     /* delete the relation tuple from pg_class, and finish up */
    1572       67834 :     CatalogTupleDelete(pg_class_desc, &tup->t_self);
    1573             : 
    1574       67834 :     ReleaseSysCache(tup);
    1575             : 
    1576       67834 :     table_close(pg_class_desc, RowExclusiveLock);
    1577       67834 : }
    1578             : 
    1579             : /*
    1580             :  *      DeleteAttributeTuples
    1581             :  *
    1582             :  * Remove pg_attribute rows for the given relid.
    1583             :  *
    1584             :  * Note: this is shared by relation deletion and index deletion.  It's
    1585             :  * not intended for use anyplace else.
    1586             :  */
    1587             : void
    1588       67834 : DeleteAttributeTuples(Oid relid)
    1589             : {
    1590             :     Relation    attrel;
    1591             :     SysScanDesc scan;
    1592             :     ScanKeyData key[1];
    1593             :     HeapTuple   atttup;
    1594             : 
    1595             :     /* Grab an appropriate lock on the pg_attribute relation */
    1596       67834 :     attrel = table_open(AttributeRelationId, RowExclusiveLock);
    1597             : 
    1598             :     /* Use the index to scan only attributes of the target relation */
    1599       67834 :     ScanKeyInit(&key[0],
    1600             :                 Anum_pg_attribute_attrelid,
    1601             :                 BTEqualStrategyNumber, F_OIDEQ,
    1602             :                 ObjectIdGetDatum(relid));
    1603             : 
    1604       67834 :     scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
    1605             :                               NULL, 1, key);
    1606             : 
    1607             :     /* Delete all the matching tuples */
    1608      445802 :     while ((atttup = systable_getnext(scan)) != NULL)
    1609      377968 :         CatalogTupleDelete(attrel, &atttup->t_self);
    1610             : 
    1611             :     /* Clean up after the scan */
    1612       67834 :     systable_endscan(scan);
    1613       67834 :     table_close(attrel, RowExclusiveLock);
    1614       67834 : }
    1615             : 
    1616             : /*
    1617             :  *      DeleteSystemAttributeTuples
    1618             :  *
    1619             :  * Remove pg_attribute rows for system columns of the given relid.
    1620             :  *
    1621             :  * Note: this is only used when converting a table to a view.  Views don't
    1622             :  * have system columns, so we should remove them from pg_attribute.
    1623             :  */
    1624             : void
    1625           0 : DeleteSystemAttributeTuples(Oid relid)
    1626             : {
    1627             :     Relation    attrel;
    1628             :     SysScanDesc scan;
    1629             :     ScanKeyData key[2];
    1630             :     HeapTuple   atttup;
    1631             : 
    1632             :     /* Grab an appropriate lock on the pg_attribute relation */
    1633           0 :     attrel = table_open(AttributeRelationId, RowExclusiveLock);
    1634             : 
    1635             :     /* Use the index to scan only system attributes of the target relation */
    1636           0 :     ScanKeyInit(&key[0],
    1637             :                 Anum_pg_attribute_attrelid,
    1638             :                 BTEqualStrategyNumber, F_OIDEQ,
    1639             :                 ObjectIdGetDatum(relid));
    1640           0 :     ScanKeyInit(&key[1],
    1641             :                 Anum_pg_attribute_attnum,
    1642             :                 BTLessEqualStrategyNumber, F_INT2LE,
    1643             :                 Int16GetDatum(0));
    1644             : 
    1645           0 :     scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
    1646             :                               NULL, 2, key);
    1647             : 
    1648             :     /* Delete all the matching tuples */
    1649           0 :     while ((atttup = systable_getnext(scan)) != NULL)
    1650           0 :         CatalogTupleDelete(attrel, &atttup->t_self);
    1651             : 
    1652             :     /* Clean up after the scan */
    1653           0 :     systable_endscan(scan);
    1654           0 :     table_close(attrel, RowExclusiveLock);
    1655           0 : }
    1656             : 
    1657             : /*
    1658             :  *      RemoveAttributeById
    1659             :  *
    1660             :  * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
    1661             :  * deleted in pg_attribute.  We also remove pg_statistic entries for it.
    1662             :  * (Everything else needed, such as getting rid of any pg_attrdef entry,
    1663             :  * is handled by dependency.c.)
    1664             :  */
    1665             : void
    1666        1990 : RemoveAttributeById(Oid relid, AttrNumber attnum)
    1667             : {
    1668             :     Relation    rel;
    1669             :     Relation    attr_rel;
    1670             :     HeapTuple   tuple;
    1671             :     Form_pg_attribute attStruct;
    1672             :     char        newattname[NAMEDATALEN];
    1673        1990 :     Datum       valuesAtt[Natts_pg_attribute] = {0};
    1674        1990 :     bool        nullsAtt[Natts_pg_attribute] = {0};
    1675        1990 :     bool        replacesAtt[Natts_pg_attribute] = {0};
    1676             : 
    1677             :     /*
    1678             :      * Grab an exclusive lock on the target table, which we will NOT release
    1679             :      * until end of transaction.  (In the simple case where we are directly
    1680             :      * dropping this column, ATExecDropColumn already did this ... but when
    1681             :      * cascading from a drop of some other object, we may not have any lock.)
    1682             :      */
    1683        1990 :     rel = relation_open(relid, AccessExclusiveLock);
    1684             : 
    1685        1990 :     attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    1686             : 
    1687        1990 :     tuple = SearchSysCacheCopy2(ATTNUM,
    1688             :                                 ObjectIdGetDatum(relid),
    1689             :                                 Int16GetDatum(attnum));
    1690        1990 :     if (!HeapTupleIsValid(tuple))   /* shouldn't happen */
    1691           0 :         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
    1692             :              attnum, relid);
    1693        1990 :     attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
    1694             : 
    1695             :     /* Mark the attribute as dropped */
    1696        1990 :     attStruct->attisdropped = true;
    1697             : 
    1698             :     /*
    1699             :      * Set the type OID to invalid.  A dropped attribute's type link cannot be
    1700             :      * relied on (once the attribute is dropped, the type might be too).
    1701             :      * Fortunately we do not need the type row --- the only really essential
    1702             :      * information is the type's typlen and typalign, which are preserved in
    1703             :      * the attribute's attlen and attalign.  We set atttypid to zero here as a
    1704             :      * means of catching code that incorrectly expects it to be valid.
    1705             :      */
    1706        1990 :     attStruct->atttypid = InvalidOid;
    1707             : 
    1708             :     /* Remove any not-null constraint the column may have */
    1709        1990 :     attStruct->attnotnull = false;
    1710             : 
    1711             :     /* Unset this so no one tries to look up the generation expression */
    1712        1990 :     attStruct->attgenerated = '\0';
    1713             : 
    1714             :     /*
    1715             :      * Change the column name to something that isn't likely to conflict
    1716             :      */
    1717        1990 :     snprintf(newattname, sizeof(newattname),
    1718             :              "........pg.dropped.%d........", attnum);
    1719        1990 :     namestrcpy(&(attStruct->attname), newattname);
    1720             : 
    1721             :     /* Clear the missing value */
    1722        1990 :     attStruct->atthasmissing = false;
    1723        1990 :     nullsAtt[Anum_pg_attribute_attmissingval - 1] = true;
    1724        1990 :     replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
    1725             : 
    1726             :     /*
    1727             :      * Clear the other nullable fields.  This saves some space in pg_attribute
    1728             :      * and removes no longer useful information.
    1729             :      */
    1730        1990 :     nullsAtt[Anum_pg_attribute_attstattarget - 1] = true;
    1731        1990 :     replacesAtt[Anum_pg_attribute_attstattarget - 1] = true;
    1732        1990 :     nullsAtt[Anum_pg_attribute_attacl - 1] = true;
    1733        1990 :     replacesAtt[Anum_pg_attribute_attacl - 1] = true;
    1734        1990 :     nullsAtt[Anum_pg_attribute_attoptions - 1] = true;
    1735        1990 :     replacesAtt[Anum_pg_attribute_attoptions - 1] = true;
    1736        1990 :     nullsAtt[Anum_pg_attribute_attfdwoptions - 1] = true;
    1737        1990 :     replacesAtt[Anum_pg_attribute_attfdwoptions - 1] = true;
    1738             : 
    1739        1990 :     tuple = heap_modify_tuple(tuple, RelationGetDescr(attr_rel),
    1740             :                               valuesAtt, nullsAtt, replacesAtt);
    1741             : 
    1742        1990 :     CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
    1743             : 
    1744             :     /*
    1745             :      * Because updating the pg_attribute row will trigger a relcache flush for
    1746             :      * the target relation, we need not do anything else to notify other
    1747             :      * backends of the change.
    1748             :      */
    1749             : 
    1750        1990 :     table_close(attr_rel, RowExclusiveLock);
    1751             : 
    1752        1990 :     RemoveStatistics(relid, attnum);
    1753             : 
    1754        1990 :     relation_close(rel, NoLock);
    1755        1990 : }
    1756             : 
    1757             : /*
    1758             :  * heap_drop_with_catalog   - removes specified relation from catalogs
    1759             :  *
    1760             :  * Note that this routine is not responsible for dropping objects that are
    1761             :  * linked to the pg_class entry via dependencies (for example, indexes and
    1762             :  * constraints).  Those are deleted by the dependency-tracing logic in
    1763             :  * dependency.c before control gets here.  In general, therefore, this routine
    1764             :  * should never be called directly; go through performDeletion() instead.
    1765             :  */
    1766             : void
    1767       45070 : heap_drop_with_catalog(Oid relid)
    1768             : {
    1769             :     Relation    rel;
    1770             :     HeapTuple   tuple;
    1771       45070 :     Oid         parentOid = InvalidOid,
    1772       45070 :                 defaultPartOid = InvalidOid;
    1773             : 
    1774             :     /*
    1775             :      * To drop a partition safely, we must grab exclusive lock on its parent,
    1776             :      * because another backend might be about to execute a query on the parent
    1777             :      * table.  If it relies on previously cached partition descriptor, then it
    1778             :      * could attempt to access the just-dropped relation as its partition. We
    1779             :      * must therefore take a table lock strong enough to prevent all queries
    1780             :      * on the table from proceeding until we commit and send out a
    1781             :      * shared-cache-inval notice that will make them update their partition
    1782             :      * descriptors.
    1783             :      */
    1784       45070 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    1785       45070 :     if (!HeapTupleIsValid(tuple))
    1786           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
    1787       45070 :     if (((Form_pg_class) GETSTRUCT(tuple))->relispartition)
    1788             :     {
    1789             :         /*
    1790             :          * We have to lock the parent if the partition is being detached,
    1791             :          * because it's possible that some query still has a partition
    1792             :          * descriptor that includes this partition.
    1793             :          */
    1794        6806 :         parentOid = get_partition_parent(relid, true);
    1795        6806 :         LockRelationOid(parentOid, AccessExclusiveLock);
    1796             : 
    1797             :         /*
    1798             :          * If this is not the default partition, dropping it will change the
    1799             :          * default partition's partition constraint, so we must lock it.
    1800             :          */
    1801        6806 :         defaultPartOid = get_default_partition_oid(parentOid);
    1802        6806 :         if (OidIsValid(defaultPartOid) && relid != defaultPartOid)
    1803         374 :             LockRelationOid(defaultPartOid, AccessExclusiveLock);
    1804             :     }
    1805             : 
    1806       45070 :     ReleaseSysCache(tuple);
    1807             : 
    1808             :     /*
    1809             :      * Open and lock the relation.
    1810             :      */
    1811       45070 :     rel = relation_open(relid, AccessExclusiveLock);
    1812             : 
    1813             :     /*
    1814             :      * There can no longer be anyone *else* touching the relation, but we
    1815             :      * might still have open queries or cursors, or pending trigger events, in
    1816             :      * our own session.
    1817             :      */
    1818       45070 :     CheckTableNotInUse(rel, "DROP TABLE");
    1819             : 
    1820             :     /*
    1821             :      * This effectively deletes all rows in the table, and may be done in a
    1822             :      * serializable transaction.  In that case we must record a rw-conflict in
    1823             :      * to this transaction from each transaction holding a predicate lock on
    1824             :      * the table.
    1825             :      */
    1826       45070 :     CheckTableForSerializableConflictIn(rel);
    1827             : 
    1828             :     /*
    1829             :      * Delete pg_foreign_table tuple first.
    1830             :      */
    1831       45070 :     if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    1832             :     {
    1833             :         Relation    ftrel;
    1834             :         HeapTuple   fttuple;
    1835             : 
    1836         232 :         ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
    1837             : 
    1838         232 :         fttuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
    1839         232 :         if (!HeapTupleIsValid(fttuple))
    1840           0 :             elog(ERROR, "cache lookup failed for foreign table %u", relid);
    1841             : 
    1842         232 :         CatalogTupleDelete(ftrel, &fttuple->t_self);
    1843             : 
    1844         232 :         ReleaseSysCache(fttuple);
    1845         232 :         table_close(ftrel, RowExclusiveLock);
    1846             :     }
    1847             : 
    1848             :     /*
    1849             :      * If a partitioned table, delete the pg_partitioned_table tuple.
    1850             :      */
    1851       45070 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    1852        3718 :         RemovePartitionKeyByRelId(relid);
    1853             : 
    1854             :     /*
    1855             :      * If the relation being dropped is the default partition itself,
    1856             :      * invalidate its entry in pg_partitioned_table.
    1857             :      */
    1858       45070 :     if (relid == defaultPartOid)
    1859         410 :         update_default_partition_oid(parentOid, InvalidOid);
    1860             : 
    1861             :     /*
    1862             :      * Schedule unlinking of the relation's physical files at commit.
    1863             :      */
    1864       45070 :     if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
    1865       35828 :         RelationDropStorage(rel);
    1866             : 
    1867             :     /* ensure that stats are dropped if transaction commits */
    1868       45070 :     pgstat_drop_relation(rel);
    1869             : 
    1870             :     /*
    1871             :      * Close relcache entry, but *keep* AccessExclusiveLock on the relation
    1872             :      * until transaction commit.  This ensures no one else will try to do
    1873             :      * something with the doomed relation.
    1874             :      */
    1875       45070 :     relation_close(rel, NoLock);
    1876             : 
    1877             :     /*
    1878             :      * Remove any associated relation synchronization states.
    1879             :      */
    1880       45070 :     RemoveSubscriptionRel(InvalidOid, relid);
    1881             : 
    1882             :     /*
    1883             :      * Forget any ON COMMIT action for the rel
    1884             :      */
    1885       45070 :     remove_on_commit_action(relid);
    1886             : 
    1887             :     /*
    1888             :      * Flush the relation from the relcache.  We want to do this before
    1889             :      * starting to remove catalog entries, just to be certain that no relcache
    1890             :      * entry rebuild will happen partway through.  (That should not really
    1891             :      * matter, since we don't do CommandCounterIncrement here, but let's be
    1892             :      * safe.)
    1893             :      */
    1894       45070 :     RelationForgetRelation(relid);
    1895             : 
    1896             :     /*
    1897             :      * remove inheritance information
    1898             :      */
    1899       45070 :     RelationRemoveInheritance(relid);
    1900             : 
    1901             :     /*
    1902             :      * delete statistics
    1903             :      */
    1904       45070 :     RemoveStatistics(relid, 0);
    1905             : 
    1906             :     /*
    1907             :      * delete attribute tuples
    1908             :      */
    1909       45070 :     DeleteAttributeTuples(relid);
    1910             : 
    1911             :     /*
    1912             :      * delete relation tuple
    1913             :      */
    1914       45070 :     DeleteRelationTuple(relid);
    1915             : 
    1916       45070 :     if (OidIsValid(parentOid))
    1917             :     {
    1918             :         /*
    1919             :          * If this is not the default partition, the partition constraint of
    1920             :          * the default partition has changed to include the portion of the key
    1921             :          * space previously covered by the dropped partition.
    1922             :          */
    1923        6806 :         if (OidIsValid(defaultPartOid) && relid != defaultPartOid)
    1924         374 :             CacheInvalidateRelcacheByRelid(defaultPartOid);
    1925             : 
    1926             :         /*
    1927             :          * Invalidate the parent's relcache so that the partition is no longer
    1928             :          * included in its partition descriptor.
    1929             :          */
    1930        6806 :         CacheInvalidateRelcacheByRelid(parentOid);
    1931             :         /* keep the lock */
    1932             :     }
    1933       45070 : }
    1934             : 
    1935             : 
    1936             : /*
    1937             :  * RelationClearMissing
    1938             :  *
    1939             :  * Set atthasmissing and attmissingval to false/null for all attributes
    1940             :  * where they are currently set. This can be safely and usefully done if
    1941             :  * the table is rewritten (e.g. by VACUUM FULL or CLUSTER) where we know there
    1942             :  * are no rows left with less than a full complement of attributes.
    1943             :  *
    1944             :  * The caller must have an AccessExclusive lock on the relation.
    1945             :  */
    1946             : void
    1947        2440 : RelationClearMissing(Relation rel)
    1948             : {
    1949             :     Relation    attr_rel;
    1950        2440 :     Oid         relid = RelationGetRelid(rel);
    1951        2440 :     int         natts = RelationGetNumberOfAttributes(rel);
    1952             :     int         attnum;
    1953             :     Datum       repl_val[Natts_pg_attribute];
    1954             :     bool        repl_null[Natts_pg_attribute];
    1955             :     bool        repl_repl[Natts_pg_attribute];
    1956             :     Form_pg_attribute attrtuple;
    1957             :     HeapTuple   tuple,
    1958             :                 newtuple;
    1959             : 
    1960        2440 :     memset(repl_val, 0, sizeof(repl_val));
    1961        2440 :     memset(repl_null, false, sizeof(repl_null));
    1962        2440 :     memset(repl_repl, false, sizeof(repl_repl));
    1963             : 
    1964        2440 :     repl_val[Anum_pg_attribute_atthasmissing - 1] = BoolGetDatum(false);
    1965        2440 :     repl_null[Anum_pg_attribute_attmissingval - 1] = true;
    1966             : 
    1967        2440 :     repl_repl[Anum_pg_attribute_atthasmissing - 1] = true;
    1968        2440 :     repl_repl[Anum_pg_attribute_attmissingval - 1] = true;
    1969             : 
    1970             : 
    1971             :     /* Get a lock on pg_attribute */
    1972        2440 :     attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    1973             : 
    1974             :     /* process each non-system attribute, including any dropped columns */
    1975        8892 :     for (attnum = 1; attnum <= natts; attnum++)
    1976             :     {
    1977        6452 :         tuple = SearchSysCache2(ATTNUM,
    1978             :                                 ObjectIdGetDatum(relid),
    1979             :                                 Int16GetDatum(attnum));
    1980        6452 :         if (!HeapTupleIsValid(tuple))   /* shouldn't happen */
    1981           0 :             elog(ERROR, "cache lookup failed for attribute %d of relation %u",
    1982             :                  attnum, relid);
    1983             : 
    1984        6452 :         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    1985             : 
    1986             :         /* ignore any where atthasmissing is not true */
    1987        6452 :         if (attrtuple->atthasmissing)
    1988             :         {
    1989          96 :             newtuple = heap_modify_tuple(tuple, RelationGetDescr(attr_rel),
    1990             :                                          repl_val, repl_null, repl_repl);
    1991             : 
    1992          96 :             CatalogTupleUpdate(attr_rel, &newtuple->t_self, newtuple);
    1993             : 
    1994          96 :             heap_freetuple(newtuple);
    1995             :         }
    1996             : 
    1997        6452 :         ReleaseSysCache(tuple);
    1998             :     }
    1999             : 
    2000             :     /*
    2001             :      * Our update of the pg_attribute rows will force a relcache rebuild, so
    2002             :      * there's nothing else to do here.
    2003             :      */
    2004        2440 :     table_close(attr_rel, RowExclusiveLock);
    2005        2440 : }
    2006             : 
    2007             : /*
    2008             :  * SetAttrMissing
    2009             :  *
    2010             :  * Set the missing value of a single attribute. This should only be used by
    2011             :  * binary upgrade. Takes an AccessExclusive lock on the relation owning the
    2012             :  * attribute.
    2013             :  */
    2014             : void
    2015           4 : SetAttrMissing(Oid relid, char *attname, char *value)
    2016             : {
    2017           4 :     Datum       valuesAtt[Natts_pg_attribute] = {0};
    2018           4 :     bool        nullsAtt[Natts_pg_attribute] = {0};
    2019           4 :     bool        replacesAtt[Natts_pg_attribute] = {0};
    2020             :     Datum       missingval;
    2021             :     Form_pg_attribute attStruct;
    2022             :     Relation    attrrel,
    2023             :                 tablerel;
    2024             :     HeapTuple   atttup,
    2025             :                 newtup;
    2026             : 
    2027             :     /* lock the table the attribute belongs to */
    2028           4 :     tablerel = table_open(relid, AccessExclusiveLock);
    2029             : 
    2030             :     /* Don't do anything unless it's a plain table */
    2031           4 :     if (tablerel->rd_rel->relkind != RELKIND_RELATION)
    2032             :     {
    2033           0 :         table_close(tablerel, AccessExclusiveLock);
    2034           0 :         return;
    2035             :     }
    2036             : 
    2037             :     /* Lock the attribute row and get the data */
    2038           4 :     attrrel = table_open(AttributeRelationId, RowExclusiveLock);
    2039           4 :     atttup = SearchSysCacheAttName(relid, attname);
    2040           4 :     if (!HeapTupleIsValid(atttup))
    2041           0 :         elog(ERROR, "cache lookup failed for attribute %s of relation %u",
    2042             :              attname, relid);
    2043           4 :     attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
    2044             : 
    2045             :     /* get an array value from the value string */
    2046           4 :     missingval = OidFunctionCall3(F_ARRAY_IN,
    2047             :                                   CStringGetDatum(value),
    2048             :                                   ObjectIdGetDatum(attStruct->atttypid),
    2049             :                                   Int32GetDatum(attStruct->atttypmod));
    2050             : 
    2051             :     /* update the tuple - set atthasmissing and attmissingval */
    2052           4 :     valuesAtt[Anum_pg_attribute_atthasmissing - 1] = BoolGetDatum(true);
    2053           4 :     replacesAtt[Anum_pg_attribute_atthasmissing - 1] = true;
    2054           4 :     valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
    2055           4 :     replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
    2056             : 
    2057           4 :     newtup = heap_modify_tuple(atttup, RelationGetDescr(attrrel),
    2058             :                                valuesAtt, nullsAtt, replacesAtt);
    2059           4 :     CatalogTupleUpdate(attrrel, &newtup->t_self, newtup);
    2060             : 
    2061             :     /* clean up */
    2062           4 :     ReleaseSysCache(atttup);
    2063           4 :     table_close(attrrel, RowExclusiveLock);
    2064           4 :     table_close(tablerel, AccessExclusiveLock);
    2065             : }
    2066             : 
    2067             : /*
    2068             :  * Store a check-constraint expression for the given relation.
    2069             :  *
    2070             :  * Caller is responsible for updating the count of constraints
    2071             :  * in the pg_class entry for the relation.
    2072             :  *
    2073             :  * The OID of the new constraint is returned.
    2074             :  */
    2075             : static Oid
    2076        2150 : StoreRelCheck(Relation rel, const char *ccname, Node *expr,
    2077             :               bool is_validated, bool is_local, int16 inhcount,
    2078             :               bool is_no_inherit, bool is_internal)
    2079             : {
    2080             :     char       *ccbin;
    2081             :     List       *varList;
    2082             :     int         keycount;
    2083             :     int16      *attNos;
    2084             :     Oid         constrOid;
    2085             : 
    2086             :     /*
    2087             :      * Flatten expression to string form for storage.
    2088             :      */
    2089        2150 :     ccbin = nodeToString(expr);
    2090             : 
    2091             :     /*
    2092             :      * Find columns of rel that are used in expr
    2093             :      *
    2094             :      * NB: pull_var_clause is okay here only because we don't allow subselects
    2095             :      * in check constraints; it would fail to examine the contents of
    2096             :      * subselects.
    2097             :      */
    2098        2150 :     varList = pull_var_clause(expr, 0);
    2099        2150 :     keycount = list_length(varList);
    2100             : 
    2101        2150 :     if (keycount > 0)
    2102             :     {
    2103             :         ListCell   *vl;
    2104        2136 :         int         i = 0;
    2105             : 
    2106        2136 :         attNos = (int16 *) palloc(keycount * sizeof(int16));
    2107        4882 :         foreach(vl, varList)
    2108             :         {
    2109        2746 :             Var        *var = (Var *) lfirst(vl);
    2110             :             int         j;
    2111             : 
    2112        2976 :             for (j = 0; j < i; j++)
    2113         630 :                 if (attNos[j] == var->varattno)
    2114         400 :                     break;
    2115        2746 :             if (j == i)
    2116        2346 :                 attNos[i++] = var->varattno;
    2117             :         }
    2118        2136 :         keycount = i;
    2119             :     }
    2120             :     else
    2121          14 :         attNos = NULL;
    2122             : 
    2123             :     /*
    2124             :      * Partitioned tables do not contain any rows themselves, so a NO INHERIT
    2125             :      * constraint makes no sense.
    2126             :      */
    2127        2150 :     if (is_no_inherit &&
    2128         112 :         rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    2129          24 :         ereport(ERROR,
    2130             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    2131             :                  errmsg("cannot add NO INHERIT constraint to partitioned table \"%s\"",
    2132             :                         RelationGetRelationName(rel))));
    2133             : 
    2134             :     /*
    2135             :      * Create the Check Constraint
    2136             :      */
    2137             :     constrOid =
    2138        2126 :         CreateConstraintEntry(ccname,   /* Constraint Name */
    2139        2126 :                               RelationGetNamespace(rel),    /* namespace */
    2140             :                               CONSTRAINT_CHECK, /* Constraint Type */
    2141             :                               false,    /* Is Deferrable */
    2142             :                               false,    /* Is Deferred */
    2143             :                               is_validated,
    2144             :                               InvalidOid,   /* no parent constraint */
    2145             :                               RelationGetRelid(rel),    /* relation */
    2146             :                               attNos,   /* attrs in the constraint */
    2147             :                               keycount, /* # key attrs in the constraint */
    2148             :                               keycount, /* # total attrs in the constraint */
    2149             :                               InvalidOid,   /* not a domain constraint */
    2150             :                               InvalidOid,   /* no associated index */
    2151             :                               InvalidOid,   /* Foreign key fields */
    2152             :                               NULL,
    2153             :                               NULL,
    2154             :                               NULL,
    2155             :                               NULL,
    2156             :                               0,
    2157             :                               ' ',
    2158             :                               ' ',
    2159             :                               NULL,
    2160             :                               0,
    2161             :                               ' ',
    2162             :                               NULL, /* not an exclusion constraint */
    2163             :                               expr, /* Tree form of check constraint */
    2164             :                               ccbin,    /* Binary form of check constraint */
    2165             :                               is_local, /* conislocal */
    2166             :                               inhcount, /* coninhcount */
    2167             :                               is_no_inherit,    /* connoinherit */
    2168             :                               false,    /* conperiod */
    2169             :                               is_internal); /* internally constructed? */
    2170             : 
    2171        2126 :     pfree(ccbin);
    2172             : 
    2173        2126 :     return constrOid;
    2174             : }
    2175             : 
    2176             : /*
    2177             :  * Store a not-null constraint for the given relation
    2178             :  *
    2179             :  * The OID of the new constraint is returned.
    2180             :  */
    2181             : static Oid
    2182       22772 : StoreRelNotNull(Relation rel, const char *nnname, AttrNumber attnum,
    2183             :                 bool is_validated, bool is_local, int inhcount,
    2184             :                 bool is_no_inherit)
    2185             : {
    2186             :     Oid         constrOid;
    2187             : 
    2188             :     Assert(attnum > InvalidAttrNumber);
    2189             : 
    2190             :     constrOid =
    2191       22772 :         CreateConstraintEntry(nnname,
    2192       22772 :                               RelationGetNamespace(rel),
    2193             :                               CONSTRAINT_NOTNULL,
    2194             :                               false,
    2195             :                               false,
    2196             :                               is_validated,
    2197             :                               InvalidOid,
    2198             :                               RelationGetRelid(rel),
    2199             :                               &attnum,
    2200             :                               1,
    2201             :                               1,
    2202             :                               InvalidOid,   /* not a domain constraint */
    2203             :                               InvalidOid,   /* no associated index */
    2204             :                               InvalidOid,   /* Foreign key fields */
    2205             :                               NULL,
    2206             :                               NULL,
    2207             :                               NULL,
    2208             :                               NULL,
    2209             :                               0,
    2210             :                               ' ',
    2211             :                               ' ',
    2212             :                               NULL,
    2213             :                               0,
    2214             :                               ' ',
    2215             :                               NULL, /* not an exclusion constraint */
    2216             :                               NULL,
    2217             :                               NULL,
    2218             :                               is_local,
    2219             :                               inhcount,
    2220             :                               is_no_inherit,
    2221             :                               false,
    2222             :                               false);
    2223       22772 :     return constrOid;
    2224             : }
    2225             : 
    2226             : /*
    2227             :  * Store defaults and constraints (passed as a list of CookedConstraint).
    2228             :  *
    2229             :  * Each CookedConstraint struct is modified to store the new catalog tuple OID.
    2230             :  *
    2231             :  * NOTE: only pre-cooked expressions will be passed this way, which is to
    2232             :  * say expressions inherited from an existing relation.  Newly parsed
    2233             :  * expressions can be added later, by direct calls to StoreAttrDefault
    2234             :  * and StoreRelCheck (see AddRelationNewConstraints()).
    2235             :  */
    2236             : static void
    2237       80602 : StoreConstraints(Relation rel, List *cooked_constraints, bool is_internal)
    2238             : {
    2239       80602 :     int         numchecks = 0;
    2240             :     ListCell   *lc;
    2241             : 
    2242       80602 :     if (cooked_constraints == NIL)
    2243       80124 :         return;                 /* nothing to do */
    2244             : 
    2245             :     /*
    2246             :      * Deparsing of constraint expressions will fail unless the just-created
    2247             :      * pg_attribute tuples for this relation are made visible.  So, bump the
    2248             :      * command counter.  CAUTION: this will cause a relcache entry rebuild.
    2249             :      */
    2250         478 :     CommandCounterIncrement();
    2251             : 
    2252        1042 :     foreach(lc, cooked_constraints)
    2253             :     {
    2254         564 :         CookedConstraint *con = (CookedConstraint *) lfirst(lc);
    2255             : 
    2256         564 :         switch (con->contype)
    2257             :         {
    2258         344 :             case CONSTR_DEFAULT:
    2259         344 :                 con->conoid = StoreAttrDefault(rel, con->attnum, con->expr,
    2260             :                                                is_internal, false);
    2261         344 :                 break;
    2262         220 :             case CONSTR_CHECK:
    2263         220 :                 con->conoid =
    2264         220 :                     StoreRelCheck(rel, con->name, con->expr,
    2265         220 :                                   !con->skip_validation, con->is_local,
    2266         220 :                                   con->inhcount, con->is_no_inherit,
    2267         220 :                                   is_internal);
    2268         220 :                 numchecks++;
    2269         220 :                 break;
    2270             : 
    2271           0 :             case CONSTR_NOTNULL:
    2272           0 :                 con->conoid =
    2273           0 :                     StoreRelNotNull(rel, con->name, con->attnum,
    2274           0 :                                     !con->skip_validation, con->is_local,
    2275           0 :                                     con->inhcount, con->is_no_inherit);
    2276           0 :                 break;
    2277             : 
    2278           0 :             default:
    2279           0 :                 elog(ERROR, "unrecognized constraint type: %d",
    2280             :                      (int) con->contype);
    2281             :         }
    2282             :     }
    2283             : 
    2284         478 :     if (numchecks > 0)
    2285         196 :         SetRelationNumChecks(rel, numchecks);
    2286             : }
    2287             : 
    2288             : /*
    2289             :  * AddRelationNewConstraints
    2290             :  *
    2291             :  * Add new column default expressions and/or constraint check expressions
    2292             :  * to an existing relation.  This is defined to do both for efficiency in
    2293             :  * DefineRelation, but of course you can do just one or the other by passing
    2294             :  * empty lists.
    2295             :  *
    2296             :  * rel: relation to be modified
    2297             :  * newColDefaults: list of RawColumnDefault structures
    2298             :  * newConstraints: list of Constraint nodes
    2299             :  * allow_merge: true if check constraints may be merged with existing ones
    2300             :  * is_local: true if definition is local, false if it's inherited
    2301             :  * is_internal: true if result of some internal process, not a user request
    2302             :  * queryString: used during expression transformation of default values and
    2303             :  *      cooked CHECK constraints
    2304             :  *
    2305             :  * All entries in newColDefaults will be processed.  Entries in newConstraints
    2306             :  * will be processed only if they are CONSTR_CHECK or CONSTR_NOTNULL types.
    2307             :  *
    2308             :  * Returns a list of CookedConstraint nodes that shows the cooked form of
    2309             :  * the default and constraint expressions added to the relation.
    2310             :  *
    2311             :  * NB: caller should have opened rel with some self-conflicting lock mode,
    2312             :  * and should hold that lock till end of transaction; for normal cases that'll
    2313             :  * be AccessExclusiveLock, but if caller knows that the constraint is already
    2314             :  * enforced by some other means, it can be ShareUpdateExclusiveLock.  Also, we
    2315             :  * assume the caller has done a CommandCounterIncrement if necessary to make
    2316             :  * the relation's catalog tuples visible.
    2317             :  */
    2318             : List *
    2319       14390 : AddRelationNewConstraints(Relation rel,
    2320             :                           List *newColDefaults,
    2321             :                           List *newConstraints,
    2322             :                           bool allow_merge,
    2323             :                           bool is_local,
    2324             :                           bool is_internal,
    2325             :                           const char *queryString)
    2326             : {
    2327       14390 :     List       *cookedConstraints = NIL;
    2328             :     TupleDesc   tupleDesc;
    2329             :     TupleConstr *oldconstr;
    2330             :     int         numoldchecks;
    2331             :     ParseState *pstate;
    2332             :     ParseNamespaceItem *nsitem;
    2333             :     int         numchecks;
    2334             :     List       *checknames;
    2335             :     List       *nnnames;
    2336             :     Node       *expr;
    2337             :     CookedConstraint *cooked;
    2338             : 
    2339             :     /*
    2340             :      * Get info about existing constraints.
    2341             :      */
    2342       14390 :     tupleDesc = RelationGetDescr(rel);
    2343       14390 :     oldconstr = tupleDesc->constr;
    2344       14390 :     if (oldconstr)
    2345       12406 :         numoldchecks = oldconstr->num_check;
    2346             :     else
    2347        1984 :         numoldchecks = 0;
    2348             : 
    2349             :     /*
    2350             :      * Create a dummy ParseState and insert the target relation as its sole
    2351             :      * rangetable entry.  We need a ParseState for transformExpr.
    2352             :      */
    2353       14390 :     pstate = make_parsestate(NULL);
    2354       14390 :     pstate->p_sourcetext = queryString;
    2355       14390 :     nsitem = addRangeTableEntryForRelation(pstate,
    2356             :                                            rel,
    2357             :                                            AccessShareLock,
    2358             :                                            NULL,
    2359             :                                            false,
    2360             :                                            true);
    2361       14390 :     addNSItemToQuery(pstate, nsitem, true, true, true);
    2362             : 
    2363             :     /*
    2364             :      * Process column default expressions.
    2365             :      */
    2366       32074 :     foreach_ptr(RawColumnDefault, colDef, newColDefaults)
    2367             :     {
    2368        3534 :         Form_pg_attribute atp = TupleDescAttr(rel->rd_att, colDef->attnum - 1);
    2369             :         Oid         defOid;
    2370             : 
    2371        3534 :         expr = cookDefault(pstate, colDef->raw_default,
    2372             :                            atp->atttypid, atp->atttypmod,
    2373        3534 :                            NameStr(atp->attname),
    2374        3534 :                            atp->attgenerated);
    2375             : 
    2376             :         /*
    2377             :          * If the expression is just a NULL constant, we do not bother to make
    2378             :          * an explicit pg_attrdef entry, since the default behavior is
    2379             :          * equivalent.  This applies to column defaults, but not for
    2380             :          * generation expressions.
    2381             :          *
    2382             :          * Note a nonobvious property of this test: if the column is of a
    2383             :          * domain type, what we'll get is not a bare null Const but a
    2384             :          * CoerceToDomain expr, so we will not discard the default.  This is
    2385             :          * critical because the column default needs to be retained to
    2386             :          * override any default that the domain might have.
    2387             :          */
    2388        3414 :         if (expr == NULL ||
    2389        3414 :             (!colDef->generated &&
    2390        2570 :              IsA(expr, Const) &&
    2391        1262 :              castNode(Const, expr)->constisnull))
    2392         122 :             continue;
    2393             : 
    2394             :         /* If the DEFAULT is volatile we cannot use a missing value */
    2395        3852 :         if (colDef->missingMode &&
    2396         560 :             contain_volatile_functions_after_planning((Expr *) expr))
    2397          78 :             colDef->missingMode = false;
    2398             : 
    2399        3292 :         defOid = StoreAttrDefault(rel, colDef->attnum, expr, is_internal,
    2400        3292 :                                   colDef->missingMode);
    2401             : 
    2402        3292 :         cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
    2403        3292 :         cooked->contype = CONSTR_DEFAULT;
    2404        3292 :         cooked->conoid = defOid;
    2405        3292 :         cooked->name = NULL;
    2406        3292 :         cooked->attnum = colDef->attnum;
    2407        3292 :         cooked->expr = expr;
    2408        3292 :         cooked->skip_validation = false;
    2409        3292 :         cooked->is_local = is_local;
    2410        3292 :         cooked->inhcount = is_local ? 0 : 1;
    2411        3292 :         cooked->is_no_inherit = false;
    2412        3292 :         cookedConstraints = lappend(cookedConstraints, cooked);
    2413             :     }
    2414             : 
    2415             :     /*
    2416             :      * Process constraint expressions.
    2417             :      */
    2418       14270 :     numchecks = numoldchecks;
    2419       14270 :     checknames = NIL;
    2420       14270 :     nnnames = NIL;
    2421       39636 :     foreach_node(Constraint, cdef, newConstraints)
    2422             :     {
    2423             :         Oid         constrOid;
    2424             : 
    2425       11348 :         if (cdef->contype == CONSTR_CHECK)
    2426             :         {
    2427             :             char       *ccname;
    2428             : 
    2429        2078 :             if (cdef->raw_expr != NULL)
    2430             :             {
    2431             :                 Assert(cdef->cooked_expr == NULL);
    2432             : 
    2433             :                 /*
    2434             :                  * Transform raw parsetree to executable expression, and
    2435             :                  * verify it's valid as a CHECK constraint.
    2436             :                  */
    2437        1848 :                 expr = cookConstraint(pstate, cdef->raw_expr,
    2438        1848 :                                       RelationGetRelationName(rel));
    2439             :             }
    2440             :             else
    2441             :             {
    2442             :                 Assert(cdef->cooked_expr != NULL);
    2443             : 
    2444             :                 /*
    2445             :                  * Here, we assume the parser will only pass us valid CHECK
    2446             :                  * expressions, so we do no particular checking.
    2447             :                  */
    2448         230 :                 expr = stringToNode(cdef->cooked_expr);
    2449             :             }
    2450             : 
    2451             :             /*
    2452             :              * Check name uniqueness, or generate a name if none was given.
    2453             :              */
    2454        2048 :             if (cdef->conname != NULL)
    2455             :             {
    2456        1386 :                 ccname = cdef->conname;
    2457             :                 /* Check against other new constraints */
    2458             :                 /* Needed because we don't do CommandCounterIncrement in loop */
    2459        2870 :                 foreach_ptr(char, chkname, checknames)
    2460             :                 {
    2461          98 :                     if (strcmp(chkname, ccname) == 0)
    2462           0 :                         ereport(ERROR,
    2463             :                                 (errcode(ERRCODE_DUPLICATE_OBJECT),
    2464             :                                  errmsg("check constraint \"%s\" already exists",
    2465             :                                         ccname)));
    2466             :                 }
    2467             : 
    2468             :                 /* save name for future checks */
    2469        1386 :                 checknames = lappend(checknames, ccname);
    2470             : 
    2471             :                 /*
    2472             :                  * Check against pre-existing constraints.  If we are allowed
    2473             :                  * to merge with an existing constraint, there's no more to do
    2474             :                  * here. (We omit the duplicate constraint from the result,
    2475             :                  * which is what ATAddCheckNNConstraint wants.)
    2476             :                  */
    2477        1362 :                 if (MergeWithExistingConstraint(rel, ccname, expr,
    2478             :                                                 allow_merge, is_local,
    2479        1386 :                                                 cdef->initially_valid,
    2480        1386 :                                                 cdef->is_no_inherit))
    2481          94 :                     continue;
    2482             :             }
    2483             :             else
    2484             :             {
    2485             :                 /*
    2486             :                  * When generating a name, we want to create "tab_col_check"
    2487             :                  * for a column constraint and "tab_check" for a table
    2488             :                  * constraint.  We no longer have any info about the syntactic
    2489             :                  * positioning of the constraint phrase, so we approximate
    2490             :                  * this by seeing whether the expression references more than
    2491             :                  * one column.  (If the user played by the rules, the result
    2492             :                  * is the same...)
    2493             :                  *
    2494             :                  * Note: pull_var_clause() doesn't descend into sublinks, but
    2495             :                  * we eliminated those above; and anyway this only needs to be
    2496             :                  * an approximate answer.
    2497             :                  */
    2498             :                 List       *vars;
    2499             :                 char       *colname;
    2500             : 
    2501         662 :                 vars = pull_var_clause(expr, 0);
    2502             : 
    2503             :                 /* eliminate duplicates */
    2504         662 :                 vars = list_union(NIL, vars);
    2505             : 
    2506         662 :                 if (list_length(vars) == 1)
    2507         590 :                     colname = get_attname(RelationGetRelid(rel),
    2508         590 :                                           ((Var *) linitial(vars))->varattno,
    2509             :                                           true);
    2510             :                 else
    2511          72 :                     colname = NULL;
    2512             : 
    2513         662 :                 ccname = ChooseConstraintName(RelationGetRelationName(rel),
    2514             :                                               colname,
    2515             :                                               "check",
    2516         662 :                                               RelationGetNamespace(rel),
    2517             :                                               checknames);
    2518             : 
    2519             :                 /* save name for future checks */
    2520         662 :                 checknames = lappend(checknames, ccname);
    2521             :             }
    2522             : 
    2523             :             /*
    2524             :              * OK, store it.
    2525             :              */
    2526             :             constrOid =
    2527        1930 :                 StoreRelCheck(rel, ccname, expr, cdef->initially_valid, is_local,
    2528        1930 :                               is_local ? 0 : 1, cdef->is_no_inherit, is_internal);
    2529             : 
    2530        1906 :             numchecks++;
    2531             : 
    2532        1906 :             cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
    2533        1906 :             cooked->contype = CONSTR_CHECK;
    2534        1906 :             cooked->conoid = constrOid;
    2535        1906 :             cooked->name = ccname;
    2536        1906 :             cooked->attnum = 0;
    2537        1906 :             cooked->expr = expr;
    2538        1906 :             cooked->skip_validation = cdef->skip_validation;
    2539        1906 :             cooked->is_local = is_local;
    2540        1906 :             cooked->inhcount = is_local ? 0 : 1;
    2541        1906 :             cooked->is_no_inherit = cdef->is_no_inherit;
    2542        1906 :             cookedConstraints = lappend(cookedConstraints, cooked);
    2543             :         }
    2544        9270 :         else if (cdef->contype == CONSTR_NOTNULL)
    2545             :         {
    2546             :             CookedConstraint *nncooked;
    2547             :             AttrNumber  colnum;
    2548        9270 :             int16       inhcount = is_local ? 0 : 1;
    2549             :             char       *nnname;
    2550             : 
    2551             :             /* Determine which column to modify */
    2552        9270 :             colnum = get_attnum(RelationGetRelid(rel), strVal(linitial(cdef->keys)));
    2553        9270 :             if (colnum == InvalidAttrNumber)
    2554          18 :                 ereport(ERROR,
    2555             :                         errcode(ERRCODE_UNDEFINED_COLUMN),
    2556             :                         errmsg("column \"%s\" of relation \"%s\" does not exist",
    2557             :                                strVal(linitial(cdef->keys)), RelationGetRelationName(rel)));
    2558        9252 :             if (colnum < InvalidAttrNumber)
    2559           0 :                 ereport(ERROR,
    2560             :                         errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2561             :                         errmsg("cannot add not-null constraint on system column \"%s\"",
    2562             :                                strVal(linitial(cdef->keys))));
    2563             : 
    2564             :             /*
    2565             :              * If the column already has a not-null constraint, we don't want
    2566             :              * to add another one; just adjust inheritance status as needed.
    2567             :              */
    2568        9228 :             if (AdjustNotNullInheritance(RelationGetRelid(rel), colnum,
    2569        9252 :                                          is_local, cdef->is_no_inherit))
    2570         524 :                 continue;
    2571             : 
    2572             :             /*
    2573             :              * If a constraint name is specified, check that it isn't already
    2574             :              * used.  Otherwise, choose a non-conflicting one ourselves.
    2575             :              */
    2576        8704 :             if (cdef->conname)
    2577             :             {
    2578         836 :                 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
    2579             :                                          RelationGetRelid(rel),
    2580         836 :                                          cdef->conname))
    2581           6 :                     ereport(ERROR,
    2582             :                             errcode(ERRCODE_DUPLICATE_OBJECT),
    2583             :                             errmsg("constraint \"%s\" for relation \"%s\" already exists",
    2584             :                                    cdef->conname, RelationGetRelationName(rel)));
    2585         830 :                 nnname = cdef->conname;
    2586             :             }
    2587             :             else
    2588       15736 :                 nnname = ChooseConstraintName(RelationGetRelationName(rel),
    2589        7868 :                                               strVal(linitial(cdef->keys)),
    2590             :                                               "not_null",
    2591        7868 :                                               RelationGetNamespace(rel),
    2592             :                                               nnnames);
    2593        8698 :             nnnames = lappend(nnnames, nnname);
    2594             : 
    2595             :             constrOid =
    2596        8698 :                 StoreRelNotNull(rel, nnname, colnum,
    2597        8698 :                                 cdef->initially_valid,
    2598             :                                 is_local,
    2599             :                                 inhcount,
    2600        8698 :                                 cdef->is_no_inherit);
    2601             : 
    2602        8698 :             nncooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
    2603        8698 :             nncooked->contype = CONSTR_NOTNULL;
    2604        8698 :             nncooked->conoid = constrOid;
    2605        8698 :             nncooked->name = nnname;
    2606        8698 :             nncooked->attnum = colnum;
    2607        8698 :             nncooked->expr = NULL;
    2608        8698 :             nncooked->skip_validation = cdef->skip_validation;
    2609        8698 :             nncooked->is_local = is_local;
    2610        8698 :             nncooked->inhcount = inhcount;
    2611        8698 :             nncooked->is_no_inherit = cdef->is_no_inherit;
    2612             : 
    2613        8698 :             cookedConstraints = lappend(cookedConstraints, nncooked);
    2614             :         }
    2615             :     }
    2616             : 
    2617             :     /*
    2618             :      * Update the count of constraints in the relation's pg_class tuple. We do
    2619             :      * this even if there was no change, in order to ensure that an SI update
    2620             :      * message is sent out for the pg_class tuple, which will force other
    2621             :      * backends to rebuild their relcache entries for the rel. (This is
    2622             :      * critical if we added defaults but not constraints.)
    2623             :      */
    2624       14144 :     SetRelationNumChecks(rel, numchecks);
    2625             : 
    2626       14144 :     return cookedConstraints;
    2627             : }
    2628             : 
    2629             : /*
    2630             :  * Check for a pre-existing check constraint that conflicts with a proposed
    2631             :  * new one, and either adjust its conislocal/coninhcount settings or throw
    2632             :  * error as needed.
    2633             :  *
    2634             :  * Returns true if merged (constraint is a duplicate), or false if it's
    2635             :  * got a so-far-unique name, or throws error if conflict.
    2636             :  *
    2637             :  * XXX See MergeConstraintsIntoExisting too if you change this code.
    2638             :  */
    2639             : static bool
    2640        1386 : MergeWithExistingConstraint(Relation rel, const char *ccname, Node *expr,
    2641             :                             bool allow_merge, bool is_local,
    2642             :                             bool is_initially_valid,
    2643             :                             bool is_no_inherit)
    2644             : {
    2645             :     bool        found;
    2646             :     Relation    conDesc;
    2647             :     SysScanDesc conscan;
    2648             :     ScanKeyData skey[3];
    2649             :     HeapTuple   tup;
    2650             : 
    2651             :     /* Search for a pg_constraint entry with same name and relation */
    2652        1386 :     conDesc = table_open(ConstraintRelationId, RowExclusiveLock);
    2653             : 
    2654        1386 :     found = false;
    2655             : 
    2656        1386 :     ScanKeyInit(&skey[0],
    2657             :                 Anum_pg_constraint_conrelid,
    2658             :                 BTEqualStrategyNumber, F_OIDEQ,
    2659             :                 ObjectIdGetDatum(RelationGetRelid(rel)));
    2660        1386 :     ScanKeyInit(&skey[1],
    2661             :                 Anum_pg_constraint_contypid,
    2662             :                 BTEqualStrategyNumber, F_OIDEQ,
    2663             :                 ObjectIdGetDatum(InvalidOid));
    2664        1386 :     ScanKeyInit(&skey[2],
    2665             :                 Anum_pg_constraint_conname,
    2666             :                 BTEqualStrategyNumber, F_NAMEEQ,
    2667             :                 CStringGetDatum(ccname));
    2668             : 
    2669        1386 :     conscan = systable_beginscan(conDesc, ConstraintRelidTypidNameIndexId, true,
    2670             :                                  NULL, 3, skey);
    2671             : 
    2672             :     /* There can be at most one matching row */
    2673        1386 :     if (HeapTupleIsValid(tup = systable_getnext(conscan)))
    2674             :     {
    2675         118 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
    2676             : 
    2677             :         /* Found it.  Conflicts if not identical check constraint */
    2678         118 :         if (con->contype == CONSTRAINT_CHECK)
    2679             :         {
    2680             :             Datum       val;
    2681             :             bool        isnull;
    2682             : 
    2683         112 :             val = fastgetattr(tup,
    2684             :                               Anum_pg_constraint_conbin,
    2685             :                               conDesc->rd_att, &isnull);
    2686         112 :             if (isnull)
    2687           0 :                 elog(ERROR, "null conbin for rel %s",
    2688             :                      RelationGetRelationName(rel));
    2689         112 :             if (equal(expr, stringToNode(TextDatumGetCString(val))))
    2690         106 :                 found = true;
    2691             :         }
    2692             : 
    2693             :         /*
    2694             :          * If the existing constraint is purely inherited (no local
    2695             :          * definition) then interpret addition of a local constraint as a
    2696             :          * legal merge.  This allows ALTER ADD CONSTRAINT on parent and child
    2697             :          * tables to be given in either order with same end state.  However if
    2698             :          * the relation is a partition, all inherited constraints are always
    2699             :          * non-local, including those that were merged.
    2700             :          */
    2701         118 :         if (is_local && !con->conislocal && !rel->rd_rel->relispartition)
    2702          54 :             allow_merge = true;
    2703             : 
    2704         118 :         if (!found || !allow_merge)
    2705          12 :             ereport(ERROR,
    2706             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    2707             :                      errmsg("constraint \"%s\" for relation \"%s\" already exists",
    2708             :                             ccname, RelationGetRelationName(rel))));
    2709             : 
    2710             :         /* If the child constraint is "no inherit" then cannot merge */
    2711         106 :         if (con->connoinherit)
    2712           0 :             ereport(ERROR,
    2713             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2714             :                      errmsg("constraint \"%s\" conflicts with non-inherited constraint on relation \"%s\"",
    2715             :                             ccname, RelationGetRelationName(rel))));
    2716             : 
    2717             :         /*
    2718             :          * Must not change an existing inherited constraint to "no inherit"
    2719             :          * status.  That's because inherited constraints should be able to
    2720             :          * propagate to lower-level children.
    2721             :          */
    2722         106 :         if (con->coninhcount > 0 && is_no_inherit)
    2723           6 :             ereport(ERROR,
    2724             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2725             :                      errmsg("constraint \"%s\" conflicts with inherited constraint on relation \"%s\"",
    2726             :                             ccname, RelationGetRelationName(rel))));
    2727             : 
    2728             :         /*
    2729             :          * If the child constraint is "not valid" then cannot merge with a
    2730             :          * valid parent constraint.
    2731             :          */
    2732         100 :         if (is_initially_valid && !con->convalidated)
    2733           6 :             ereport(ERROR,
    2734             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2735             :                      errmsg("constraint \"%s\" conflicts with NOT VALID constraint on relation \"%s\"",
    2736             :                             ccname, RelationGetRelationName(rel))));
    2737             : 
    2738             :         /* OK to update the tuple */
    2739          94 :         ereport(NOTICE,
    2740             :                 (errmsg("merging constraint \"%s\" with inherited definition",
    2741             :                         ccname)));
    2742             : 
    2743          94 :         tup = heap_copytuple(tup);
    2744          94 :         con = (Form_pg_constraint) GETSTRUCT(tup);
    2745             : 
    2746             :         /*
    2747             :          * In case of partitions, an inherited constraint must be inherited
    2748             :          * only once since it cannot have multiple parents and it is never
    2749             :          * considered local.
    2750             :          */
    2751          94 :         if (rel->rd_rel->relispartition)
    2752             :         {
    2753          12 :             con->coninhcount = 1;
    2754          12 :             con->conislocal = false;
    2755             :         }
    2756             :         else
    2757             :         {
    2758          82 :             if (is_local)
    2759          48 :                 con->conislocal = true;
    2760          34 :             else if (pg_add_s16_overflow(con->coninhcount, 1,
    2761             :                                          &con->coninhcount))
    2762           0 :                 ereport(ERROR,
    2763             :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2764             :                         errmsg("too many inheritance parents"));
    2765             :         }
    2766             : 
    2767          94 :         if (is_no_inherit)
    2768             :         {
    2769             :             Assert(is_local);
    2770           0 :             con->connoinherit = true;
    2771             :         }
    2772             : 
    2773          94 :         CatalogTupleUpdate(conDesc, &tup->t_self, tup);
    2774             :     }
    2775             : 
    2776        1362 :     systable_endscan(conscan);
    2777        1362 :     table_close(conDesc, RowExclusiveLock);
    2778             : 
    2779        1362 :     return found;
    2780             : }
    2781             : 
    2782             : /*
    2783             :  * Create the not-null constraints when creating a new relation
    2784             :  *
    2785             :  * These come from two sources: the 'constraints' list (of Constraint) is
    2786             :  * specified directly by the user; the 'old_notnulls' list (of
    2787             :  * CookedConstraint) comes from inheritance.  We create one constraint
    2788             :  * for each column, giving priority to user-specified ones, and setting
    2789             :  * inhcount according to how many parents cause each column to get a
    2790             :  * not-null constraint.  If a user-specified name clashes with another
    2791             :  * user-specified name, an error is raised.
    2792             :  *
    2793             :  * Returns a list of AttrNumber for columns that need to have the attnotnull
    2794             :  * flag set.
    2795             :  */
    2796             : List *
    2797       55958 : AddRelationNotNullConstraints(Relation rel, List *constraints,
    2798             :                               List *old_notnulls)
    2799             : {
    2800             :     List       *givennames;
    2801             :     List       *nnnames;
    2802       55958 :     List       *nncols = NIL;
    2803             : 
    2804             :     /*
    2805             :      * We track two lists of names: nnnames keeps all the constraint names,
    2806             :      * givennames tracks user-generated names.  The distinction is important,
    2807             :      * because we must raise error for user-generated name conflicts, but for
    2808             :      * system-generated name conflicts we just generate another.
    2809             :      */
    2810       55958 :     nnnames = NIL;
    2811       55958 :     givennames = NIL;
    2812             : 
    2813             :     /*
    2814             :      * First, create all not-null constraints that are directly specified by
    2815             :      * the user.  Note that inheritance might have given us another source for
    2816             :      * each, so we must scan the old_notnulls list and increment inhcount for
    2817             :      * each element with identical attnum.  We delete from there any element
    2818             :      * that we process.
    2819             :      *
    2820             :      * We don't use foreach() here because we have two nested loops over the
    2821             :      * constraint list, with possible element deletions in the inner one. If
    2822             :      * we used foreach_delete_current() it could only fix up the state of one
    2823             :      * of the loops, so it seems cleaner to use looping over list indexes for
    2824             :      * both loops.  Note that any deletion will happen beyond where the outer
    2825             :      * loop is, so its index never needs adjustment.
    2826             :      */
    2827       68130 :     for (int outerpos = 0; outerpos < list_length(constraints); outerpos++)
    2828             :     {
    2829             :         Constraint *constr;
    2830             :         AttrNumber  attnum;
    2831             :         char       *conname;
    2832       12250 :         int         inhcount = 0;
    2833             : 
    2834       12250 :         constr = list_nth_node(Constraint, constraints, outerpos);
    2835             : 
    2836             :         Assert(constr->contype == CONSTR_NOTNULL);
    2837             : 
    2838       12250 :         attnum = get_attnum(RelationGetRelid(rel),
    2839       12250 :                             strVal(linitial(constr->keys)));
    2840       12250 :         if (attnum == InvalidAttrNumber)
    2841           0 :             ereport(ERROR,
    2842             :                     errcode(ERRCODE_UNDEFINED_COLUMN),
    2843             :                     errmsg("column \"%s\" of relation \"%s\" does not exist",
    2844             :                            strVal(linitial(constr->keys)),
    2845             :                            RelationGetRelationName(rel)));
    2846       12250 :         if (attnum < InvalidAttrNumber)
    2847           0 :             ereport(ERROR,
    2848             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2849             :                     errmsg("cannot add not-null constraint on system column \"%s\"",
    2850             :                            strVal(linitial(constr->keys))));
    2851             : 
    2852             :         /*
    2853             :          * A column can only have one not-null constraint, so discard any
    2854             :          * additional ones that appear for columns we already saw; but check
    2855             :          * that the NO INHERIT flags match.
    2856             :          */
    2857       16232 :         for (int restpos = outerpos + 1; restpos < list_length(constraints);)
    2858             :         {
    2859             :             Constraint *other;
    2860             : 
    2861        4042 :             other = list_nth_node(Constraint, constraints, restpos);
    2862        4042 :             if (strcmp(strVal(linitial(constr->keys)),
    2863        4042 :                        strVal(linitial(other->keys))) == 0)
    2864             :             {
    2865          96 :                 if (other->is_no_inherit != constr->is_no_inherit)
    2866          42 :                     ereport(ERROR,
    2867             :                             errcode(ERRCODE_SYNTAX_ERROR),
    2868             :                             errmsg("conflicting NO INHERIT declaration for not-null constraint on column \"%s\"",
    2869             :                                    strVal(linitial(constr->keys))));
    2870             : 
    2871             :                 /*
    2872             :                  * Preserve constraint name if one is specified, but raise an
    2873             :                  * error if conflicting ones are specified.
    2874             :                  */
    2875          54 :                 if (other->conname)
    2876             :                 {
    2877          36 :                     if (!constr->conname)
    2878          12 :                         constr->conname = pstrdup(other->conname);
    2879          24 :                     else if (strcmp(constr->conname, other->conname) != 0)
    2880          18 :                         ereport(ERROR,
    2881             :                                 errcode(ERRCODE_SYNTAX_ERROR),
    2882             :                                 errmsg("conflicting not-null constraint names \"%s\" and \"%s\"",
    2883             :                                        constr->conname, other->conname));
    2884             :                 }
    2885             : 
    2886             :                 /* XXX do we need to verify any other fields? */
    2887          36 :                 constraints = list_delete_nth_cell(constraints, restpos);
    2888             :             }
    2889             :             else
    2890        3946 :                 restpos++;
    2891             :         }
    2892             : 
    2893             :         /*
    2894             :          * Search in the list of inherited constraints for any entries on the
    2895             :          * same column; determine an inheritance count from that.  Also, if at
    2896             :          * least one parent has a constraint for this column, then we must not
    2897             :          * accept a user specification for a NO INHERIT one.  Any constraint
    2898             :          * from parents that we process here is deleted from the list: we no
    2899             :          * longer need to process it in the loop below.
    2900             :          */
    2901       24532 :         foreach_ptr(CookedConstraint, old, old_notnulls)
    2902             :         {
    2903         176 :             if (old->attnum == attnum)
    2904             :             {
    2905             :                 /*
    2906             :                  * If we get a constraint from the parent, having a local NO
    2907             :                  * INHERIT one doesn't work.
    2908             :                  */
    2909         146 :                 if (constr->is_no_inherit)
    2910          12 :                     ereport(ERROR,
    2911             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2912             :                              errmsg("cannot define not-null constraint on column \"%s\" with NO INHERIT",
    2913             :                                     strVal(linitial(constr->keys))),
    2914             :                              errdetail("The column has an inherited not-null constraint.")));
    2915             : 
    2916         134 :                 inhcount++;
    2917         134 :                 old_notnulls = foreach_delete_current(old_notnulls, old);
    2918             :             }
    2919             :         }
    2920             : 
    2921             :         /*
    2922             :          * Determine a constraint name, which may have been specified by the
    2923             :          * user, or raise an error if a conflict exists with another
    2924             :          * user-specified name.
    2925             :          */
    2926       12178 :         if (constr->conname)
    2927             :         {
    2928        1294 :             foreach_ptr(char, thisname, givennames)
    2929             :             {
    2930         114 :                 if (strcmp(thisname, constr->conname) == 0)
    2931           6 :                     ereport(ERROR,
    2932             :                             errcode(ERRCODE_DUPLICATE_OBJECT),
    2933             :                             errmsg("constraint \"%s\" for relation \"%s\" already exists",
    2934             :                                    constr->conname,
    2935             :                                    RelationGetRelationName(rel)));
    2936             :             }
    2937             : 
    2938         590 :             conname = constr->conname;
    2939         590 :             givennames = lappend(givennames, conname);
    2940             :         }
    2941             :         else
    2942       11582 :             conname = ChooseConstraintName(RelationGetRelationName(rel),
    2943       11582 :                                            get_attname(RelationGetRelid(rel),
    2944             :                                                        attnum, false),
    2945             :                                            "not_null",
    2946       11582 :                                            RelationGetNamespace(rel),
    2947             :                                            nnnames);
    2948       12172 :         nnnames = lappend(nnnames, conname);
    2949             : 
    2950       12172 :         StoreRelNotNull(rel, conname,
    2951             :                         attnum, true, true,
    2952       12172 :                         inhcount, constr->is_no_inherit);
    2953             : 
    2954       12172 :         nncols = lappend_int(nncols, attnum);
    2955             :     }
    2956             : 
    2957             :     /*
    2958             :      * If any column remains in the old_notnulls list, we must create a not-
    2959             :      * null constraint marked not-local for that column.  Because multiple
    2960             :      * parents could specify a not-null constraint for the same column, we
    2961             :      * must count how many there are and set an appropriate inhcount
    2962             :      * accordingly, deleting elements we've already processed.
    2963             :      *
    2964             :      * We don't use foreach() here because we have two nested loops over the
    2965             :      * constraint list, with possible element deletions in the inner one. If
    2966             :      * we used foreach_delete_current() it could only fix up the state of one
    2967             :      * of the loops, so it seems cleaner to use looping over list indexes for
    2968             :      * both loops.  Note that any deletion will happen beyond where the outer
    2969             :      * loop is, so its index never needs adjustment.
    2970             :      */
    2971       57782 :     for (int outerpos = 0; outerpos < list_length(old_notnulls); outerpos++)
    2972             :     {
    2973             :         CookedConstraint *cooked;
    2974        1902 :         char       *conname = NULL;
    2975        1902 :         int         inhcount = 1;
    2976             : 
    2977        1902 :         cooked = (CookedConstraint *) list_nth(old_notnulls, outerpos);
    2978             :         Assert(cooked->contype == CONSTR_NOTNULL);
    2979             :         Assert(cooked->name);
    2980             : 
    2981             :         /*
    2982             :          * Preserve the first non-conflicting constraint name we come across.
    2983             :          */
    2984        1902 :         if (conname == NULL)
    2985        1902 :             conname = cooked->name;
    2986             : 
    2987        2368 :         for (int restpos = outerpos + 1; restpos < list_length(old_notnulls);)
    2988             :         {
    2989             :             CookedConstraint *other;
    2990             : 
    2991         466 :             other = (CookedConstraint *) list_nth(old_notnulls, restpos);
    2992             :             Assert(other->name);
    2993         466 :             if (other->attnum == cooked->attnum)
    2994             :             {
    2995          32 :                 if (conname == NULL)
    2996           0 :                     conname = other->name;
    2997             : 
    2998          32 :                 inhcount++;
    2999          32 :                 old_notnulls = list_delete_nth_cell(old_notnulls, restpos);
    3000             :             }
    3001             :             else
    3002         434 :                 restpos++;
    3003             :         }
    3004             : 
    3005             :         /* If we got a name, make sure it isn't one we've already used */
    3006        1902 :         if (conname != NULL)
    3007             :         {
    3008        4256 :             foreach_ptr(char, thisname, nnnames)
    3009             :             {
    3010         458 :                 if (strcmp(thisname, conname) == 0)
    3011             :                 {
    3012           6 :                     conname = NULL;
    3013           6 :                     break;
    3014             :                 }
    3015             :             }
    3016             :         }
    3017             : 
    3018             :         /* and choose a name, if needed */
    3019        1902 :         if (conname == NULL)
    3020           6 :             conname = ChooseConstraintName(RelationGetRelationName(rel),
    3021           6 :                                            get_attname(RelationGetRelid(rel),
    3022           6 :                                                        cooked->attnum, false),
    3023             :                                            "not_null",
    3024           6 :                                            RelationGetNamespace(rel),
    3025             :                                            nnnames);
    3026        1902 :         nnnames = lappend(nnnames, conname);
    3027             : 
    3028             :         /* ignore the origin constraint's is_local and inhcount */
    3029        1902 :         StoreRelNotNull(rel, conname, cooked->attnum, true,
    3030             :                         false, inhcount, false);
    3031             : 
    3032        1902 :         nncols = lappend_int(nncols, cooked->attnum);
    3033             :     }
    3034             : 
    3035       55880 :     return nncols;
    3036             : }
    3037             : 
    3038             : /*
    3039             :  * Update the count of constraints in the relation's pg_class tuple.
    3040             :  *
    3041             :  * Caller had better hold exclusive lock on the relation.
    3042             :  *
    3043             :  * An important side effect is that a SI update message will be sent out for
    3044             :  * the pg_class tuple, which will force other backends to rebuild their
    3045             :  * relcache entries for the rel.  Also, this backend will rebuild its
    3046             :  * own relcache entry at the next CommandCounterIncrement.
    3047             :  */
    3048             : static void
    3049       14340 : SetRelationNumChecks(Relation rel, int numchecks)
    3050             : {
    3051             :     Relation    relrel;
    3052             :     HeapTuple   reltup;
    3053             :     Form_pg_class relStruct;
    3054             : 
    3055       14340 :     relrel = table_open(RelationRelationId, RowExclusiveLock);
    3056       14340 :     reltup = SearchSysCacheCopy1(RELOID,
    3057             :                                  ObjectIdGetDatum(RelationGetRelid(rel)));
    3058       14340 :     if (!HeapTupleIsValid(reltup))
    3059           0 :         elog(ERROR, "cache lookup failed for relation %u",
    3060             :              RelationGetRelid(rel));
    3061       14340 :     relStruct = (Form_pg_class) GETSTRUCT(reltup);
    3062             : 
    3063       14340 :     if (relStruct->relchecks != numchecks)
    3064             :     {
    3065        1984 :         relStruct->relchecks = numchecks;
    3066             : 
    3067        1984 :         CatalogTupleUpdate(relrel, &reltup->t_self, reltup);
    3068             :     }
    3069             :     else
    3070             :     {
    3071             :         /* Skip the disk update, but force relcache inval anyway */
    3072       12356 :         CacheInvalidateRelcache(rel);
    3073             :     }
    3074             : 
    3075       14340 :     heap_freetuple(reltup);
    3076       14340 :     table_close(relrel, RowExclusiveLock);
    3077       14340 : }
    3078             : 
    3079             : /*
    3080             :  * Check for references to generated columns
    3081             :  */
    3082             : static bool
    3083        2908 : check_nested_generated_walker(Node *node, void *context)
    3084             : {
    3085        2908 :     ParseState *pstate = context;
    3086             : 
    3087        2908 :     if (node == NULL)
    3088           0 :         return false;
    3089        2908 :     else if (IsA(node, Var))
    3090             :     {
    3091        1080 :         Var        *var = (Var *) node;
    3092             :         Oid         relid;
    3093             :         AttrNumber  attnum;
    3094             : 
    3095        1080 :         relid = rt_fetch(var->varno, pstate->p_rtable)->relid;
    3096        1080 :         if (!OidIsValid(relid))
    3097           0 :             return false;       /* XXX shouldn't we raise an error? */
    3098             : 
    3099        1080 :         attnum = var->varattno;
    3100             : 
    3101        1080 :         if (attnum > 0 && get_attgenerated(relid, attnum))
    3102          18 :             ereport(ERROR,
    3103             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3104             :                      errmsg("cannot use generated column \"%s\" in column generation expression",
    3105             :                             get_attname(relid, attnum, false)),
    3106             :                      errdetail("A generated column cannot reference another generated column."),
    3107             :                      parser_errposition(pstate, var->location)));
    3108             :         /* A whole-row Var is necessarily self-referential, so forbid it */
    3109        1062 :         if (attnum == 0)
    3110           6 :             ereport(ERROR,
    3111             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3112             :                      errmsg("cannot use whole-row variable in column generation expression"),
    3113             :                      errdetail("This would cause the generated column to depend on its own value."),
    3114             :                      parser_errposition(pstate, var->location)));
    3115             :         /* System columns were already checked in the parser */
    3116             : 
    3117        1056 :         return false;
    3118             :     }
    3119             :     else
    3120        1828 :         return expression_tree_walker(node, check_nested_generated_walker,
    3121             :                                       (void *) context);
    3122             : }
    3123             : 
    3124             : static void
    3125         874 : check_nested_generated(ParseState *pstate, Node *node)
    3126             : {
    3127         874 :     check_nested_generated_walker(node, pstate);
    3128         850 : }
    3129             : 
    3130             : /*
    3131             :  * Take a raw default and convert it to a cooked format ready for
    3132             :  * storage.
    3133             :  *
    3134             :  * Parse state should be set up to recognize any vars that might appear
    3135             :  * in the expression.  (Even though we plan to reject vars, it's more
    3136             :  * user-friendly to give the correct error message than "unknown var".)
    3137             :  *
    3138             :  * If atttypid is not InvalidOid, coerce the expression to the specified
    3139             :  * type (and typmod atttypmod).   attname is only needed in this case:
    3140             :  * it is used in the error message, if any.
    3141             :  */
    3142             : Node *
    3143        3670 : cookDefault(ParseState *pstate,
    3144             :             Node *raw_default,
    3145             :             Oid atttypid,
    3146             :             int32 atttypmod,
    3147             :             const char *attname,
    3148             :             char attgenerated)
    3149             : {
    3150             :     Node       *expr;
    3151             : 
    3152             :     Assert(raw_default != NULL);
    3153             : 
    3154             :     /*
    3155             :      * Transform raw parsetree to executable expression.
    3156             :      */
    3157        3670 :     expr = transformExpr(pstate, raw_default, attgenerated ? EXPR_KIND_GENERATED_COLUMN : EXPR_KIND_COLUMN_DEFAULT);
    3158             : 
    3159        3586 :     if (attgenerated)
    3160             :     {
    3161             :         /* Disallow refs to other generated columns */
    3162         874 :         check_nested_generated(pstate, expr);
    3163             : 
    3164             :         /* Disallow mutable functions */
    3165         850 :         if (contain_mutable_functions_after_planning((Expr *) expr))
    3166           6 :             ereport(ERROR,
    3167             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3168             :                      errmsg("generation expression is not immutable")));
    3169             :     }
    3170             :     else
    3171             :     {
    3172             :         /*
    3173             :          * For a default expression, transformExpr() should have rejected
    3174             :          * column references.
    3175             :          */
    3176             :         Assert(!contain_var_clause(expr));
    3177             :     }
    3178             : 
    3179             :     /*
    3180             :      * Coerce the expression to the correct type and typmod, if given. This
    3181             :      * should match the parser's processing of non-defaulted expressions ---
    3182             :      * see transformAssignedExpr().
    3183             :      */
    3184        3556 :     if (OidIsValid(atttypid))
    3185             :     {
    3186        3556 :         Oid         type_id = exprType(expr);
    3187             : 
    3188        3556 :         expr = coerce_to_target_type(pstate, expr, type_id,
    3189             :                                      atttypid, atttypmod,
    3190             :                                      COERCION_ASSIGNMENT,
    3191             :                                      COERCE_IMPLICIT_CAST,
    3192             :                                      -1);
    3193        3550 :         if (expr == NULL)
    3194           0 :             ereport(ERROR,
    3195             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3196             :                      errmsg("column \"%s\" is of type %s"
    3197             :                             " but default expression is of type %s",
    3198             :                             attname,
    3199             :                             format_type_be(atttypid),
    3200             :                             format_type_be(type_id)),
    3201             :                      errhint("You will need to rewrite or cast the expression.")));
    3202             :     }
    3203             : 
    3204             :     /*
    3205             :      * Finally, take care of collations in the finished expression.
    3206             :      */
    3207        3550 :     assign_expr_collations(pstate, expr);
    3208             : 
    3209        3550 :     return expr;
    3210             : }
    3211             : 
    3212             : /*
    3213             :  * Take a raw CHECK constraint expression and convert it to a cooked format
    3214             :  * ready for storage.
    3215             :  *
    3216             :  * Parse state must be set up to recognize any vars that might appear
    3217             :  * in the expression.
    3218             :  */
    3219             : static Node *
    3220        1848 : cookConstraint(ParseState *pstate,
    3221             :                Node *raw_constraint,
    3222             :                char *relname)
    3223             : {
    3224             :     Node       *expr;
    3225             : 
    3226             :     /*
    3227             :      * Transform raw parsetree to executable expression.
    3228             :      */
    3229        1848 :     expr = transformExpr(pstate, raw_constraint, EXPR_KIND_CHECK_CONSTRAINT);
    3230             : 
    3231             :     /*
    3232             :      * Make sure it yields a boolean result.
    3233             :      */
    3234        1818 :     expr = coerce_to_boolean(pstate, expr, "CHECK");
    3235             : 
    3236             :     /*
    3237             :      * Take care of collations.
    3238             :      */
    3239        1818 :     assign_expr_collations(pstate, expr);
    3240             : 
    3241             :     /*
    3242             :      * Make sure no outside relations are referred to (this is probably dead
    3243             :      * code now that add_missing_from is history).
    3244             :      */
    3245        1818 :     if (list_length(pstate->p_rtable) != 1)
    3246           0 :         ereport(ERROR,
    3247             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    3248             :                  errmsg("only table \"%s\" can be referenced in check constraint",
    3249             :                         relname)));
    3250             : 
    3251        1818 :     return expr;
    3252             : }
    3253             : 
    3254             : /*
    3255             :  * CopyStatistics --- copy entries in pg_statistic from one rel to another
    3256             :  */
    3257             : void
    3258         490 : CopyStatistics(Oid fromrelid, Oid torelid)
    3259             : {
    3260             :     HeapTuple   tup;
    3261             :     SysScanDesc scan;
    3262             :     ScanKeyData key[1];
    3263             :     Relation    statrel;
    3264         490 :     CatalogIndexState indstate = NULL;
    3265             : 
    3266         490 :     statrel = table_open(StatisticRelationId, RowExclusiveLock);
    3267             : 
    3268             :     /* Now search for stat records */
    3269         490 :     ScanKeyInit(&key[0],
    3270             :                 Anum_pg_statistic_starelid,
    3271             :                 BTEqualStrategyNumber, F_OIDEQ,
    3272             :                 ObjectIdGetDatum(fromrelid));
    3273             : 
    3274         490 :     scan = systable_beginscan(statrel, StatisticRelidAttnumInhIndexId,
    3275             :                               true, NULL, 1, key);
    3276             : 
    3277         496 :     while (HeapTupleIsValid((tup = systable_getnext(scan))))
    3278             :     {
    3279             :         Form_pg_statistic statform;
    3280             : 
    3281             :         /* make a modifiable copy */
    3282           6 :         tup = heap_copytuple(tup);
    3283           6 :         statform = (Form_pg_statistic) GETSTRUCT(tup);
    3284             : 
    3285             :         /* update the copy of the tuple and insert it */
    3286           6 :         statform->starelid = torelid;
    3287             : 
    3288             :         /* fetch index information when we know we need it */
    3289           6 :         if (indstate == NULL)
    3290           6 :             indstate = CatalogOpenIndexes(statrel);
    3291             : 
    3292           6 :         CatalogTupleInsertWithInfo(statrel, tup, indstate);
    3293             : 
    3294           6 :         heap_freetuple(tup);
    3295             :     }
    3296             : 
    3297         490 :     systable_endscan(scan);
    3298             : 
    3299         490 :     if (indstate != NULL)
    3300           6 :         CatalogCloseIndexes(indstate);
    3301         490 :     table_close(statrel, RowExclusiveLock);
    3302         490 : }
    3303             : 
    3304             : /*
    3305             :  * RemoveStatistics --- remove entries in pg_statistic for a rel or column
    3306             :  *
    3307             :  * If attnum is zero, remove all entries for rel; else remove only the one(s)
    3308             :  * for that column.
    3309             :  */
    3310             : void
    3311       48820 : RemoveStatistics(Oid relid, AttrNumber attnum)
    3312             : {
    3313             :     Relation    pgstatistic;
    3314             :     SysScanDesc scan;
    3315             :     ScanKeyData key[2];
    3316             :     int         nkeys;
    3317             :     HeapTuple   tuple;
    3318             : 
    3319       48820 :     pgstatistic = table_open(StatisticRelationId, RowExclusiveLock);
    3320             : 
    3321       48820 :     ScanKeyInit(&key[0],
    3322             :                 Anum_pg_statistic_starelid,
    3323             :                 BTEqualStrategyNumber, F_OIDEQ,
    3324             :                 ObjectIdGetDatum(relid));
    3325             : 
    3326       48820 :     if (attnum == 0)
    3327       45812 :         nkeys = 1;
    3328             :     else
    3329             :     {
    3330        3008 :         ScanKeyInit(&key[1],
    3331             :                     Anum_pg_statistic_staattnum,
    3332             :                     BTEqualStrategyNumber, F_INT2EQ,
    3333             :                     Int16GetDatum(attnum));
    3334        3008 :         nkeys = 2;
    3335             :     }
    3336             : 
    3337       48820 :     scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
    3338             :                               NULL, nkeys, key);
    3339             : 
    3340             :     /* we must loop even when attnum != 0, in case of inherited stats */
    3341       51970 :     while (HeapTupleIsValid(tuple = systable_getnext(scan)))
    3342        3150 :         CatalogTupleDelete(pgstatistic, &tuple->t_self);
    3343             : 
    3344       48820 :     systable_endscan(scan);
    3345             : 
    3346       48820 :     table_close(pgstatistic, RowExclusiveLock);
    3347       48820 : }
    3348             : 
    3349             : 
    3350             : /*
    3351             :  * RelationTruncateIndexes - truncate all indexes associated
    3352             :  * with the heap relation to zero tuples.
    3353             :  *
    3354             :  * The routine will truncate and then reconstruct the indexes on
    3355             :  * the specified relation.  Caller must hold exclusive lock on rel.
    3356             :  */
    3357             : static void
    3358         576 : RelationTruncateIndexes(Relation heapRelation)
    3359             : {
    3360             :     ListCell   *indlist;
    3361             : 
    3362             :     /* Ask the relcache to produce a list of the indexes of the rel */
    3363         780 :     foreach(indlist, RelationGetIndexList(heapRelation))
    3364             :     {
    3365         204 :         Oid         indexId = lfirst_oid(indlist);
    3366             :         Relation    currentIndex;
    3367             :         IndexInfo  *indexInfo;
    3368             : 
    3369             :         /* Open the index relation; use exclusive lock, just to be sure */
    3370         204 :         currentIndex = index_open(indexId, AccessExclusiveLock);
    3371             : 
    3372             :         /*
    3373             :          * Fetch info needed for index_build.  Since we know there are no
    3374             :          * tuples that actually need indexing, we can use a dummy IndexInfo.
    3375             :          * This is slightly cheaper to build, but the real point is to avoid
    3376             :          * possibly running user-defined code in index expressions or
    3377             :          * predicates.  We might be getting invoked during ON COMMIT
    3378             :          * processing, and we don't want to run any such code then.
    3379             :          */
    3380         204 :         indexInfo = BuildDummyIndexInfo(currentIndex);
    3381             : 
    3382             :         /*
    3383             :          * Now truncate the actual file (and discard buffers).
    3384             :          */
    3385         204 :         RelationTruncate(currentIndex, 0);
    3386             : 
    3387             :         /* Initialize the index and rebuild */
    3388             :         /* Note: we do not need to re-establish pkey setting */
    3389         204 :         index_build(heapRelation, currentIndex, indexInfo, true, false);
    3390             : 
    3391             :         /* We're done with this index */
    3392         204 :         index_close(currentIndex, NoLock);
    3393             :     }
    3394         576 : }
    3395             : 
    3396             : /*
    3397             :  *   heap_truncate
    3398             :  *
    3399             :  *   This routine deletes all data within all the specified relations.
    3400             :  *
    3401             :  * This is not transaction-safe!  There is another, transaction-safe
    3402             :  * implementation in commands/tablecmds.c.  We now use this only for
    3403             :  * ON COMMIT truncation of temporary tables, where it doesn't matter.
    3404             :  */
    3405             : void
    3406         334 : heap_truncate(List *relids)
    3407             : {
    3408         334 :     List       *relations = NIL;
    3409             :     ListCell   *cell;
    3410             : 
    3411             :     /* Open relations for processing, and grab exclusive access on each */
    3412         734 :     foreach(cell, relids)
    3413             :     {
    3414         400 :         Oid         rid = lfirst_oid(cell);
    3415             :         Relation    rel;
    3416             : 
    3417         400 :         rel = table_open(rid, AccessExclusiveLock);
    3418         400 :         relations = lappend(relations, rel);
    3419             :     }
    3420             : 
    3421             :     /* Don't allow truncate on tables that are referenced by foreign keys */
    3422         334 :     heap_truncate_check_FKs(relations, true);
    3423             : 
    3424             :     /* OK to do it */
    3425         716 :     foreach(cell, relations)
    3426             :     {
    3427         388 :         Relation    rel = lfirst(cell);
    3428             : 
    3429             :         /* Truncate the relation */
    3430         388 :         heap_truncate_one_rel(rel);
    3431             : 
    3432             :         /* Close the relation, but keep exclusive lock on it until commit */
    3433         388 :         table_close(rel, NoLock);
    3434             :     }
    3435         328 : }
    3436             : 
    3437             : /*
    3438             :  *   heap_truncate_one_rel
    3439             :  *
    3440             :  *   This routine deletes all data within the specified relation.
    3441             :  *
    3442             :  * This is not transaction-safe, because the truncation is done immediately
    3443             :  * and cannot be rolled back later.  Caller is responsible for having
    3444             :  * checked permissions etc, and must have obtained AccessExclusiveLock.
    3445             :  */
    3446             : void
    3447         478 : heap_truncate_one_rel(Relation rel)
    3448             : {
    3449             :     Oid         toastrelid;
    3450             : 
    3451             :     /*
    3452             :      * Truncate the relation.  Partitioned tables have no storage, so there is
    3453             :      * nothing to do for them here.
    3454             :      */
    3455         478 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    3456          24 :         return;
    3457             : 
    3458             :     /* Truncate the underlying relation */
    3459         454 :     table_relation_nontransactional_truncate(rel);
    3460             : 
    3461             :     /* If the relation has indexes, truncate the indexes too */
    3462         454 :     RelationTruncateIndexes(rel);
    3463             : 
    3464             :     /* If there is a toast table, truncate that too */
    3465         454 :     toastrelid = rel->rd_rel->reltoastrelid;
    3466         454 :     if (OidIsValid(toastrelid))
    3467             :     {
    3468         122 :         Relation    toastrel = table_open(toastrelid, AccessExclusiveLock);
    3469             : 
    3470         122 :         table_relation_nontransactional_truncate(toastrel);
    3471         122 :         RelationTruncateIndexes(toastrel);
    3472             :         /* keep the lock... */
    3473         122 :         table_close(toastrel, NoLock);
    3474             :     }
    3475             : }
    3476             : 
    3477             : /*
    3478             :  * heap_truncate_check_FKs
    3479             :  *      Check for foreign keys referencing a list of relations that
    3480             :  *      are to be truncated, and raise error if there are any
    3481             :  *
    3482             :  * We disallow such FKs (except self-referential ones) since the whole point
    3483             :  * of TRUNCATE is to not scan the individual rows to be thrown away.
    3484             :  *
    3485             :  * This is split out so it can be shared by both implementations of truncate.
    3486             :  * Caller should already hold a suitable lock on the relations.
    3487             :  *
    3488             :  * tempTables is only used to select an appropriate error message.
    3489             :  */
    3490             : void
    3491        1882 : heap_truncate_check_FKs(List *relations, bool tempTables)
    3492             : {
    3493        1882 :     List       *oids = NIL;
    3494             :     List       *dependents;
    3495             :     ListCell   *cell;
    3496             : 
    3497             :     /*
    3498             :      * Build a list of OIDs of the interesting relations.
    3499             :      *
    3500             :      * If a relation has no triggers, then it can neither have FKs nor be
    3501             :      * referenced by a FK from another table, so we can ignore it.  For
    3502             :      * partitioned tables, FKs have no triggers, so we must include them
    3503             :      * anyway.
    3504             :      */
    3505        5974 :     foreach(cell, relations)
    3506             :     {
    3507        4092 :         Relation    rel = lfirst(cell);
    3508             : 
    3509        4092 :         if (rel->rd_rel->relhastriggers ||
    3510        2704 :             rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    3511        1872 :             oids = lappend_oid(oids, RelationGetRelid(rel));
    3512             :     }
    3513             : 
    3514             :     /*
    3515             :      * Fast path: if no relation has triggers, none has FKs either.
    3516             :      */
    3517        1882 :     if (oids == NIL)
    3518        1158 :         return;
    3519             : 
    3520             :     /*
    3521             :      * Otherwise, must scan pg_constraint.  We make one pass with all the
    3522             :      * relations considered; if this finds nothing, then all is well.
    3523             :      */
    3524         724 :     dependents = heap_truncate_find_FKs(oids);
    3525         724 :     if (dependents == NIL)
    3526         644 :         return;
    3527             : 
    3528             :     /*
    3529             :      * Otherwise we repeat the scan once per relation to identify a particular
    3530             :      * pair of relations to complain about.  This is pretty slow, but
    3531             :      * performance shouldn't matter much in a failure path.  The reason for
    3532             :      * doing things this way is to ensure that the message produced is not
    3533             :      * dependent on chance row locations within pg_constraint.
    3534             :      */
    3535         104 :     foreach(cell, oids)
    3536             :     {
    3537         104 :         Oid         relid = lfirst_oid(cell);
    3538             :         ListCell   *cell2;
    3539             : 
    3540         104 :         dependents = heap_truncate_find_FKs(list_make1_oid(relid));
    3541             : 
    3542         164 :         foreach(cell2, dependents)
    3543             :         {
    3544         140 :             Oid         relid2 = lfirst_oid(cell2);
    3545             : 
    3546         140 :             if (!list_member_oid(oids, relid2))
    3547             :             {
    3548          80 :                 char       *relname = get_rel_name(relid);
    3549          80 :                 char       *relname2 = get_rel_name(relid2);
    3550             : 
    3551          80 :                 if (tempTables)
    3552           6 :                     ereport(ERROR,
    3553             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3554             :                              errmsg("unsupported ON COMMIT and foreign key combination"),
    3555             :                              errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
    3556             :                                        relname2, relname)));
    3557             :                 else
    3558          74 :                     ereport(ERROR,
    3559             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3560             :                              errmsg("cannot truncate a table referenced in a foreign key constraint"),
    3561             :                              errdetail("Table \"%s\" references \"%s\".",
    3562             :                                        relname2, relname),
    3563             :                              errhint("Truncate table \"%s\" at the same time, "
    3564             :                                      "or use TRUNCATE ... CASCADE.",
    3565             :                                      relname2)));
    3566             :             }
    3567             :         }
    3568             :     }
    3569             : }
    3570             : 
    3571             : /*
    3572             :  * heap_truncate_find_FKs
    3573             :  *      Find relations having foreign keys referencing any of the given rels
    3574             :  *
    3575             :  * Input and result are both lists of relation OIDs.  The result contains
    3576             :  * no duplicates, does *not* include any rels that were already in the input
    3577             :  * list, and is sorted in OID order.  (The last property is enforced mainly
    3578             :  * to guarantee consistent behavior in the regression tests; we don't want
    3579             :  * behavior to change depending on chance locations of rows in pg_constraint.)
    3580             :  *
    3581             :  * Note: caller should already have appropriate lock on all rels mentioned
    3582             :  * in relationIds.  Since adding or dropping an FK requires exclusive lock
    3583             :  * on both rels, this ensures that the answer will be stable.
    3584             :  */
    3585             : List *
    3586         908 : heap_truncate_find_FKs(List *relationIds)
    3587             : {
    3588         908 :     List       *result = NIL;
    3589             :     List       *oids;
    3590             :     List       *parent_cons;
    3591             :     ListCell   *cell;
    3592             :     ScanKeyData key;
    3593             :     Relation    fkeyRel;
    3594             :     SysScanDesc fkeyScan;
    3595             :     HeapTuple   tuple;
    3596             :     bool        restart;
    3597             : 
    3598         908 :     oids = list_copy(relationIds);
    3599             : 
    3600             :     /*
    3601             :      * Must scan pg_constraint.  Right now, it is a seqscan because there is
    3602             :      * no available index on confrelid.
    3603             :      */
    3604         908 :     fkeyRel = table_open(ConstraintRelationId, AccessShareLock);
    3605             : 
    3606         932 : restart:
    3607         932 :     restart = false;
    3608         932 :     parent_cons = NIL;
    3609             : 
    3610         932 :     fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
    3611             :                                   NULL, 0, NULL);
    3612             : 
    3613      424888 :     while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
    3614             :     {
    3615      423956 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
    3616             : 
    3617             :         /* Not a foreign key */
    3618      423956 :         if (con->contype != CONSTRAINT_FOREIGN)
    3619      387444 :             continue;
    3620             : 
    3621             :         /* Not referencing one of our list of tables */
    3622       36512 :         if (!list_member_oid(oids, con->confrelid))
    3623       35386 :             continue;
    3624             : 
    3625             :         /*
    3626             :          * If this constraint has a parent constraint which we have not seen
    3627             :          * yet, keep track of it for the second loop, below.  Tracking parent
    3628             :          * constraints allows us to climb up to the top-level constraint and
    3629             :          * look for all possible relations referencing the partitioned table.
    3630             :          */
    3631        1126 :         if (OidIsValid(con->conparentid) &&
    3632         384 :             !list_member_oid(parent_cons, con->conparentid))
    3633         168 :             parent_cons = lappend_oid(parent_cons, con->conparentid);
    3634             : 
    3635             :         /*
    3636             :          * Add referencer to result, unless present in input list.  (Don't
    3637             :          * worry about dupes: we'll fix that below).
    3638             :          */
    3639        1126 :         if (!list_member_oid(relationIds, con->conrelid))
    3640         500 :             result = lappend_oid(result, con->conrelid);
    3641             :     }
    3642             : 
    3643         932 :     systable_endscan(fkeyScan);
    3644             : 
    3645             :     /*
    3646             :      * Process each parent constraint we found to add the list of referenced
    3647             :      * relations by them to the oids list.  If we do add any new such
    3648             :      * relations, redo the first loop above.  Also, if we see that the parent
    3649             :      * constraint in turn has a parent, add that so that we process all
    3650             :      * relations in a single additional pass.
    3651             :      */
    3652        1112 :     foreach(cell, parent_cons)
    3653             :     {
    3654         180 :         Oid         parent = lfirst_oid(cell);
    3655             : 
    3656         180 :         ScanKeyInit(&key,
    3657             :                     Anum_pg_constraint_oid,
    3658             :                     BTEqualStrategyNumber, F_OIDEQ,
    3659             :                     ObjectIdGetDatum(parent));
    3660             : 
    3661         180 :         fkeyScan = systable_beginscan(fkeyRel, ConstraintOidIndexId,
    3662             :                                       true, NULL, 1, &key);
    3663             : 
    3664         180 :         tuple = systable_getnext(fkeyScan);
    3665         180 :         if (HeapTupleIsValid(tuple))
    3666             :         {
    3667         180 :             Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
    3668             : 
    3669             :             /*
    3670             :              * pg_constraint rows always appear for partitioned hierarchies
    3671             :              * this way: on the each side of the constraint, one row appears
    3672             :              * for each partition that points to the top-most table on the
    3673             :              * other side.
    3674             :              *
    3675             :              * Because of this arrangement, we can correctly catch all
    3676             :              * relevant relations by adding to 'parent_cons' all rows with
    3677             :              * valid conparentid, and to the 'oids' list all rows with a zero
    3678             :              * conparentid.  If any oids are added to 'oids', redo the first
    3679             :              * loop above by setting 'restart'.
    3680             :              */
    3681         180 :             if (OidIsValid(con->conparentid))
    3682          54 :                 parent_cons = list_append_unique_oid(parent_cons,
    3683             :                                                      con->conparentid);
    3684         126 :             else if (!list_member_oid(oids, con->confrelid))
    3685             :             {
    3686          24 :                 oids = lappend_oid(oids, con->confrelid);
    3687          24 :                 restart = true;
    3688             :             }
    3689             :         }
    3690             : 
    3691         180 :         systable_endscan(fkeyScan);
    3692             :     }
    3693             : 
    3694         932 :     list_free(parent_cons);
    3695         932 :     if (restart)
    3696          24 :         goto restart;
    3697             : 
    3698         908 :     table_close(fkeyRel, AccessShareLock);
    3699         908 :     list_free(oids);
    3700             : 
    3701             :     /* Now sort and de-duplicate the result list */
    3702         908 :     list_sort(result, list_oid_cmp);
    3703         908 :     list_deduplicate_oid(result);
    3704             : 
    3705         908 :     return result;
    3706             : }
    3707             : 
    3708             : /*
    3709             :  * StorePartitionKey
    3710             :  *      Store information about the partition key rel into the catalog
    3711             :  */
    3712             : void
    3713        4640 : StorePartitionKey(Relation rel,
    3714             :                   char strategy,
    3715             :                   int16 partnatts,
    3716             :                   AttrNumber *partattrs,
    3717             :                   List *partexprs,
    3718             :                   Oid *partopclass,
    3719             :                   Oid *partcollation)
    3720             : {
    3721             :     int         i;
    3722             :     int2vector *partattrs_vec;
    3723             :     oidvector  *partopclass_vec;
    3724             :     oidvector  *partcollation_vec;
    3725             :     Datum       partexprDatum;
    3726             :     Relation    pg_partitioned_table;
    3727             :     HeapTuple   tuple;
    3728             :     Datum       values[Natts_pg_partitioned_table];
    3729        4640 :     bool        nulls[Natts_pg_partitioned_table] = {0};
    3730             :     ObjectAddress myself;
    3731             :     ObjectAddress referenced;
    3732             :     ObjectAddresses *addrs;
    3733             : 
    3734             :     Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    3735             : 
    3736             :     /* Copy the partition attribute numbers, opclass OIDs into arrays */
    3737        4640 :     partattrs_vec = buildint2vector(partattrs, partnatts);
    3738        4640 :     partopclass_vec = buildoidvector(partopclass, partnatts);
    3739        4640 :     partcollation_vec = buildoidvector(partcollation, partnatts);
    3740             : 
    3741             :     /* Convert the expressions (if any) to a text datum */
    3742        4640 :     if (partexprs)
    3743             :     {
    3744             :         char       *exprString;
    3745             : 
    3746         214 :         exprString = nodeToString(partexprs);
    3747         214 :         partexprDatum = CStringGetTextDatum(exprString);
    3748         214 :         pfree(exprString);
    3749             :     }
    3750             :     else
    3751        4426 :         partexprDatum = (Datum) 0;
    3752             : 
    3753        4640 :     pg_partitioned_table = table_open(PartitionedRelationId, RowExclusiveLock);
    3754             : 
    3755             :     /* Only this can ever be NULL */
    3756        4640 :     if (!partexprDatum)
    3757        4426 :         nulls[Anum_pg_partitioned_table_partexprs - 1] = true;
    3758             : 
    3759        4640 :     values[Anum_pg_partitioned_table_partrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
    3760        4640 :     values[Anum_pg_partitioned_table_partstrat - 1] = CharGetDatum(strategy);
    3761        4640 :     values[Anum_pg_partitioned_table_partnatts - 1] = Int16GetDatum(partnatts);
    3762        4640 :     values[Anum_pg_partitioned_table_partdefid - 1] = ObjectIdGetDatum(InvalidOid);
    3763        4640 :     values[Anum_pg_partitioned_table_partattrs - 1] = PointerGetDatum(partattrs_vec);
    3764        4640 :     values[Anum_pg_partitioned_table_partclass - 1] = PointerGetDatum(partopclass_vec);
    3765        4640 :     values[Anum_pg_partitioned_table_partcollation - 1] = PointerGetDatum(partcollation_vec);
    3766        4640 :     values[Anum_pg_partitioned_table_partexprs - 1] = partexprDatum;
    3767             : 
    3768        4640 :     tuple = heap_form_tuple(RelationGetDescr(pg_partitioned_table), values, nulls);
    3769             : 
    3770        4640 :     CatalogTupleInsert(pg_partitioned_table, tuple);
    3771        4640 :     table_close(pg_partitioned_table, RowExclusiveLock);
    3772             : 
    3773             :     /* Mark this relation as dependent on a few things as follows */
    3774        4640 :     addrs = new_object_addresses();
    3775        4640 :     ObjectAddressSet(myself, RelationRelationId, RelationGetRelid(rel));
    3776             : 
    3777             :     /* Operator class and collation per key column */
    3778        9706 :     for (i = 0; i < partnatts; i++)
    3779             :     {
    3780        5066 :         ObjectAddressSet(referenced, OperatorClassRelationId, partopclass[i]);
    3781        5066 :         add_exact_object_address(&referenced, addrs);
    3782             : 
    3783             :         /* The default collation is pinned, so don't bother recording it */
    3784        5066 :         if (OidIsValid(partcollation[i]) &&
    3785         596 :             partcollation[i] != DEFAULT_COLLATION_OID)
    3786             :         {
    3787         120 :             ObjectAddressSet(referenced, CollationRelationId, partcollation[i]);
    3788         120 :             add_exact_object_address(&referenced, addrs);
    3789             :         }
    3790             :     }
    3791             : 
    3792        4640 :     record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
    3793        4640 :     free_object_addresses(addrs);
    3794             : 
    3795             :     /*
    3796             :      * The partitioning columns are made internally dependent on the table,
    3797             :      * because we cannot drop any of them without dropping the whole table.
    3798             :      * (ATExecDropColumn independently enforces that, but it's not bulletproof
    3799             :      * so we need the dependencies too.)
    3800             :      */
    3801        9706 :     for (i = 0; i < partnatts; i++)
    3802             :     {
    3803        5066 :         if (partattrs[i] == 0)
    3804         232 :             continue;           /* ignore expressions here */
    3805             : 
    3806        4834 :         ObjectAddressSubSet(referenced, RelationRelationId,
    3807             :                             RelationGetRelid(rel), partattrs[i]);
    3808        4834 :         recordDependencyOn(&referenced, &myself, DEPENDENCY_INTERNAL);
    3809             :     }
    3810             : 
    3811             :     /*
    3812             :      * Also consider anything mentioned in partition expressions.  External
    3813             :      * references (e.g. functions) get NORMAL dependencies.  Table columns
    3814             :      * mentioned in the expressions are handled the same as plain partitioning
    3815             :      * columns, i.e. they become internally dependent on the whole table.
    3816             :      */
    3817        4640 :     if (partexprs)
    3818         214 :         recordDependencyOnSingleRelExpr(&myself,
    3819             :                                         (Node *) partexprs,
    3820             :                                         RelationGetRelid(rel),
    3821             :                                         DEPENDENCY_NORMAL,
    3822             :                                         DEPENDENCY_INTERNAL,
    3823             :                                         true /* reverse the self-deps */ );
    3824             : 
    3825             :     /*
    3826             :      * We must invalidate the relcache so that the next
    3827             :      * CommandCounterIncrement() will cause the same to be rebuilt using the
    3828             :      * information in just created catalog entry.
    3829             :      */
    3830        4640 :     CacheInvalidateRelcache(rel);
    3831        4640 : }
    3832             : 
    3833             : /*
    3834             :  *  RemovePartitionKeyByRelId
    3835             :  *      Remove pg_partitioned_table entry for a relation
    3836             :  */
    3837             : void
    3838        3718 : RemovePartitionKeyByRelId(Oid relid)
    3839             : {
    3840             :     Relation    rel;
    3841             :     HeapTuple   tuple;
    3842             : 
    3843        3718 :     rel = table_open(PartitionedRelationId, RowExclusiveLock);
    3844             : 
    3845        3718 :     tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
    3846        3718 :     if (!HeapTupleIsValid(tuple))
    3847           0 :         elog(ERROR, "cache lookup failed for partition key of relation %u",
    3848             :              relid);
    3849             : 
    3850        3718 :     CatalogTupleDelete(rel, &tuple->t_self);
    3851             : 
    3852        3718 :     ReleaseSysCache(tuple);
    3853        3718 :     table_close(rel, RowExclusiveLock);
    3854        3718 : }
    3855             : 
    3856             : /*
    3857             :  * StorePartitionBound
    3858             :  *      Update pg_class tuple of rel to store the partition bound and set
    3859             :  *      relispartition to true
    3860             :  *
    3861             :  * If this is the default partition, also update the default partition OID in
    3862             :  * pg_partitioned_table.
    3863             :  *
    3864             :  * Also, invalidate the parent's relcache, so that the next rebuild will load
    3865             :  * the new partition's info into its partition descriptor.  If there is a
    3866             :  * default partition, we must invalidate its relcache entry as well.
    3867             :  */
    3868             : void
    3869        9310 : StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
    3870             : {
    3871             :     Relation    classRel;
    3872             :     HeapTuple   tuple,
    3873             :                 newtuple;
    3874             :     Datum       new_val[Natts_pg_class];
    3875             :     bool        new_null[Natts_pg_class],
    3876             :                 new_repl[Natts_pg_class];
    3877             :     Oid         defaultPartOid;
    3878             : 
    3879             :     /* Update pg_class tuple */
    3880        9310 :     classRel = table_open(RelationRelationId, RowExclusiveLock);
    3881        9310 :     tuple = SearchSysCacheCopy1(RELOID,
    3882             :                                 ObjectIdGetDatum(RelationGetRelid(rel)));
    3883        9310 :     if (!HeapTupleIsValid(tuple))
    3884           0 :         elog(ERROR, "cache lookup failed for relation %u",
    3885             :              RelationGetRelid(rel));
    3886             : 
    3887             : #ifdef USE_ASSERT_CHECKING
    3888             :     {
    3889             :         Form_pg_class classForm;
    3890             :         bool        isnull;
    3891             : 
    3892             :         classForm = (Form_pg_class) GETSTRUCT(tuple);
    3893             :         Assert(!classForm->relispartition);
    3894             :         (void) SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relpartbound,
    3895             :                                &isnull);
    3896             :         Assert(isnull);
    3897             :     }
    3898             : #endif
    3899             : 
    3900             :     /* Fill in relpartbound value */
    3901        9310 :     memset(new_val, 0, sizeof(new_val));
    3902        9310 :     memset(new_null, false, sizeof(new_null));
    3903        9310 :     memset(new_repl, false, sizeof(new_repl));
    3904        9310 :     new_val[Anum_pg_class_relpartbound - 1] = CStringGetTextDatum(nodeToString(bound));
    3905        9310 :     new_null[Anum_pg_class_relpartbound - 1] = false;
    3906        9310 :     new_repl[Anum_pg_class_relpartbound - 1] = true;
    3907        9310 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
    3908             :                                  new_val, new_null, new_repl);
    3909             :     /* Also set the flag */
    3910        9310 :     ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = true;
    3911             : 
    3912             :     /*
    3913             :      * We already checked for no inheritance children, but reset
    3914             :      * relhassubclass in case it was left over.
    3915             :      */
    3916        9310 :     if (rel->rd_rel->relkind == RELKIND_RELATION && rel->rd_rel->relhassubclass)
    3917           6 :         ((Form_pg_class) GETSTRUCT(newtuple))->relhassubclass = false;
    3918             : 
    3919        9310 :     CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
    3920        9310 :     heap_freetuple(newtuple);
    3921        9310 :     table_close(classRel, RowExclusiveLock);
    3922             : 
    3923             :     /*
    3924             :      * If we're storing bounds for the default partition, update
    3925             :      * pg_partitioned_table too.
    3926             :      */
    3927        9310 :     if (bound->is_default)
    3928         518 :         update_default_partition_oid(RelationGetRelid(parent),
    3929             :                                      RelationGetRelid(rel));
    3930             : 
    3931             :     /* Make these updates visible */
    3932        9310 :     CommandCounterIncrement();
    3933             : 
    3934             :     /*
    3935             :      * The partition constraint for the default partition depends on the
    3936             :      * partition bounds of every other partition, so we must invalidate the
    3937             :      * relcache entry for that partition every time a partition is added or
    3938             :      * removed.
    3939             :      */
    3940             :     defaultPartOid =
    3941        9310 :         get_default_oid_from_partdesc(RelationGetPartitionDesc(parent, true));
    3942        9310 :     if (OidIsValid(defaultPartOid))
    3943         644 :         CacheInvalidateRelcacheByRelid(defaultPartOid);
    3944             : 
    3945        9310 :     CacheInvalidateRelcache(parent);
    3946        9310 : }

Generated by: LCOV version 1.14