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

Generated by: LCOV version 1.14