LCOV - differential code coverage report
Current view: top level - src/backend/catalog - heap.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 94.9 % 1188 1128 60 10 1118 32
Current Date: 2026-11-28 16:48:44 +0900 Functions: 98.0 % 49 48 1 7 41
Baseline: lcov-20261128-baseline Branches: 76.1 % 918 699 219 699
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 92.1 % 76 70 6 9 61
(30,360] days: 90.6 % 32 29 3 1 28
(360..) days: 95.3 % 1080 1029 51 1029
Function coverage date bins:
(7,30] days: 100.0 % 5 5 2 3
(360..) days: 97.7 % 44 43 1 5 38
Branch coverage date bins:
(7,30] days: 66.7 % 72 48 24 48
(30,360] days: 62.5 % 32 20 12 20
(360..) days: 77.5 % 814 631 183 631

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

Generated by: LCOV version 2.0-1