LCOV - differential code coverage report
Current view: top level - src/backend/catalog - heap.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 93.1 % 1024 953 19 7 16 29 5 339 159 450 29 440 8 56
Current Date: 2023-04-08 15:15:32 Functions: 97.6 % 41 40 1 22 7 11 25
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

           TLA  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 *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 CBC       15451 : SystemAttributeDefinition(AttrNumber attno)
     240                 : {
     241           15451 :     if (attno >= 0 || attno < -(int) lengthof(SysAtt))
     242 UBC           0 :         elog(ERROR, "invalid system attribute number %d", attno);
     243 CBC       15451 :     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          370061 : SystemAttributeByName(const char *attname)
     252                 : {
     253                 :     int         j;
     254                 : 
     255         2541256 :     for (j = 0; j < (int) lengthof(SysAtt); j++)
     256                 :     {
     257         2186666 :         const FormData_pg_attribute *att = SysAtt[j];
     258                 : 
     259         2186666 :         if (strcmp(NameStr(att->attname), attname) == 0)
     260           15471 :             return att;
     261                 :     }
     262                 : 
     263          354590 :     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          164475 : 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          164475 :     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          228367 :     if (!allow_system_table_mods &&
     319          165607 :         ((IsCatalogNamespace(relnamespace) && relkind != RELKIND_INDEX) ||
     320           63888 :          IsToastNamespace(relnamespace)) &&
     321               4 :         IsNormalProcessingMode())
     322               4 :         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          164471 :     *relfrozenxid = InvalidTransactionId;
     329          164471 :     *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          164471 :     if (!RELKIND_HAS_TABLESPACE(relkind))
     336           45189 :         reltablespace = InvalidOid;
     337                 : 
     338                 :     /* Don't create storage for relkinds without physical storage. */
     339          164471 :     if (!RELKIND_HAS_STORAGE(relkind))
     340           47423 :         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 GNC      117048 :         if (!RelFileNumberIsValid(relfilenumber))
     348          115726 :             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 CBC      164471 :     if (reltablespace == MyDatabaseTableSpace)
     361               3 :         reltablespace = InvalidOid;
     362                 : 
     363                 :     /*
     364                 :      * build the relcache entry.
     365                 :      */
     366          164471 :     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          164471 :     if (create_storage)
     386                 :     {
     387          117012 :         if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
     388 GNC       53662 :             table_relation_set_new_filelocator(rel, &rel->rd_locator,
     389                 :                                                relpersistence,
     390                 :                                                relfrozenxid, relminmxid);
     391 CBC       63350 :         else if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
     392 GNC       63350 :             RelationCreateStorage(rel->rd_locator, relpersistence, true);
     393                 :         else
     394 UBC           0 :             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 CBC      164471 :     if (!create_storage && reltablespace != InvalidOid)
     403              53 :         recordDependencyOnTablespace(RelationRelationId, relid,
     404                 :                                      reltablespace);
     405                 : 
     406                 :     /* ensure that stats are dropped if transaction aborts */
     407          164471 :     pgstat_create_relation(rel);
     408                 : 
     409          164471 :     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          100168 : CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
     456                 :                          int flags)
     457                 : {
     458                 :     int         i;
     459                 :     int         j;
     460          100168 :     int         natts = tupdesc->natts;
     461                 : 
     462                 :     /* Sanity check on column count */
     463          100168 :     if (natts < 0 || natts > MaxHeapAttributeNumber)
     464 UBC           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 CBC      100168 :     if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
     476                 :     {
     477          305139 :         for (i = 0; i < natts; i++)
     478                 :         {
     479          249576 :             Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
     480                 : 
     481          249576 :             if (SystemAttributeByName(NameStr(attr->attname)) != NULL)
     482 UBC           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 CBC      690008 :     for (i = 1; i < natts; i++)
     493                 :     {
     494         7756728 :         for (j = 0; j < i; j++)
     495                 :         {
     496         7166888 :             if (strcmp(NameStr(TupleDescAttr(tupdesc, j)->attname),
     497         7166888 :                        NameStr(TupleDescAttr(tupdesc, i)->attname)) == 0)
     498 UBC           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 CBC      789981 :     for (i = 0; i < natts; i++)
     509                 :     {
     510          689820 :         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          100161 : }
     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          935864 : CheckAttributeType(const char *attname,
     548                 :                    Oid atttypid, Oid attcollation,
     549                 :                    List *containing_rowtypes,
     550                 :                    int flags)
     551                 : {
     552          935864 :     char        att_typtype = get_typtype(atttypid);
     553                 :     Oid         att_typelem;
     554                 : 
     555          935864 :     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            4911 :         if (!((atttypid == ANYARRAYOID && (flags & CHKATYPE_ANYARRAY)) ||
     568              12 :               (atttypid == RECORDOID && (flags & CHKATYPE_ANYRECORD)) ||
     569               3 :               (atttypid == RECORDARRAYOID && (flags & CHKATYPE_ANYRECORD))))
     570                 :         {
     571              16 :             if (flags & CHKATYPE_IS_PARTKEY)
     572               6 :                 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              10 :                 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          930959 :     else if (att_typtype == TYPTYPE_DOMAIN)
     585                 :     {
     586                 :         /*
     587                 :          * If it's a domain, recurse to check its base type.
     588                 :          */
     589          207547 :         CheckAttributeType(attname, getBaseType(atttypid), attcollation,
     590                 :                            containing_rowtypes,
     591                 :                            flags);
     592                 :     }
     593          723412 :     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             590 :         if (list_member_oid(containing_rowtypes, atttypid))
     609              18 :             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             572 :         containing_rowtypes = lappend_oid(containing_rowtypes, atttypid);
     615                 : 
     616             572 :         relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
     617                 : 
     618             572 :         tupdesc = RelationGetDescr(relation);
     619                 : 
     620           10641 :         for (i = 0; i < tupdesc->natts; i++)
     621                 :         {
     622           10075 :             Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
     623                 : 
     624           10075 :             if (attr->attisdropped)
     625               1 :                 continue;
     626           10074 :             CheckAttributeType(NameStr(attr->attname),
     627                 :                                attr->atttypid, attr->attcollation,
     628                 :                                containing_rowtypes,
     629                 :                                flags & ~CHKATYPE_IS_PARTKEY);
     630                 :         }
     631                 : 
     632             566 :         relation_close(relation, AccessShareLock);
     633                 : 
     634             566 :         containing_rowtypes = list_delete_last(containing_rowtypes);
     635                 :     }
     636          722822 :     else if (att_typtype == TYPTYPE_RANGE)
     637                 :     {
     638                 :         /*
     639                 :          * If it's a range, recurse to check its subtype.
     640                 :          */
     641             168 :         CheckAttributeType(attname, get_range_subtype(atttypid),
     642                 :                            get_range_collation(atttypid),
     643                 :                            containing_rowtypes,
     644                 :                            flags);
     645                 :     }
     646          722654 :     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           26088 :         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          935812 :     if (!OidIsValid(attcollation) && type_is_collatable(atttypid))
     661                 :     {
     662 UBC           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 CBC      935812 : }
     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          219926 : InsertPgAttributeTuples(Relation pg_attribute_rel,
     698                 :                         TupleDesc tupdesc,
     699                 :                         Oid new_rel_oid,
     700                 :                         Datum *attoptions,
     701                 :                         CatalogIndexState indstate)
     702                 : {
     703                 :     TupleTableSlot **slot;
     704                 :     TupleDesc   td;
     705                 :     int         nslots;
     706          219926 :     int         natts = 0;
     707          219926 :     int         slotCount = 0;
     708          219926 :     bool        close_index = false;
     709                 : 
     710          219926 :     td = RelationGetDescr(pg_attribute_rel);
     711                 : 
     712                 :     /* Initialize the number of slots to use */
     713          219926 :     nslots = Min(tupdesc->natts,
     714                 :                  (MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_attribute)));
     715          219926 :     slot = palloc(sizeof(TupleTableSlot *) * nslots);
     716         1349337 :     for (int i = 0; i < nslots; i++)
     717         1129411 :         slot[i] = MakeSingleTupleTableSlot(td, &TTSOpsHeapTuple);
     718                 : 
     719         1351321 :     while (natts < tupdesc->natts)
     720                 :     {
     721         1131395 :         Form_pg_attribute attrs = TupleDescAttr(tupdesc, natts);
     722                 : 
     723         1131395 :         ExecClearTuple(slot[slotCount]);
     724                 : 
     725         1131395 :         memset(slot[slotCount]->tts_isnull, false,
     726         1131395 :                slot[slotCount]->tts_tupleDescriptor->natts * sizeof(bool));
     727                 : 
     728         1131395 :         if (new_rel_oid != InvalidOid)
     729         1023406 :             slot[slotCount]->tts_values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_rel_oid);
     730                 :         else
     731          107989 :             slot[slotCount]->tts_values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(attrs->attrelid);
     732                 : 
     733         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attname - 1] = NameGetDatum(&attrs->attname);
     734         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(attrs->atttypid);
     735         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(attrs->attlen);
     736         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(attrs->attnum);
     737         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(-1);
     738         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(attrs->atttypmod);
     739 GNC     1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attndims - 1] = Int16GetDatum(attrs->attndims);
     740 CBC     1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(attrs->attbyval);
     741         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attalign - 1] = CharGetDatum(attrs->attalign);
     742         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(attrs->attstorage);
     743         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attcompression - 1] = CharGetDatum(attrs->attcompression);
     744         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(attrs->attnotnull);
     745         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(attrs->atthasdef);
     746         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_atthasmissing - 1] = BoolGetDatum(attrs->atthasmissing);
     747         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attidentity - 1] = CharGetDatum(attrs->attidentity);
     748         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attgenerated - 1] = CharGetDatum(attrs->attgenerated);
     749         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(attrs->attisdropped);
     750         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(attrs->attislocal);
     751 GNC     1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attinhcount - 1] = Int16GetDatum(attrs->attinhcount);
     752         1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attstattarget - 1] = Int16GetDatum(attrs->attstattarget);
     753 CBC     1131395 :         slot[slotCount]->tts_values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(attrs->attcollation);
     754         1131395 :         if (attoptions && attoptions[natts] != (Datum) 0)
     755              75 :             slot[slotCount]->tts_values[Anum_pg_attribute_attoptions - 1] = attoptions[natts];
     756                 :         else
     757         1131320 :             slot[slotCount]->tts_isnull[Anum_pg_attribute_attoptions - 1] = true;
     758                 : 
     759                 :         /* start out with empty permissions and empty options */
     760         1131395 :         slot[slotCount]->tts_isnull[Anum_pg_attribute_attacl - 1] = true;
     761         1131395 :         slot[slotCount]->tts_isnull[Anum_pg_attribute_attfdwoptions - 1] = true;
     762         1131395 :         slot[slotCount]->tts_isnull[Anum_pg_attribute_attmissingval - 1] = true;
     763                 : 
     764         1131395 :         ExecStoreVirtualTuple(slot[slotCount]);
     765         1131395 :         slotCount++;
     766                 : 
     767                 :         /*
     768                 :          * If slots are full or the end of processing has been reached, insert
     769                 :          * a batch of tuples.
     770                 :          */
     771         1131395 :         if (slotCount == nslots || natts == tupdesc->natts - 1)
     772                 :         {
     773                 :             /* fetch index info only when we know we need it */
     774          219745 :             if (!indstate)
     775                 :             {
     776            1121 :                 indstate = CatalogOpenIndexes(pg_attribute_rel);
     777            1121 :                 close_index = true;
     778                 :             }
     779                 : 
     780                 :             /* insert the new tuples and update the indexes */
     781          219745 :             CatalogTuplesMultiInsertWithInfo(pg_attribute_rel, slot, slotCount,
     782                 :                                              indstate);
     783          219745 :             slotCount = 0;
     784                 :         }
     785                 : 
     786         1131395 :         natts++;
     787                 :     }
     788                 : 
     789          219926 :     if (close_index)
     790            1121 :         CatalogCloseIndexes(indstate);
     791         1349337 :     for (int i = 0; i < nslots; i++)
     792         1129411 :         ExecDropSingleTupleTableSlot(slot[i]);
     793          219926 :     pfree(slot);
     794          219926 : }
     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           99794 : AddNewAttributeTuples(Oid new_rel_oid,
     805                 :                       TupleDesc tupdesc,
     806                 :                       char relkind)
     807                 : {
     808                 :     Relation    rel;
     809                 :     CatalogIndexState indstate;
     810           99794 :     int         natts = tupdesc->natts;
     811                 :     ObjectAddress myself,
     812                 :                 referenced;
     813                 : 
     814                 :     /*
     815                 :      * open pg_attribute and its indexes.
     816                 :      */
     817           99794 :     rel = table_open(AttributeRelationId, RowExclusiveLock);
     818                 : 
     819           99794 :     indstate = CatalogOpenIndexes(rel);
     820                 : 
     821                 :     /* set stats detail level to a sane default */
     822          788755 :     for (int i = 0; i < natts; i++)
     823          688961 :         tupdesc->attrs[i].attstattarget = -1;
     824           99794 :     InsertPgAttributeTuples(rel, tupdesc, new_rel_oid, NULL, indstate);
     825                 : 
     826                 :     /* add dependencies on their datatypes and collations */
     827          788755 :     for (int i = 0; i < natts; i++)
     828                 :     {
     829                 :         /* Add dependency info */
     830          688961 :         ObjectAddressSubSet(myself, RelationRelationId, new_rel_oid, i + 1);
     831          688961 :         ObjectAddressSet(referenced, TypeRelationId,
     832                 :                          tupdesc->attrs[i].atttypid);
     833          688961 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     834                 : 
     835                 :         /* The default collation is pinned, so don't bother recording it */
     836          688961 :         if (OidIsValid(tupdesc->attrs[i].attcollation) &&
     837          291849 :             tupdesc->attrs[i].attcollation != DEFAULT_COLLATION_OID)
     838                 :         {
     839          251099 :             ObjectAddressSet(referenced, CollationRelationId,
     840                 :                              tupdesc->attrs[i].attcollation);
     841          251099 :             recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     842                 :         }
     843                 :     }
     844                 : 
     845                 :     /*
     846                 :      * Next we add the system attributes.  Skip OID if rel has no OIDs. Skip
     847                 :      * all for a view or type relation.  We don't bother with making datatype
     848                 :      * dependencies here, since presumably all these types are pinned.
     849                 :      */
     850           99794 :     if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
     851                 :     {
     852                 :         TupleDesc   td;
     853                 : 
     854           55554 :         td = CreateTupleDesc(lengthof(SysAtt), (FormData_pg_attribute **) &SysAtt);
     855                 : 
     856           55554 :         InsertPgAttributeTuples(rel, td, new_rel_oid, NULL, indstate);
     857           55554 :         FreeTupleDesc(td);
     858                 :     }
     859                 : 
     860                 :     /*
     861                 :      * clean up
     862                 :      */
     863           99794 :     CatalogCloseIndexes(indstate);
     864                 : 
     865           99794 :     table_close(rel, RowExclusiveLock);
     866           99794 : }
     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          163251 : InsertPgClassTuple(Relation pg_class_desc,
     883                 :                    Relation new_rel_desc,
     884                 :                    Oid new_rel_oid,
     885                 :                    Datum relacl,
     886                 :                    Datum reloptions)
     887                 : {
     888          163251 :     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          163251 :     memset(values, 0, sizeof(values));
     895          163251 :     memset(nulls, false, sizeof(nulls));
     896                 : 
     897          163251 :     values[Anum_pg_class_oid - 1] = ObjectIdGetDatum(new_rel_oid);
     898          163251 :     values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
     899          163251 :     values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
     900          163251 :     values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
     901          163251 :     values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
     902          163251 :     values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
     903          163251 :     values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
     904          163251 :     values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
     905          163251 :     values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
     906          163251 :     values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
     907          163251 :     values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
     908          163251 :     values[Anum_pg_class_relallvisible - 1] = Int32GetDatum(rd_rel->relallvisible);
     909          163251 :     values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
     910          163251 :     values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
     911          163251 :     values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
     912          163251 :     values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
     913          163251 :     values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
     914          163251 :     values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
     915          163251 :     values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
     916          163251 :     values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
     917          163251 :     values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
     918          163251 :     values[Anum_pg_class_relrowsecurity - 1] = BoolGetDatum(rd_rel->relrowsecurity);
     919          163251 :     values[Anum_pg_class_relforcerowsecurity - 1] = BoolGetDatum(rd_rel->relforcerowsecurity);
     920          163251 :     values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
     921          163251 :     values[Anum_pg_class_relispopulated - 1] = BoolGetDatum(rd_rel->relispopulated);
     922          163251 :     values[Anum_pg_class_relreplident - 1] = CharGetDatum(rd_rel->relreplident);
     923          163251 :     values[Anum_pg_class_relispartition - 1] = BoolGetDatum(rd_rel->relispartition);
     924          163251 :     values[Anum_pg_class_relrewrite - 1] = ObjectIdGetDatum(rd_rel->relrewrite);
     925          163251 :     values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
     926          163251 :     values[Anum_pg_class_relminmxid - 1] = MultiXactIdGetDatum(rd_rel->relminmxid);
     927          163251 :     if (relacl != (Datum) 0)
     928              66 :         values[Anum_pg_class_relacl - 1] = relacl;
     929                 :     else
     930          163185 :         nulls[Anum_pg_class_relacl - 1] = true;
     931          163251 :     if (reloptions != (Datum) 0)
     932            1440 :         values[Anum_pg_class_reloptions - 1] = reloptions;
     933                 :     else
     934          161811 :         nulls[Anum_pg_class_reloptions - 1] = true;
     935                 : 
     936                 :     /* relpartbound is set by updating this tuple, if necessary */
     937          163251 :     nulls[Anum_pg_class_relpartbound - 1] = true;
     938                 : 
     939          163251 :     tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
     940                 : 
     941                 :     /* finally insert the new tuple, update the indexes, and clean up */
     942          163251 :     CatalogTupleInsert(pg_class_desc, tup);
     943                 : 
     944          163251 :     heap_freetuple(tup);
     945          163251 : }
     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           99794 : 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           99794 :     new_rel_reltup = new_rel_desc->rd_rel;
     974                 : 
     975                 :     /* The relation is empty */
     976           99794 :     new_rel_reltup->relpages = 0;
     977           99794 :     new_rel_reltup->reltuples = -1;
     978           99794 :     new_rel_reltup->relallvisible = 0;
     979                 : 
     980                 :     /* Sequences always have a known size */
     981           99794 :     if (relkind == RELKIND_SEQUENCE)
     982                 :     {
     983             744 :         new_rel_reltup->relpages = 1;
     984             744 :         new_rel_reltup->reltuples = 1;
     985                 :     }
     986                 : 
     987           99794 :     new_rel_reltup->relfrozenxid = relfrozenxid;
     988           99794 :     new_rel_reltup->relminmxid = relminmxid;
     989           99794 :     new_rel_reltup->relowner = relowner;
     990           99794 :     new_rel_reltup->reltype = new_type_oid;
     991           99794 :     new_rel_reltup->reloftype = reloftype;
     992                 : 
     993                 :     /* relispartition is always set by updating this tuple later */
     994           99794 :     new_rel_reltup->relispartition = false;
     995                 : 
     996                 :     /* fill rd_att's type ID with something sane even if reltype is zero */
     997           99794 :     new_rel_desc->rd_att->tdtypeid = new_type_oid ? new_type_oid : RECORDOID;
     998           99794 :     new_rel_desc->rd_att->tdtypmod = -1;
     999                 : 
    1000                 :     /* Now build and insert the tuple */
    1001           99794 :     InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
    1002                 :                        relacl, reloptions);
    1003           99794 : }
    1004                 : 
    1005                 : 
    1006                 : /* --------------------------------
    1007                 :  *      AddNewRelationType -
    1008                 :  *
    1009                 :  *      define a composite type corresponding to the new relation
    1010                 :  * --------------------------------
    1011                 :  */
    1012                 : static ObjectAddress
    1013           81024 : 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           81024 :         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           99806 : 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 GNC       99806 :     RelFileNumber relfilenumber = InvalidRelFileNumber;
    1122                 :     TransactionId relfrozenxid;
    1123                 :     MultiXactId relminmxid;
    1124                 : 
    1125 CBC       99806 :     pg_class_desc = table_open(RelationRelationId, RowExclusiveLock);
    1126                 : 
    1127                 :     /*
    1128                 :      * sanity checks
    1129                 :      */
    1130           99806 :     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           99806 :     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           99799 :     existing_relid = get_relname_relid(relname, relnamespace);
    1145           99799 :     if (existing_relid != InvalidOid)
    1146               1 :         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           99798 :     old_type_oid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
    1157                 :                                    CStringGetDatum(relname),
    1158                 :                                    ObjectIdGetDatum(relnamespace));
    1159           99798 :     if (OidIsValid(old_type_oid))
    1160                 :     {
    1161               1 :         if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
    1162 UBC           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 CBC       99798 :     if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
    1174 UBC           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 CBC       99798 :     if (!OidIsValid(relid))
    1183                 :     {
    1184                 :         /* Use binary-upgrade override for pg_class.oid and relfilenumber */
    1185           70518 :         if (IsBinaryUpgrade)
    1186                 :         {
    1187                 :             /*
    1188                 :              * Indexes are not supported here; they use
    1189                 :              * binary_upgrade_next_index_pg_class_oid.
    1190                 :              */
    1191             965 :             Assert(relkind != RELKIND_INDEX);
    1192             965 :             Assert(relkind != RELKIND_PARTITIONED_INDEX);
    1193                 : 
    1194             965 :             if (relkind == RELKIND_TOASTVALUE)
    1195                 :             {
    1196                 :                 /* There might be no TOAST table, so we have to test for it. */
    1197             244 :                 if (OidIsValid(binary_upgrade_next_toast_pg_class_oid))
    1198                 :                 {
    1199             244 :                     relid = binary_upgrade_next_toast_pg_class_oid;
    1200             244 :                     binary_upgrade_next_toast_pg_class_oid = InvalidOid;
    1201                 : 
    1202 GNC         244 :                     if (!RelFileNumberIsValid(binary_upgrade_next_toast_pg_class_relfilenumber))
    1203 UBC           0 :                         ereport(ERROR,
    1204                 :                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1205                 :                                  errmsg("toast relfilenumber value not set when in binary upgrade mode")));
    1206                 : 
    1207 GNC         244 :                     relfilenumber = binary_upgrade_next_toast_pg_class_relfilenumber;
    1208             244 :                     binary_upgrade_next_toast_pg_class_relfilenumber = InvalidRelFileNumber;
    1209                 :                 }
    1210                 :             }
    1211                 :             else
    1212                 :             {
    1213 CBC         721 :                 if (!OidIsValid(binary_upgrade_next_heap_pg_class_oid))
    1214 UBC           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 CBC         721 :                 relid = binary_upgrade_next_heap_pg_class_oid;
    1219             721 :                 binary_upgrade_next_heap_pg_class_oid = InvalidOid;
    1220                 : 
    1221             721 :                 if (RELKIND_HAS_STORAGE(relkind))
    1222                 :                 {
    1223 GNC         582 :                     if (!RelFileNumberIsValid(binary_upgrade_next_heap_pg_class_relfilenumber))
    1224 UBC           0 :                         ereport(ERROR,
    1225                 :                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1226                 :                                  errmsg("relfilenumber value not set when in binary upgrade mode")));
    1227                 : 
    1228 GNC         582 :                     relfilenumber = binary_upgrade_next_heap_pg_class_relfilenumber;
    1229             582 :                     binary_upgrade_next_heap_pg_class_relfilenumber = InvalidRelFileNumber;
    1230                 :                 }
    1231                 :             }
    1232                 :         }
    1233                 : 
    1234 CBC       70518 :         if (!OidIsValid(relid))
    1235 GNC       69553 :             relid = GetNewRelFileNumber(reltablespace, pg_class_desc,
    1236                 :                                         relpersistence);
    1237                 :     }
    1238                 : 
    1239                 :     /*
    1240                 :      * Determine the relation's initial permissions.
    1241                 :      */
    1242 CBC       99798 :     if (use_user_acl)
    1243                 :     {
    1244           62728 :         switch (relkind)
    1245                 :         {
    1246           61675 :             case RELKIND_RELATION:
    1247                 :             case RELKIND_VIEW:
    1248                 :             case RELKIND_MATVIEW:
    1249                 :             case RELKIND_FOREIGN_TABLE:
    1250                 :             case RELKIND_PARTITIONED_TABLE:
    1251           61675 :                 relacl = get_user_default_acl(OBJECT_TABLE, ownerid,
    1252                 :                                               relnamespace);
    1253           61675 :                 break;
    1254             744 :             case RELKIND_SEQUENCE:
    1255             744 :                 relacl = get_user_default_acl(OBJECT_SEQUENCE, ownerid,
    1256                 :                                               relnamespace);
    1257             744 :                 break;
    1258             309 :             default:
    1259             309 :                 relacl = NULL;
    1260             309 :                 break;
    1261                 :         }
    1262                 :     }
    1263                 :     else
    1264           37070 :         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           99798 :     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           99794 :     Assert(relid == RelationGetRelid(new_rel_desc));
    1292                 : 
    1293           99794 :     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          180818 :     if (!(relkind == RELKIND_SEQUENCE ||
    1301           81024 :           relkind == RELKIND_TOASTVALUE ||
    1302                 :           relkind == RELKIND_INDEX ||
    1303                 :           relkind == RELKIND_PARTITIONED_INDEX))
    1304           81024 :     {
    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           81024 :         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           81024 :         new_type_addr = AddNewRelationType(relname,
    1325                 :                                            relnamespace,
    1326                 :                                            relid,
    1327                 :                                            relkind,
    1328                 :                                            ownerid,
    1329                 :                                            reltypeid,
    1330                 :                                            new_array_oid);
    1331           81024 :         new_type_oid = new_type_addr.objectId;
    1332           81024 :         if (typaddress)
    1333             309 :             *typaddress = new_type_addr;
    1334                 : 
    1335                 :         /* Now create the array type. */
    1336           81024 :         relarrayname = makeArrayTypeName(relname, relnamespace);
    1337                 : 
    1338           81024 :         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           81024 :         pfree(relarrayname);
    1372                 :     }
    1373                 :     else
    1374                 :     {
    1375                 :         /* Caller should not be expecting a type to be created. */
    1376           18770 :         Assert(reltypeid == InvalidOid);
    1377           18770 :         Assert(typaddress == NULL);
    1378                 : 
    1379           18770 :         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           99794 :     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           99794 :     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           99794 :     if (relkind != RELKIND_COMPOSITE_TYPE &&
    1422           81459 :         relkind != RELKIND_TOASTVALUE &&
    1423           81459 :         !IsBootstrapProcessingMode())
    1424                 :     {
    1425                 :         ObjectAddress myself,
    1426                 :                     referenced;
    1427                 :         ObjectAddresses *addrs;
    1428                 : 
    1429           63159 :         ObjectAddressSet(myself, RelationRelationId, relid);
    1430                 : 
    1431           63159 :         recordDependencyOnOwner(RelationRelationId, relid, ownerid);
    1432                 : 
    1433           63159 :         recordDependencyOnNewAcl(RelationRelationId, relid, 0, ownerid, relacl);
    1434                 : 
    1435           63159 :         recordDependencyOnCurrentExtension(&myself, false);
    1436                 : 
    1437           63159 :         addrs = new_object_addresses();
    1438                 : 
    1439           63159 :         ObjectAddressSet(referenced, NamespaceRelationId, relnamespace);
    1440           63159 :         add_exact_object_address(&referenced, addrs);
    1441                 : 
    1442           63159 :         if (reloftypeid)
    1443                 :         {
    1444              34 :             ObjectAddressSet(referenced, TypeRelationId, reloftypeid);
    1445              34 :             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           63159 :         if (RELKIND_HAS_TABLE_AM(relkind) && relkind != RELKIND_TOASTVALUE)
    1456                 :         {
    1457           16116 :             ObjectAddressSet(referenced, AccessMethodRelationId, accessmtd);
    1458           16116 :             add_exact_object_address(&referenced, addrs);
    1459                 :         }
    1460                 : 
    1461           63159 :         record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
    1462           63159 :         free_object_addresses(addrs);
    1463                 :     }
    1464                 : 
    1465                 :     /* Post creation hook for new relation */
    1466           99794 :     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           99794 :     StoreConstraints(new_rel_desc, cooked_constraints, is_internal);
    1476                 : 
    1477                 :     /*
    1478                 :      * If there's a special on-commit action, remember it
    1479                 :      */
    1480           99794 :     if (oncommit != ONCOMMIT_NOOP)
    1481              80 :         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           99794 :     table_close(new_rel_desc, NoLock);  /* do not unlock till end of xact */
    1488           99794 :     table_close(pg_class_desc, RowExclusiveLock);
    1489                 : 
    1490           99794 :     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           19166 : RelationRemoveInheritance(Oid relid)
    1504                 : {
    1505                 :     Relation    catalogRelation;
    1506                 :     SysScanDesc scan;
    1507                 :     ScanKeyData key;
    1508                 :     HeapTuple   tuple;
    1509                 : 
    1510           19166 :     catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
    1511                 : 
    1512           19166 :     ScanKeyInit(&key,
    1513                 :                 Anum_pg_inherits_inhrelid,
    1514                 :                 BTEqualStrategyNumber, F_OIDEQ,
    1515                 :                 ObjectIdGetDatum(relid));
    1516                 : 
    1517           19166 :     scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
    1518                 :                               NULL, 1, &key);
    1519                 : 
    1520           22972 :     while (HeapTupleIsValid(tuple = systable_getnext(scan)))
    1521            3806 :         CatalogTupleDelete(catalogRelation, &tuple->t_self);
    1522                 : 
    1523           19166 :     systable_endscan(scan);
    1524           19166 :     table_close(catalogRelation, RowExclusiveLock);
    1525           19166 : }
    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           29441 : DeleteRelationTuple(Oid relid)
    1537                 : {
    1538                 :     Relation    pg_class_desc;
    1539                 :     HeapTuple   tup;
    1540                 : 
    1541                 :     /* Grab an appropriate lock on the pg_class relation */
    1542           29441 :     pg_class_desc = table_open(RelationRelationId, RowExclusiveLock);
    1543                 : 
    1544           29441 :     tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    1545           29441 :     if (!HeapTupleIsValid(tup))
    1546 UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
    1547                 : 
    1548                 :     /* delete the relation tuple from pg_class, and finish up */
    1549 CBC       29441 :     CatalogTupleDelete(pg_class_desc, &tup->t_self);
    1550                 : 
    1551           29441 :     ReleaseSysCache(tup);
    1552                 : 
    1553           29441 :     table_close(pg_class_desc, RowExclusiveLock);
    1554           29441 : }
    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           29441 : 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           29441 :     attrel = table_open(AttributeRelationId, RowExclusiveLock);
    1574                 : 
    1575                 :     /* Use the index to scan only attributes of the target relation */
    1576           29441 :     ScanKeyInit(&key[0],
    1577                 :                 Anum_pg_attribute_attrelid,
    1578                 :                 BTEqualStrategyNumber, F_OIDEQ,
    1579                 :                 ObjectIdGetDatum(relid));
    1580                 : 
    1581           29441 :     scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
    1582                 :                               NULL, 1, key);
    1583                 : 
    1584                 :     /* Delete all the matching tuples */
    1585          199812 :     while ((atttup = systable_getnext(scan)) != NULL)
    1586          170371 :         CatalogTupleDelete(attrel, &atttup->t_self);
    1587                 : 
    1588                 :     /* Clean up after the scan */
    1589           29441 :     systable_endscan(scan);
    1590           29441 :     table_close(attrel, RowExclusiveLock);
    1591           29441 : }
    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 UBC           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 CBC         977 : 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             977 :     rel = relation_open(relid, AccessExclusiveLock);
    1658                 : 
    1659             977 :     attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    1660                 : 
    1661             977 :     tuple = SearchSysCacheCopy2(ATTNUM,
    1662                 :                                 ObjectIdGetDatum(relid),
    1663                 :                                 Int16GetDatum(attnum));
    1664             977 :     if (!HeapTupleIsValid(tuple))   /* shouldn't happen */
    1665 UBC           0 :         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
    1666                 :              attnum, relid);
    1667 CBC         977 :     attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
    1668                 : 
    1669             977 :     if (attnum < 0)
    1670                 :     {
    1671                 :         /* System attribute (probably OID) ... just delete the row */
    1672                 : 
    1673 UBC           0 :         CatalogTupleDelete(attr_rel, &tuple->t_self);
    1674                 :     }
    1675                 :     else
    1676                 :     {
    1677                 :         /* Dropping user attributes is lots harder */
    1678                 : 
    1679                 :         /* Mark the attribute as dropped */
    1680 CBC         977 :         attStruct->attisdropped = true;
    1681                 : 
    1682                 :         /*
    1683                 :          * Set the type OID to invalid.  A dropped attribute's type link
    1684                 :          * cannot be relied on (once the attribute is dropped, the type might
    1685                 :          * be too). Fortunately we do not need the type row --- the only
    1686                 :          * really essential information is the type's typlen and typalign,
    1687                 :          * which are preserved in the attribute's attlen and attalign.  We set
    1688                 :          * atttypid to zero here as a means of catching code that incorrectly
    1689                 :          * expects it to be valid.
    1690                 :          */
    1691             977 :         attStruct->atttypid = InvalidOid;
    1692                 : 
    1693                 :         /* Remove any NOT NULL constraint the column may have */
    1694             977 :         attStruct->attnotnull = false;
    1695                 : 
    1696                 :         /* We don't want to keep stats for it anymore */
    1697             977 :         attStruct->attstattarget = 0;
    1698                 : 
    1699                 :         /* Unset this so no one tries to look up the generation expression */
    1700             977 :         attStruct->attgenerated = '\0';
    1701                 : 
    1702                 :         /*
    1703                 :          * Change the column name to something that isn't likely to conflict
    1704                 :          */
    1705             977 :         snprintf(newattname, sizeof(newattname),
    1706                 :                  "........pg.dropped.%d........", attnum);
    1707             977 :         namestrcpy(&(attStruct->attname), newattname);
    1708                 : 
    1709                 :         /* clear the missing value if any */
    1710             977 :         if (attStruct->atthasmissing)
    1711                 :         {
    1712 UNC           0 :             Datum       valuesAtt[Natts_pg_attribute] = {0};
    1713               0 :             bool        nullsAtt[Natts_pg_attribute] = {0};
    1714               0 :             bool        replacesAtt[Natts_pg_attribute] = {0};
    1715                 : 
    1716                 :             /* update the tuple - set atthasmissing and attmissingval */
    1717 UBC           0 :             valuesAtt[Anum_pg_attribute_atthasmissing - 1] =
    1718               0 :                 BoolGetDatum(false);
    1719 UIC           0 :             replacesAtt[Anum_pg_attribute_atthasmissing - 1] = true;
    1720 UBC           0 :             valuesAtt[Anum_pg_attribute_attmissingval - 1] = (Datum) 0;
    1721 UIC           0 :             nullsAtt[Anum_pg_attribute_attmissingval - 1] = true;
    1722               0 :             replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
    1723                 : 
    1724 LBC           0 :             tuple = heap_modify_tuple(tuple, RelationGetDescr(attr_rel),
    1725                 :                                       valuesAtt, nullsAtt, replacesAtt);
    1726                 :         }
    1727                 : 
    1728 GIC         977 :         CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
    1729                 :     }
    1730                 : 
    1731                 :     /*
    1732                 :      * Because updating the pg_attribute row will trigger a relcache flush for
    1733 ECB             :      * the target relation, we need not do anything else to notify other
    1734                 :      * backends of the change.
    1735                 :      */
    1736                 : 
    1737 GIC         977 :     table_close(attr_rel, RowExclusiveLock);
    1738 ECB             : 
    1739 CBC         977 :     if (attnum > 0)
    1740 GIC         977 :         RemoveStatistics(relid, attnum);
    1741                 : 
    1742             977 :     relation_close(rel, NoLock);
    1743             977 : }
    1744                 : 
    1745                 : /*
    1746                 :  * heap_drop_with_catalog   - removes specified relation from catalogs
    1747                 :  *
    1748                 :  * Note that this routine is not responsible for dropping objects that are
    1749                 :  * linked to the pg_class entry via dependencies (for example, indexes and
    1750                 :  * constraints).  Those are deleted by the dependency-tracing logic in
    1751 ECB             :  * dependency.c before control gets here.  In general, therefore, this routine
    1752                 :  * should never be called directly; go through performDeletion() instead.
    1753                 :  */
    1754                 : void
    1755 CBC       19166 : heap_drop_with_catalog(Oid relid)
    1756 ECB             : {
    1757                 :     Relation    rel;
    1758                 :     HeapTuple   tuple;
    1759 GIC       19166 :     Oid         parentOid = InvalidOid,
    1760           19166 :                 defaultPartOid = InvalidOid;
    1761                 : 
    1762                 :     /*
    1763                 :      * To drop a partition safely, we must grab exclusive lock on its parent,
    1764                 :      * because another backend might be about to execute a query on the parent
    1765                 :      * table.  If it relies on previously cached partition descriptor, then it
    1766                 :      * could attempt to access the just-dropped relation as its partition. We
    1767                 :      * must therefore take a table lock strong enough to prevent all queries
    1768 ECB             :      * on the table from proceeding until we commit and send out a
    1769                 :      * shared-cache-inval notice that will make them update their partition
    1770 EUB             :      * descriptors.
    1771 ECB             :      */
    1772 GIC       19166 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    1773           19166 :     if (!HeapTupleIsValid(tuple))
    1774 UIC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
    1775 GIC       19166 :     if (((Form_pg_class) GETSTRUCT(tuple))->relispartition)
    1776                 :     {
    1777                 :         /*
    1778 ECB             :          * We have to lock the parent if the partition is being detached,
    1779                 :          * because it's possible that some query still has a partition
    1780                 :          * descriptor that includes this partition.
    1781                 :          */
    1782 GIC        3138 :         parentOid = get_partition_parent(relid, true);
    1783            3138 :         LockRelationOid(parentOid, AccessExclusiveLock);
    1784                 : 
    1785 ECB             :         /*
    1786                 :          * If this is not the default partition, dropping it will change the
    1787                 :          * default partition's partition constraint, so we must lock it.
    1788                 :          */
    1789 GIC        3138 :         defaultPartOid = get_default_partition_oid(parentOid);
    1790 CBC        3138 :         if (OidIsValid(defaultPartOid) && relid != defaultPartOid)
    1791 GIC         175 :             LockRelationOid(defaultPartOid, AccessExclusiveLock);
    1792                 :     }
    1793                 : 
    1794           19166 :     ReleaseSysCache(tuple);
    1795 ECB             : 
    1796                 :     /*
    1797                 :      * Open and lock the relation.
    1798                 :      */
    1799 GIC       19166 :     rel = relation_open(relid, AccessExclusiveLock);
    1800                 : 
    1801                 :     /*
    1802 ECB             :      * There can no longer be anyone *else* touching the relation, but we
    1803                 :      * might still have open queries or cursors, or pending trigger events, in
    1804                 :      * our own session.
    1805                 :      */
    1806 GIC       19166 :     CheckTableNotInUse(rel, "DROP TABLE");
    1807                 : 
    1808                 :     /*
    1809                 :      * This effectively deletes all rows in the table, and may be done in a
    1810 ECB             :      * serializable transaction.  In that case we must record a rw-conflict in
    1811                 :      * to this transaction from each transaction holding a predicate lock on
    1812                 :      * the table.
    1813                 :      */
    1814 GIC       19166 :     CheckTableForSerializableConflictIn(rel);
    1815 ECB             : 
    1816                 :     /*
    1817                 :      * Delete pg_foreign_table tuple first.
    1818                 :      */
    1819 GIC       19166 :     if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    1820 ECB             :     {
    1821                 :         Relation    ftrel;
    1822                 :         HeapTuple   fttuple;
    1823                 : 
    1824 GNC         114 :         ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
    1825                 : 
    1826             114 :         fttuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
    1827             114 :         if (!HeapTupleIsValid(fttuple))
    1828 LBC           0 :             elog(ERROR, "cache lookup failed for foreign table %u", relid);
    1829 ECB             : 
    1830 GNC         114 :         CatalogTupleDelete(ftrel, &fttuple->t_self);
    1831                 : 
    1832             114 :         ReleaseSysCache(fttuple);
    1833             114 :         table_close(ftrel, RowExclusiveLock);
    1834                 :     }
    1835 ECB             : 
    1836                 :     /*
    1837                 :      * If a partitioned table, delete the pg_partitioned_table tuple.
    1838                 :      */
    1839 GIC       19166 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    1840            1677 :         RemovePartitionKeyByRelId(relid);
    1841                 : 
    1842 ECB             :     /*
    1843                 :      * If the relation being dropped is the default partition itself,
    1844                 :      * invalidate its entry in pg_partitioned_table.
    1845                 :      */
    1846 GIC       19166 :     if (relid == defaultPartOid)
    1847             197 :         update_default_partition_oid(parentOid, InvalidOid);
    1848 ECB             : 
    1849                 :     /*
    1850                 :      * Schedule unlinking of the relation's physical files at commit.
    1851                 :      */
    1852 CBC       19166 :     if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
    1853 GIC       16209 :         RelationDropStorage(rel);
    1854                 : 
    1855                 :     /* ensure that stats are dropped if transaction commits */
    1856           19166 :     pgstat_drop_relation(rel);
    1857                 : 
    1858                 :     /*
    1859 ECB             :      * Close relcache entry, but *keep* AccessExclusiveLock on the relation
    1860                 :      * until transaction commit.  This ensures no one else will try to do
    1861                 :      * something with the doomed relation.
    1862                 :      */
    1863 GIC       19166 :     relation_close(rel, NoLock);
    1864 ECB             : 
    1865                 :     /*
    1866                 :      * Remove any associated relation synchronization states.
    1867                 :      */
    1868 GIC       19166 :     RemoveSubscriptionRel(InvalidOid, relid);
    1869 ECB             : 
    1870                 :     /*
    1871                 :      * Forget any ON COMMIT action for the rel
    1872                 :      */
    1873 GIC       19166 :     remove_on_commit_action(relid);
    1874                 : 
    1875                 :     /*
    1876                 :      * Flush the relation from the relcache.  We want to do this before
    1877                 :      * starting to remove catalog entries, just to be certain that no relcache
    1878 ECB             :      * entry rebuild will happen partway through.  (That should not really
    1879                 :      * matter, since we don't do CommandCounterIncrement here, but let's be
    1880                 :      * safe.)
    1881                 :      */
    1882 GIC       19166 :     RelationForgetRelation(relid);
    1883 ECB             : 
    1884                 :     /*
    1885                 :      * remove inheritance information
    1886                 :      */
    1887 GIC       19166 :     RelationRemoveInheritance(relid);
    1888 ECB             : 
    1889                 :     /*
    1890                 :      * delete statistics
    1891                 :      */
    1892 GIC       19166 :     RemoveStatistics(relid, 0);
    1893 ECB             : 
    1894                 :     /*
    1895                 :      * delete attribute tuples
    1896                 :      */
    1897 GIC       19166 :     DeleteAttributeTuples(relid);
    1898 ECB             : 
    1899                 :     /*
    1900                 :      * delete relation tuple
    1901                 :      */
    1902 GIC       19166 :     DeleteRelationTuple(relid);
    1903                 : 
    1904           19166 :     if (OidIsValid(parentOid))
    1905                 :     {
    1906                 :         /*
    1907 ECB             :          * If this is not the default partition, the partition constraint of
    1908                 :          * the default partition has changed to include the portion of the key
    1909                 :          * space previously covered by the dropped partition.
    1910                 :          */
    1911 GIC        3138 :         if (OidIsValid(defaultPartOid) && relid != defaultPartOid)
    1912             175 :             CacheInvalidateRelcacheByRelid(defaultPartOid);
    1913                 : 
    1914 ECB             :         /*
    1915                 :          * Invalidate the parent's relcache so that the partition is no longer
    1916                 :          * included in its partition descriptor.
    1917                 :          */
    1918 GIC        3138 :         CacheInvalidateRelcacheByRelid(parentOid);
    1919                 :         /* keep the lock */
    1920                 :     }
    1921           19166 : }
    1922                 : 
    1923                 : 
    1924                 : /*
    1925                 :  * RelationClearMissing
    1926                 :  *
    1927                 :  * Set atthasmissing and attmissingval to false/null for all attributes
    1928                 :  * where they are currently set. This can be safely and usefully done if
    1929                 :  * the table is rewritten (e.g. by VACUUM FULL or CLUSTER) where we know there
    1930                 :  * are no rows left with less than a full complement of attributes.
    1931 ECB             :  *
    1932                 :  * The caller must have an AccessExclusive lock on the relation.
    1933                 :  */
    1934                 : void
    1935 CBC         912 : RelationClearMissing(Relation rel)
    1936                 : {
    1937                 :     Relation    attr_rel;
    1938 GIC         912 :     Oid         relid = RelationGetRelid(rel);
    1939             912 :     int         natts = RelationGetNumberOfAttributes(rel);
    1940                 :     int         attnum;
    1941                 :     Datum       repl_val[Natts_pg_attribute];
    1942                 :     bool        repl_null[Natts_pg_attribute];
    1943                 :     bool        repl_repl[Natts_pg_attribute];
    1944 ECB             :     Form_pg_attribute attrtuple;
    1945                 :     HeapTuple   tuple,
    1946                 :                 newtuple;
    1947                 : 
    1948 CBC         912 :     memset(repl_val, 0, sizeof(repl_val));
    1949             912 :     memset(repl_null, false, sizeof(repl_null));
    1950 GIC         912 :     memset(repl_repl, false, sizeof(repl_repl));
    1951 ECB             : 
    1952 CBC         912 :     repl_val[Anum_pg_attribute_atthasmissing - 1] = BoolGetDatum(false);
    1953 GIC         912 :     repl_null[Anum_pg_attribute_attmissingval - 1] = true;
    1954                 : 
    1955             912 :     repl_repl[Anum_pg_attribute_atthasmissing - 1] = true;
    1956 CBC         912 :     repl_repl[Anum_pg_attribute_attmissingval - 1] = true;
    1957                 : 
    1958                 : 
    1959 ECB             :     /* Get a lock on pg_attribute */
    1960 GIC         912 :     attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    1961 ECB             : 
    1962                 :     /* process each non-system attribute, including any dropped columns */
    1963 GIC        3439 :     for (attnum = 1; attnum <= natts; attnum++)
    1964 ECB             :     {
    1965 GBC        2527 :         tuple = SearchSysCache2(ATTNUM,
    1966                 :                                 ObjectIdGetDatum(relid),
    1967                 :                                 Int16GetDatum(attnum));
    1968 CBC        2527 :         if (!HeapTupleIsValid(tuple))   /* shouldn't happen */
    1969 UIC           0 :             elog(ERROR, "cache lookup failed for attribute %d of relation %u",
    1970                 :                  attnum, relid);
    1971 ECB             : 
    1972 GIC        2527 :         attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    1973 ECB             : 
    1974                 :         /* ignore any where atthasmissing is not true */
    1975 GIC        2527 :         if (attrtuple->atthasmissing)
    1976 ECB             :         {
    1977 GIC          48 :             newtuple = heap_modify_tuple(tuple, RelationGetDescr(attr_rel),
    1978 ECB             :                                          repl_val, repl_null, repl_repl);
    1979                 : 
    1980 GIC          48 :             CatalogTupleUpdate(attr_rel, &newtuple->t_self, newtuple);
    1981 ECB             : 
    1982 GIC          48 :             heap_freetuple(newtuple);
    1983                 :         }
    1984                 : 
    1985            2527 :         ReleaseSysCache(tuple);
    1986                 :     }
    1987                 : 
    1988 ECB             :     /*
    1989                 :      * Our update of the pg_attribute rows will force a relcache rebuild, so
    1990                 :      * there's nothing else to do here.
    1991                 :      */
    1992 GIC         912 :     table_close(attr_rel, RowExclusiveLock);
    1993             912 : }
    1994                 : 
    1995                 : /*
    1996                 :  * SetAttrMissing
    1997                 :  *
    1998                 :  * Set the missing value of a single attribute. This should only be used by
    1999 ECB             :  * binary upgrade. Takes an AccessExclusive lock on the relation owning the
    2000                 :  * attribute.
    2001                 :  */
    2002                 : void
    2003 CBC           2 : SetAttrMissing(Oid relid, char *attname, char *value)
    2004                 : {
    2005 GNC           2 :     Datum       valuesAtt[Natts_pg_attribute] = {0};
    2006               2 :     bool        nullsAtt[Natts_pg_attribute] = {0};
    2007               2 :     bool        replacesAtt[Natts_pg_attribute] = {0};
    2008                 :     Datum       missingval;
    2009                 :     Form_pg_attribute attStruct;
    2010                 :     Relation    attrrel,
    2011                 :                 tablerel;
    2012 ECB             :     HeapTuple   atttup,
    2013                 :                 newtup;
    2014                 : 
    2015                 :     /* lock the table the attribute belongs to */
    2016 GIC           2 :     tablerel = table_open(relid, AccessExclusiveLock);
    2017 EUB             : 
    2018                 :     /* Don't do anything unless it's a plain table */
    2019 GIC           2 :     if (tablerel->rd_rel->relkind != RELKIND_RELATION)
    2020                 :     {
    2021 UIC           0 :         table_close(tablerel, AccessExclusiveLock);
    2022 LBC           0 :         return;
    2023 ECB             :     }
    2024                 : 
    2025 EUB             :     /* Lock the attribute row and get the data */
    2026 GIC           2 :     attrrel = table_open(AttributeRelationId, RowExclusiveLock);
    2027 CBC           2 :     atttup = SearchSysCacheAttName(relid, attname);
    2028 GIC           2 :     if (!HeapTupleIsValid(atttup))
    2029 UIC           0 :         elog(ERROR, "cache lookup failed for attribute %s of relation %u",
    2030 ECB             :              attname, relid);
    2031 GIC           2 :     attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
    2032                 : 
    2033                 :     /* get an array value from the value string */
    2034               2 :     missingval = OidFunctionCall3(F_ARRAY_IN,
    2035                 :                                   CStringGetDatum(value),
    2036 ECB             :                                   ObjectIdGetDatum(attStruct->atttypid),
    2037                 :                                   Int32GetDatum(attStruct->atttypmod));
    2038                 : 
    2039                 :     /* update the tuple - set atthasmissing and attmissingval */
    2040 GIC           2 :     valuesAtt[Anum_pg_attribute_atthasmissing - 1] = BoolGetDatum(true);
    2041               2 :     replacesAtt[Anum_pg_attribute_atthasmissing - 1] = true;
    2042 CBC           2 :     valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
    2043               2 :     replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
    2044 ECB             : 
    2045 GIC           2 :     newtup = heap_modify_tuple(atttup, RelationGetDescr(attrrel),
    2046                 :                                valuesAtt, nullsAtt, replacesAtt);
    2047               2 :     CatalogTupleUpdate(attrrel, &newtup->t_self, newtup);
    2048                 : 
    2049                 :     /* clean up */
    2050               2 :     ReleaseSysCache(atttup);
    2051               2 :     table_close(attrrel, RowExclusiveLock);
    2052               2 :     table_close(tablerel, AccessExclusiveLock);
    2053                 : }
    2054                 : 
    2055                 : /*
    2056 ECB             :  * Store a check-constraint expression for the given relation.
    2057                 :  *
    2058                 :  * Caller is responsible for updating the count of constraints
    2059                 :  * in the pg_class entry for the relation.
    2060                 :  *
    2061                 :  * The OID of the new constraint is returned.
    2062                 :  */
    2063                 : static Oid
    2064 GIC         988 : StoreRelCheck(Relation rel, const char *ccname, Node *expr,
    2065                 :               bool is_validated, bool is_local, int inhcount,
    2066                 :               bool is_no_inherit, bool is_internal)
    2067                 : {
    2068                 :     char       *ccbin;
    2069 ECB             :     List       *varList;
    2070                 :     int         keycount;
    2071                 :     int16      *attNos;
    2072                 :     Oid         constrOid;
    2073                 : 
    2074                 :     /*
    2075                 :      * Flatten expression to string form for storage.
    2076                 :      */
    2077 GIC         988 :     ccbin = nodeToString(expr);
    2078 ECB             : 
    2079                 :     /*
    2080                 :      * Find columns of rel that are used in expr
    2081                 :      *
    2082                 :      * NB: pull_var_clause is okay here only because we don't allow subselects
    2083                 :      * in check constraints; it would fail to examine the contents of
    2084                 :      * subselects.
    2085                 :      */
    2086 CBC         988 :     varList = pull_var_clause(expr, 0);
    2087             988 :     keycount = list_length(varList);
    2088                 : 
    2089             988 :     if (keycount > 0)
    2090                 :     {
    2091                 :         ListCell   *vl;
    2092             981 :         int         i = 0;
    2093 ECB             : 
    2094 CBC         981 :         attNos = (int16 *) palloc(keycount * sizeof(int16));
    2095            2257 :         foreach(vl, varList)
    2096 ECB             :         {
    2097 GIC        1276 :             Var        *var = (Var *) lfirst(vl);
    2098 ECB             :             int         j;
    2099                 : 
    2100 GIC        1381 :             for (j = 0; j < i; j++)
    2101 CBC         302 :                 if (attNos[j] == var->varattno)
    2102 GIC         197 :                     break;
    2103            1276 :             if (j == i)
    2104            1079 :                 attNos[i++] = var->varattno;
    2105                 :         }
    2106             981 :         keycount = i;
    2107 ECB             :     }
    2108                 :     else
    2109 CBC           7 :         attNos = NULL;
    2110                 : 
    2111                 :     /*
    2112                 :      * Partitioned tables do not contain any rows themselves, so a NO INHERIT
    2113                 :      * constraint makes no sense.
    2114                 :      */
    2115 GIC         988 :     if (is_no_inherit &&
    2116              53 :         rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    2117              12 :         ereport(ERROR,
    2118 ECB             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    2119                 :                  errmsg("cannot add NO INHERIT constraint to partitioned table \"%s\"",
    2120                 :                         RelationGetRelationName(rel))));
    2121                 : 
    2122                 :     /*
    2123                 :      * Create the Check Constraint
    2124                 :      */
    2125                 :     constrOid =
    2126 GIC         976 :         CreateConstraintEntry(ccname,   /* Constraint Name */
    2127             976 :                               RelationGetNamespace(rel),    /* namespace */
    2128                 :                               CONSTRAINT_CHECK, /* Constraint Type */
    2129                 :                               false,    /* Is Deferrable */
    2130                 :                               false,    /* Is Deferred */
    2131                 :                               is_validated,
    2132                 :                               InvalidOid,   /* no parent constraint */
    2133                 :                               RelationGetRelid(rel),    /* relation */
    2134                 :                               attNos,   /* attrs in the constraint */
    2135                 :                               keycount, /* # key attrs in the constraint */
    2136                 :                               keycount, /* # total attrs in the constraint */
    2137                 :                               InvalidOid,   /* not a domain constraint */
    2138                 :                               InvalidOid,   /* no associated index */
    2139                 :                               InvalidOid,   /* Foreign key fields */
    2140                 :                               NULL,
    2141                 :                               NULL,
    2142                 :                               NULL,
    2143                 :                               NULL,
    2144                 :                               0,
    2145                 :                               ' ',
    2146                 :                               ' ',
    2147                 :                               NULL,
    2148                 :                               0,
    2149                 :                               ' ',
    2150 ECB             :                               NULL, /* not an exclusion constraint */
    2151                 :                               expr, /* Tree form of check constraint */
    2152                 :                               ccbin,    /* Binary form of check constraint */
    2153                 :                               is_local, /* conislocal */
    2154                 :                               inhcount, /* coninhcount */
    2155                 :                               is_no_inherit,    /* connoinherit */
    2156                 :                               is_internal); /* internally constructed? */
    2157                 : 
    2158 GIC         976 :     pfree(ccbin);
    2159                 : 
    2160             976 :     return constrOid;
    2161 ECB             : }
    2162                 : 
    2163                 : /*
    2164                 :  * Store a NOT NULL constraint for the given relation
    2165                 :  *
    2166                 :  * The OID of the new constraint is returned.
    2167                 :  */
    2168                 : static Oid
    2169 GNC        3683 : StoreRelNotNull(Relation rel, const char *nnname, AttrNumber attnum,
    2170                 :                 bool is_validated, bool is_local, int inhcount,
    2171                 :                 bool is_no_inherit)
    2172                 : {
    2173                 :     int16       attNos;
    2174                 :     Oid         constrOid;
    2175                 : 
    2176                 :     /* We only ever store one column per constraint */
    2177            3683 :     attNos = attnum;
    2178                 : 
    2179                 :     constrOid =
    2180            3683 :         CreateConstraintEntry(nnname,
    2181            3683 :                               RelationGetNamespace(rel),
    2182                 :                               CONSTRAINT_NOTNULL,
    2183                 :                               false,
    2184                 :                               false,
    2185                 :                               is_validated,
    2186                 :                               InvalidOid,
    2187                 :                               RelationGetRelid(rel),
    2188                 :                               &attNos,
    2189                 :                               1,
    2190                 :                               1,
    2191                 :                               InvalidOid,   /* not a domain constraint */
    2192                 :                               InvalidOid,   /* no associated index */
    2193                 :                               InvalidOid,   /* Foreign key fields */
    2194                 :                               NULL,
    2195                 :                               NULL,
    2196                 :                               NULL,
    2197                 :                               NULL,
    2198                 :                               0,
    2199                 :                               ' ',
    2200                 :                               ' ',
    2201                 :                               NULL,
    2202                 :                               0,
    2203                 :                               ' ',
    2204                 :                               NULL, /* not an exclusion constraint */
    2205                 :                               NULL,
    2206                 :                               NULL,
    2207                 :                               is_local,
    2208                 :                               inhcount,
    2209                 :                               is_no_inherit,
    2210                 :                               false);
    2211            3683 :     return constrOid;
    2212                 : }
    2213                 : 
    2214                 : /*
    2215                 :  * Store defaults and constraints (passed as a list of CookedConstraint).
    2216                 :  *
    2217                 :  * Each CookedConstraint struct is modified to store the new catalog tuple OID.
    2218                 :  *
    2219                 :  * NOTE: only pre-cooked expressions will be passed this way, which is to
    2220 ECB             :  * say expressions inherited from an existing relation.  Newly parsed
    2221                 :  * expressions can be added later, by direct calls to StoreAttrDefault
    2222                 :  * and StoreRelCheck (see AddRelationNewConstraints()).
    2223                 :  */
    2224                 : static void
    2225 GIC       99794 : StoreConstraints(Relation rel, List *cooked_constraints, bool is_internal)
    2226                 : {
    2227           99794 :     int         numchecks = 0;
    2228                 :     ListCell   *lc;
    2229                 : 
    2230           99794 :     if (cooked_constraints == NIL)
    2231           99597 :         return;                 /* nothing to do */
    2232                 : 
    2233                 :     /*
    2234                 :      * Deparsing of constraint expressions will fail unless the just-created
    2235                 :      * pg_attribute tuples for this relation are made visible.  So, bump the
    2236                 :      * command counter.  CAUTION: this will cause a relcache entry rebuild.
    2237                 :      */
    2238             197 :     CommandCounterIncrement();
    2239                 : 
    2240             437 :     foreach(lc, cooked_constraints)
    2241                 :     {
    2242             240 :         CookedConstraint *con = (CookedConstraint *) lfirst(lc);
    2243                 : 
    2244             240 :         switch (con->contype)
    2245                 :         {
    2246             160 :             case CONSTR_DEFAULT:
    2247             160 :                 con->conoid = StoreAttrDefault(rel, con->attnum, con->expr,
    2248                 :                                                is_internal, false);
    2249             160 :                 break;
    2250              80 :             case CONSTR_CHECK:
    2251              80 :                 con->conoid =
    2252              80 :                     StoreRelCheck(rel, con->name, con->expr,
    2253              80 :                                   !con->skip_validation, con->is_local,
    2254 CBC          80 :                                   con->inhcount, con->is_no_inherit,
    2255 GIC          80 :                                   is_internal);
    2256              80 :                 numchecks++;
    2257              80 :                 break;
    2258                 : 
    2259 UNC           0 :             case CONSTR_NOTNULL:
    2260               0 :                 con->conoid =
    2261               0 :                     StoreRelNotNull(rel, con->name, con->attnum,
    2262               0 :                                     !con->skip_validation, con->is_local,
    2263               0 :                                     con->inhcount, con->is_no_inherit);
    2264               0 :                 break;
    2265                 : 
    2266 UIC           0 :             default:
    2267               0 :                 elog(ERROR, "unrecognized constraint type: %d",
    2268                 :                      (int) con->contype);
    2269                 :         }
    2270                 :     }
    2271                 : 
    2272 GIC         197 :     if (numchecks > 0)
    2273              68 :         SetRelationNumChecks(rel, numchecks);
    2274                 : }
    2275                 : 
    2276 ECB             : /*
    2277                 :  * AddRelationNewConstraints
    2278                 :  *
    2279                 :  * Add new column default expressions and/or constraint check expressions
    2280                 :  * to an existing relation.  This is defined to do both for efficiency in
    2281                 :  * DefineRelation, but of course you can do just one or the other by passing
    2282                 :  * empty lists.
    2283                 :  *
    2284                 :  * rel: relation to be modified
    2285                 :  * newColDefaults: list of RawColumnDefault structures
    2286                 :  * newConstraints: list of Constraint nodes
    2287                 :  * allow_merge: true if check constraints may be merged with existing ones
    2288                 :  * is_local: true if definition is local, false if it's inherited
    2289                 :  * is_internal: true if result of some internal process, not a user request
    2290                 :  *
    2291                 :  * All entries in newColDefaults will be processed.  Entries in newConstraints
    2292                 :  * will be processed only if they are CONSTR_CHECK type.
    2293                 :  *
    2294                 :  * Returns a list of CookedConstraint nodes that shows the cooked form of
    2295                 :  * the default and constraint expressions added to the relation.
    2296                 :  *
    2297                 :  * NB: caller should have opened rel with some self-conflicting lock mode,
    2298                 :  * and should hold that lock till end of transaction; for normal cases that'll
    2299                 :  * be AccessExclusiveLock, but if caller knows that the constraint is already
    2300                 :  * enforced by some other means, it can be ShareUpdateExclusiveLock.  Also, we
    2301                 :  * assume the caller has done a CommandCounterIncrement if necessary to make
    2302                 :  * the relation's catalog tuples visible.
    2303                 :  */
    2304                 : List *
    2305 CBC        2792 : AddRelationNewConstraints(Relation rel,
    2306 ECB             :                           List *newColDefaults,
    2307                 :                           List *newConstraints,
    2308                 :                           bool allow_merge,
    2309                 :                           bool is_local,
    2310 EUB             :                           bool is_internal,
    2311                 :                           const char *queryString)
    2312                 : {
    2313 GBC        2792 :     List       *cookedConstraints = NIL;
    2314 EUB             :     TupleDesc   tupleDesc;
    2315                 :     TupleConstr *oldconstr;
    2316                 :     int         numoldchecks;
    2317                 :     ParseState *pstate;
    2318                 :     ParseNamespaceItem *nsitem;
    2319                 :     int         numchecks;
    2320                 :     List       *checknames;
    2321                 :     List       *nnnames;
    2322                 :     ListCell   *cell;
    2323                 :     Node       *expr;
    2324 ECB             :     CookedConstraint *cooked;
    2325                 : 
    2326                 :     /*
    2327                 :      * Get info about existing constraints.
    2328                 :      */
    2329 GIC        2792 :     tupleDesc = RelationGetDescr(rel);
    2330            2792 :     oldconstr = tupleDesc->constr;
    2331            2792 :     if (oldconstr)
    2332            2102 :         numoldchecks = oldconstr->num_check;
    2333                 :     else
    2334             690 :         numoldchecks = 0;
    2335                 : 
    2336                 :     /*
    2337                 :      * Create a dummy ParseState and insert the target relation as its sole
    2338                 :      * rangetable entry.  We need a ParseState for transformExpr.
    2339                 :      */
    2340            2792 :     pstate = make_parsestate(NULL);
    2341            2792 :     pstate->p_sourcetext = queryString;
    2342            2792 :     nsitem = addRangeTableEntryForRelation(pstate,
    2343                 :                                            rel,
    2344                 :                                            AccessShareLock,
    2345                 :                                            NULL,
    2346                 :                                            false,
    2347                 :                                            true);
    2348            2792 :     addNSItemToQuery(pstate, nsitem, true, true, true);
    2349                 : 
    2350                 :     /*
    2351                 :      * Process column default expressions.
    2352                 :      */
    2353            4350 :     foreach(cell, newColDefaults)
    2354                 :     {
    2355            1618 :         RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
    2356            1618 :         Form_pg_attribute atp = TupleDescAttr(rel->rd_att, colDef->attnum - 1);
    2357 ECB             :         Oid         defOid;
    2358                 : 
    2359 GIC        1618 :         expr = cookDefault(pstate, colDef->raw_default,
    2360                 :                            atp->atttypid, atp->atttypmod,
    2361            1618 :                            NameStr(atp->attname),
    2362            1618 :                            atp->attgenerated);
    2363                 : 
    2364                 :         /*
    2365 ECB             :          * If the expression is just a NULL constant, we do not bother to make
    2366                 :          * an explicit pg_attrdef entry, since the default behavior is
    2367                 :          * equivalent.  This applies to column defaults, but not for
    2368                 :          * generation expressions.
    2369                 :          *
    2370                 :          * Note a nonobvious property of this test: if the column is of a
    2371                 :          * domain type, what we'll get is not a bare null Const but a
    2372                 :          * CoerceToDomain expr, so we will not discard the default.  This is
    2373                 :          * critical because the column default needs to be retained to
    2374                 :          * override any default that the domain might have.
    2375                 :          */
    2376 GIC        1558 :         if (expr == NULL ||
    2377            1558 :             (!colDef->generated &&
    2378            1203 :              IsA(expr, Const) &&
    2379             607 :              castNode(Const, expr)->constisnull))
    2380              54 :             continue;
    2381 ECB             : 
    2382                 :         /* If the DEFAULT is volatile we cannot use a missing value */
    2383 CBC        1504 :         if (colDef->missingMode && contain_volatile_functions((Node *) expr))
    2384              33 :             colDef->missingMode = false;
    2385                 : 
    2386            1504 :         defOid = StoreAttrDefault(rel, colDef->attnum, expr, is_internal,
    2387 GIC        1504 :                                   colDef->missingMode);
    2388                 : 
    2389            1504 :         cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
    2390            1504 :         cooked->contype = CONSTR_DEFAULT;
    2391            1504 :         cooked->conoid = defOid;
    2392 CBC        1504 :         cooked->name = NULL;
    2393            1504 :         cooked->attnum = colDef->attnum;
    2394            1504 :         cooked->expr = expr;
    2395 GIC        1504 :         cooked->skip_validation = false;
    2396            1504 :         cooked->is_local = is_local;
    2397            1504 :         cooked->inhcount = is_local ? 0 : 1;
    2398            1504 :         cooked->is_no_inherit = false;
    2399            1504 :         cookedConstraints = lappend(cookedConstraints, cooked);
    2400 ECB             :     }
    2401                 : 
    2402                 :     /*
    2403                 :      * Process constraint expressions.
    2404                 :      */
    2405 CBC        2732 :     numchecks = numoldchecks;
    2406 GIC        2732 :     checknames = NIL;
    2407 GNC        2732 :     nnnames = NIL;
    2408 CBC        4096 :     foreach(cell, newConstraints)
    2409 ECB             :     {
    2410 GIC        1403 :         Constraint *cdef = (Constraint *) lfirst(cell);
    2411 ECB             :         Oid         constrOid;
    2412                 : 
    2413 GNC        1403 :         if (cdef->contype == CONSTR_CHECK)
    2414                 :         {
    2415                 :             char       *ccname;
    2416                 : 
    2417                 :             /*
    2418                 :              * XXX Should we detect the case with CHECK (foo IS NOT NULL) and
    2419                 :              * handle it as a NOT NULL constraint?
    2420                 :              */
    2421 ECB             : 
    2422 GNC         973 :             if (cdef->raw_expr != NULL)
    2423 ECB             :             {
    2424 GNC         858 :                 Assert(cdef->cooked_expr == NULL);
    2425                 : 
    2426                 :                 /*
    2427                 :                  * Transform raw parsetree to executable expression, and
    2428                 :                  * verify it's valid as a CHECK constraint.
    2429                 :                  */
    2430             858 :                 expr = cookConstraint(pstate, cdef->raw_expr,
    2431             858 :                                       RelationGetRelationName(rel));
    2432                 :             }
    2433                 :             else
    2434                 :             {
    2435             115 :                 Assert(cdef->cooked_expr != NULL);
    2436                 : 
    2437                 :                 /*
    2438                 :                  * Here, we assume the parser will only pass us valid CHECK
    2439                 :                  * expressions, so we do no particular checking.
    2440                 :                  */
    2441             115 :                 expr = stringToNode(cdef->cooked_expr);
    2442                 :             }
    2443                 : 
    2444 ECB             :             /*
    2445                 :              * Check name uniqueness, or generate a name if none was given.
    2446                 :              */
    2447 GNC         958 :             if (cdef->conname != NULL)
    2448                 :             {
    2449                 :                 ListCell   *cell2;
    2450                 : 
    2451             639 :                 ccname = cdef->conname;
    2452                 :                 /* Check against other new constraints */
    2453                 :                 /* Needed because we don't do CommandCounterIncrement in loop */
    2454             658 :                 foreach(cell2, checknames)
    2455                 :                 {
    2456              19 :                     if (strcmp((char *) lfirst(cell2), ccname) == 0)
    2457 UNC           0 :                         ereport(ERROR,
    2458                 :                                 (errcode(ERRCODE_DUPLICATE_OBJECT),
    2459                 :                                  errmsg("check constraint \"%s\" already exists",
    2460                 :                                         ccname)));
    2461                 :                 }
    2462                 : 
    2463                 :                 /* save name for future checks */
    2464 GNC         639 :                 checknames = lappend(checknames, ccname);
    2465 ECB             : 
    2466                 :                 /*
    2467                 :                  * Check against pre-existing constraints.  If we are allowed
    2468                 :                  * to merge with an existing constraint, there's no more to do
    2469                 :                  * here. (We omit the duplicate constraint from the result,
    2470                 :                  * which is what ATAddCheckConstraint wants.)
    2471                 :                  */
    2472 GNC         627 :                 if (MergeWithExistingConstraint(rel, ccname, expr,
    2473                 :                                                 allow_merge, is_local,
    2474             639 :                                                 cdef->initially_valid,
    2475             639 :                                                 cdef->is_no_inherit))
    2476              38 :                     continue;
    2477                 :             }
    2478                 :             else
    2479                 :             {
    2480                 :                 /*
    2481                 :                  * When generating a name, we want to create "tab_col_check"
    2482                 :                  * for a column constraint and "tab_check" for a table
    2483                 :                  * constraint.  We no longer have any info about the syntactic
    2484                 :                  * positioning of the constraint phrase, so we approximate
    2485                 :                  * this by seeing whether the expression references more than
    2486                 :                  * one column.  (If the user played by the rules, the result
    2487                 :                  * is the same...)
    2488                 :                  *
    2489                 :                  * Note: pull_var_clause() doesn't descend into sublinks, but
    2490                 :                  * we eliminated those above; and anyway this only needs to be
    2491                 :                  * an approximate answer.
    2492                 :                  */
    2493                 :                 List       *vars;
    2494                 :                 char       *colname;
    2495                 : 
    2496             319 :                 vars = pull_var_clause(expr, 0);
    2497 ECB             : 
    2498                 :                 /* eliminate duplicates */
    2499 GNC         319 :                 vars = list_union(NIL, vars);
    2500                 : 
    2501             319 :                 if (list_length(vars) == 1)
    2502             283 :                     colname = get_attname(RelationGetRelid(rel),
    2503             283 :                                           ((Var *) linitial(vars))->varattno,
    2504                 :                                           true);
    2505                 :                 else
    2506              36 :                     colname = NULL;
    2507                 : 
    2508             319 :                 ccname = ChooseConstraintName(RelationGetRelationName(rel),
    2509                 :                                               colname,
    2510                 :                                               "check",
    2511             319 :                                               RelationGetNamespace(rel),
    2512                 :                                               checknames);
    2513                 : 
    2514                 :                 /* save name for future checks */
    2515             319 :                 checknames = lappend(checknames, ccname);
    2516                 :             }
    2517                 : 
    2518                 :             /*
    2519                 :              * OK, store it.
    2520                 :              */
    2521                 :             constrOid =
    2522             908 :                 StoreRelCheck(rel, ccname, expr, cdef->initially_valid, is_local,
    2523             908 :                               is_local ? 0 : 1, cdef->is_no_inherit, is_internal);
    2524                 : 
    2525             896 :             numchecks++;
    2526                 : 
    2527             896 :             cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
    2528             896 :             cooked->contype = CONSTR_CHECK;
    2529             896 :             cooked->conoid = constrOid;
    2530             896 :             cooked->name = ccname;
    2531             896 :             cooked->attnum = 0;
    2532             896 :             cooked->expr = expr;
    2533             896 :             cooked->skip_validation = cdef->skip_validation;
    2534             896 :             cooked->is_local = is_local;
    2535             896 :             cooked->inhcount = is_local ? 0 : 1;
    2536             896 :             cooked->is_no_inherit = cdef->is_no_inherit;
    2537             896 :             cookedConstraints = lappend(cookedConstraints, cooked);
    2538 EUB             :         }
    2539 GNC         430 :         else if (cdef->contype == CONSTR_NOTNULL)
    2540                 :         {
    2541                 :             CookedConstraint *nncooked;
    2542                 :             AttrNumber  colnum;
    2543                 :             char       *nnname;
    2544                 : 
    2545             430 :             colnum = get_attnum(RelationGetRelid(rel),
    2546             430 :                                 cdef->colname);
    2547             430 :             if (colnum == InvalidAttrNumber)
    2548 UNC           0 :                 elog(ERROR, "invalid column name \"%s\"", cdef->colname);
    2549                 : 
    2550 GNC         430 :             if (cdef->conname)
    2551             314 :                 nnname = cdef->conname; /* verify clash? */
    2552                 :             else
    2553             116 :                 nnname = ChooseConstraintName(RelationGetRelationName(rel),
    2554             116 :                                               cdef->colname,
    2555                 :                                               "not_null",
    2556             116 :                                               RelationGetNamespace(rel),
    2557                 :                                               nnnames);
    2558             430 :             nnnames = lappend(nnnames, nnname);
    2559                 : 
    2560                 :             constrOid =
    2561             430 :                 StoreRelNotNull(rel, nnname, colnum,
    2562             430 :                                 cdef->initially_valid,
    2563                 :                                 is_local,
    2564                 :                                 is_local ? 0 : 1,
    2565             430 :                                 cdef->is_no_inherit);
    2566                 : 
    2567             430 :             nncooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
    2568             430 :             nncooked->contype = CONSTR_NOTNULL;
    2569             430 :             nncooked->conoid = constrOid;
    2570             430 :             nncooked->name = nnname;
    2571             430 :             nncooked->attnum = colnum;
    2572             430 :             nncooked->expr = NULL;
    2573             430 :             nncooked->skip_validation = cdef->skip_validation;
    2574             430 :             nncooked->is_local = is_local;
    2575             430 :             nncooked->inhcount = is_local ? 0 : 1;
    2576             430 :             nncooked->is_no_inherit = cdef->is_no_inherit;
    2577                 : 
    2578             430 :             cookedConstraints = lappend(cookedConstraints, nncooked);
    2579                 :         }
    2580                 :     }
    2581                 : 
    2582                 :     /*
    2583                 :      * Update the count of constraints in the relation's pg_class tuple. We do
    2584                 :      * this even if there was no change, in order to ensure that an SI update
    2585                 :      * message is sent out for the pg_class tuple, which will force other
    2586                 :      * backends to rebuild their relcache entries for the rel. (This is
    2587                 :      * critical if we added defaults but not constraints.)
    2588                 :      */
    2589 GIC        2693 :     SetRelationNumChecks(rel, numchecks);
    2590                 : 
    2591            2693 :     return cookedConstraints;
    2592                 : }
    2593                 : 
    2594                 : /*
    2595                 :  * Check for a pre-existing check constraint that conflicts with a proposed
    2596                 :  * new one, and either adjust its conislocal/coninhcount settings or throw
    2597 ECB             :  * error as needed.
    2598                 :  *
    2599                 :  * Returns true if merged (constraint is a duplicate), or false if it's
    2600                 :  * got a so-far-unique name, or throws error if conflict.
    2601                 :  *
    2602                 :  * XXX See MergeConstraintsIntoExisting too if you change this code.
    2603                 :  */
    2604                 : static bool
    2605 GIC         639 : MergeWithExistingConstraint(Relation rel, const char *ccname, Node *expr,
    2606                 :                             bool allow_merge, bool is_local,
    2607 ECB             :                             bool is_initially_valid,
    2608                 :                             bool is_no_inherit)
    2609                 : {
    2610                 :     bool        found;
    2611                 :     Relation    conDesc;
    2612                 :     SysScanDesc conscan;
    2613                 :     ScanKeyData skey[3];
    2614                 :     HeapTuple   tup;
    2615                 : 
    2616                 :     /* Search for a pg_constraint entry with same name and relation */
    2617 GIC         639 :     conDesc = table_open(ConstraintRelationId, RowExclusiveLock);
    2618                 : 
    2619             639 :     found = false;
    2620                 : 
    2621             639 :     ScanKeyInit(&skey[0],
    2622                 :                 Anum_pg_constraint_conrelid,
    2623 ECB             :                 BTEqualStrategyNumber, F_OIDEQ,
    2624                 :                 ObjectIdGetDatum(RelationGetRelid(rel)));
    2625 GIC         639 :     ScanKeyInit(&skey[1],
    2626 ECB             :                 Anum_pg_constraint_contypid,
    2627                 :                 BTEqualStrategyNumber, F_OIDEQ,
    2628                 :                 ObjectIdGetDatum(InvalidOid));
    2629 CBC         639 :     ScanKeyInit(&skey[2],
    2630 ECB             :                 Anum_pg_constraint_conname,
    2631                 :                 BTEqualStrategyNumber, F_NAMEEQ,
    2632                 :                 CStringGetDatum(ccname));
    2633                 : 
    2634 CBC         639 :     conscan = systable_beginscan(conDesc, ConstraintRelidTypidNameIndexId, true,
    2635 ECB             :                                  NULL, 3, skey);
    2636                 : 
    2637                 :     /* There can be at most one matching row */
    2638 CBC         639 :     if (HeapTupleIsValid(tup = systable_getnext(conscan)))
    2639                 :     {
    2640              50 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
    2641                 : 
    2642                 :         /* Found it.  Conflicts if not identical check constraint */
    2643 GIC          50 :         if (con->contype == CONSTRAINT_CHECK)
    2644                 :         {
    2645                 :             Datum       val;
    2646 ECB             :             bool        isnull;
    2647                 : 
    2648 CBC          47 :             val = fastgetattr(tup,
    2649 EUB             :                               Anum_pg_constraint_conbin,
    2650                 :                               conDesc->rd_att, &isnull);
    2651 CBC          47 :             if (isnull)
    2652 LBC           0 :                 elog(ERROR, "null conbin for rel %s",
    2653                 :                      RelationGetRelationName(rel));
    2654 CBC          47 :             if (equal(expr, stringToNode(TextDatumGetCString(val))))
    2655              44 :                 found = true;
    2656                 :         }
    2657 ECB             : 
    2658                 :         /*
    2659                 :          * If the existing constraint is purely inherited (no local
    2660                 :          * definition) then interpret addition of a local constraint as a
    2661                 :          * legal merge.  This allows ALTER ADD CONSTRAINT on parent and child
    2662                 :          * tables to be given in either order with same end state.  However if
    2663                 :          * the relation is a partition, all inherited constraints are always
    2664                 :          * non-local, including those that were merged.
    2665                 :          */
    2666 CBC          50 :         if (is_local && !con->conislocal && !rel->rd_rel->relispartition)
    2667 GIC          18 :             allow_merge = true;
    2668 ECB             : 
    2669 CBC          50 :         if (!found || !allow_merge)
    2670               6 :             ereport(ERROR,
    2671 ECB             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    2672                 :                      errmsg("constraint \"%s\" for relation \"%s\" already exists",
    2673                 :                             ccname, RelationGetRelationName(rel))));
    2674                 : 
    2675                 :         /* If the child constraint is "no inherit" then cannot merge */
    2676 CBC          44 :         if (con->connoinherit)
    2677 LBC           0 :             ereport(ERROR,
    2678                 :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2679 ECB             :                      errmsg("constraint \"%s\" conflicts with non-inherited constraint on relation \"%s\"",
    2680                 :                             ccname, RelationGetRelationName(rel))));
    2681                 : 
    2682                 :         /*
    2683                 :          * Must not change an existing inherited constraint to "no inherit"
    2684                 :          * status.  That's because inherited constraints should be able to
    2685                 :          * propagate to lower-level children.
    2686                 :          */
    2687 GIC          44 :         if (con->coninhcount > 0 && is_no_inherit)
    2688               3 :             ereport(ERROR,
    2689                 :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2690 ECB             :                      errmsg("constraint \"%s\" conflicts with inherited constraint on relation \"%s\"",
    2691                 :                             ccname, RelationGetRelationName(rel))));
    2692                 : 
    2693                 :         /*
    2694                 :          * If the child constraint is "not valid" then cannot merge with a
    2695                 :          * valid parent constraint.
    2696                 :          */
    2697 GIC          41 :         if (is_initially_valid && !con->convalidated)
    2698               3 :             ereport(ERROR,
    2699                 :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2700                 :                      errmsg("constraint \"%s\" conflicts with NOT VALID constraint on relation \"%s\"",
    2701                 :                             ccname, RelationGetRelationName(rel))));
    2702                 : 
    2703                 :         /* OK to update the tuple */
    2704              38 :         ereport(NOTICE,
    2705                 :                 (errmsg("merging constraint \"%s\" with inherited definition",
    2706 ECB             :                         ccname)));
    2707                 : 
    2708 GIC          38 :         tup = heap_copytuple(tup);
    2709              38 :         con = (Form_pg_constraint) GETSTRUCT(tup);
    2710                 : 
    2711                 :         /*
    2712                 :          * In case of partitions, an inherited constraint must be inherited
    2713                 :          * only once since it cannot have multiple parents and it is never
    2714                 :          * considered local.
    2715                 :          */
    2716              38 :         if (rel->rd_rel->relispartition)
    2717                 :         {
    2718 CBC           6 :             con->coninhcount = 1;
    2719 GIC           6 :             con->conislocal = false;
    2720 ECB             :         }
    2721                 :         else
    2722                 :         {
    2723 GIC          32 :             if (is_local)
    2724              15 :                 con->conislocal = true;
    2725                 :             else
    2726 CBC          17 :                 con->coninhcount++;
    2727                 : 
    2728 GNC          32 :             if (con->coninhcount < 0)
    2729 UNC           0 :                 ereport(ERROR,
    2730                 :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2731                 :                         errmsg("too many inheritance parents"));
    2732                 :         }
    2733                 : 
    2734 GIC          38 :         if (is_no_inherit)
    2735 ECB             :         {
    2736 UIC           0 :             Assert(is_local);
    2737               0 :             con->connoinherit = true;
    2738                 :         }
    2739                 : 
    2740 CBC          38 :         CatalogTupleUpdate(conDesc, &tup->t_self, tup);
    2741                 :     }
    2742                 : 
    2743 GIC         627 :     systable_endscan(conscan);
    2744 CBC         627 :     table_close(conDesc, RowExclusiveLock);
    2745                 : 
    2746             627 :     return found;
    2747                 : }
    2748                 : 
    2749                 : /* list_sort comparator to sort CookedConstraint by attnum */
    2750                 : static int
    2751 GNC         106 : list_cookedconstr_attnum_cmp(const ListCell *p1, const ListCell *p2)
    2752                 : {
    2753             106 :     AttrNumber  v1 = ((CookedConstraint *) lfirst(p1))->attnum;
    2754             106 :     AttrNumber  v2 = ((CookedConstraint *) lfirst(p2))->attnum;
    2755                 : 
    2756             106 :     if (v1 < v2)
    2757              67 :         return -1;
    2758              39 :     if (v1 > v2)
    2759               3 :         return 1;
    2760              36 :     return 0;
    2761                 : }
    2762                 : 
    2763                 : /*
    2764                 :  * Create the NOT NULL constraints for the relation
    2765                 :  *
    2766                 :  * These come from two sources: the 'constraints' list (of Constraint) is
    2767                 :  * specified directly by the user; the 'old_notnulls' list (of
    2768                 :  * CookedConstraint) comes from inheritance.  We create one constraint
    2769                 :  * for each column, giving priority to user-specified ones, and setting
    2770                 :  * inhcount according to how many parents cause each column to get a
    2771                 :  * NOT NULL constraint.  If a user-specified name clashes with another
    2772                 :  * user-specified name, an error is raised.
    2773                 :  *
    2774                 :  * Note that inherited constraints have two shapes: those coming from another
    2775                 :  * NOT NULL constraint in the parent, which have a name already, and those
    2776                 :  * coming from a PRIMARY KEY in the parent, which don't.  Any name specified
    2777                 :  * in a parent is disregarded in case of a conflict.
    2778                 :  *
    2779                 :  * Returns a list of AttrNumber for columns that need to have the attnotnull
    2780                 :  * flag set.
    2781                 :  */
    2782                 : List *
    2783           62424 : AddRelationNotNullConstraints(Relation rel, List *constraints,
    2784                 :                               List *old_notnulls)
    2785                 : {
    2786           62424 :     List       *nnnames = NIL;
    2787           62424 :     List       *givennames = NIL;
    2788           62424 :     List       *nncols = NIL;
    2789                 :     ListCell   *lc;
    2790                 : 
    2791                 :     /*
    2792                 :      * First, create all NOT NULLs that are directly specified by the user.
    2793                 :      * Note that inheritance might have given us another source for each, so
    2794                 :      * we must scan the old_notnulls list and increment inhcount for each
    2795                 :      * element with identical attnum.  We delete from there any element that
    2796                 :      * we process.
    2797                 :      */
    2798           65360 :     foreach(lc, constraints)
    2799                 :     {
    2800            2936 :         Constraint *constr = lfirst_node(Constraint, lc);
    2801                 :         AttrNumber  attnum;
    2802                 :         char       *conname;
    2803            2936 :         bool        is_local = true;
    2804            2936 :         int         inhcount = 0;
    2805                 :         ListCell   *lc2;
    2806                 : 
    2807            2936 :         attnum = get_attnum(RelationGetRelid(rel), constr->colname);
    2808                 : 
    2809            2958 :         foreach(lc2, old_notnulls)
    2810                 :         {
    2811              22 :             CookedConstraint *old = (CookedConstraint *) lfirst(lc2);
    2812                 : 
    2813              22 :             if (old->attnum == attnum)
    2814                 :             {
    2815              13 :                 inhcount++;
    2816              13 :                 old_notnulls = foreach_delete_current(old_notnulls, lc2);
    2817                 :             }
    2818                 :         }
    2819                 : 
    2820                 :         /*
    2821                 :          * Determine a constraint name, which may have been specified by the
    2822                 :          * user, or raise an error if a conflict exists with another
    2823                 :          * user-specified name.
    2824                 :          */
    2825            2936 :         if (constr->conname)
    2826                 :         {
    2827 UNC           0 :             foreach(lc2, givennames)
    2828                 :             {
    2829               0 :                 if (strcmp(lfirst(lc2), conname) == 0)
    2830               0 :                     ereport(ERROR,
    2831                 :                             errmsg("constraint name \"%s\" is already in use in relation \"%s\"",
    2832                 :                                    constr->conname,
    2833                 :                                    RelationGetRelationName(rel)));
    2834                 :             }
    2835                 : 
    2836               0 :             conname = constr->conname;
    2837               0 :             givennames = lappend(givennames, conname);
    2838                 :         }
    2839                 :         else
    2840 GNC        2936 :             conname = ChooseConstraintName(RelationGetRelationName(rel),
    2841            2936 :                                            get_attname(RelationGetRelid(rel),
    2842                 :                                                        attnum, false),
    2843                 :                                            "not_null",
    2844            2936 :                                            RelationGetNamespace(rel),
    2845                 :                                            nnnames);
    2846            2936 :         nnnames = lappend(nnnames, conname);
    2847                 : 
    2848            2936 :         StoreRelNotNull(rel, conname,
    2849                 :                         attnum, true, is_local,
    2850            2936 :                         inhcount, constr->is_no_inherit);
    2851                 : 
    2852            2936 :         nncols = lappend_int(nncols, attnum);
    2853                 :     }
    2854                 : 
    2855                 :     /*
    2856                 :      * If any column remains in the additional_notnulls list, we must create a
    2857                 :      * NOT NULL constraint marked not-local.  Because multiple parents could
    2858                 :      * specify a NOT NULL for the same column, we must count how many there
    2859                 :      * are and set inhcount accordingly, deleting elements we've already
    2860                 :      * processed.
    2861                 :      *
    2862                 :      * We don't use foreach() here because we have two nested loops over the
    2863                 :      * cooked constraint list, with possible element deletions in the inner one.
    2864                 :      * If we used foreach_delete_current() it could only fix up the state of one
    2865                 :      * of the loops, so it seems cleaner to use looping over list indexes for
    2866                 :      * both loops.  Note that any deletion will happen beyond where the outer
    2867                 :      * loop is, so its index never needs adjustment.
    2868                 :      */
    2869           62424 :     list_sort(old_notnulls, list_cookedconstr_attnum_cmp);
    2870           62741 :     for (int outerpos = 0; outerpos < list_length(old_notnulls); outerpos++)
    2871                 :     {
    2872                 :         CookedConstraint *cooked;
    2873             317 :         char       *conname = NULL;
    2874             317 :         int         inhcount = 1;
    2875                 :         ListCell   *lc2;
    2876                 : 
    2877             317 :         cooked = (CookedConstraint *) list_nth(old_notnulls, outerpos);
    2878                 : 
    2879                 :         /* We just preserve the first constraint name we come across, if any */
    2880             317 :         if (conname == NULL && cooked->name)
    2881             243 :             conname = cooked->name;
    2882                 : 
    2883             423 :         for (int restpos = outerpos + 1; restpos < list_length(old_notnulls);)
    2884                 :         {
    2885                 :             CookedConstraint *other;
    2886                 : 
    2887             106 :             other = (CookedConstraint *) list_nth(old_notnulls, restpos);
    2888             106 :             if (other->attnum == cooked->attnum)
    2889                 :             {
    2890              36 :                 if (conname == NULL && other->name)
    2891              26 :                     conname = other->name;
    2892                 : 
    2893              36 :                 inhcount++;
    2894              36 :                 old_notnulls = list_delete_nth_cell(old_notnulls, restpos);
    2895                 :             }
    2896                 :             else
    2897              70 :                 restpos++;
    2898                 :         }
    2899                 : 
    2900                 :         /* If we got a name, make sure it isn't one we've already used */
    2901             317 :         if (conname != NULL)
    2902                 :         {
    2903             345 :             foreach(lc2, nnnames)
    2904                 :             {
    2905              76 :                 if (strcmp(lfirst(lc2), conname) == 0)
    2906                 :                 {
    2907 UNC           0 :                     conname = NULL;
    2908               0 :                     break;
    2909                 :                 }
    2910                 :             }
    2911                 :         }
    2912                 : 
    2913                 :         /* and choose a name, if needed */
    2914 GNC         317 :         if (conname == NULL)
    2915              48 :             conname = ChooseConstraintName(RelationGetRelationName(rel),
    2916              48 :                                            get_attname(RelationGetRelid(rel),
    2917              48 :                                                        cooked->attnum, false),
    2918                 :                                            "not_null",
    2919              48 :                                            RelationGetNamespace(rel),
    2920                 :                                            nnnames);
    2921             317 :         nnnames = lappend(nnnames, conname);
    2922                 : 
    2923             317 :         StoreRelNotNull(rel, conname, cooked->attnum, true,
    2924                 :                         false, inhcount,
    2925             317 :                         cooked->is_no_inherit);
    2926                 : 
    2927             317 :         nncols = lappend_int(nncols, cooked->attnum);
    2928                 :     }
    2929                 : 
    2930           62424 :     return nncols;
    2931                 : }
    2932                 : 
    2933 ECB             : /*
    2934                 :  * Update the count of constraints in the relation's pg_class tuple.
    2935                 :  *
    2936                 :  * Caller had better hold exclusive lock on the relation.
    2937                 :  *
    2938                 :  * An important side effect is that a SI update message will be sent out for
    2939                 :  * the pg_class tuple, which will force other backends to rebuild their
    2940                 :  * relcache entries for the rel.  Also, this backend will rebuild its
    2941                 :  * own relcache entry at the next CommandCounterIncrement.
    2942 EUB             :  */
    2943                 : static void
    2944 CBC        2761 : SetRelationNumChecks(Relation rel, int numchecks)
    2945 ECB             : {
    2946                 :     Relation    relrel;
    2947                 :     HeapTuple   reltup;
    2948                 :     Form_pg_class relStruct;
    2949                 : 
    2950 GIC        2761 :     relrel = table_open(RelationRelationId, RowExclusiveLock);
    2951            2761 :     reltup = SearchSysCacheCopy1(RELOID,
    2952                 :                                  ObjectIdGetDatum(RelationGetRelid(rel)));
    2953            2761 :     if (!HeapTupleIsValid(reltup))
    2954 UIC           0 :         elog(ERROR, "cache lookup failed for relation %u",
    2955                 :              RelationGetRelid(rel));
    2956 CBC        2761 :     relStruct = (Form_pg_class) GETSTRUCT(reltup);
    2957 ECB             : 
    2958 GIC        2761 :     if (relStruct->relchecks != numchecks)
    2959 ECB             :     {
    2960 CBC         917 :         relStruct->relchecks = numchecks;
    2961                 : 
    2962 GIC         917 :         CatalogTupleUpdate(relrel, &reltup->t_self, reltup);
    2963                 :     }
    2964                 :     else
    2965                 :     {
    2966 ECB             :         /* Skip the disk update, but force relcache inval anyway */
    2967 GBC        1844 :         CacheInvalidateRelcache(rel);
    2968                 :     }
    2969                 : 
    2970 GIC        2761 :     heap_freetuple(reltup);
    2971            2761 :     table_close(relrel, RowExclusiveLock);
    2972            2761 : }
    2973                 : 
    2974                 : /*
    2975                 :  * Check for references to generated columns
    2976                 :  */
    2977 ECB             : static bool
    2978 CBC        1235 : check_nested_generated_walker(Node *node, void *context)
    2979                 : {
    2980 GIC        1235 :     ParseState *pstate = context;
    2981                 : 
    2982            1235 :     if (node == NULL)
    2983 UIC           0 :         return false;
    2984 GIC        1235 :     else if (IsA(node, Var))
    2985                 :     {
    2986             461 :         Var        *var = (Var *) node;
    2987 ECB             :         Oid         relid;
    2988                 :         AttrNumber  attnum;
    2989                 : 
    2990 GIC         461 :         relid = rt_fetch(var->varno, pstate->p_rtable)->relid;
    2991             461 :         if (!OidIsValid(relid))
    2992 UIC           0 :             return false;       /* XXX shouldn't we raise an error? */
    2993                 : 
    2994 CBC         461 :         attnum = var->varattno;
    2995                 : 
    2996 GIC         461 :         if (attnum > 0 && get_attgenerated(relid, attnum))
    2997               9 :             ereport(ERROR,
    2998 ECB             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2999                 :                      errmsg("cannot use generated column \"%s\" in column generation expression",
    3000                 :                             get_attname(relid, attnum, false)),
    3001                 :                      errdetail("A generated column cannot reference another generated column."),
    3002                 :                      parser_errposition(pstate, var->location)));
    3003                 :         /* A whole-row Var is necessarily self-referential, so forbid it */
    3004 GIC         452 :         if (attnum == 0)
    3005               3 :             ereport(ERROR,
    3006 ECB             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3007                 :                      errmsg("cannot use whole-row variable in column generation expression"),
    3008                 :                      errdetail("This would cause the generated column to depend on its own value."),
    3009                 :                      parser_errposition(pstate, var->location)));
    3010                 :         /* System columns were already checked in the parser */
    3011                 : 
    3012 GIC         449 :         return false;
    3013 ECB             :     }
    3014                 :     else
    3015 GIC         774 :         return expression_tree_walker(node, check_nested_generated_walker,
    3016 ECB             :                                       (void *) context);
    3017                 : }
    3018                 : 
    3019 EUB             : static void
    3020 GIC         370 : check_nested_generated(ParseState *pstate, Node *node)
    3021                 : {
    3022             370 :     check_nested_generated_walker(node, pstate);
    3023             358 : }
    3024 ECB             : 
    3025                 : /*
    3026 EUB             :  * Take a raw default and convert it to a cooked format ready for
    3027                 :  * storage.
    3028                 :  *
    3029                 :  * Parse state should be set up to recognize any vars that might appear
    3030 ECB             :  * in the expression.  (Even though we plan to reject vars, it's more
    3031                 :  * user-friendly to give the correct error message than "unknown var".)
    3032                 :  *
    3033                 :  * If atttypid is not InvalidOid, coerce the expression to the specified
    3034                 :  * type (and typmod atttypmod).   attname is only needed in this case:
    3035                 :  * it is used in the error message, if any.
    3036                 :  */
    3037                 : Node *
    3038 GIC        1946 : cookDefault(ParseState *pstate,
    3039                 :             Node *raw_default,
    3040                 :             Oid atttypid,
    3041 ECB             :             int32 atttypmod,
    3042                 :             const char *attname,
    3043                 :             char attgenerated)
    3044                 : {
    3045                 :     Node       *expr;
    3046                 : 
    3047 CBC        1946 :     Assert(raw_default != NULL);
    3048 ECB             : 
    3049                 :     /*
    3050                 :      * Transform raw parsetree to executable expression.
    3051                 :      */
    3052 GIC        1946 :     expr = transformExpr(pstate, raw_default, attgenerated ? EXPR_KIND_GENERATED_COLUMN : EXPR_KIND_COLUMN_DEFAULT);
    3053                 : 
    3054            1904 :     if (attgenerated)
    3055                 :     {
    3056             370 :         check_nested_generated(pstate, expr);
    3057                 : 
    3058             358 :         if (contain_mutable_functions(expr))
    3059               3 :             ereport(ERROR,
    3060                 :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3061                 :                      errmsg("generation expression is not immutable")));
    3062                 :     }
    3063                 :     else
    3064                 :     {
    3065                 :         /*
    3066                 :          * For a default expression, transformExpr() should have rejected
    3067                 :          * column references.
    3068                 :          */
    3069            1534 :         Assert(!contain_var_clause(expr));
    3070                 :     }
    3071                 : 
    3072                 :     /*
    3073 ECB             :      * Coerce the expression to the correct type and typmod, if given. This
    3074                 :      * should match the parser's processing of non-defaulted expressions ---
    3075                 :      * see transformAssignedExpr().
    3076                 :      */
    3077 CBC        1889 :     if (OidIsValid(atttypid))
    3078 ECB             :     {
    3079 GIC        1889 :         Oid         type_id = exprType(expr);
    3080                 : 
    3081            1889 :         expr = coerce_to_target_type(pstate, expr, type_id,
    3082                 :                                      atttypid, atttypmod,
    3083                 :                                      COERCION_ASSIGNMENT,
    3084                 :                                      COERCE_IMPLICIT_CAST,
    3085                 :                                      -1);
    3086            1886 :         if (expr == NULL)
    3087 UIC           0 :             ereport(ERROR,
    3088 ECB             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3089                 :                      errmsg("column \"%s\" is of type %s"
    3090                 :                             " but default expression is of type %s",
    3091                 :                             attname,
    3092                 :                             format_type_be(atttypid),
    3093                 :                             format_type_be(type_id)),
    3094                 :                      errhint("You will need to rewrite or cast the expression.")));
    3095                 :     }
    3096                 : 
    3097                 :     /*
    3098                 :      * Finally, take care of collations in the finished expression.
    3099                 :      */
    3100 GIC        1886 :     assign_expr_collations(pstate, expr);
    3101 ECB             : 
    3102 GIC        1886 :     return expr;
    3103 ECB             : }
    3104                 : 
    3105                 : /*
    3106                 :  * Take a raw CHECK constraint expression and convert it to a cooked format
    3107                 :  * ready for storage.
    3108                 :  *
    3109                 :  * Parse state must be set up to recognize any vars that might appear
    3110                 :  * in the expression.
    3111                 :  */
    3112                 : static Node *
    3113 GIC         858 : cookConstraint(ParseState *pstate,
    3114                 :                Node *raw_constraint,
    3115 ECB             :                char *relname)
    3116                 : {
    3117 EUB             :     Node       *expr;
    3118                 : 
    3119                 :     /*
    3120                 :      * Transform raw parsetree to executable expression.
    3121                 :      */
    3122 GIC         858 :     expr = transformExpr(pstate, raw_constraint, EXPR_KIND_CHECK_CONSTRAINT);
    3123                 : 
    3124                 :     /*
    3125                 :      * Make sure it yields a boolean result.
    3126 EUB             :      */
    3127 GBC         843 :     expr = coerce_to_boolean(pstate, expr, "CHECK");
    3128                 : 
    3129                 :     /*
    3130 ECB             :      * Take care of collations.
    3131                 :      */
    3132 GIC         843 :     assign_expr_collations(pstate, expr);
    3133                 : 
    3134 ECB             :     /*
    3135                 :      * Make sure no outside relations are referred to (this is probably dead
    3136                 :      * code now that add_missing_from is history).
    3137                 :      */
    3138 CBC         843 :     if (list_length(pstate->p_rtable) != 1)
    3139 UIC           0 :         ereport(ERROR,
    3140 ECB             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    3141                 :                  errmsg("only table \"%s\" can be referenced in check constraint",
    3142                 :                         relname)));
    3143                 : 
    3144 GIC         843 :     return expr;
    3145                 : }
    3146                 : 
    3147                 : /*
    3148                 :  * CopyStatistics --- copy entries in pg_statistic from one rel to another
    3149                 :  */
    3150                 : void
    3151             207 : CopyStatistics(Oid fromrelid, Oid torelid)
    3152                 : {
    3153                 :     HeapTuple   tup;
    3154                 :     SysScanDesc scan;
    3155                 :     ScanKeyData key[1];
    3156                 :     Relation    statrel;
    3157 GNC         207 :     CatalogIndexState indstate = NULL;
    3158                 : 
    3159 GIC         207 :     statrel = table_open(StatisticRelationId, RowExclusiveLock);
    3160 ECB             : 
    3161                 :     /* Now search for stat records */
    3162 GIC         207 :     ScanKeyInit(&key[0],
    3163                 :                 Anum_pg_statistic_starelid,
    3164 ECB             :                 BTEqualStrategyNumber, F_OIDEQ,
    3165                 :                 ObjectIdGetDatum(fromrelid));
    3166                 : 
    3167 GIC         207 :     scan = systable_beginscan(statrel, StatisticRelidAttnumInhIndexId,
    3168 ECB             :                               true, NULL, 1, key);
    3169                 : 
    3170 GIC         210 :     while (HeapTupleIsValid((tup = systable_getnext(scan))))
    3171 ECB             :     {
    3172                 :         Form_pg_statistic statform;
    3173                 : 
    3174                 :         /* make a modifiable copy */
    3175 GIC           3 :         tup = heap_copytuple(tup);
    3176               3 :         statform = (Form_pg_statistic) GETSTRUCT(tup);
    3177                 : 
    3178 ECB             :         /* update the copy of the tuple and insert it */
    3179 CBC           3 :         statform->starelid = torelid;
    3180                 : 
    3181                 :         /* fetch index information when we know we need it */
    3182 GNC           3 :         if (indstate == NULL)
    3183               3 :             indstate = CatalogOpenIndexes(statrel);
    3184                 : 
    3185               3 :         CatalogTupleInsertWithInfo(statrel, tup, indstate);
    3186 ECB             : 
    3187 CBC           3 :         heap_freetuple(tup);
    3188                 :     }
    3189 ECB             : 
    3190 CBC         207 :     systable_endscan(scan);
    3191                 : 
    3192 GNC         207 :     if (indstate != NULL)
    3193               3 :         CatalogCloseIndexes(indstate);
    3194 GIC         207 :     table_close(statrel, RowExclusiveLock);
    3195 CBC         207 : }
    3196                 : 
    3197                 : /*
    3198                 :  * RemoveStatistics --- remove entries in pg_statistic for a rel or column
    3199 ECB             :  *
    3200                 :  * If attnum is zero, remove all entries for rel; else remove only the one(s)
    3201                 :  * for that column.
    3202                 :  */
    3203                 : void
    3204 GIC       20880 : RemoveStatistics(Oid relid, AttrNumber attnum)
    3205 EUB             : {
    3206                 :     Relation    pgstatistic;
    3207                 :     SysScanDesc scan;
    3208                 :     ScanKeyData key[2];
    3209                 :     int         nkeys;
    3210                 :     HeapTuple   tuple;
    3211                 : 
    3212 CBC       20880 :     pgstatistic = table_open(StatisticRelationId, RowExclusiveLock);
    3213 ECB             : 
    3214 CBC       20880 :     ScanKeyInit(&key[0],
    3215 ECB             :                 Anum_pg_statistic_starelid,
    3216                 :                 BTEqualStrategyNumber, F_OIDEQ,
    3217                 :                 ObjectIdGetDatum(relid));
    3218                 : 
    3219 CBC       20880 :     if (attnum == 0)
    3220 GIC       19458 :         nkeys = 1;
    3221 ECB             :     else
    3222                 :     {
    3223 CBC        1422 :         ScanKeyInit(&key[1],
    3224                 :                     Anum_pg_statistic_staattnum,
    3225 ECB             :                     BTEqualStrategyNumber, F_INT2EQ,
    3226                 :                     Int16GetDatum(attnum));
    3227 GIC        1422 :         nkeys = 2;
    3228 ECB             :     }
    3229                 : 
    3230 GIC       20880 :     scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
    3231                 :                               NULL, nkeys, key);
    3232                 : 
    3233                 :     /* we must loop even when attnum != 0, in case of inherited stats */
    3234           22236 :     while (HeapTupleIsValid(tuple = systable_getnext(scan)))
    3235            1356 :         CatalogTupleDelete(pgstatistic, &tuple->t_self);
    3236                 : 
    3237           20880 :     systable_endscan(scan);
    3238                 : 
    3239           20880 :     table_close(pgstatistic, RowExclusiveLock);
    3240           20880 : }
    3241                 : 
    3242 ECB             : 
    3243                 : /*
    3244                 :  * RelationTruncateIndexes - truncate all indexes associated
    3245                 :  * with the heap relation to zero tuples.
    3246                 :  *
    3247                 :  * The routine will truncate and then reconstruct the indexes on
    3248                 :  * the specified relation.  Caller must hold exclusive lock on rel.
    3249                 :  */
    3250                 : static void
    3251 CBC         262 : RelationTruncateIndexes(Relation heapRelation)
    3252 EUB             : {
    3253                 :     ListCell   *indlist;
    3254 ECB             : 
    3255                 :     /* Ask the relcache to produce a list of the indexes of the rel */
    3256 CBC         359 :     foreach(indlist, RelationGetIndexList(heapRelation))
    3257                 :     {
    3258              97 :         Oid         indexId = lfirst_oid(indlist);
    3259                 :         Relation    currentIndex;
    3260 ECB             :         IndexInfo  *indexInfo;
    3261                 : 
    3262                 :         /* Open the index relation; use exclusive lock, just to be sure */
    3263 GIC          97 :         currentIndex = index_open(indexId, AccessExclusiveLock);
    3264                 : 
    3265 ECB             :         /*
    3266                 :          * Fetch info needed for index_build.  Since we know there are no
    3267                 :          * tuples that actually need indexing, we can use a dummy IndexInfo.
    3268                 :          * This is slightly cheaper to build, but the real point is to avoid
    3269                 :          * possibly running user-defined code in index expressions or
    3270                 :          * predicates.  We might be getting invoked during ON COMMIT
    3271                 :          * processing, and we don't want to run any such code then.
    3272                 :          */
    3273 GIC          97 :         indexInfo = BuildDummyIndexInfo(currentIndex);
    3274                 : 
    3275                 :         /*
    3276 ECB             :          * Now truncate the actual file (and discard buffers).
    3277                 :          */
    3278 CBC          97 :         RelationTruncate(currentIndex, 0);
    3279                 : 
    3280 ECB             :         /* Initialize the index and rebuild */
    3281 EUB             :         /* Note: we do not need to re-establish pkey setting */
    3282 CBC          97 :         index_build(heapRelation, currentIndex, indexInfo, true, false);
    3283                 : 
    3284 ECB             :         /* We're done with this index */
    3285 GIC          97 :         index_close(currentIndex, NoLock);
    3286                 :     }
    3287             262 : }
    3288 ECB             : 
    3289                 : /*
    3290 EUB             :  *   heap_truncate
    3291                 :  *
    3292 ECB             :  *   This routine deletes all data within all the specified relations.
    3293                 :  *
    3294                 :  * This is not transaction-safe!  There is another, transaction-safe
    3295                 :  * implementation in commands/tablecmds.c.  We now use this only for
    3296                 :  * ON COMMIT truncation of temporary tables, where it doesn't matter.
    3297                 :  */
    3298                 : void
    3299 GIC         167 : heap_truncate(List *relids)
    3300                 : {
    3301             167 :     List       *relations = NIL;
    3302 ECB             :     ListCell   *cell;
    3303                 : 
    3304                 :     /* Open relations for processing, and grab exclusive access on each */
    3305 GIC         367 :     foreach(cell, relids)
    3306                 :     {
    3307             200 :         Oid         rid = lfirst_oid(cell);
    3308                 :         Relation    rel;
    3309                 : 
    3310 CBC         200 :         rel = table_open(rid, AccessExclusiveLock);
    3311 GIC         200 :         relations = lappend(relations, rel);
    3312                 :     }
    3313 ECB             : 
    3314                 :     /* Don't allow truncate on tables that are referenced by foreign keys */
    3315 GIC         167 :     heap_truncate_check_FKs(relations, true);
    3316                 : 
    3317                 :     /* OK to do it */
    3318 CBC         358 :     foreach(cell, relations)
    3319                 :     {
    3320             194 :         Relation    rel = lfirst(cell);
    3321 ECB             : 
    3322                 :         /* Truncate the relation */
    3323 GIC         194 :         heap_truncate_one_rel(rel);
    3324                 : 
    3325                 :         /* Close the relation, but keep exclusive lock on it until commit */
    3326             194 :         table_close(rel, NoLock);
    3327                 :     }
    3328             164 : }
    3329                 : 
    3330                 : /*
    3331                 :  *   heap_truncate_one_rel
    3332                 :  *
    3333                 :  *   This routine deletes all data within the specified relation.
    3334                 :  *
    3335                 :  * This is not transaction-safe, because the truncation is done immediately
    3336 ECB             :  * and cannot be rolled back later.  Caller is responsible for having
    3337                 :  * checked permissions etc, and must have obtained AccessExclusiveLock.
    3338                 :  */
    3339                 : void
    3340 GIC         218 : heap_truncate_one_rel(Relation rel)
    3341                 : {
    3342                 :     Oid         toastrelid;
    3343                 : 
    3344                 :     /*
    3345 ECB             :      * Truncate the relation.  Partitioned tables have no storage, so there is
    3346                 :      * nothing to do for them here.
    3347                 :      */
    3348 GIC         218 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    3349              12 :         return;
    3350 ECB             : 
    3351                 :     /* Truncate the underlying relation */
    3352 CBC         206 :     table_relation_nontransactional_truncate(rel);
    3353                 : 
    3354 ECB             :     /* If the relation has indexes, truncate the indexes too */
    3355 GIC         206 :     RelationTruncateIndexes(rel);
    3356 ECB             : 
    3357                 :     /* If there is a toast table, truncate that too */
    3358 GIC         206 :     toastrelid = rel->rd_rel->reltoastrelid;
    3359             206 :     if (OidIsValid(toastrelid))
    3360                 :     {
    3361              56 :         Relation    toastrel = table_open(toastrelid, AccessExclusiveLock);
    3362                 : 
    3363              56 :         table_relation_nontransactional_truncate(toastrel);
    3364              56 :         RelationTruncateIndexes(toastrel);
    3365                 :         /* keep the lock... */
    3366              56 :         table_close(toastrel, NoLock);
    3367 ECB             :     }
    3368                 : }
    3369                 : 
    3370                 : /*
    3371                 :  * heap_truncate_check_FKs
    3372                 :  *      Check for foreign keys referencing a list of relations that
    3373                 :  *      are to be truncated, and raise error if there are any
    3374                 :  *
    3375                 :  * We disallow such FKs (except self-referential ones) since the whole point
    3376                 :  * of TRUNCATE is to not scan the individual rows to be thrown away.
    3377                 :  *
    3378                 :  * This is split out so it can be shared by both implementations of truncate.
    3379                 :  * Caller should already hold a suitable lock on the relations.
    3380                 :  *
    3381                 :  * tempTables is only used to select an appropriate error message.
    3382                 :  */
    3383                 : void
    3384 CBC         801 : heap_truncate_check_FKs(List *relations, bool tempTables)
    3385 EUB             : {
    3386 GIC         801 :     List       *oids = NIL;
    3387                 :     List       *dependents;
    3388                 :     ListCell   *cell;
    3389                 : 
    3390                 :     /*
    3391                 :      * Build a list of OIDs of the interesting relations.
    3392                 :      *
    3393                 :      * If a relation has no triggers, then it can neither have FKs nor be
    3394                 :      * referenced by a FK from another table, so we can ignore it.  For
    3395                 :      * partitioned tables, FKs have no triggers, so we must include them
    3396                 :      * anyway.
    3397                 :      */
    3398 CBC        2612 :     foreach(cell, relations)
    3399                 :     {
    3400            1811 :         Relation    rel = lfirst(cell);
    3401                 : 
    3402 GIC        1811 :         if (rel->rd_rel->relhastriggers ||
    3403            1246 :             rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    3404             807 :             oids = lappend_oid(oids, RelationGetRelid(rel));
    3405                 :     }
    3406                 : 
    3407                 :     /*
    3408                 :      * Fast path: if no relation has triggers, none has FKs either.
    3409                 :      */
    3410             801 :     if (oids == NIL)
    3411 CBC         471 :         return;
    3412                 : 
    3413                 :     /*
    3414                 :      * Otherwise, must scan pg_constraint.  We make one pass with all the
    3415                 :      * relations considered; if this finds nothing, then all is well.
    3416                 :      */
    3417 GIC         330 :     dependents = heap_truncate_find_FKs(oids);
    3418             330 :     if (dependents == NIL)
    3419             290 :         return;
    3420 ECB             : 
    3421                 :     /*
    3422                 :      * Otherwise we repeat the scan once per relation to identify a particular
    3423                 :      * pair of relations to complain about.  This is pretty slow, but
    3424                 :      * performance shouldn't matter much in a failure path.  The reason for
    3425                 :      * doing things this way is to ensure that the message produced is not
    3426                 :      * dependent on chance row locations within pg_constraint.
    3427                 :      */
    3428 GIC          52 :     foreach(cell, oids)
    3429                 :     {
    3430 CBC          52 :         Oid         relid = lfirst_oid(cell);
    3431                 :         ListCell   *cell2;
    3432                 : 
    3433 GIC          52 :         dependents = heap_truncate_find_FKs(list_make1_oid(relid));
    3434                 : 
    3435              82 :         foreach(cell2, dependents)
    3436 ECB             :         {
    3437 GBC          70 :             Oid         relid2 = lfirst_oid(cell2);
    3438                 : 
    3439 GIC          70 :             if (!list_member_oid(oids, relid2))
    3440                 :             {
    3441              40 :                 char       *relname = get_rel_name(relid);
    3442 CBC          40 :                 char       *relname2 = get_rel_name(relid2);
    3443                 : 
    3444 GIC          40 :                 if (tempTables)
    3445               3 :                     ereport(ERROR,
    3446                 :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3447                 :                              errmsg("unsupported ON COMMIT and foreign key combination"),
    3448                 :                              errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
    3449 ECB             :                                        relname2, relname)));
    3450                 :                 else
    3451 GIC          37 :                     ereport(ERROR,
    3452                 :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3453                 :                              errmsg("cannot truncate a table referenced in a foreign key constraint"),
    3454                 :                              errdetail("Table \"%s\" references \"%s\".",
    3455 ECB             :                                        relname2, relname),
    3456                 :                              errhint("Truncate table \"%s\" at the same time, "
    3457                 :                                      "or use TRUNCATE ... CASCADE.",
    3458                 :                                      relname2)));
    3459                 :             }
    3460                 :         }
    3461                 :     }
    3462                 : }
    3463                 : 
    3464                 : /*
    3465                 :  * heap_truncate_find_FKs
    3466                 :  *      Find relations having foreign keys referencing any of the given rels
    3467                 :  *
    3468                 :  * Input and result are both lists of relation OIDs.  The result contains
    3469                 :  * no duplicates, does *not* include any rels that were already in the input
    3470                 :  * list, and is sorted in OID order.  (The last property is enforced mainly
    3471                 :  * to guarantee consistent behavior in the regression tests; we don't want
    3472                 :  * behavior to change depending on chance locations of rows in pg_constraint.)
    3473                 :  *
    3474                 :  * Note: caller should already have appropriate lock on all rels mentioned
    3475                 :  * in relationIds.  Since adding or dropping an FK requires exclusive lock
    3476                 :  * on both rels, this ensures that the answer will be stable.
    3477                 :  */
    3478                 : List *
    3479 GIC         422 : heap_truncate_find_FKs(List *relationIds)
    3480 ECB             : {
    3481 CBC         422 :     List       *result = NIL;
    3482                 :     List       *oids;
    3483 ECB             :     List       *parent_cons;
    3484                 :     ListCell   *cell;
    3485                 :     ScanKeyData key;
    3486                 :     Relation    fkeyRel;
    3487                 :     SysScanDesc fkeyScan;
    3488                 :     HeapTuple   tuple;
    3489                 :     bool        restart;
    3490                 : 
    3491 CBC         422 :     oids = list_copy(relationIds);
    3492 ECB             : 
    3493                 :     /*
    3494                 :      * Must scan pg_constraint.  Right now, it is a seqscan because there is
    3495                 :      * no available index on confrelid.
    3496                 :      */
    3497 GIC         422 :     fkeyRel = table_open(ConstraintRelationId, AccessShareLock);
    3498                 : 
    3499             440 : restart:
    3500             440 :     restart = false;
    3501             440 :     parent_cons = NIL;
    3502 ECB             : 
    3503 GIC         440 :     fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
    3504                 :                                   NULL, 0, NULL);
    3505                 : 
    3506          122864 :     while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
    3507                 :     {
    3508          122424 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
    3509                 : 
    3510 ECB             :         /* Not a foreign key */
    3511 GIC      122424 :         if (con->contype != CONSTRAINT_FOREIGN)
    3512 CBC      104302 :             continue;
    3513                 : 
    3514                 :         /* Not referencing one of our list of tables */
    3515 GIC       18122 :         if (!list_member_oid(oids, con->confrelid))
    3516           17641 :             continue;
    3517 ECB             : 
    3518                 :         /*
    3519                 :          * If this constraint has a parent constraint which we have not seen
    3520                 :          * yet, keep track of it for the second loop, below.  Tracking parent
    3521                 :          * constraints allows us to climb up to the top-level constraint and
    3522                 :          * look for all possible relations referencing the partitioned table.
    3523                 :          */
    3524 GIC         481 :         if (OidIsValid(con->conparentid) &&
    3525 CBC         126 :             !list_member_oid(parent_cons, con->conparentid))
    3526 GIC          81 :             parent_cons = lappend_oid(parent_cons, con->conparentid);
    3527                 : 
    3528 ECB             :         /*
    3529                 :          * Add referencer to result, unless present in input list.  (Don't
    3530                 :          * worry about dupes: we'll fix that below).
    3531                 :          */
    3532 CBC         481 :         if (!list_member_oid(relationIds, con->conrelid))
    3533             250 :             result = lappend_oid(result, con->conrelid);
    3534                 :     }
    3535 ECB             : 
    3536 GIC         440 :     systable_endscan(fkeyScan);
    3537 ECB             : 
    3538                 :     /*
    3539                 :      * Process each parent constraint we found to add the list of referenced
    3540                 :      * relations by them to the oids list.  If we do add any new such
    3541                 :      * relations, redo the first loop above.  Also, if we see that the parent
    3542                 :      * constraint in turn has a parent, add that so that we process all
    3543                 :      * relations in a single additional pass.
    3544                 :      */
    3545 GIC         530 :     foreach(cell, parent_cons)
    3546                 :     {
    3547              90 :         Oid         parent = lfirst_oid(cell);
    3548                 : 
    3549 CBC          90 :         ScanKeyInit(&key,
    3550                 :                     Anum_pg_constraint_oid,
    3551                 :                     BTEqualStrategyNumber, F_OIDEQ,
    3552                 :                     ObjectIdGetDatum(parent));
    3553                 : 
    3554              90 :         fkeyScan = systable_beginscan(fkeyRel, ConstraintOidIndexId,
    3555                 :                                       true, NULL, 1, &key);
    3556 ECB             : 
    3557 GIC          90 :         tuple = systable_getnext(fkeyScan);
    3558              90 :         if (HeapTupleIsValid(tuple))
    3559                 :         {
    3560              90 :             Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
    3561 ECB             : 
    3562                 :             /*
    3563                 :              * pg_constraint rows always appear for partitioned hierarchies
    3564                 :              * this way: on the each side of the constraint, one row appears
    3565                 :              * for each partition that points to the top-most table on the
    3566                 :              * other side.
    3567                 :              *
    3568                 :              * Because of this arrangement, we can correctly catch all
    3569                 :              * relevant relations by adding to 'parent_cons' all rows with
    3570                 :              * valid conparentid, and to the 'oids' list all rows with a zero
    3571                 :              * conparentid.  If any oids are added to 'oids', redo the first
    3572                 :              * loop above by setting 'restart'.
    3573                 :              */
    3574 GIC          90 :             if (OidIsValid(con->conparentid))
    3575              36 :                 parent_cons = list_append_unique_oid(parent_cons,
    3576 ECB             :                                                      con->conparentid);
    3577 GIC          54 :             else if (!list_member_oid(oids, con->confrelid))
    3578                 :             {
    3579              18 :                 oids = lappend_oid(oids, con->confrelid);
    3580 CBC          18 :                 restart = true;
    3581                 :             }
    3582                 :         }
    3583 ECB             : 
    3584 GIC          90 :         systable_endscan(fkeyScan);
    3585 ECB             :     }
    3586                 : 
    3587 GIC         440 :     list_free(parent_cons);
    3588             440 :     if (restart)
    3589              18 :         goto restart;
    3590                 : 
    3591             422 :     table_close(fkeyRel, AccessShareLock);
    3592             422 :     list_free(oids);
    3593                 : 
    3594                 :     /* Now sort and de-duplicate the result list */
    3595             422 :     list_sort(result, list_oid_cmp);
    3596             422 :     list_deduplicate_oid(result);
    3597 ECB             : 
    3598 GIC         422 :     return result;
    3599 ECB             : }
    3600                 : 
    3601                 : /*
    3602                 :  * StorePartitionKey
    3603                 :  *      Store information about the partition key rel into the catalog
    3604                 :  */
    3605                 : void
    3606 GIC        2106 : StorePartitionKey(Relation rel,
    3607                 :                   char strategy,
    3608 ECB             :                   int16 partnatts,
    3609                 :                   AttrNumber *partattrs,
    3610                 :                   List *partexprs,
    3611                 :                   Oid *partopclass,
    3612                 :                   Oid *partcollation)
    3613                 : {
    3614                 :     int         i;
    3615                 :     int2vector *partattrs_vec;
    3616                 :     oidvector  *partopclass_vec;
    3617                 :     oidvector  *partcollation_vec;
    3618                 :     Datum       partexprDatum;
    3619                 :     Relation    pg_partitioned_table;
    3620                 :     HeapTuple   tuple;
    3621                 :     Datum       values[Natts_pg_partitioned_table];
    3622 GNC        2106 :     bool        nulls[Natts_pg_partitioned_table] = {0};
    3623                 :     ObjectAddress myself;
    3624 ECB             :     ObjectAddress referenced;
    3625                 :     ObjectAddresses *addrs;
    3626                 : 
    3627 GIC        2106 :     Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    3628                 : 
    3629                 :     /* Copy the partition attribute numbers, opclass OIDs into arrays */
    3630            2106 :     partattrs_vec = buildint2vector(partattrs, partnatts);
    3631            2106 :     partopclass_vec = buildoidvector(partopclass, partnatts);
    3632            2106 :     partcollation_vec = buildoidvector(partcollation, partnatts);
    3633                 : 
    3634                 :     /* Convert the expressions (if any) to a text datum */
    3635            2106 :     if (partexprs)
    3636                 :     {
    3637                 :         char       *exprString;
    3638 ECB             : 
    3639 GIC         101 :         exprString = nodeToString(partexprs);
    3640             101 :         partexprDatum = CStringGetTextDatum(exprString);
    3641             101 :         pfree(exprString);
    3642                 :     }
    3643                 :     else
    3644            2005 :         partexprDatum = (Datum) 0;
    3645                 : 
    3646 CBC        2106 :     pg_partitioned_table = table_open(PartitionedRelationId, RowExclusiveLock);
    3647 ECB             : 
    3648                 :     /* Only this can ever be NULL */
    3649 GIC        2106 :     if (!partexprDatum)
    3650            2005 :         nulls[Anum_pg_partitioned_table_partexprs - 1] = true;
    3651 ECB             : 
    3652 GIC        2106 :     values[Anum_pg_partitioned_table_partrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
    3653            2106 :     values[Anum_pg_partitioned_table_partstrat - 1] = CharGetDatum(strategy);
    3654 CBC        2106 :     values[Anum_pg_partitioned_table_partnatts - 1] = Int16GetDatum(partnatts);
    3655            2106 :     values[Anum_pg_partitioned_table_partdefid - 1] = ObjectIdGetDatum(InvalidOid);
    3656 GIC        2106 :     values[Anum_pg_partitioned_table_partattrs - 1] = PointerGetDatum(partattrs_vec);
    3657 CBC        2106 :     values[Anum_pg_partitioned_table_partclass - 1] = PointerGetDatum(partopclass_vec);
    3658 GIC        2106 :     values[Anum_pg_partitioned_table_partcollation - 1] = PointerGetDatum(partcollation_vec);
    3659 CBC        2106 :     values[Anum_pg_partitioned_table_partexprs - 1] = partexprDatum;
    3660 ECB             : 
    3661 GIC        2106 :     tuple = heap_form_tuple(RelationGetDescr(pg_partitioned_table), values, nulls);
    3662 ECB             : 
    3663 GIC        2106 :     CatalogTupleInsert(pg_partitioned_table, tuple);
    3664            2106 :     table_close(pg_partitioned_table, RowExclusiveLock);
    3665                 : 
    3666                 :     /* Mark this relation as dependent on a few things as follows */
    3667            2106 :     addrs = new_object_addresses();
    3668            2106 :     ObjectAddressSet(myself, RelationRelationId, RelationGetRelid(rel));
    3669                 : 
    3670                 :     /* Operator class and collation per key column */
    3671            4401 :     for (i = 0; i < partnatts; i++)
    3672                 :     {
    3673            2295 :         ObjectAddressSet(referenced, OperatorClassRelationId, partopclass[i]);
    3674            2295 :         add_exact_object_address(&referenced, addrs);
    3675                 : 
    3676                 :         /* The default collation is pinned, so don't bother recording it */
    3677            2295 :         if (OidIsValid(partcollation[i]) &&
    3678             283 :             partcollation[i] != DEFAULT_COLLATION_OID)
    3679                 :         {
    3680 CBC          48 :             ObjectAddressSet(referenced, CollationRelationId, partcollation[i]);
    3681 GIC          48 :             add_exact_object_address(&referenced, addrs);
    3682 ECB             :         }
    3683                 :     }
    3684                 : 
    3685 GIC        2106 :     record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
    3686            2106 :     free_object_addresses(addrs);
    3687                 : 
    3688                 :     /*
    3689                 :      * The partitioning columns are made internally dependent on the table,
    3690                 :      * because we cannot drop any of them without dropping the whole table.
    3691                 :      * (ATExecDropColumn independently enforces that, but it's not bulletproof
    3692                 :      * so we need the dependencies too.)
    3693                 :      */
    3694 CBC        4401 :     for (i = 0; i < partnatts; i++)
    3695                 :     {
    3696            2295 :         if (partattrs[i] == 0)
    3697 GIC         110 :             continue;           /* ignore expressions here */
    3698 ECB             : 
    3699 CBC        2185 :         ObjectAddressSubSet(referenced, RelationRelationId,
    3700 ECB             :                             RelationGetRelid(rel), partattrs[i]);
    3701 GIC        2185 :         recordDependencyOn(&referenced, &myself, DEPENDENCY_INTERNAL);
    3702                 :     }
    3703                 : 
    3704                 :     /*
    3705                 :      * Also consider anything mentioned in partition expressions.  External
    3706 ECB             :      * references (e.g. functions) get NORMAL dependencies.  Table columns
    3707                 :      * mentioned in the expressions are handled the same as plain partitioning
    3708                 :      * columns, i.e. they become internally dependent on the whole table.
    3709                 :      */
    3710 GIC        2106 :     if (partexprs)
    3711             101 :         recordDependencyOnSingleRelExpr(&myself,
    3712                 :                                         (Node *) partexprs,
    3713 ECB             :                                         RelationGetRelid(rel),
    3714                 :                                         DEPENDENCY_NORMAL,
    3715                 :                                         DEPENDENCY_INTERNAL,
    3716                 :                                         true /* reverse the self-deps */ );
    3717                 : 
    3718                 :     /*
    3719                 :      * We must invalidate the relcache so that the next
    3720                 :      * CommandCounterIncrement() will cause the same to be rebuilt using the
    3721                 :      * information in just created catalog entry.
    3722                 :      */
    3723 GIC        2106 :     CacheInvalidateRelcache(rel);
    3724 CBC        2106 : }
    3725                 : 
    3726 ECB             : /*
    3727                 :  *  RemovePartitionKeyByRelId
    3728                 :  *      Remove pg_partitioned_table entry for a relation
    3729                 :  */
    3730                 : void
    3731 CBC        1677 : RemovePartitionKeyByRelId(Oid relid)
    3732                 : {
    3733 ECB             :     Relation    rel;
    3734                 :     HeapTuple   tuple;
    3735                 : 
    3736 GIC        1677 :     rel = table_open(PartitionedRelationId, RowExclusiveLock);
    3737 ECB             : 
    3738 CBC        1677 :     tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
    3739 GIC        1677 :     if (!HeapTupleIsValid(tuple))
    3740 LBC           0 :         elog(ERROR, "cache lookup failed for partition key of relation %u",
    3741 ECB             :              relid);
    3742                 : 
    3743 GIC        1677 :     CatalogTupleDelete(rel, &tuple->t_self);
    3744                 : 
    3745            1677 :     ReleaseSysCache(tuple);
    3746            1677 :     table_close(rel, RowExclusiveLock);
    3747 CBC        1677 : }
    3748                 : 
    3749                 : /*
    3750                 :  * StorePartitionBound
    3751                 :  *      Update pg_class tuple of rel to store the partition bound and set
    3752                 :  *      relispartition to true
    3753                 :  *
    3754                 :  * If this is the default partition, also update the default partition OID in
    3755                 :  * pg_partitioned_table.
    3756                 :  *
    3757                 :  * Also, invalidate the parent's relcache, so that the next rebuild will load
    3758                 :  * the new partition's info into its partition descriptor.  If there is a
    3759                 :  * default partition, we must invalidate its relcache entry as well.
    3760                 :  */
    3761                 : void
    3762 GIC        4342 : StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
    3763                 : {
    3764                 :     Relation    classRel;
    3765                 :     HeapTuple   tuple,
    3766                 :                 newtuple;
    3767                 :     Datum       new_val[Natts_pg_class];
    3768                 :     bool        new_null[Natts_pg_class],
    3769                 :                 new_repl[Natts_pg_class];
    3770                 :     Oid         defaultPartOid;
    3771                 : 
    3772                 :     /* Update pg_class tuple */
    3773            4342 :     classRel = table_open(RelationRelationId, RowExclusiveLock);
    3774            4342 :     tuple = SearchSysCacheCopy1(RELOID,
    3775 ECB             :                                 ObjectIdGetDatum(RelationGetRelid(rel)));
    3776 GIC        4342 :     if (!HeapTupleIsValid(tuple))
    3777 LBC           0 :         elog(ERROR, "cache lookup failed for relation %u",
    3778                 :              RelationGetRelid(rel));
    3779                 : 
    3780                 : #ifdef USE_ASSERT_CHECKING
    3781                 :     {
    3782                 :         Form_pg_class classForm;
    3783                 :         bool        isnull;
    3784                 : 
    3785 GIC        4342 :         classForm = (Form_pg_class) GETSTRUCT(tuple);
    3786            4342 :         Assert(!classForm->relispartition);
    3787 CBC        4342 :         (void) SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relpartbound,
    3788                 :                                &isnull);
    3789 GIC        4342 :         Assert(isnull);
    3790                 :     }
    3791                 : #endif
    3792                 : 
    3793 ECB             :     /* Fill in relpartbound value */
    3794 GIC        4342 :     memset(new_val, 0, sizeof(new_val));
    3795 CBC        4342 :     memset(new_null, false, sizeof(new_null));
    3796            4342 :     memset(new_repl, false, sizeof(new_repl));
    3797            4342 :     new_val[Anum_pg_class_relpartbound - 1] = CStringGetTextDatum(nodeToString(bound));
    3798 GIC        4342 :     new_null[Anum_pg_class_relpartbound - 1] = false;
    3799 CBC        4342 :     new_repl[Anum_pg_class_relpartbound - 1] = true;
    3800 GIC        4342 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
    3801                 :                                  new_val, new_null, new_repl);
    3802 ECB             :     /* Also set the flag */
    3803 GIC        4342 :     ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = true;
    3804 CBC        4342 :     CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
    3805 GIC        4342 :     heap_freetuple(newtuple);
    3806            4342 :     table_close(classRel, RowExclusiveLock);
    3807 ECB             : 
    3808                 :     /*
    3809                 :      * If we're storing bounds for the default partition, update
    3810                 :      * pg_partitioned_table too.
    3811                 :      */
    3812 CBC        4342 :     if (bound->is_default)
    3813 GIC         251 :         update_default_partition_oid(RelationGetRelid(parent),
    3814                 :                                      RelationGetRelid(rel));
    3815                 : 
    3816                 :     /* Make these updates visible */
    3817            4342 :     CommandCounterIncrement();
    3818                 : 
    3819                 :     /*
    3820 ECB             :      * The partition constraint for the default partition depends on the
    3821                 :      * partition bounds of every other partition, so we must invalidate the
    3822                 :      * relcache entry for that partition every time a partition is added or
    3823                 :      * removed.
    3824                 :      */
    3825                 :     defaultPartOid =
    3826 GIC        4342 :         get_default_oid_from_partdesc(RelationGetPartitionDesc(parent, true));
    3827            4342 :     if (OidIsValid(defaultPartOid))
    3828 CBC         308 :         CacheInvalidateRelcacheByRelid(defaultPartOid);
    3829 ECB             : 
    3830 GIC        4342 :     CacheInvalidateRelcache(parent);
    3831            4342 : }
        

Generated by: LCOV version v1.16-55-g56c0a2a