LCOV - code coverage report
Current view: top level - src/backend/catalog - heap.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 95.6 % 1084 1036
Test Date: 2026-09-23 14:15:49 Functions: 97.7 % 44 43
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 79.3 % 778 617

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

Generated by: LCOV version 2.0-1