|           Line data    Source code 
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * tablecmds.c
       4             :  *    Commands for creating and altering table structures and settings
       5             :  *
       6             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/commands/tablecmds.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : #include "postgres.h"
      16             : 
      17             : #include "access/attmap.h"
      18             : #include "access/genam.h"
      19             : #include "access/gist.h"
      20             : #include "access/heapam.h"
      21             : #include "access/heapam_xlog.h"
      22             : #include "access/multixact.h"
      23             : #include "access/reloptions.h"
      24             : #include "access/relscan.h"
      25             : #include "access/sysattr.h"
      26             : #include "access/tableam.h"
      27             : #include "access/toast_compression.h"
      28             : #include "access/xact.h"
      29             : #include "access/xlog.h"
      30             : #include "access/xloginsert.h"
      31             : #include "catalog/catalog.h"
      32             : #include "catalog/heap.h"
      33             : #include "catalog/index.h"
      34             : #include "catalog/namespace.h"
      35             : #include "catalog/objectaccess.h"
      36             : #include "catalog/partition.h"
      37             : #include "catalog/pg_am.h"
      38             : #include "catalog/pg_attrdef.h"
      39             : #include "catalog/pg_collation.h"
      40             : #include "catalog/pg_constraint.h"
      41             : #include "catalog/pg_depend.h"
      42             : #include "catalog/pg_foreign_table.h"
      43             : #include "catalog/pg_inherits.h"
      44             : #include "catalog/pg_largeobject.h"
      45             : #include "catalog/pg_largeobject_metadata.h"
      46             : #include "catalog/pg_namespace.h"
      47             : #include "catalog/pg_opclass.h"
      48             : #include "catalog/pg_policy.h"
      49             : #include "catalog/pg_proc.h"
      50             : #include "catalog/pg_publication_rel.h"
      51             : #include "catalog/pg_rewrite.h"
      52             : #include "catalog/pg_statistic_ext.h"
      53             : #include "catalog/pg_tablespace.h"
      54             : #include "catalog/pg_trigger.h"
      55             : #include "catalog/pg_type.h"
      56             : #include "catalog/storage.h"
      57             : #include "catalog/storage_xlog.h"
      58             : #include "catalog/toasting.h"
      59             : #include "commands/cluster.h"
      60             : #include "commands/comment.h"
      61             : #include "commands/defrem.h"
      62             : #include "commands/event_trigger.h"
      63             : #include "commands/sequence.h"
      64             : #include "commands/tablecmds.h"
      65             : #include "commands/tablespace.h"
      66             : #include "commands/trigger.h"
      67             : #include "commands/typecmds.h"
      68             : #include "commands/user.h"
      69             : #include "commands/vacuum.h"
      70             : #include "common/int.h"
      71             : #include "executor/executor.h"
      72             : #include "foreign/fdwapi.h"
      73             : #include "foreign/foreign.h"
      74             : #include "miscadmin.h"
      75             : #include "nodes/makefuncs.h"
      76             : #include "nodes/nodeFuncs.h"
      77             : #include "nodes/parsenodes.h"
      78             : #include "optimizer/optimizer.h"
      79             : #include "parser/parse_coerce.h"
      80             : #include "parser/parse_collate.h"
      81             : #include "parser/parse_expr.h"
      82             : #include "parser/parse_relation.h"
      83             : #include "parser/parse_type.h"
      84             : #include "parser/parse_utilcmd.h"
      85             : #include "parser/parser.h"
      86             : #include "partitioning/partbounds.h"
      87             : #include "partitioning/partdesc.h"
      88             : #include "pgstat.h"
      89             : #include "rewrite/rewriteDefine.h"
      90             : #include "rewrite/rewriteHandler.h"
      91             : #include "rewrite/rewriteManip.h"
      92             : #include "storage/bufmgr.h"
      93             : #include "storage/lmgr.h"
      94             : #include "storage/lock.h"
      95             : #include "storage/predicate.h"
      96             : #include "storage/smgr.h"
      97             : #include "tcop/utility.h"
      98             : #include "utils/acl.h"
      99             : #include "utils/builtins.h"
     100             : #include "utils/fmgroids.h"
     101             : #include "utils/inval.h"
     102             : #include "utils/lsyscache.h"
     103             : #include "utils/memutils.h"
     104             : #include "utils/partcache.h"
     105             : #include "utils/relcache.h"
     106             : #include "utils/ruleutils.h"
     107             : #include "utils/snapmgr.h"
     108             : #include "utils/syscache.h"
     109             : #include "utils/timestamp.h"
     110             : #include "utils/typcache.h"
     111             : #include "utils/usercontext.h"
     112             : 
     113             : /*
     114             :  * ON COMMIT action list
     115             :  */
     116             : typedef struct OnCommitItem
     117             : {
     118             :     Oid         relid;          /* relid of relation */
     119             :     OnCommitAction oncommit;    /* what to do at end of xact */
     120             : 
     121             :     /*
     122             :      * If this entry was created during the current transaction,
     123             :      * creating_subid is the ID of the creating subxact; if created in a prior
     124             :      * transaction, creating_subid is zero.  If deleted during the current
     125             :      * transaction, deleting_subid is the ID of the deleting subxact; if no
     126             :      * deletion request is pending, deleting_subid is zero.
     127             :      */
     128             :     SubTransactionId creating_subid;
     129             :     SubTransactionId deleting_subid;
     130             : } OnCommitItem;
     131             : 
     132             : static List *on_commits = NIL;
     133             : 
     134             : 
     135             : /*
     136             :  * State information for ALTER TABLE
     137             :  *
     138             :  * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
     139             :  * structs, one for each table modified by the operation (the named table
     140             :  * plus any child tables that are affected).  We save lists of subcommands
     141             :  * to apply to this table (possibly modified by parse transformation steps);
     142             :  * these lists will be executed in Phase 2.  If a Phase 3 step is needed,
     143             :  * necessary information is stored in the constraints and newvals lists.
     144             :  *
     145             :  * Phase 2 is divided into multiple passes; subcommands are executed in
     146             :  * a pass determined by subcommand type.
     147             :  */
     148             : 
     149             : typedef enum AlterTablePass
     150             : {
     151             :     AT_PASS_UNSET = -1,         /* UNSET will cause ERROR */
     152             :     AT_PASS_DROP,               /* DROP (all flavors) */
     153             :     AT_PASS_ALTER_TYPE,         /* ALTER COLUMN TYPE */
     154             :     AT_PASS_ADD_COL,            /* ADD COLUMN */
     155             :     AT_PASS_SET_EXPRESSION,     /* ALTER SET EXPRESSION */
     156             :     AT_PASS_OLD_INDEX,          /* re-add existing indexes */
     157             :     AT_PASS_OLD_CONSTR,         /* re-add existing constraints */
     158             :     /* We could support a RENAME COLUMN pass here, but not currently used */
     159             :     AT_PASS_ADD_CONSTR,         /* ADD constraints (initial examination) */
     160             :     AT_PASS_COL_ATTRS,          /* set column attributes, eg NOT NULL */
     161             :     AT_PASS_ADD_INDEXCONSTR,    /* ADD index-based constraints */
     162             :     AT_PASS_ADD_INDEX,          /* ADD indexes */
     163             :     AT_PASS_ADD_OTHERCONSTR,    /* ADD other constraints, defaults */
     164             :     AT_PASS_MISC,               /* other stuff */
     165             : } AlterTablePass;
     166             : 
     167             : #define AT_NUM_PASSES           (AT_PASS_MISC + 1)
     168             : 
     169             : typedef struct AlteredTableInfo
     170             : {
     171             :     /* Information saved before any work commences: */
     172             :     Oid         relid;          /* Relation to work on */
     173             :     char        relkind;        /* Its relkind */
     174             :     TupleDesc   oldDesc;        /* Pre-modification tuple descriptor */
     175             : 
     176             :     /*
     177             :      * Transiently set during Phase 2, normally set to NULL.
     178             :      *
     179             :      * ATRewriteCatalogs sets this when it starts, and closes when ATExecCmd
     180             :      * returns control.  This can be exploited by ATExecCmd subroutines to
     181             :      * close/reopen across transaction boundaries.
     182             :      */
     183             :     Relation    rel;
     184             : 
     185             :     /* Information saved by Phase 1 for Phase 2: */
     186             :     List       *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
     187             :     /* Information saved by Phases 1/2 for Phase 3: */
     188             :     List       *constraints;    /* List of NewConstraint */
     189             :     List       *newvals;        /* List of NewColumnValue */
     190             :     List       *afterStmts;     /* List of utility command parsetrees */
     191             :     bool        verify_new_notnull; /* T if we should recheck NOT NULL */
     192             :     int         rewrite;        /* Reason for forced rewrite, if any */
     193             :     bool        chgAccessMethod;    /* T if SET ACCESS METHOD is used */
     194             :     Oid         newAccessMethod;    /* new access method; 0 means no change,
     195             :                                      * if above is true */
     196             :     Oid         newTableSpace;  /* new tablespace; 0 means no change */
     197             :     bool        chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
     198             :     char        newrelpersistence;  /* if above is true */
     199             :     Expr       *partition_constraint;   /* for attach partition validation */
     200             :     /* true, if validating default due to some other attach/detach */
     201             :     bool        validate_default;
     202             :     /* Objects to rebuild after completing ALTER TYPE operations */
     203             :     List       *changedConstraintOids;  /* OIDs of constraints to rebuild */
     204             :     List       *changedConstraintDefs;  /* string definitions of same */
     205             :     List       *changedIndexOids;   /* OIDs of indexes to rebuild */
     206             :     List       *changedIndexDefs;   /* string definitions of same */
     207             :     char       *replicaIdentityIndex;   /* index to reset as REPLICA IDENTITY */
     208             :     char       *clusterOnIndex; /* index to use for CLUSTER */
     209             :     List       *changedStatisticsOids;  /* OIDs of statistics to rebuild */
     210             :     List       *changedStatisticsDefs;  /* string definitions of same */
     211             : } AlteredTableInfo;
     212             : 
     213             : /* Struct describing one new constraint to check in Phase 3 scan */
     214             : /* Note: new not-null constraints are handled elsewhere */
     215             : typedef struct NewConstraint
     216             : {
     217             :     char       *name;           /* Constraint name, or NULL if none */
     218             :     ConstrType  contype;        /* CHECK or FOREIGN */
     219             :     Oid         refrelid;       /* PK rel, if FOREIGN */
     220             :     Oid         refindid;       /* OID of PK's index, if FOREIGN */
     221             :     bool        conwithperiod;  /* Whether the new FOREIGN KEY uses PERIOD */
     222             :     Oid         conid;          /* OID of pg_constraint entry, if FOREIGN */
     223             :     Node       *qual;           /* Check expr or CONSTR_FOREIGN Constraint */
     224             :     ExprState  *qualstate;      /* Execution state for CHECK expr */
     225             : } NewConstraint;
     226             : 
     227             : /*
     228             :  * Struct describing one new column value that needs to be computed during
     229             :  * Phase 3 copy (this could be either a new column with a non-null default, or
     230             :  * a column that we're changing the type of).  Columns without such an entry
     231             :  * are just copied from the old table during ATRewriteTable.  Note that the
     232             :  * expr is an expression over *old* table values, except when is_generated
     233             :  * is true; then it is an expression over columns of the *new* tuple.
     234             :  */
     235             : typedef struct NewColumnValue
     236             : {
     237             :     AttrNumber  attnum;         /* which column */
     238             :     Expr       *expr;           /* expression to compute */
     239             :     ExprState  *exprstate;      /* execution state */
     240             :     bool        is_generated;   /* is it a GENERATED expression? */
     241             : } NewColumnValue;
     242             : 
     243             : /*
     244             :  * Error-reporting support for RemoveRelations
     245             :  */
     246             : struct dropmsgstrings
     247             : {
     248             :     char        kind;
     249             :     int         nonexistent_code;
     250             :     const char *nonexistent_msg;
     251             :     const char *skipping_msg;
     252             :     const char *nota_msg;
     253             :     const char *drophint_msg;
     254             : };
     255             : 
     256             : static const struct dropmsgstrings dropmsgstringarray[] = {
     257             :     {RELKIND_RELATION,
     258             :         ERRCODE_UNDEFINED_TABLE,
     259             :         gettext_noop("table \"%s\" does not exist"),
     260             :         gettext_noop("table \"%s\" does not exist, skipping"),
     261             :         gettext_noop("\"%s\" is not a table"),
     262             :     gettext_noop("Use DROP TABLE to remove a table.")},
     263             :     {RELKIND_SEQUENCE,
     264             :         ERRCODE_UNDEFINED_TABLE,
     265             :         gettext_noop("sequence \"%s\" does not exist"),
     266             :         gettext_noop("sequence \"%s\" does not exist, skipping"),
     267             :         gettext_noop("\"%s\" is not a sequence"),
     268             :     gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
     269             :     {RELKIND_VIEW,
     270             :         ERRCODE_UNDEFINED_TABLE,
     271             :         gettext_noop("view \"%s\" does not exist"),
     272             :         gettext_noop("view \"%s\" does not exist, skipping"),
     273             :         gettext_noop("\"%s\" is not a view"),
     274             :     gettext_noop("Use DROP VIEW to remove a view.")},
     275             :     {RELKIND_MATVIEW,
     276             :         ERRCODE_UNDEFINED_TABLE,
     277             :         gettext_noop("materialized view \"%s\" does not exist"),
     278             :         gettext_noop("materialized view \"%s\" does not exist, skipping"),
     279             :         gettext_noop("\"%s\" is not a materialized view"),
     280             :     gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
     281             :     {RELKIND_INDEX,
     282             :         ERRCODE_UNDEFINED_OBJECT,
     283             :         gettext_noop("index \"%s\" does not exist"),
     284             :         gettext_noop("index \"%s\" does not exist, skipping"),
     285             :         gettext_noop("\"%s\" is not an index"),
     286             :     gettext_noop("Use DROP INDEX to remove an index.")},
     287             :     {RELKIND_COMPOSITE_TYPE,
     288             :         ERRCODE_UNDEFINED_OBJECT,
     289             :         gettext_noop("type \"%s\" does not exist"),
     290             :         gettext_noop("type \"%s\" does not exist, skipping"),
     291             :         gettext_noop("\"%s\" is not a type"),
     292             :     gettext_noop("Use DROP TYPE to remove a type.")},
     293             :     {RELKIND_FOREIGN_TABLE,
     294             :         ERRCODE_UNDEFINED_OBJECT,
     295             :         gettext_noop("foreign table \"%s\" does not exist"),
     296             :         gettext_noop("foreign table \"%s\" does not exist, skipping"),
     297             :         gettext_noop("\"%s\" is not a foreign table"),
     298             :     gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
     299             :     {RELKIND_PARTITIONED_TABLE,
     300             :         ERRCODE_UNDEFINED_TABLE,
     301             :         gettext_noop("table \"%s\" does not exist"),
     302             :         gettext_noop("table \"%s\" does not exist, skipping"),
     303             :         gettext_noop("\"%s\" is not a table"),
     304             :     gettext_noop("Use DROP TABLE to remove a table.")},
     305             :     {RELKIND_PARTITIONED_INDEX,
     306             :         ERRCODE_UNDEFINED_OBJECT,
     307             :         gettext_noop("index \"%s\" does not exist"),
     308             :         gettext_noop("index \"%s\" does not exist, skipping"),
     309             :         gettext_noop("\"%s\" is not an index"),
     310             :     gettext_noop("Use DROP INDEX to remove an index.")},
     311             :     {'\0', 0, NULL, NULL, NULL, NULL}
     312             : };
     313             : 
     314             : /* communication between RemoveRelations and RangeVarCallbackForDropRelation */
     315             : struct DropRelationCallbackState
     316             : {
     317             :     /* These fields are set by RemoveRelations: */
     318             :     char        expected_relkind;
     319             :     LOCKMODE    heap_lockmode;
     320             :     /* These fields are state to track which subsidiary locks are held: */
     321             :     Oid         heapOid;
     322             :     Oid         partParentOid;
     323             :     /* These fields are passed back by RangeVarCallbackForDropRelation: */
     324             :     char        actual_relkind;
     325             :     char        actual_relpersistence;
     326             : };
     327             : 
     328             : /* Alter table target-type flags for ATSimplePermissions */
     329             : #define     ATT_TABLE               0x0001
     330             : #define     ATT_VIEW                0x0002
     331             : #define     ATT_MATVIEW             0x0004
     332             : #define     ATT_INDEX               0x0008
     333             : #define     ATT_COMPOSITE_TYPE      0x0010
     334             : #define     ATT_FOREIGN_TABLE       0x0020
     335             : #define     ATT_PARTITIONED_INDEX   0x0040
     336             : #define     ATT_SEQUENCE            0x0080
     337             : #define     ATT_PARTITIONED_TABLE   0x0100
     338             : 
     339             : /*
     340             :  * ForeignTruncateInfo
     341             :  *
     342             :  * Information related to truncation of foreign tables.  This is used for
     343             :  * the elements in a hash table. It uses the server OID as lookup key,
     344             :  * and includes a per-server list of all foreign tables involved in the
     345             :  * truncation.
     346             :  */
     347             : typedef struct ForeignTruncateInfo
     348             : {
     349             :     Oid         serverid;
     350             :     List       *rels;
     351             : } ForeignTruncateInfo;
     352             : 
     353             : /* Partial or complete FK creation in addFkConstraint() */
     354             : typedef enum addFkConstraintSides
     355             : {
     356             :     addFkReferencedSide,
     357             :     addFkReferencingSide,
     358             :     addFkBothSides,
     359             : } addFkConstraintSides;
     360             : 
     361             : /*
     362             :  * Partition tables are expected to be dropped when the parent partitioned
     363             :  * table gets dropped. Hence for partitioning we use AUTO dependency.
     364             :  * Otherwise, for regular inheritance use NORMAL dependency.
     365             :  */
     366             : #define child_dependency_type(child_is_partition)   \
     367             :     ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
     368             : 
     369             : static void truncate_check_rel(Oid relid, Form_pg_class reltuple);
     370             : static void truncate_check_perms(Oid relid, Form_pg_class reltuple);
     371             : static void truncate_check_activity(Relation rel);
     372             : static void RangeVarCallbackForTruncate(const RangeVar *relation,
     373             :                                         Oid relId, Oid oldRelId, void *arg);
     374             : static List *MergeAttributes(List *columns, const List *supers, char relpersistence,
     375             :                              bool is_partition, List **supconstr,
     376             :                              List **supnotnulls);
     377             : static List *MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced);
     378             : static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef);
     379             : static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef);
     380             : static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition);
     381             : static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
     382             : static void StoreCatalogInheritance(Oid relationId, List *supers,
     383             :                                     bool child_is_partition);
     384             : static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
     385             :                                      int32 seqNumber, Relation inhRelation,
     386             :                                      bool child_is_partition);
     387             : static int  findAttrByName(const char *attributeName, const List *columns);
     388             : static void AlterIndexNamespaces(Relation classRel, Relation rel,
     389             :                                  Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
     390             : static void AlterSeqNamespaces(Relation classRel, Relation rel,
     391             :                                Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
     392             :                                LOCKMODE lockmode);
     393             : static ObjectAddress ATExecAlterConstraint(List **wqueue, Relation rel,
     394             :                                            ATAlterConstraint *cmdcon,
     395             :                                            bool recurse, LOCKMODE lockmode);
     396             : static bool ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel,
     397             :                                           Relation tgrel, Relation rel, HeapTuple contuple,
     398             :                                           bool recurse, LOCKMODE lockmode);
     399             : static bool ATExecAlterConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
     400             :                                             Relation conrel, Relation tgrel,
     401             :                                             Oid fkrelid, Oid pkrelid,
     402             :                                             HeapTuple contuple, LOCKMODE lockmode,
     403             :                                             Oid ReferencedParentDelTrigger,
     404             :                                             Oid ReferencedParentUpdTrigger,
     405             :                                             Oid ReferencingParentInsTrigger,
     406             :                                             Oid ReferencingParentUpdTrigger);
     407             : static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
     408             :                                            Relation conrel, Relation tgrel, Relation rel,
     409             :                                            HeapTuple contuple, bool recurse,
     410             :                                            List **otherrelids, LOCKMODE lockmode);
     411             : static bool ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
     412             :                                             Relation conrel, Relation rel,
     413             :                                             HeapTuple contuple, LOCKMODE lockmode);
     414             : static void AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
     415             :                                             bool deferrable, bool initdeferred,
     416             :                                             List **otherrelids);
     417             : static void AlterConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
     418             :                                              Relation conrel, Relation tgrel,
     419             :                                              Oid fkrelid, Oid pkrelid,
     420             :                                              HeapTuple contuple, LOCKMODE lockmode,
     421             :                                              Oid ReferencedParentDelTrigger,
     422             :                                              Oid ReferencedParentUpdTrigger,
     423             :                                              Oid ReferencingParentInsTrigger,
     424             :                                              Oid ReferencingParentUpdTrigger);
     425             : static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
     426             :                                             Relation conrel, Relation tgrel, Relation rel,
     427             :                                             HeapTuple contuple, bool recurse,
     428             :                                             List **otherrelids, LOCKMODE lockmode);
     429             : static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
     430             :                                              HeapTuple contuple);
     431             : static ObjectAddress ATExecValidateConstraint(List **wqueue,
     432             :                                               Relation rel, char *constrName,
     433             :                                               bool recurse, bool recursing, LOCKMODE lockmode);
     434             : static void QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
     435             :                                         Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode);
     436             : static void QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
     437             :                                            char *constrName, HeapTuple contuple,
     438             :                                            bool recurse, bool recursing, LOCKMODE lockmode);
     439             : static void QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
     440             :                                         HeapTuple contuple, bool recurse, bool recursing,
     441             :                                         LOCKMODE lockmode);
     442             : static int  transformColumnNameList(Oid relId, List *colList,
     443             :                                     int16 *attnums, Oid *atttypids, Oid *attcollids);
     444             : static int  transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
     445             :                                        List **attnamelist,
     446             :                                        int16 *attnums, Oid *atttypids, Oid *attcollids,
     447             :                                        Oid *opclasses, bool *pk_has_without_overlaps);
     448             : static Oid  transformFkeyCheckAttrs(Relation pkrel,
     449             :                                     int numattrs, int16 *attnums,
     450             :                                     bool with_period, Oid *opclasses,
     451             :                                     bool *pk_has_without_overlaps);
     452             : static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
     453             : static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
     454             :                                      Oid *funcid);
     455             : static void validateForeignKeyConstraint(char *conname,
     456             :                                          Relation rel, Relation pkrel,
     457             :                                          Oid pkindOid, Oid constraintOid, bool hasperiod);
     458             : static void CheckAlterTableIsSafe(Relation rel);
     459             : static void ATController(AlterTableStmt *parsetree,
     460             :                          Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
     461             :                          AlterTableUtilityContext *context);
     462             : static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
     463             :                       bool recurse, bool recursing, LOCKMODE lockmode,
     464             :                       AlterTableUtilityContext *context);
     465             : static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
     466             :                               AlterTableUtilityContext *context);
     467             : static void ATExecCmd(List **wqueue, AlteredTableInfo *tab,
     468             :                       AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
     469             :                       AlterTableUtilityContext *context);
     470             : static AlterTableCmd *ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab,
     471             :                                           Relation rel, AlterTableCmd *cmd,
     472             :                                           bool recurse, LOCKMODE lockmode,
     473             :                                           AlterTablePass cur_pass,
     474             :                                           AlterTableUtilityContext *context);
     475             : static void ATRewriteTables(AlterTableStmt *parsetree,
     476             :                             List **wqueue, LOCKMODE lockmode,
     477             :                             AlterTableUtilityContext *context);
     478             : static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
     479             : static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
     480             : static void ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets);
     481             : static void ATSimpleRecursion(List **wqueue, Relation rel,
     482             :                               AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
     483             :                               AlterTableUtilityContext *context);
     484             : static void ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode);
     485             : static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
     486             :                                   LOCKMODE lockmode,
     487             :                                   AlterTableUtilityContext *context);
     488             : static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
     489             :                                            DropBehavior behavior);
     490             : static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
     491             :                             bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
     492             :                             AlterTableUtilityContext *context);
     493             : static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab,
     494             :                                      Relation rel, AlterTableCmd **cmd,
     495             :                                      bool recurse, bool recursing,
     496             :                                      LOCKMODE lockmode, AlterTablePass cur_pass,
     497             :                                      AlterTableUtilityContext *context);
     498             : static bool check_for_column_name_collision(Relation rel, const char *colname,
     499             :                                             bool if_not_exists);
     500             : static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
     501             : static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
     502             : static ObjectAddress ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
     503             :                                        LOCKMODE lockmode);
     504             : static void set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
     505             :                            bool is_valid, bool queue_validation);
     506             : static ObjectAddress ATExecSetNotNull(List **wqueue, Relation rel,
     507             :                                       char *conName, char *colName,
     508             :                                       bool recurse, bool recursing,
     509             :                                       LOCKMODE lockmode);
     510             : static bool NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr);
     511             : static bool ConstraintImpliedByRelConstraint(Relation scanrel,
     512             :                                              List *testConstraint, List *provenConstraint);
     513             : static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
     514             :                                          Node *newDefault, LOCKMODE lockmode);
     515             : static ObjectAddress ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
     516             :                                                Node *newDefault);
     517             : static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName,
     518             :                                        Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
     519             : static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName,
     520             :                                        Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
     521             : static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
     522             :                                         bool recurse, bool recursing);
     523             : static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
     524             :                                          Node *newExpr, LOCKMODE lockmode);
     525             : static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode);
     526             : static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
     527             : static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum,
     528             :                                          Node *newValue, LOCKMODE lockmode);
     529             : static ObjectAddress ATExecSetOptions(Relation rel, const char *colName,
     530             :                                       Node *options, bool isReset, LOCKMODE lockmode);
     531             : static ObjectAddress ATExecSetStorage(Relation rel, const char *colName,
     532             :                                       Node *newValue, LOCKMODE lockmode);
     533             : static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
     534             :                              AlterTableCmd *cmd, LOCKMODE lockmode,
     535             :                              AlterTableUtilityContext *context);
     536             : static ObjectAddress ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
     537             :                                       DropBehavior behavior,
     538             :                                       bool recurse, bool recursing,
     539             :                                       bool missing_ok, LOCKMODE lockmode,
     540             :                                       ObjectAddresses *addrs);
     541             : static void ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
     542             :                                 bool recurse, LOCKMODE lockmode,
     543             :                                 AlterTableUtilityContext *context);
     544             : static void verifyNotNullPKCompatible(HeapTuple tuple, const char *colname);
     545             : static ObjectAddress ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
     546             :                                     IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
     547             : static ObjectAddress ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
     548             :                                          CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
     549             : static ObjectAddress ATExecAddConstraint(List **wqueue,
     550             :                                          AlteredTableInfo *tab, Relation rel,
     551             :                                          Constraint *newConstraint, bool recurse, bool is_readd,
     552             :                                          LOCKMODE lockmode);
     553             : static char *ChooseForeignKeyConstraintNameAddition(List *colnames);
     554             : static ObjectAddress ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
     555             :                                               IndexStmt *stmt, LOCKMODE lockmode);
     556             : static ObjectAddress ATAddCheckNNConstraint(List **wqueue,
     557             :                                             AlteredTableInfo *tab, Relation rel,
     558             :                                             Constraint *constr,
     559             :                                             bool recurse, bool recursing, bool is_readd,
     560             :                                             LOCKMODE lockmode);
     561             : static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab,
     562             :                                                Relation rel, Constraint *fkconstraint,
     563             :                                                bool recurse, bool recursing,
     564             :                                                LOCKMODE lockmode);
     565             : static int  validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
     566             :                                          int numfksetcols, int16 *fksetcolsattnums,
     567             :                                          List *fksetcols);
     568             : static ObjectAddress addFkConstraint(addFkConstraintSides fkside,
     569             :                                      char *constraintname,
     570             :                                      Constraint *fkconstraint, Relation rel,
     571             :                                      Relation pkrel, Oid indexOid,
     572             :                                      Oid parentConstr,
     573             :                                      int numfks, int16 *pkattnum, int16 *fkattnum,
     574             :                                      Oid *pfeqoperators, Oid *ppeqoperators,
     575             :                                      Oid *ffeqoperators, int numfkdelsetcols,
     576             :                                      int16 *fkdelsetcols, bool is_internal,
     577             :                                      bool with_period);
     578             : static void addFkRecurseReferenced(Constraint *fkconstraint,
     579             :                                    Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
     580             :                                    int numfks, int16 *pkattnum, int16 *fkattnum,
     581             :                                    Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
     582             :                                    int numfkdelsetcols, int16 *fkdelsetcols,
     583             :                                    bool old_check_ok,
     584             :                                    Oid parentDelTrigger, Oid parentUpdTrigger,
     585             :                                    bool with_period);
     586             : static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
     587             :                                     Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
     588             :                                     int numfks, int16 *pkattnum, int16 *fkattnum,
     589             :                                     Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
     590             :                                     int numfkdelsetcols, int16 *fkdelsetcols,
     591             :                                     bool old_check_ok, LOCKMODE lockmode,
     592             :                                     Oid parentInsTrigger, Oid parentUpdTrigger,
     593             :                                     bool with_period);
     594             : static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
     595             :                                        Relation partitionRel);
     596             : static void CloneFkReferenced(Relation parentRel, Relation partitionRel);
     597             : static void CloneFkReferencing(List **wqueue, Relation parentRel,
     598             :                                Relation partRel);
     599             : static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
     600             :                                           Constraint *fkconstraint, Oid constraintOid,
     601             :                                           Oid indexOid,
     602             :                                           Oid parentInsTrigger, Oid parentUpdTrigger,
     603             :                                           Oid *insertTrigOid, Oid *updateTrigOid);
     604             : static void createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid,
     605             :                                            Constraint *fkconstraint, Oid constraintOid,
     606             :                                            Oid indexOid,
     607             :                                            Oid parentDelTrigger, Oid parentUpdTrigger,
     608             :                                            Oid *deleteTrigOid, Oid *updateTrigOid);
     609             : static bool tryAttachPartitionForeignKey(List **wqueue,
     610             :                                          ForeignKeyCacheInfo *fk,
     611             :                                          Relation partition,
     612             :                                          Oid parentConstrOid, int numfks,
     613             :                                          AttrNumber *mapped_conkey, AttrNumber *confkey,
     614             :                                          Oid *conpfeqop,
     615             :                                          Oid parentInsTrigger,
     616             :                                          Oid parentUpdTrigger,
     617             :                                          Relation trigrel);
     618             : static void AttachPartitionForeignKey(List **wqueue, Relation partition,
     619             :                                       Oid partConstrOid, Oid parentConstrOid,
     620             :                                       Oid parentInsTrigger, Oid parentUpdTrigger,
     621             :                                       Relation trigrel);
     622             : static void RemoveInheritedConstraint(Relation conrel, Relation trigrel,
     623             :                                       Oid conoid, Oid conrelid);
     624             : static void DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid,
     625             :                                              Oid confrelid, Oid conrelid);
     626             : static void GetForeignKeyActionTriggers(Relation trigrel,
     627             :                                         Oid conoid, Oid confrelid, Oid conrelid,
     628             :                                         Oid *deleteTriggerOid,
     629             :                                         Oid *updateTriggerOid);
     630             : static void GetForeignKeyCheckTriggers(Relation trigrel,
     631             :                                        Oid conoid, Oid confrelid, Oid conrelid,
     632             :                                        Oid *insertTriggerOid,
     633             :                                        Oid *updateTriggerOid);
     634             : static void ATExecDropConstraint(Relation rel, const char *constrName,
     635             :                                  DropBehavior behavior, bool recurse,
     636             :                                  bool missing_ok, LOCKMODE lockmode);
     637             : static ObjectAddress dropconstraint_internal(Relation rel,
     638             :                                              HeapTuple constraintTup, DropBehavior behavior,
     639             :                                              bool recurse, bool recursing,
     640             :                                              bool missing_ok, LOCKMODE lockmode);
     641             : static void ATPrepAlterColumnType(List **wqueue,
     642             :                                   AlteredTableInfo *tab, Relation rel,
     643             :                                   bool recurse, bool recursing,
     644             :                                   AlterTableCmd *cmd, LOCKMODE lockmode,
     645             :                                   AlterTableUtilityContext *context);
     646             : static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
     647             : static ObjectAddress ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
     648             :                                            AlterTableCmd *cmd, LOCKMODE lockmode);
     649             : static void RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
     650             :                                               Relation rel, AttrNumber attnum, const char *colName);
     651             : static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
     652             : static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
     653             : static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
     654             : static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
     655             :                                    LOCKMODE lockmode);
     656             : static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId,
     657             :                                  char *cmd, List **wqueue, LOCKMODE lockmode,
     658             :                                  bool rewrite);
     659             : static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass,
     660             :                                      Oid objid, Relation rel, List *domname,
     661             :                                      const char *conname);
     662             : static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
     663             : static void TryReuseForeignKey(Oid oldId, Constraint *con);
     664             : static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
     665             :                                                      List *options, LOCKMODE lockmode);
     666             : static void change_owner_fix_column_acls(Oid relationOid,
     667             :                                          Oid oldOwnerId, Oid newOwnerId);
     668             : static void change_owner_recurse_to_sequences(Oid relationOid,
     669             :                                               Oid newOwnerId, LOCKMODE lockmode);
     670             : static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
     671             :                                      LOCKMODE lockmode);
     672             : static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
     673             : static void ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname);
     674             : static void ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId);
     675             : static void ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel,
     676             :                                     bool toLogged);
     677             : static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
     678             :                                 const char *tablespacename, LOCKMODE lockmode);
     679             : static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
     680             : static void ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace);
     681             : static void ATExecSetRelOptions(Relation rel, List *defList,
     682             :                                 AlterTableType operation,
     683             :                                 LOCKMODE lockmode);
     684             : static void ATExecEnableDisableTrigger(Relation rel, const char *trigname,
     685             :                                        char fires_when, bool skip_system, bool recurse,
     686             :                                        LOCKMODE lockmode);
     687             : static void ATExecEnableDisableRule(Relation rel, const char *rulename,
     688             :                                     char fires_when, LOCKMODE lockmode);
     689             : static void ATPrepAddInherit(Relation child_rel);
     690             : static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
     691             : static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
     692             : static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
     693             :                                    DependencyType deptype);
     694             : static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
     695             : static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
     696             : static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
     697             : static void ATExecGenericOptions(Relation rel, List *options);
     698             : static void ATExecSetRowSecurity(Relation rel, bool rls);
     699             : static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
     700             : static ObjectAddress ATExecSetCompression(Relation rel,
     701             :                                           const char *column, Node *newValue, LOCKMODE lockmode);
     702             : 
     703             : static void index_copy_data(Relation rel, RelFileLocator newrlocator);
     704             : static const char *storage_name(char c);
     705             : 
     706             : static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
     707             :                                             Oid oldRelOid, void *arg);
     708             : static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
     709             :                                              Oid oldrelid, void *arg);
     710             : static PartitionSpec *transformPartitionSpec(Relation rel, PartitionSpec *partspec);
     711             : static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
     712             :                                   List **partexprs, Oid *partopclass, Oid *partcollation,
     713             :                                   PartitionStrategy strategy);
     714             : static void CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition);
     715             : static void RemoveInheritance(Relation child_rel, Relation parent_rel,
     716             :                               bool expect_detached);
     717             : static ObjectAddress ATExecAttachPartition(List **wqueue, Relation rel,
     718             :                                            PartitionCmd *cmd,
     719             :                                            AlterTableUtilityContext *context);
     720             : static void AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel);
     721             : static void QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
     722             :                                                List *partConstraint,
     723             :                                                bool validate_default);
     724             : static void CloneRowTriggersToPartition(Relation parent, Relation partition);
     725             : static void DropClonedTriggersFromPartition(Oid partitionId);
     726             : static ObjectAddress ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab,
     727             :                                            Relation rel, RangeVar *name,
     728             :                                            bool concurrent);
     729             : static void DetachPartitionFinalize(Relation rel, Relation partRel,
     730             :                                     bool concurrent, Oid defaultPartOid);
     731             : static ObjectAddress ATExecDetachPartitionFinalize(Relation rel, RangeVar *name);
     732             : static ObjectAddress ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx,
     733             :                                               RangeVar *name);
     734             : static void validatePartitionedIndex(Relation partedIdx, Relation partedTbl);
     735             : static void refuseDupeIndexAttach(Relation parentIdx, Relation partIdx,
     736             :                                   Relation partitionTbl);
     737             : static void verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition);
     738             : static List *GetParentedForeignKeyRefs(Relation partition);
     739             : static void ATDetachCheckNoForeignKeyRefs(Relation partition);
     740             : static char GetAttributeCompression(Oid atttypid, const char *compression);
     741             : static char GetAttributeStorage(Oid atttypid, const char *storagemode);
     742             : 
     743             : 
     744             : /* ----------------------------------------------------------------
     745             :  *      DefineRelation
     746             :  *              Creates a new relation.
     747             :  *
     748             :  * stmt carries parsetree information from an ordinary CREATE TABLE statement.
     749             :  * The other arguments are used to extend the behavior for other cases:
     750             :  * relkind: relkind to assign to the new relation
     751             :  * ownerId: if not InvalidOid, use this as the new relation's owner.
     752             :  * typaddress: if not null, it's set to the pg_type entry's address.
     753             :  * queryString: for error reporting
     754             :  *
     755             :  * Note that permissions checks are done against current user regardless of
     756             :  * ownerId.  A nonzero ownerId is used when someone is creating a relation
     757             :  * "on behalf of" someone else, so we still want to see that the current user
     758             :  * has permissions to do it.
     759             :  *
     760             :  * If successful, returns the address of the new relation.
     761             :  * ----------------------------------------------------------------
     762             :  */
     763             : ObjectAddress
     764       63212 : DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
     765             :                ObjectAddress *typaddress, const char *queryString)
     766             : {
     767             :     char        relname[NAMEDATALEN];
     768             :     Oid         namespaceId;
     769             :     Oid         relationId;
     770             :     Oid         tablespaceId;
     771             :     Relation    rel;
     772             :     TupleDesc   descriptor;
     773             :     List       *inheritOids;
     774             :     List       *old_constraints;
     775             :     List       *old_notnulls;
     776             :     List       *rawDefaults;
     777             :     List       *cookedDefaults;
     778             :     List       *nncols;
     779             :     Datum       reloptions;
     780             :     ListCell   *listptr;
     781             :     AttrNumber  attnum;
     782             :     bool        partitioned;
     783       63212 :     const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
     784             :     Oid         ofTypeId;
     785             :     ObjectAddress address;
     786             :     LOCKMODE    parentLockmode;
     787       63212 :     Oid         accessMethodId = InvalidOid;
     788             : 
     789             :     /*
     790             :      * Truncate relname to appropriate length (probably a waste of time, as
     791             :      * parser should have done this already).
     792             :      */
     793       63212 :     strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
     794             : 
     795             :     /*
     796             :      * Check consistency of arguments
     797             :      */
     798       63212 :     if (stmt->oncommit != ONCOMMIT_NOOP
     799         188 :         && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
     800          12 :         ereport(ERROR,
     801             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
     802             :                  errmsg("ON COMMIT can only be used on temporary tables")));
     803             : 
     804       63200 :     if (stmt->partspec != NULL)
     805             :     {
     806        5094 :         if (relkind != RELKIND_RELATION)
     807           0 :             elog(ERROR, "unexpected relkind: %d", (int) relkind);
     808             : 
     809        5094 :         relkind = RELKIND_PARTITIONED_TABLE;
     810        5094 :         partitioned = true;
     811             :     }
     812             :     else
     813       58106 :         partitioned = false;
     814             : 
     815       63200 :     if (relkind == RELKIND_PARTITIONED_TABLE &&
     816        5094 :         stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
     817           6 :         ereport(ERROR,
     818             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     819             :                  errmsg("partitioned tables cannot be unlogged")));
     820             : 
     821             :     /*
     822             :      * Look up the namespace in which we are supposed to create the relation,
     823             :      * check we have permission to create there, lock it against concurrent
     824             :      * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
     825             :      * namespace is selected.
     826             :      */
     827             :     namespaceId =
     828       63194 :         RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
     829             : 
     830             :     /*
     831             :      * Security check: disallow creating temp tables from security-restricted
     832             :      * code.  This is needed because calling code might not expect untrusted
     833             :      * tables to appear in pg_temp at the front of its search path.
     834             :      */
     835       63194 :     if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
     836        3220 :         && InSecurityRestrictedOperation())
     837           0 :         ereport(ERROR,
     838             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     839             :                  errmsg("cannot create temporary table within security-restricted operation")));
     840             : 
     841             :     /*
     842             :      * Determine the lockmode to use when scanning parents.  A self-exclusive
     843             :      * lock is needed here.
     844             :      *
     845             :      * For regular inheritance, if two backends attempt to add children to the
     846             :      * same parent simultaneously, and that parent has no pre-existing
     847             :      * children, then both will attempt to update the parent's relhassubclass
     848             :      * field, leading to a "tuple concurrently updated" error.  Also, this
     849             :      * interlocks against a concurrent ANALYZE on the parent table, which
     850             :      * might otherwise be attempting to clear the parent's relhassubclass
     851             :      * field, if its previous children were recently dropped.
     852             :      *
     853             :      * If the child table is a partition, then we instead grab an exclusive
     854             :      * lock on the parent because its partition descriptor will be changed by
     855             :      * addition of the new partition.
     856             :      */
     857       63194 :     parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
     858             :                       ShareUpdateExclusiveLock);
     859             : 
     860             :     /* Determine the list of OIDs of the parents. */
     861       63194 :     inheritOids = NIL;
     862       73900 :     foreach(listptr, stmt->inhRelations)
     863             :     {
     864       10706 :         RangeVar   *rv = (RangeVar *) lfirst(listptr);
     865             :         Oid         parentOid;
     866             : 
     867       10706 :         parentOid = RangeVarGetRelid(rv, parentLockmode, false);
     868             : 
     869             :         /*
     870             :          * Reject duplications in the list of parents.
     871             :          */
     872       10706 :         if (list_member_oid(inheritOids, parentOid))
     873           0 :             ereport(ERROR,
     874             :                     (errcode(ERRCODE_DUPLICATE_TABLE),
     875             :                      errmsg("relation \"%s\" would be inherited from more than once",
     876             :                             get_rel_name(parentOid))));
     877             : 
     878       10706 :         inheritOids = lappend_oid(inheritOids, parentOid);
     879             :     }
     880             : 
     881             :     /*
     882             :      * Select tablespace to use: an explicitly indicated one, or (in the case
     883             :      * of a partitioned table) the parent's, if it has one.
     884             :      */
     885       63194 :     if (stmt->tablespacename)
     886             :     {
     887         128 :         tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
     888             : 
     889         122 :         if (partitioned && tablespaceId == MyDatabaseTableSpace)
     890           6 :             ereport(ERROR,
     891             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     892             :                      errmsg("cannot specify default tablespace for partitioned relations")));
     893             :     }
     894       63066 :     else if (stmt->partbound)
     895             :     {
     896             :         Assert(list_length(inheritOids) == 1);
     897        8180 :         tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
     898             :     }
     899             :     else
     900       54886 :         tablespaceId = InvalidOid;
     901             : 
     902             :     /* still nothing? use the default */
     903       63182 :     if (!OidIsValid(tablespaceId))
     904       63044 :         tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
     905             :                                             partitioned);
     906             : 
     907             :     /* Check permissions except when using database's default */
     908       63176 :     if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
     909             :     {
     910             :         AclResult   aclresult;
     911             : 
     912         164 :         aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
     913             :                                     ACL_CREATE);
     914         164 :         if (aclresult != ACLCHECK_OK)
     915           6 :             aclcheck_error(aclresult, OBJECT_TABLESPACE,
     916           6 :                            get_tablespace_name(tablespaceId));
     917             :     }
     918             : 
     919             :     /* In all cases disallow placing user relations in pg_global */
     920       63170 :     if (tablespaceId == GLOBALTABLESPACE_OID)
     921          18 :         ereport(ERROR,
     922             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     923             :                  errmsg("only shared relations can be placed in pg_global tablespace")));
     924             : 
     925             :     /* Identify user ID that will own the table */
     926       63152 :     if (!OidIsValid(ownerId))
     927       62912 :         ownerId = GetUserId();
     928             : 
     929             :     /*
     930             :      * Parse and validate reloptions, if any.
     931             :      */
     932       63152 :     reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
     933             :                                      true, false);
     934             : 
     935       63134 :     switch (relkind)
     936             :     {
     937       16786 :         case RELKIND_VIEW:
     938       16786 :             (void) view_reloptions(reloptions, true);
     939       16768 :             break;
     940        5070 :         case RELKIND_PARTITIONED_TABLE:
     941        5070 :             (void) partitioned_table_reloptions(reloptions, true);
     942        5064 :             break;
     943       41278 :         default:
     944       41278 :             (void) heap_reloptions(relkind, reloptions, true);
     945             :     }
     946             : 
     947       63014 :     if (stmt->ofTypename)
     948             :     {
     949             :         AclResult   aclresult;
     950             : 
     951          86 :         ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
     952             : 
     953          86 :         aclresult = object_aclcheck(TypeRelationId, ofTypeId, GetUserId(), ACL_USAGE);
     954          86 :         if (aclresult != ACLCHECK_OK)
     955           6 :             aclcheck_error_type(aclresult, ofTypeId);
     956             :     }
     957             :     else
     958       62928 :         ofTypeId = InvalidOid;
     959             : 
     960             :     /*
     961             :      * Look up inheritance ancestors and generate relation schema, including
     962             :      * inherited attributes.  (Note that stmt->tableElts is destructively
     963             :      * modified by MergeAttributes.)
     964             :      */
     965       62768 :     stmt->tableElts =
     966       63008 :         MergeAttributes(stmt->tableElts, inheritOids,
     967       63008 :                         stmt->relation->relpersistence,
     968       63008 :                         stmt->partbound != NULL,
     969             :                         &old_constraints, &old_notnulls);
     970             : 
     971             :     /*
     972             :      * Create a tuple descriptor from the relation schema.  Note that this
     973             :      * deals with column names, types, and in-descriptor NOT NULL flags, but
     974             :      * not default values, NOT NULL or CHECK constraints; we handle those
     975             :      * below.
     976             :      */
     977       62768 :     descriptor = BuildDescForRelation(stmt->tableElts);
     978             : 
     979             :     /*
     980             :      * Find columns with default values and prepare for insertion of the
     981             :      * defaults.  Pre-cooked (that is, inherited) defaults go into a list of
     982             :      * CookedConstraint structs that we'll pass to heap_create_with_catalog,
     983             :      * while raw defaults go into a list of RawColumnDefault structs that will
     984             :      * be processed by AddRelationNewConstraints.  (We can't deal with raw
     985             :      * expressions until we can do transformExpr.)
     986             :      */
     987       62720 :     rawDefaults = NIL;
     988       62720 :     cookedDefaults = NIL;
     989       62720 :     attnum = 0;
     990             : 
     991      318742 :     foreach(listptr, stmt->tableElts)
     992             :     {
     993      256022 :         ColumnDef  *colDef = lfirst(listptr);
     994             : 
     995      256022 :         attnum++;
     996      256022 :         if (colDef->raw_default != NULL)
     997             :         {
     998             :             RawColumnDefault *rawEnt;
     999             : 
    1000             :             Assert(colDef->cooked_default == NULL);
    1001             : 
    1002        3220 :             rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
    1003        3220 :             rawEnt->attnum = attnum;
    1004        3220 :             rawEnt->raw_default = colDef->raw_default;
    1005        3220 :             rawEnt->generated = colDef->generated;
    1006        3220 :             rawDefaults = lappend(rawDefaults, rawEnt);
    1007             :         }
    1008      252802 :         else if (colDef->cooked_default != NULL)
    1009             :         {
    1010             :             CookedConstraint *cooked;
    1011             : 
    1012         402 :             cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
    1013         402 :             cooked->contype = CONSTR_DEFAULT;
    1014         402 :             cooked->conoid = InvalidOid; /* until created */
    1015         402 :             cooked->name = NULL;
    1016         402 :             cooked->attnum = attnum;
    1017         402 :             cooked->expr = colDef->cooked_default;
    1018         402 :             cooked->is_enforced = true;
    1019         402 :             cooked->skip_validation = false;
    1020         402 :             cooked->is_local = true; /* not used for defaults */
    1021         402 :             cooked->inhcount = 0;    /* ditto */
    1022         402 :             cooked->is_no_inherit = false;
    1023         402 :             cookedDefaults = lappend(cookedDefaults, cooked);
    1024             :         }
    1025             :     }
    1026             : 
    1027             :     /*
    1028             :      * For relations with table AM and partitioned tables, select access
    1029             :      * method to use: an explicitly indicated one, or (in the case of a
    1030             :      * partitioned table) the parent's, if it has one.
    1031             :      */
    1032       62720 :     if (stmt->accessMethod != NULL)
    1033             :     {
    1034             :         Assert(RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE);
    1035         122 :         accessMethodId = get_table_am_oid(stmt->accessMethod, false);
    1036             :     }
    1037       62598 :     else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
    1038             :     {
    1039       39040 :         if (stmt->partbound)
    1040             :         {
    1041             :             Assert(list_length(inheritOids) == 1);
    1042        7998 :             accessMethodId = get_rel_relam(linitial_oid(inheritOids));
    1043             :         }
    1044             : 
    1045       39040 :         if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
    1046       33962 :             accessMethodId = get_table_am_oid(default_table_access_method, false);
    1047             :     }
    1048             : 
    1049             :     /*
    1050             :      * Create the relation.  Inherited defaults and CHECK constraints are
    1051             :      * passed in for immediate handling --- since they don't need parsing,
    1052             :      * they can be stored immediately.
    1053             :      */
    1054       62702 :     relationId = heap_create_with_catalog(relname,
    1055             :                                           namespaceId,
    1056             :                                           tablespaceId,
    1057             :                                           InvalidOid,
    1058             :                                           InvalidOid,
    1059             :                                           ofTypeId,
    1060             :                                           ownerId,
    1061             :                                           accessMethodId,
    1062             :                                           descriptor,
    1063             :                                           list_concat(cookedDefaults,
    1064             :                                                       old_constraints),
    1065             :                                           relkind,
    1066       62702 :                                           stmt->relation->relpersistence,
    1067             :                                           false,
    1068             :                                           false,
    1069             :                                           stmt->oncommit,
    1070             :                                           reloptions,
    1071             :                                           true,
    1072             :                                           allowSystemTableMods,
    1073             :                                           false,
    1074             :                                           InvalidOid,
    1075             :                                           typaddress);
    1076             : 
    1077             :     /*
    1078             :      * We must bump the command counter to make the newly-created relation
    1079             :      * tuple visible for opening.
    1080             :      */
    1081       62654 :     CommandCounterIncrement();
    1082             : 
    1083             :     /*
    1084             :      * Open the new relation and acquire exclusive lock on it.  This isn't
    1085             :      * really necessary for locking out other backends (since they can't see
    1086             :      * the new rel anyway until we commit), but it keeps the lock manager from
    1087             :      * complaining about deadlock risks.
    1088             :      */
    1089       62654 :     rel = relation_open(relationId, AccessExclusiveLock);
    1090             : 
    1091             :     /*
    1092             :      * Now add any newly specified column default and generation expressions
    1093             :      * to the new relation.  These are passed to us in the form of raw
    1094             :      * parsetrees; we need to transform them to executable expression trees
    1095             :      * before they can be added. The most convenient way to do that is to
    1096             :      * apply the parser's transformExpr routine, but transformExpr doesn't
    1097             :      * work unless we have a pre-existing relation. So, the transformation has
    1098             :      * to be postponed to this final step of CREATE TABLE.
    1099             :      *
    1100             :      * This needs to be before processing the partitioning clauses because
    1101             :      * those could refer to generated columns.
    1102             :      */
    1103       62654 :     if (rawDefaults)
    1104        2754 :         AddRelationNewConstraints(rel, rawDefaults, NIL,
    1105             :                                   true, true, false, queryString);
    1106             : 
    1107             :     /*
    1108             :      * Make column generation expressions visible for use by partitioning.
    1109             :      */
    1110       62462 :     CommandCounterIncrement();
    1111             : 
    1112             :     /* Process and store partition bound, if any. */
    1113       62462 :     if (stmt->partbound)
    1114             :     {
    1115             :         PartitionBoundSpec *bound;
    1116             :         ParseState *pstate;
    1117        8102 :         Oid         parentId = linitial_oid(inheritOids),
    1118             :                     defaultPartOid;
    1119             :         Relation    parent,
    1120        8102 :                     defaultRel = NULL;
    1121             :         ParseNamespaceItem *nsitem;
    1122             : 
    1123             :         /* Already have strong enough lock on the parent */
    1124        8102 :         parent = table_open(parentId, NoLock);
    1125             : 
    1126             :         /*
    1127             :          * We are going to try to validate the partition bound specification
    1128             :          * against the partition key of parentRel, so it better have one.
    1129             :          */
    1130        8102 :         if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    1131          18 :             ereport(ERROR,
    1132             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1133             :                      errmsg("\"%s\" is not partitioned",
    1134             :                             RelationGetRelationName(parent))));
    1135             : 
    1136             :         /*
    1137             :          * The partition constraint of the default partition depends on the
    1138             :          * partition bounds of every other partition. It is possible that
    1139             :          * another backend might be about to execute a query on the default
    1140             :          * partition table, and that the query relies on previously cached
    1141             :          * default partition constraints. We must therefore take a table lock
    1142             :          * strong enough to prevent all queries on the default partition from
    1143             :          * proceeding until we commit and send out a shared-cache-inval notice
    1144             :          * that will make them update their index lists.
    1145             :          *
    1146             :          * Order of locking: The relation being added won't be visible to
    1147             :          * other backends until it is committed, hence here in
    1148             :          * DefineRelation() the order of locking the default partition and the
    1149             :          * relation being added does not matter. But at all other places we
    1150             :          * need to lock the default relation before we lock the relation being
    1151             :          * added or removed i.e. we should take the lock in same order at all
    1152             :          * the places such that lock parent, lock default partition and then
    1153             :          * lock the partition so as to avoid a deadlock.
    1154             :          */
    1155             :         defaultPartOid =
    1156        8084 :             get_default_oid_from_partdesc(RelationGetPartitionDesc(parent,
    1157             :                                                                    true));
    1158        8084 :         if (OidIsValid(defaultPartOid))
    1159         378 :             defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
    1160             : 
    1161             :         /* Transform the bound values */
    1162        8084 :         pstate = make_parsestate(NULL);
    1163        8084 :         pstate->p_sourcetext = queryString;
    1164             : 
    1165             :         /*
    1166             :          * Add an nsitem containing this relation, so that transformExpr
    1167             :          * called on partition bound expressions is able to report errors
    1168             :          * using a proper context.
    1169             :          */
    1170        8084 :         nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
    1171             :                                                NULL, false, false);
    1172        8084 :         addNSItemToQuery(pstate, nsitem, false, true, true);
    1173             : 
    1174        8084 :         bound = transformPartitionBound(pstate, parent, stmt->partbound);
    1175             : 
    1176             :         /*
    1177             :          * Check first that the new partition's bound is valid and does not
    1178             :          * overlap with any of existing partitions of the parent.
    1179             :          */
    1180        7880 :         check_new_partition_bound(relname, parent, bound, pstate);
    1181             : 
    1182             :         /*
    1183             :          * If the default partition exists, its partition constraints will
    1184             :          * change after the addition of this new partition such that it won't
    1185             :          * allow any row that qualifies for this new partition. So, check that
    1186             :          * the existing data in the default partition satisfies the constraint
    1187             :          * as it will exist after adding this partition.
    1188             :          */
    1189        7766 :         if (OidIsValid(defaultPartOid))
    1190             :         {
    1191         348 :             check_default_partition_contents(parent, defaultRel, bound);
    1192             :             /* Keep the lock until commit. */
    1193         330 :             table_close(defaultRel, NoLock);
    1194             :         }
    1195             : 
    1196             :         /* Update the pg_class entry. */
    1197        7748 :         StorePartitionBound(rel, parent, bound);
    1198             : 
    1199        7748 :         table_close(parent, NoLock);
    1200             :     }
    1201             : 
    1202             :     /* Store inheritance information for new rel. */
    1203       62108 :     StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
    1204             : 
    1205             :     /*
    1206             :      * Process the partitioning specification (if any) and store the partition
    1207             :      * key information into the catalog.
    1208             :      */
    1209       62108 :     if (partitioned)
    1210             :     {
    1211             :         ParseState *pstate;
    1212             :         int         partnatts;
    1213             :         AttrNumber  partattrs[PARTITION_MAX_KEYS];
    1214             :         Oid         partopclass[PARTITION_MAX_KEYS];
    1215             :         Oid         partcollation[PARTITION_MAX_KEYS];
    1216        5064 :         List       *partexprs = NIL;
    1217             : 
    1218        5064 :         pstate = make_parsestate(NULL);
    1219        5064 :         pstate->p_sourcetext = queryString;
    1220             : 
    1221        5064 :         partnatts = list_length(stmt->partspec->partParams);
    1222             : 
    1223             :         /* Protect fixed-size arrays here and in executor */
    1224        5064 :         if (partnatts > PARTITION_MAX_KEYS)
    1225           0 :             ereport(ERROR,
    1226             :                     (errcode(ERRCODE_TOO_MANY_COLUMNS),
    1227             :                      errmsg("cannot partition using more than %d columns",
    1228             :                             PARTITION_MAX_KEYS)));
    1229             : 
    1230             :         /*
    1231             :          * We need to transform the raw parsetrees corresponding to partition
    1232             :          * expressions into executable expression trees.  Like column defaults
    1233             :          * and CHECK constraints, we could not have done the transformation
    1234             :          * earlier.
    1235             :          */
    1236        5064 :         stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
    1237             : 
    1238        5034 :         ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
    1239             :                               partattrs, &partexprs, partopclass,
    1240        5034 :                               partcollation, stmt->partspec->strategy);
    1241             : 
    1242        4938 :         StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
    1243             :                           partexprs,
    1244             :                           partopclass, partcollation);
    1245             : 
    1246             :         /* make it all visible */
    1247        4938 :         CommandCounterIncrement();
    1248             :     }
    1249             : 
    1250             :     /*
    1251             :      * If we're creating a partition, create now all the indexes, triggers,
    1252             :      * FKs defined in the parent.
    1253             :      *
    1254             :      * We can't do it earlier, because DefineIndex wants to know the partition
    1255             :      * key which we just stored.
    1256             :      */
    1257       61982 :     if (stmt->partbound)
    1258             :     {
    1259        7742 :         Oid         parentId = linitial_oid(inheritOids);
    1260             :         Relation    parent;
    1261             :         List       *idxlist;
    1262             :         ListCell   *cell;
    1263             : 
    1264             :         /* Already have strong enough lock on the parent */
    1265        7742 :         parent = table_open(parentId, NoLock);
    1266        7742 :         idxlist = RelationGetIndexList(parent);
    1267             : 
    1268             :         /*
    1269             :          * For each index in the parent table, create one in the partition
    1270             :          */
    1271        9162 :         foreach(cell, idxlist)
    1272             :         {
    1273        1438 :             Relation    idxRel = index_open(lfirst_oid(cell), AccessShareLock);
    1274             :             AttrMap    *attmap;
    1275             :             IndexStmt  *idxstmt;
    1276             :             Oid         constraintOid;
    1277             : 
    1278        1438 :             if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    1279             :             {
    1280          36 :                 if (idxRel->rd_index->indisunique)
    1281          12 :                     ereport(ERROR,
    1282             :                             (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1283             :                              errmsg("cannot create foreign partition of partitioned table \"%s\"",
    1284             :                                     RelationGetRelationName(parent)),
    1285             :                              errdetail("Table \"%s\" contains indexes that are unique.",
    1286             :                                        RelationGetRelationName(parent))));
    1287             :                 else
    1288             :                 {
    1289          24 :                     index_close(idxRel, AccessShareLock);
    1290          24 :                     continue;
    1291             :                 }
    1292             :             }
    1293             : 
    1294        1402 :             attmap = build_attrmap_by_name(RelationGetDescr(rel),
    1295             :                                            RelationGetDescr(parent),
    1296             :                                            false);
    1297             :             idxstmt =
    1298        1402 :                 generateClonedIndexStmt(NULL, idxRel,
    1299             :                                         attmap, &constraintOid);
    1300        1402 :             DefineIndex(RelationGetRelid(rel),
    1301             :                         idxstmt,
    1302             :                         InvalidOid,
    1303             :                         RelationGetRelid(idxRel),
    1304             :                         constraintOid,
    1305             :                         -1,
    1306             :                         false, false, false, false, false);
    1307             : 
    1308        1396 :             index_close(idxRel, AccessShareLock);
    1309             :         }
    1310             : 
    1311        7724 :         list_free(idxlist);
    1312             : 
    1313             :         /*
    1314             :          * If there are any row-level triggers, clone them to the new
    1315             :          * partition.
    1316             :          */
    1317        7724 :         if (parent->trigdesc != NULL)
    1318         444 :             CloneRowTriggersToPartition(parent, rel);
    1319             : 
    1320             :         /*
    1321             :          * And foreign keys too.  Note that because we're freshly creating the
    1322             :          * table, there is no need to verify these new constraints.
    1323             :          */
    1324        7724 :         CloneForeignKeyConstraints(NULL, parent, rel);
    1325             : 
    1326        7724 :         table_close(parent, NoLock);
    1327             :     }
    1328             : 
    1329             :     /*
    1330             :      * Now add any newly specified CHECK constraints to the new relation. Same
    1331             :      * as for defaults above, but these need to come after partitioning is set
    1332             :      * up.
    1333             :      */
    1334       61964 :     if (stmt->constraints)
    1335         736 :         AddRelationNewConstraints(rel, NIL, stmt->constraints,
    1336             :                                   true, true, false, queryString);
    1337             : 
    1338             :     /*
    1339             :      * Finally, merge the not-null constraints that are declared directly with
    1340             :      * those that come from parent relations (making sure to count inheritance
    1341             :      * appropriately for each), create them, and set the attnotnull flag on
    1342             :      * columns that don't yet have it.
    1343             :      */
    1344       61934 :     nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
    1345             :                                            old_notnulls);
    1346      139058 :     foreach_int(attrnum, nncols)
    1347       15346 :         set_attnotnull(NULL, rel, attrnum, true, false);
    1348             : 
    1349       61856 :     ObjectAddressSet(address, RelationRelationId, relationId);
    1350             : 
    1351             :     /*
    1352             :      * Clean up.  We keep lock on new relation (although it shouldn't be
    1353             :      * visible to anyone else anyway, until commit).
    1354             :      */
    1355       61856 :     relation_close(rel, NoLock);
    1356             : 
    1357       61856 :     return address;
    1358             : }
    1359             : 
    1360             : /*
    1361             :  * BuildDescForRelation
    1362             :  *
    1363             :  * Given a list of ColumnDef nodes, build a TupleDesc.
    1364             :  *
    1365             :  * Note: This is only for the limited purpose of table and view creation.  Not
    1366             :  * everything is filled in.  A real tuple descriptor should be obtained from
    1367             :  * the relcache.
    1368             :  */
    1369             : TupleDesc
    1370       65758 : BuildDescForRelation(const List *columns)
    1371             : {
    1372             :     int         natts;
    1373             :     AttrNumber  attnum;
    1374             :     ListCell   *l;
    1375             :     TupleDesc   desc;
    1376             :     char       *attname;
    1377             :     Oid         atttypid;
    1378             :     int32       atttypmod;
    1379             :     Oid         attcollation;
    1380             :     int         attdim;
    1381             : 
    1382             :     /*
    1383             :      * allocate a new tuple descriptor
    1384             :      */
    1385       65758 :     natts = list_length(columns);
    1386       65758 :     desc = CreateTemplateTupleDesc(natts);
    1387             : 
    1388       65758 :     attnum = 0;
    1389             : 
    1390      325034 :     foreach(l, columns)
    1391             :     {
    1392      259336 :         ColumnDef  *entry = lfirst(l);
    1393             :         AclResult   aclresult;
    1394             :         Form_pg_attribute att;
    1395             : 
    1396             :         /*
    1397             :          * for each entry in the list, get the name and type information from
    1398             :          * the list and have TupleDescInitEntry fill in the attribute
    1399             :          * information we need.
    1400             :          */
    1401      259336 :         attnum++;
    1402             : 
    1403      259336 :         attname = entry->colname;
    1404      259336 :         typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
    1405             : 
    1406      259336 :         aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
    1407      259336 :         if (aclresult != ACLCHECK_OK)
    1408          42 :             aclcheck_error_type(aclresult, atttypid);
    1409             : 
    1410      259294 :         attcollation = GetColumnDefCollation(NULL, entry, atttypid);
    1411      259294 :         attdim = list_length(entry->typeName->arrayBounds);
    1412      259294 :         if (attdim > PG_INT16_MAX)
    1413           0 :             ereport(ERROR,
    1414             :                     errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1415             :                     errmsg("too many array dimensions"));
    1416             : 
    1417      259294 :         if (entry->typeName->setof)
    1418           0 :             ereport(ERROR,
    1419             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    1420             :                      errmsg("column \"%s\" cannot be declared SETOF",
    1421             :                             attname)));
    1422             : 
    1423      259294 :         TupleDescInitEntry(desc, attnum, attname,
    1424             :                            atttypid, atttypmod, attdim);
    1425      259294 :         att = TupleDescAttr(desc, attnum - 1);
    1426             : 
    1427             :         /* Override TupleDescInitEntry's settings as requested */
    1428      259294 :         TupleDescInitEntryCollation(desc, attnum, attcollation);
    1429             : 
    1430             :         /* Fill in additional stuff not handled by TupleDescInitEntry */
    1431      259294 :         att->attnotnull = entry->is_not_null;
    1432      259294 :         att->attislocal = entry->is_local;
    1433      259294 :         att->attinhcount = entry->inhcount;
    1434      259294 :         att->attidentity = entry->identity;
    1435      259294 :         att->attgenerated = entry->generated;
    1436      259294 :         att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
    1437      259282 :         if (entry->storage)
    1438       20624 :             att->attstorage = entry->storage;
    1439      238658 :         else if (entry->storage_name)
    1440          26 :             att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
    1441             : 
    1442      259276 :         populate_compact_attribute(desc, attnum - 1);
    1443             :     }
    1444             : 
    1445       65698 :     return desc;
    1446             : }
    1447             : 
    1448             : /*
    1449             :  * Emit the right error or warning message for a "DROP" command issued on a
    1450             :  * non-existent relation
    1451             :  */
    1452             : static void
    1453        1088 : DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
    1454             : {
    1455             :     const struct dropmsgstrings *rentry;
    1456             : 
    1457        1208 :     if (rel->schemaname != NULL &&
    1458         120 :         !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
    1459             :     {
    1460          42 :         if (!missing_ok)
    1461             :         {
    1462           0 :             ereport(ERROR,
    1463             :                     (errcode(ERRCODE_UNDEFINED_SCHEMA),
    1464             :                      errmsg("schema \"%s\" does not exist", rel->schemaname)));
    1465             :         }
    1466             :         else
    1467             :         {
    1468          42 :             ereport(NOTICE,
    1469             :                     (errmsg("schema \"%s\" does not exist, skipping",
    1470             :                             rel->schemaname)));
    1471             :         }
    1472          42 :         return;
    1473             :     }
    1474             : 
    1475        1366 :     for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
    1476             :     {
    1477        1366 :         if (rentry->kind == rightkind)
    1478             :         {
    1479        1046 :             if (!missing_ok)
    1480             :             {
    1481         138 :                 ereport(ERROR,
    1482             :                         (errcode(rentry->nonexistent_code),
    1483             :                          errmsg(rentry->nonexistent_msg, rel->relname)));
    1484             :             }
    1485             :             else
    1486             :             {
    1487         908 :                 ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
    1488         908 :                 break;
    1489             :             }
    1490             :         }
    1491             :     }
    1492             : 
    1493             :     Assert(rentry->kind != '\0');    /* Should be impossible */
    1494             : }
    1495             : 
    1496             : /*
    1497             :  * Emit the right error message for a "DROP" command issued on a
    1498             :  * relation of the wrong type
    1499             :  */
    1500             : static void
    1501           0 : DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
    1502             : {
    1503             :     const struct dropmsgstrings *rentry;
    1504             :     const struct dropmsgstrings *wentry;
    1505             : 
    1506           0 :     for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
    1507           0 :         if (rentry->kind == rightkind)
    1508           0 :             break;
    1509             :     Assert(rentry->kind != '\0');
    1510             : 
    1511           0 :     for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
    1512           0 :         if (wentry->kind == wrongkind)
    1513           0 :             break;
    1514             :     /* wrongkind could be something we don't have in our table... */
    1515             : 
    1516           0 :     ereport(ERROR,
    1517             :             (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1518             :              errmsg(rentry->nota_msg, relname),
    1519             :              (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
    1520             : }
    1521             : 
    1522             : /*
    1523             :  * RemoveRelations
    1524             :  *      Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
    1525             :  *      DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
    1526             :  */
    1527             : void
    1528       17556 : RemoveRelations(DropStmt *drop)
    1529             : {
    1530             :     ObjectAddresses *objects;
    1531             :     char        relkind;
    1532             :     ListCell   *cell;
    1533       17556 :     int         flags = 0;
    1534       17556 :     LOCKMODE    lockmode = AccessExclusiveLock;
    1535             : 
    1536             :     /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
    1537       17556 :     if (drop->concurrent)
    1538             :     {
    1539             :         /*
    1540             :          * Note that for temporary relations this lock may get upgraded later
    1541             :          * on, but as no other session can access a temporary relation, this
    1542             :          * is actually fine.
    1543             :          */
    1544         210 :         lockmode = ShareUpdateExclusiveLock;
    1545             :         Assert(drop->removeType == OBJECT_INDEX);
    1546         210 :         if (list_length(drop->objects) != 1)
    1547           6 :             ereport(ERROR,
    1548             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1549             :                      errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
    1550         204 :         if (drop->behavior == DROP_CASCADE)
    1551           0 :             ereport(ERROR,
    1552             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1553             :                      errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
    1554             :     }
    1555             : 
    1556             :     /*
    1557             :      * First we identify all the relations, then we delete them in a single
    1558             :      * performMultipleDeletions() call.  This is to avoid unwanted DROP
    1559             :      * RESTRICT errors if one of the relations depends on another.
    1560             :      */
    1561             : 
    1562             :     /* Determine required relkind */
    1563       17550 :     switch (drop->removeType)
    1564             :     {
    1565       15232 :         case OBJECT_TABLE:
    1566       15232 :             relkind = RELKIND_RELATION;
    1567       15232 :             break;
    1568             : 
    1569         892 :         case OBJECT_INDEX:
    1570         892 :             relkind = RELKIND_INDEX;
    1571         892 :             break;
    1572             : 
    1573         176 :         case OBJECT_SEQUENCE:
    1574         176 :             relkind = RELKIND_SEQUENCE;
    1575         176 :             break;
    1576             : 
    1577         960 :         case OBJECT_VIEW:
    1578         960 :             relkind = RELKIND_VIEW;
    1579         960 :             break;
    1580             : 
    1581         126 :         case OBJECT_MATVIEW:
    1582         126 :             relkind = RELKIND_MATVIEW;
    1583         126 :             break;
    1584             : 
    1585         164 :         case OBJECT_FOREIGN_TABLE:
    1586         164 :             relkind = RELKIND_FOREIGN_TABLE;
    1587         164 :             break;
    1588             : 
    1589           0 :         default:
    1590           0 :             elog(ERROR, "unrecognized drop object type: %d",
    1591             :                  (int) drop->removeType);
    1592             :             relkind = 0;        /* keep compiler quiet */
    1593             :             break;
    1594             :     }
    1595             : 
    1596             :     /* Lock and validate each relation; build a list of object addresses */
    1597       17550 :     objects = new_object_addresses();
    1598             : 
    1599       39110 :     foreach(cell, drop->objects)
    1600             :     {
    1601       21724 :         RangeVar   *rel = makeRangeVarFromNameList((List *) lfirst(cell));
    1602             :         Oid         relOid;
    1603             :         ObjectAddress obj;
    1604             :         struct DropRelationCallbackState state;
    1605             : 
    1606             :         /*
    1607             :          * These next few steps are a great deal like relation_openrv, but we
    1608             :          * don't bother building a relcache entry since we don't need it.
    1609             :          *
    1610             :          * Check for shared-cache-inval messages before trying to access the
    1611             :          * relation.  This is needed to cover the case where the name
    1612             :          * identifies a rel that has been dropped and recreated since the
    1613             :          * start of our transaction: if we don't flush the old syscache entry,
    1614             :          * then we'll latch onto that entry and suffer an error later.
    1615             :          */
    1616       21724 :         AcceptInvalidationMessages();
    1617             : 
    1618             :         /* Look up the appropriate relation using namespace search. */
    1619       21724 :         state.expected_relkind = relkind;
    1620       43448 :         state.heap_lockmode = drop->concurrent ?
    1621       21724 :             ShareUpdateExclusiveLock : AccessExclusiveLock;
    1622             :         /* We must initialize these fields to show that no locks are held: */
    1623       21724 :         state.heapOid = InvalidOid;
    1624       21724 :         state.partParentOid = InvalidOid;
    1625             : 
    1626       21724 :         relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
    1627             :                                           RangeVarCallbackForDropRelation,
    1628             :                                           &state);
    1629             : 
    1630             :         /* Not there? */
    1631       21704 :         if (!OidIsValid(relOid))
    1632             :         {
    1633        1088 :             DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
    1634         950 :             continue;
    1635             :         }
    1636             : 
    1637             :         /*
    1638             :          * Decide if concurrent mode needs to be used here or not.  The
    1639             :          * callback retrieved the rel's persistence for us.
    1640             :          */
    1641       20616 :         if (drop->concurrent &&
    1642         198 :             state.actual_relpersistence != RELPERSISTENCE_TEMP)
    1643             :         {
    1644             :             Assert(list_length(drop->objects) == 1 &&
    1645             :                    drop->removeType == OBJECT_INDEX);
    1646         180 :             flags |= PERFORM_DELETION_CONCURRENTLY;
    1647             :         }
    1648             : 
    1649             :         /*
    1650             :          * Concurrent index drop cannot be used with partitioned indexes,
    1651             :          * either.
    1652             :          */
    1653       20616 :         if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
    1654         180 :             state.actual_relkind == RELKIND_PARTITIONED_INDEX)
    1655           6 :             ereport(ERROR,
    1656             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1657             :                      errmsg("cannot drop partitioned index \"%s\" concurrently",
    1658             :                             rel->relname)));
    1659             : 
    1660             :         /*
    1661             :          * If we're told to drop a partitioned index, we must acquire lock on
    1662             :          * all the children of its parent partitioned table before proceeding.
    1663             :          * Otherwise we'd try to lock the child index partitions before their
    1664             :          * tables, leading to potential deadlock against other sessions that
    1665             :          * will lock those objects in the other order.
    1666             :          */
    1667       20610 :         if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
    1668          76 :             (void) find_all_inheritors(state.heapOid,
    1669             :                                        state.heap_lockmode,
    1670             :                                        NULL);
    1671             : 
    1672             :         /* OK, we're ready to delete this one */
    1673       20610 :         obj.classId = RelationRelationId;
    1674       20610 :         obj.objectId = relOid;
    1675       20610 :         obj.objectSubId = 0;
    1676             : 
    1677       20610 :         add_exact_object_address(&obj, objects);
    1678             :     }
    1679             : 
    1680       17386 :     performMultipleDeletions(objects, drop->behavior, flags);
    1681             : 
    1682       17244 :     free_object_addresses(objects);
    1683       17244 : }
    1684             : 
    1685             : /*
    1686             :  * Before acquiring a table lock, check whether we have sufficient rights.
    1687             :  * In the case of DROP INDEX, also try to lock the table before the index.
    1688             :  * Also, if the table to be dropped is a partition, we try to lock the parent
    1689             :  * first.
    1690             :  */
    1691             : static void
    1692       22152 : RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
    1693             :                                 void *arg)
    1694             : {
    1695             :     HeapTuple   tuple;
    1696             :     struct DropRelationCallbackState *state;
    1697             :     char        expected_relkind;
    1698             :     bool        is_partition;
    1699             :     Form_pg_class classform;
    1700             :     LOCKMODE    heap_lockmode;
    1701       22152 :     bool        invalid_system_index = false;
    1702             : 
    1703       22152 :     state = (struct DropRelationCallbackState *) arg;
    1704       22152 :     heap_lockmode = state->heap_lockmode;
    1705             : 
    1706             :     /*
    1707             :      * If we previously locked some other index's heap, and the name we're
    1708             :      * looking up no longer refers to that relation, release the now-useless
    1709             :      * lock.
    1710             :      */
    1711       22152 :     if (relOid != oldRelOid && OidIsValid(state->heapOid))
    1712             :     {
    1713           0 :         UnlockRelationOid(state->heapOid, heap_lockmode);
    1714           0 :         state->heapOid = InvalidOid;
    1715             :     }
    1716             : 
    1717             :     /*
    1718             :      * Similarly, if we previously locked some other partition's heap, and the
    1719             :      * name we're looking up no longer refers to that relation, release the
    1720             :      * now-useless lock.
    1721             :      */
    1722       22152 :     if (relOid != oldRelOid && OidIsValid(state->partParentOid))
    1723             :     {
    1724           0 :         UnlockRelationOid(state->partParentOid, AccessExclusiveLock);
    1725           0 :         state->partParentOid = InvalidOid;
    1726             :     }
    1727             : 
    1728             :     /* Didn't find a relation, so no need for locking or permission checks. */
    1729       22152 :     if (!OidIsValid(relOid))
    1730        1100 :         return;
    1731             : 
    1732       21052 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
    1733       21052 :     if (!HeapTupleIsValid(tuple))
    1734           0 :         return;                 /* concurrently dropped, so nothing to do */
    1735       21052 :     classform = (Form_pg_class) GETSTRUCT(tuple);
    1736       21052 :     is_partition = classform->relispartition;
    1737             : 
    1738             :     /* Pass back some data to save lookups in RemoveRelations */
    1739       21052 :     state->actual_relkind = classform->relkind;
    1740       21052 :     state->actual_relpersistence = classform->relpersistence;
    1741             : 
    1742             :     /*
    1743             :      * Both RELKIND_RELATION and RELKIND_PARTITIONED_TABLE are OBJECT_TABLE,
    1744             :      * but RemoveRelations() can only pass one relkind for a given relation.
    1745             :      * It chooses RELKIND_RELATION for both regular and partitioned tables.
    1746             :      * That means we must be careful before giving the wrong type error when
    1747             :      * the relation is RELKIND_PARTITIONED_TABLE.  An equivalent problem
    1748             :      * exists with indexes.
    1749             :      */
    1750       21052 :     if (classform->relkind == RELKIND_PARTITIONED_TABLE)
    1751        3042 :         expected_relkind = RELKIND_RELATION;
    1752       18010 :     else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
    1753          88 :         expected_relkind = RELKIND_INDEX;
    1754             :     else
    1755       17922 :         expected_relkind = classform->relkind;
    1756             : 
    1757       21052 :     if (state->expected_relkind != expected_relkind)
    1758           0 :         DropErrorMsgWrongType(rel->relname, classform->relkind,
    1759           0 :                               state->expected_relkind);
    1760             : 
    1761             :     /* Allow DROP to either table owner or schema owner */
    1762       21052 :     if (!object_ownercheck(RelationRelationId, relOid, GetUserId()) &&
    1763          18 :         !object_ownercheck(NamespaceRelationId, classform->relnamespace, GetUserId()))
    1764          18 :         aclcheck_error(ACLCHECK_NOT_OWNER,
    1765          18 :                        get_relkind_objtype(classform->relkind),
    1766          18 :                        rel->relname);
    1767             : 
    1768             :     /*
    1769             :      * Check the case of a system index that might have been invalidated by a
    1770             :      * failed concurrent process and allow its drop. For the time being, this
    1771             :      * only concerns indexes of toast relations that became invalid during a
    1772             :      * REINDEX CONCURRENTLY process.
    1773             :      */
    1774       21034 :     if (IsSystemClass(relOid, classform) && classform->relkind == RELKIND_INDEX)
    1775             :     {
    1776             :         HeapTuple   locTuple;
    1777             :         Form_pg_index indexform;
    1778             :         bool        indisvalid;
    1779             : 
    1780           0 :         locTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
    1781           0 :         if (!HeapTupleIsValid(locTuple))
    1782             :         {
    1783           0 :             ReleaseSysCache(tuple);
    1784           0 :             return;
    1785             :         }
    1786             : 
    1787           0 :         indexform = (Form_pg_index) GETSTRUCT(locTuple);
    1788           0 :         indisvalid = indexform->indisvalid;
    1789           0 :         ReleaseSysCache(locTuple);
    1790             : 
    1791             :         /* Mark object as being an invalid index of system catalogs */
    1792           0 :         if (!indisvalid)
    1793           0 :             invalid_system_index = true;
    1794             :     }
    1795             : 
    1796             :     /* In the case of an invalid index, it is fine to bypass this check */
    1797       21034 :     if (!invalid_system_index && !allowSystemTableMods && IsSystemClass(relOid, classform))
    1798           2 :         ereport(ERROR,
    1799             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1800             :                  errmsg("permission denied: \"%s\" is a system catalog",
    1801             :                         rel->relname)));
    1802             : 
    1803       21032 :     ReleaseSysCache(tuple);
    1804             : 
    1805             :     /*
    1806             :      * In DROP INDEX, attempt to acquire lock on the parent table before
    1807             :      * locking the index.  index_drop() will need this anyway, and since
    1808             :      * regular queries lock tables before their indexes, we risk deadlock if
    1809             :      * we do it the other way around.  No error if we don't find a pg_index
    1810             :      * entry, though --- the relation may have been dropped.  Note that this
    1811             :      * code will execute for either plain or partitioned indexes.
    1812             :      */
    1813       21032 :     if (expected_relkind == RELKIND_INDEX &&
    1814             :         relOid != oldRelOid)
    1815             :     {
    1816         880 :         state->heapOid = IndexGetRelation(relOid, true);
    1817         880 :         if (OidIsValid(state->heapOid))
    1818         880 :             LockRelationOid(state->heapOid, heap_lockmode);
    1819             :     }
    1820             : 
    1821             :     /*
    1822             :      * Similarly, if the relation is a partition, we must acquire lock on its
    1823             :      * parent before locking the partition.  That's because queries lock the
    1824             :      * parent before its partitions, so we risk deadlock if we do it the other
    1825             :      * way around.
    1826             :      */
    1827       21032 :     if (is_partition && relOid != oldRelOid)
    1828             :     {
    1829         618 :         state->partParentOid = get_partition_parent(relOid, true);
    1830         618 :         if (OidIsValid(state->partParentOid))
    1831         618 :             LockRelationOid(state->partParentOid, AccessExclusiveLock);
    1832             :     }
    1833             : }
    1834             : 
    1835             : /*
    1836             :  * ExecuteTruncate
    1837             :  *      Executes a TRUNCATE command.
    1838             :  *
    1839             :  * This is a multi-relation truncate.  We first open and grab exclusive
    1840             :  * lock on all relations involved, checking permissions and otherwise
    1841             :  * verifying that the relation is OK for truncation.  Note that if relations
    1842             :  * are foreign tables, at this stage, we have not yet checked that their
    1843             :  * foreign data in external data sources are OK for truncation.  These are
    1844             :  * checked when foreign data are actually truncated later.  In CASCADE mode,
    1845             :  * relations having FK references to the targeted relations are automatically
    1846             :  * added to the group; in RESTRICT mode, we check that all FK references are
    1847             :  * internal to the group that's being truncated.  Finally all the relations
    1848             :  * are truncated and reindexed.
    1849             :  */
    1850             : void
    1851        1764 : ExecuteTruncate(TruncateStmt *stmt)
    1852             : {
    1853        1764 :     List       *rels = NIL;
    1854        1764 :     List       *relids = NIL;
    1855        1764 :     List       *relids_logged = NIL;
    1856             :     ListCell   *cell;
    1857             : 
    1858             :     /*
    1859             :      * Open, exclusive-lock, and check all the explicitly-specified relations
    1860             :      */
    1861        3740 :     foreach(cell, stmt->relations)
    1862             :     {
    1863        2032 :         RangeVar   *rv = lfirst(cell);
    1864             :         Relation    rel;
    1865        2032 :         bool        recurse = rv->inh;
    1866             :         Oid         myrelid;
    1867        2032 :         LOCKMODE    lockmode = AccessExclusiveLock;
    1868             : 
    1869        2032 :         myrelid = RangeVarGetRelidExtended(rv, lockmode,
    1870             :                                            0, RangeVarCallbackForTruncate,
    1871             :                                            NULL);
    1872             : 
    1873             :         /* don't throw error for "TRUNCATE foo, foo" */
    1874        1994 :         if (list_member_oid(relids, myrelid))
    1875           2 :             continue;
    1876             : 
    1877             :         /* open the relation, we already hold a lock on it */
    1878        1992 :         rel = table_open(myrelid, NoLock);
    1879             : 
    1880             :         /*
    1881             :          * RangeVarGetRelidExtended() has done most checks with its callback,
    1882             :          * but other checks with the now-opened Relation remain.
    1883             :          */
    1884        1992 :         truncate_check_activity(rel);
    1885             : 
    1886        1986 :         rels = lappend(rels, rel);
    1887        1986 :         relids = lappend_oid(relids, myrelid);
    1888             : 
    1889             :         /* Log this relation only if needed for logical decoding */
    1890        1986 :         if (RelationIsLogicallyLogged(rel))
    1891          74 :             relids_logged = lappend_oid(relids_logged, myrelid);
    1892             : 
    1893        1986 :         if (recurse)
    1894             :         {
    1895             :             ListCell   *child;
    1896             :             List       *children;
    1897             : 
    1898        1932 :             children = find_all_inheritors(myrelid, lockmode, NULL);
    1899             : 
    1900        5668 :             foreach(child, children)
    1901             :             {
    1902        3736 :                 Oid         childrelid = lfirst_oid(child);
    1903             : 
    1904        3736 :                 if (list_member_oid(relids, childrelid))
    1905        1932 :                     continue;
    1906             : 
    1907             :                 /* find_all_inheritors already got lock */
    1908        1804 :                 rel = table_open(childrelid, NoLock);
    1909             : 
    1910             :                 /*
    1911             :                  * It is possible that the parent table has children that are
    1912             :                  * temp tables of other backends.  We cannot safely access
    1913             :                  * such tables (because of buffering issues), and the best
    1914             :                  * thing to do is to silently ignore them.  Note that this
    1915             :                  * check is the same as one of the checks done in
    1916             :                  * truncate_check_activity() called below, still it is kept
    1917             :                  * here for simplicity.
    1918             :                  */
    1919        1804 :                 if (RELATION_IS_OTHER_TEMP(rel))
    1920             :                 {
    1921           8 :                     table_close(rel, lockmode);
    1922           8 :                     continue;
    1923             :                 }
    1924             : 
    1925             :                 /*
    1926             :                  * Inherited TRUNCATE commands perform access permission
    1927             :                  * checks on the parent table only. So we skip checking the
    1928             :                  * children's permissions and don't call
    1929             :                  * truncate_check_perms() here.
    1930             :                  */
    1931        1796 :                 truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
    1932        1796 :                 truncate_check_activity(rel);
    1933             : 
    1934        1796 :                 rels = lappend(rels, rel);
    1935        1796 :                 relids = lappend_oid(relids, childrelid);
    1936             : 
    1937             :                 /* Log this relation only if needed for logical decoding */
    1938        1796 :                 if (RelationIsLogicallyLogged(rel))
    1939          22 :                     relids_logged = lappend_oid(relids_logged, childrelid);
    1940             :             }
    1941             :         }
    1942          54 :         else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    1943          12 :             ereport(ERROR,
    1944             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1945             :                      errmsg("cannot truncate only a partitioned table"),
    1946             :                      errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
    1947             :     }
    1948             : 
    1949        1708 :     ExecuteTruncateGuts(rels, relids, relids_logged,
    1950        1708 :                         stmt->behavior, stmt->restart_seqs, false);
    1951             : 
    1952             :     /* And close the rels */
    1953        5242 :     foreach(cell, rels)
    1954             :     {
    1955        3616 :         Relation    rel = (Relation) lfirst(cell);
    1956             : 
    1957        3616 :         table_close(rel, NoLock);
    1958             :     }
    1959        1626 : }
    1960             : 
    1961             : /*
    1962             :  * ExecuteTruncateGuts
    1963             :  *
    1964             :  * Internal implementation of TRUNCATE.  This is called by the actual TRUNCATE
    1965             :  * command (see above) as well as replication subscribers that execute a
    1966             :  * replicated TRUNCATE action.
    1967             :  *
    1968             :  * explicit_rels is the list of Relations to truncate that the command
    1969             :  * specified.  relids is the list of Oids corresponding to explicit_rels.
    1970             :  * relids_logged is the list of Oids (a subset of relids) that require
    1971             :  * WAL-logging.  This is all a bit redundant, but the existing callers have
    1972             :  * this information handy in this form.
    1973             :  */
    1974             : void
    1975        1748 : ExecuteTruncateGuts(List *explicit_rels,
    1976             :                     List *relids,
    1977             :                     List *relids_logged,
    1978             :                     DropBehavior behavior, bool restart_seqs,
    1979             :                     bool run_as_table_owner)
    1980             : {
    1981             :     List       *rels;
    1982        1748 :     List       *seq_relids = NIL;
    1983        1748 :     HTAB       *ft_htab = NULL;
    1984             :     EState     *estate;
    1985             :     ResultRelInfo *resultRelInfos;
    1986             :     ResultRelInfo *resultRelInfo;
    1987             :     SubTransactionId mySubid;
    1988             :     ListCell   *cell;
    1989             :     Oid        *logrelids;
    1990             : 
    1991             :     /*
    1992             :      * Check the explicitly-specified relations.
    1993             :      *
    1994             :      * In CASCADE mode, suck in all referencing relations as well.  This
    1995             :      * requires multiple iterations to find indirectly-dependent relations. At
    1996             :      * each phase, we need to exclusive-lock new rels before looking for their
    1997             :      * dependencies, else we might miss something.  Also, we check each rel as
    1998             :      * soon as we open it, to avoid a faux pas such as holding lock for a long
    1999             :      * time on a rel we have no permissions for.
    2000             :      */
    2001        1748 :     rels = list_copy(explicit_rels);
    2002        1748 :     if (behavior == DROP_CASCADE)
    2003             :     {
    2004             :         for (;;)
    2005          40 :         {
    2006             :             List       *newrelids;
    2007             : 
    2008          80 :             newrelids = heap_truncate_find_FKs(relids);
    2009          80 :             if (newrelids == NIL)
    2010          40 :                 break;          /* nothing else to add */
    2011             : 
    2012         134 :             foreach(cell, newrelids)
    2013             :             {
    2014          94 :                 Oid         relid = lfirst_oid(cell);
    2015             :                 Relation    rel;
    2016             : 
    2017          94 :                 rel = table_open(relid, AccessExclusiveLock);
    2018          94 :                 ereport(NOTICE,
    2019             :                         (errmsg("truncate cascades to table \"%s\"",
    2020             :                                 RelationGetRelationName(rel))));
    2021          94 :                 truncate_check_rel(relid, rel->rd_rel);
    2022          94 :                 truncate_check_perms(relid, rel->rd_rel);
    2023          94 :                 truncate_check_activity(rel);
    2024          94 :                 rels = lappend(rels, rel);
    2025          94 :                 relids = lappend_oid(relids, relid);
    2026             : 
    2027             :                 /* Log this relation only if needed for logical decoding */
    2028          94 :                 if (RelationIsLogicallyLogged(rel))
    2029           0 :                     relids_logged = lappend_oid(relids_logged, relid);
    2030             :             }
    2031             :         }
    2032             :     }
    2033             : 
    2034             :     /*
    2035             :      * Check foreign key references.  In CASCADE mode, this should be
    2036             :      * unnecessary since we just pulled in all the references; but as a
    2037             :      * cross-check, do it anyway if in an Assert-enabled build.
    2038             :      */
    2039             : #ifdef USE_ASSERT_CHECKING
    2040             :     heap_truncate_check_FKs(rels, false);
    2041             : #else
    2042        1748 :     if (behavior == DROP_RESTRICT)
    2043        1708 :         heap_truncate_check_FKs(rels, false);
    2044             : #endif
    2045             : 
    2046             :     /*
    2047             :      * If we are asked to restart sequences, find all the sequences, lock them
    2048             :      * (we need AccessExclusiveLock for ResetSequence), and check permissions.
    2049             :      * We want to do this early since it's pointless to do all the truncation
    2050             :      * work only to fail on sequence permissions.
    2051             :      */
    2052        1674 :     if (restart_seqs)
    2053             :     {
    2054          48 :         foreach(cell, rels)
    2055             :         {
    2056          24 :             Relation    rel = (Relation) lfirst(cell);
    2057          24 :             List       *seqlist = getOwnedSequences(RelationGetRelid(rel));
    2058             :             ListCell   *seqcell;
    2059             : 
    2060          58 :             foreach(seqcell, seqlist)
    2061             :             {
    2062          34 :                 Oid         seq_relid = lfirst_oid(seqcell);
    2063             :                 Relation    seq_rel;
    2064             : 
    2065          34 :                 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
    2066             : 
    2067             :                 /* This check must match AlterSequence! */
    2068          34 :                 if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
    2069           0 :                     aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SEQUENCE,
    2070           0 :                                    RelationGetRelationName(seq_rel));
    2071             : 
    2072          34 :                 seq_relids = lappend_oid(seq_relids, seq_relid);
    2073             : 
    2074          34 :                 relation_close(seq_rel, NoLock);
    2075             :             }
    2076             :         }
    2077             :     }
    2078             : 
    2079             :     /* Prepare to catch AFTER triggers. */
    2080        1674 :     AfterTriggerBeginQuery();
    2081             : 
    2082             :     /*
    2083             :      * To fire triggers, we'll need an EState as well as a ResultRelInfo for
    2084             :      * each relation.  We don't need to call ExecOpenIndices, though.
    2085             :      *
    2086             :      * We put the ResultRelInfos in the es_opened_result_relations list, even
    2087             :      * though we don't have a range table and don't populate the
    2088             :      * es_result_relations array.  That's a bit bogus, but it's enough to make
    2089             :      * ExecGetTriggerResultRel() find them.
    2090             :      */
    2091        1674 :     estate = CreateExecutorState();
    2092             :     resultRelInfos = (ResultRelInfo *)
    2093        1674 :         palloc(list_length(rels) * sizeof(ResultRelInfo));
    2094        1674 :     resultRelInfo = resultRelInfos;
    2095        5464 :     foreach(cell, rels)
    2096             :     {
    2097        3790 :         Relation    rel = (Relation) lfirst(cell);
    2098             : 
    2099        3790 :         InitResultRelInfo(resultRelInfo,
    2100             :                           rel,
    2101             :                           0,    /* dummy rangetable index */
    2102             :                           NULL,
    2103             :                           0);
    2104        3790 :         estate->es_opened_result_relations =
    2105        3790 :             lappend(estate->es_opened_result_relations, resultRelInfo);
    2106        3790 :         resultRelInfo++;
    2107             :     }
    2108             : 
    2109             :     /*
    2110             :      * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
    2111             :      * truncating (this is because one of them might throw an error). Also, if
    2112             :      * we were to allow them to prevent statement execution, that would need
    2113             :      * to be handled here.
    2114             :      */
    2115        1674 :     resultRelInfo = resultRelInfos;
    2116        5464 :     foreach(cell, rels)
    2117             :     {
    2118             :         UserContext ucxt;
    2119             : 
    2120        3790 :         if (run_as_table_owner)
    2121          72 :             SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
    2122             :                                   &ucxt);
    2123        3790 :         ExecBSTruncateTriggers(estate, resultRelInfo);
    2124        3790 :         if (run_as_table_owner)
    2125          72 :             RestoreUserContext(&ucxt);
    2126        3790 :         resultRelInfo++;
    2127             :     }
    2128             : 
    2129             :     /*
    2130             :      * OK, truncate each table.
    2131             :      */
    2132        1674 :     mySubid = GetCurrentSubTransactionId();
    2133             : 
    2134        5464 :     foreach(cell, rels)
    2135             :     {
    2136        3790 :         Relation    rel = (Relation) lfirst(cell);
    2137             : 
    2138             :         /* Skip partitioned tables as there is nothing to do */
    2139        3790 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    2140         704 :             continue;
    2141             : 
    2142             :         /*
    2143             :          * Build the lists of foreign tables belonging to each foreign server
    2144             :          * and pass each list to the foreign data wrapper's callback function,
    2145             :          * so that each server can truncate its all foreign tables in bulk.
    2146             :          * Each list is saved as a single entry in a hash table that uses the
    2147             :          * server OID as lookup key.
    2148             :          */
    2149        3086 :         if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    2150          34 :         {
    2151          34 :             Oid         serverid = GetForeignServerIdByRelId(RelationGetRelid(rel));
    2152             :             bool        found;
    2153             :             ForeignTruncateInfo *ft_info;
    2154             : 
    2155             :             /* First time through, initialize hashtable for foreign tables */
    2156          34 :             if (!ft_htab)
    2157             :             {
    2158             :                 HASHCTL     hctl;
    2159             : 
    2160          30 :                 memset(&hctl, 0, sizeof(HASHCTL));
    2161          30 :                 hctl.keysize = sizeof(Oid);
    2162          30 :                 hctl.entrysize = sizeof(ForeignTruncateInfo);
    2163          30 :                 hctl.hcxt = CurrentMemoryContext;
    2164             : 
    2165          30 :                 ft_htab = hash_create("TRUNCATE for Foreign Tables",
    2166             :                                       32,   /* start small and extend */
    2167             :                                       &hctl,
    2168             :                                       HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    2169             :             }
    2170             : 
    2171             :             /* Find or create cached entry for the foreign table */
    2172          34 :             ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
    2173          34 :             if (!found)
    2174          30 :                 ft_info->rels = NIL;
    2175             : 
    2176             :             /*
    2177             :              * Save the foreign table in the entry of the server that the
    2178             :              * foreign table belongs to.
    2179             :              */
    2180          34 :             ft_info->rels = lappend(ft_info->rels, rel);
    2181          34 :             continue;
    2182             :         }
    2183             : 
    2184             :         /*
    2185             :          * Normally, we need a transaction-safe truncation here.  However, if
    2186             :          * the table was either created in the current (sub)transaction or has
    2187             :          * a new relfilenumber in the current (sub)transaction, then we can
    2188             :          * just truncate it in-place, because a rollback would cause the whole
    2189             :          * table or the current physical file to be thrown away anyway.
    2190             :          */
    2191        3052 :         if (rel->rd_createSubid == mySubid ||
    2192        3026 :             rel->rd_newRelfilelocatorSubid == mySubid)
    2193             :         {
    2194             :             /* Immediate, non-rollbackable truncation is OK */
    2195          90 :             heap_truncate_one_rel(rel);
    2196             :         }
    2197             :         else
    2198             :         {
    2199             :             Oid         heap_relid;
    2200             :             Oid         toast_relid;
    2201        2962 :             ReindexParams reindex_params = {0};
    2202             : 
    2203             :             /*
    2204             :              * This effectively deletes all rows in the table, and may be done
    2205             :              * in a serializable transaction.  In that case we must record a
    2206             :              * rw-conflict in to this transaction from each transaction
    2207             :              * holding a predicate lock on the table.
    2208             :              */
    2209        2962 :             CheckTableForSerializableConflictIn(rel);
    2210             : 
    2211             :             /*
    2212             :              * Need the full transaction-safe pushups.
    2213             :              *
    2214             :              * Create a new empty storage file for the relation, and assign it
    2215             :              * as the relfilenumber value. The old storage file is scheduled
    2216             :              * for deletion at commit.
    2217             :              */
    2218        2962 :             RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
    2219             : 
    2220        2962 :             heap_relid = RelationGetRelid(rel);
    2221             : 
    2222             :             /*
    2223             :              * The same for the toast table, if any.
    2224             :              */
    2225        2962 :             toast_relid = rel->rd_rel->reltoastrelid;
    2226        2962 :             if (OidIsValid(toast_relid))
    2227             :             {
    2228        1784 :                 Relation    toastrel = relation_open(toast_relid,
    2229             :                                                      AccessExclusiveLock);
    2230             : 
    2231        1784 :                 RelationSetNewRelfilenumber(toastrel,
    2232        1784 :                                             toastrel->rd_rel->relpersistence);
    2233        1784 :                 table_close(toastrel, NoLock);
    2234             :             }
    2235             : 
    2236             :             /*
    2237             :              * Reconstruct the indexes to match, and we're done.
    2238             :              */
    2239        2962 :             reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
    2240             :                              &reindex_params);
    2241             :         }
    2242             : 
    2243        3052 :         pgstat_count_truncate(rel);
    2244             :     }
    2245             : 
    2246             :     /* Now go through the hash table, and truncate foreign tables */
    2247        1674 :     if (ft_htab)
    2248             :     {
    2249             :         ForeignTruncateInfo *ft_info;
    2250             :         HASH_SEQ_STATUS seq;
    2251             : 
    2252          30 :         hash_seq_init(&seq, ft_htab);
    2253             : 
    2254          30 :         PG_TRY();
    2255             :         {
    2256          52 :             while ((ft_info = hash_seq_search(&seq)) != NULL)
    2257             :             {
    2258          30 :                 FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
    2259             : 
    2260             :                 /* truncate_check_rel() has checked that already */
    2261             :                 Assert(routine->ExecForeignTruncate != NULL);
    2262             : 
    2263          30 :                 routine->ExecForeignTruncate(ft_info->rels,
    2264             :                                              behavior,
    2265             :                                              restart_seqs);
    2266             :             }
    2267             :         }
    2268           8 :         PG_FINALLY();
    2269             :         {
    2270          30 :             hash_destroy(ft_htab);
    2271             :         }
    2272          30 :         PG_END_TRY();
    2273             :     }
    2274             : 
    2275             :     /*
    2276             :      * Restart owned sequences if we were asked to.
    2277             :      */
    2278        1700 :     foreach(cell, seq_relids)
    2279             :     {
    2280          34 :         Oid         seq_relid = lfirst_oid(cell);
    2281             : 
    2282          34 :         ResetSequence(seq_relid);
    2283             :     }
    2284             : 
    2285             :     /*
    2286             :      * Write a WAL record to allow this set of actions to be logically
    2287             :      * decoded.
    2288             :      *
    2289             :      * Assemble an array of relids so we can write a single WAL record for the
    2290             :      * whole action.
    2291             :      */
    2292        1666 :     if (relids_logged != NIL)
    2293             :     {
    2294             :         xl_heap_truncate xlrec;
    2295          62 :         int         i = 0;
    2296             : 
    2297             :         /* should only get here if wal_level >= logical */
    2298             :         Assert(XLogLogicalInfoActive());
    2299             : 
    2300          62 :         logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
    2301         160 :         foreach(cell, relids_logged)
    2302          98 :             logrelids[i++] = lfirst_oid(cell);
    2303             : 
    2304          62 :         xlrec.dbId = MyDatabaseId;
    2305          62 :         xlrec.nrelids = list_length(relids_logged);
    2306          62 :         xlrec.flags = 0;
    2307          62 :         if (behavior == DROP_CASCADE)
    2308           2 :             xlrec.flags |= XLH_TRUNCATE_CASCADE;
    2309          62 :         if (restart_seqs)
    2310           4 :             xlrec.flags |= XLH_TRUNCATE_RESTART_SEQS;
    2311             : 
    2312          62 :         XLogBeginInsert();
    2313          62 :         XLogRegisterData(&xlrec, SizeOfHeapTruncate);
    2314          62 :         XLogRegisterData(logrelids, list_length(relids_logged) * sizeof(Oid));
    2315             : 
    2316          62 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
    2317             : 
    2318          62 :         (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
    2319             :     }
    2320             : 
    2321             :     /*
    2322             :      * Process all AFTER STATEMENT TRUNCATE triggers.
    2323             :      */
    2324        1666 :     resultRelInfo = resultRelInfos;
    2325        5448 :     foreach(cell, rels)
    2326             :     {
    2327             :         UserContext ucxt;
    2328             : 
    2329        3782 :         if (run_as_table_owner)
    2330          72 :             SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
    2331             :                                   &ucxt);
    2332        3782 :         ExecASTruncateTriggers(estate, resultRelInfo);
    2333        3782 :         if (run_as_table_owner)
    2334          72 :             RestoreUserContext(&ucxt);
    2335        3782 :         resultRelInfo++;
    2336             :     }
    2337             : 
    2338             :     /* Handle queued AFTER triggers */
    2339        1666 :     AfterTriggerEndQuery(estate);
    2340             : 
    2341             :     /* We can clean up the EState now */
    2342        1666 :     FreeExecutorState(estate);
    2343             : 
    2344             :     /*
    2345             :      * Close any rels opened by CASCADE (can't do this while EState still
    2346             :      * holds refs)
    2347             :      */
    2348        1666 :     rels = list_difference_ptr(rels, explicit_rels);
    2349        1760 :     foreach(cell, rels)
    2350             :     {
    2351          94 :         Relation    rel = (Relation) lfirst(cell);
    2352             : 
    2353          94 :         table_close(rel, NoLock);
    2354             :     }
    2355        1666 : }
    2356             : 
    2357             : /*
    2358             :  * Check that a given relation is safe to truncate.  Subroutine for
    2359             :  * ExecuteTruncate() and RangeVarCallbackForTruncate().
    2360             :  */
    2361             : static void
    2362        4056 : truncate_check_rel(Oid relid, Form_pg_class reltuple)
    2363             : {
    2364        4056 :     char       *relname = NameStr(reltuple->relname);
    2365             : 
    2366             :     /*
    2367             :      * Only allow truncate on regular tables, foreign tables using foreign
    2368             :      * data wrappers supporting TRUNCATE and partitioned tables (although, the
    2369             :      * latter are only being included here for the following checks; no
    2370             :      * physical truncation will occur in their case.).
    2371             :      */
    2372        4056 :     if (reltuple->relkind == RELKIND_FOREIGN_TABLE)
    2373             :     {
    2374          38 :         Oid         serverid = GetForeignServerIdByRelId(relid);
    2375          38 :         FdwRoutine *fdwroutine = GetFdwRoutineByServerId(serverid);
    2376             : 
    2377          36 :         if (!fdwroutine->ExecForeignTruncate)
    2378           2 :             ereport(ERROR,
    2379             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2380             :                      errmsg("cannot truncate foreign table \"%s\"",
    2381             :                             relname)));
    2382             :     }
    2383        4018 :     else if (reltuple->relkind != RELKIND_RELATION &&
    2384         726 :              reltuple->relkind != RELKIND_PARTITIONED_TABLE)
    2385           0 :         ereport(ERROR,
    2386             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2387             :                  errmsg("\"%s\" is not a table", relname)));
    2388             : 
    2389             :     /*
    2390             :      * Most system catalogs can't be truncated at all, or at least not unless
    2391             :      * allow_system_table_mods=on. As an exception, however, we allow
    2392             :      * pg_largeobject and pg_largeobject_metadata to be truncated as part of
    2393             :      * pg_upgrade, because we need to change its relfilenode to match the old
    2394             :      * cluster, and allowing a TRUNCATE command to be executed is the easiest
    2395             :      * way of doing that.
    2396             :      */
    2397        4052 :     if (!allowSystemTableMods && IsSystemClass(relid, reltuple)
    2398         114 :         && (!IsBinaryUpgrade ||
    2399          56 :             (relid != LargeObjectRelationId &&
    2400             :              relid != LargeObjectMetadataRelationId)))
    2401           2 :         ereport(ERROR,
    2402             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    2403             :                  errmsg("permission denied: \"%s\" is a system catalog",
    2404             :                         relname)));
    2405             : 
    2406        4050 :     InvokeObjectTruncateHook(relid);
    2407        4050 : }
    2408             : 
    2409             : /*
    2410             :  * Check that current user has the permission to truncate given relation.
    2411             :  */
    2412             : static void
    2413        2254 : truncate_check_perms(Oid relid, Form_pg_class reltuple)
    2414             : {
    2415        2254 :     char       *relname = NameStr(reltuple->relname);
    2416             :     AclResult   aclresult;
    2417             : 
    2418             :     /* Permissions checks */
    2419        2254 :     aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
    2420        2254 :     if (aclresult != ACLCHECK_OK)
    2421          32 :         aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
    2422             :                        relname);
    2423        2222 : }
    2424             : 
    2425             : /*
    2426             :  * Set of extra sanity checks to check if a given relation is safe to
    2427             :  * truncate.  This is split with truncate_check_rel() as
    2428             :  * RangeVarCallbackForTruncate() cannot open a Relation yet.
    2429             :  */
    2430             : static void
    2431        3882 : truncate_check_activity(Relation rel)
    2432             : {
    2433             :     /*
    2434             :      * Don't allow truncate on temp tables of other backends ... their local
    2435             :      * buffer manager is not going to cope.
    2436             :      */
    2437        3882 :     if (RELATION_IS_OTHER_TEMP(rel))
    2438           0 :         ereport(ERROR,
    2439             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2440             :                  errmsg("cannot truncate temporary tables of other sessions")));
    2441             : 
    2442             :     /*
    2443             :      * Also check for active uses of the relation in the current transaction,
    2444             :      * including open scans and pending AFTER trigger events.
    2445             :      */
    2446        3882 :     CheckTableNotInUse(rel, "TRUNCATE");
    2447        3876 : }
    2448             : 
    2449             : /*
    2450             :  * storage_name
    2451             :  *    returns the name corresponding to a typstorage/attstorage enum value
    2452             :  */
    2453             : static const char *
    2454          24 : storage_name(char c)
    2455             : {
    2456          24 :     switch (c)
    2457             :     {
    2458           0 :         case TYPSTORAGE_PLAIN:
    2459           0 :             return "PLAIN";
    2460           0 :         case TYPSTORAGE_EXTERNAL:
    2461           0 :             return "EXTERNAL";
    2462          12 :         case TYPSTORAGE_EXTENDED:
    2463          12 :             return "EXTENDED";
    2464          12 :         case TYPSTORAGE_MAIN:
    2465          12 :             return "MAIN";
    2466           0 :         default:
    2467           0 :             return "???";
    2468             :     }
    2469             : }
    2470             : 
    2471             : /*----------
    2472             :  * MergeAttributes
    2473             :  *      Returns new schema given initial schema and superclasses.
    2474             :  *
    2475             :  * Input arguments:
    2476             :  * 'columns' is the column/attribute definition for the table. (It's a list
    2477             :  *      of ColumnDef's.) It is destructively changed.
    2478             :  * 'supers' is a list of OIDs of parent relations, already locked by caller.
    2479             :  * 'relpersistence' is the persistence type of the table.
    2480             :  * 'is_partition' tells if the table is a partition.
    2481             :  *
    2482             :  * Output arguments:
    2483             :  * 'supconstr' receives a list of CookedConstraint representing
    2484             :  *      CHECK constraints belonging to parent relations, updated as
    2485             :  *      necessary to be valid for the child.
    2486             :  * 'supnotnulls' receives a list of CookedConstraint representing
    2487             :  *      not-null constraints based on those from parent relations.
    2488             :  *
    2489             :  * Return value:
    2490             :  * Completed schema list.
    2491             :  *
    2492             :  * Notes:
    2493             :  *    The order in which the attributes are inherited is very important.
    2494             :  *    Intuitively, the inherited attributes should come first. If a table
    2495             :  *    inherits from multiple parents, the order of those attributes are
    2496             :  *    according to the order of the parents specified in CREATE TABLE.
    2497             :  *
    2498             :  *    Here's an example:
    2499             :  *
    2500             :  *      create table person (name text, age int4, location point);
    2501             :  *      create table emp (salary int4, manager text) inherits(person);
    2502             :  *      create table student (gpa float8) inherits (person);
    2503             :  *      create table stud_emp (percent int4) inherits (emp, student);
    2504             :  *
    2505             :  *    The order of the attributes of stud_emp is:
    2506             :  *
    2507             :  *                          person {1:name, 2:age, 3:location}
    2508             :  *                          /    \
    2509             :  *             {6:gpa}  student   emp {4:salary, 5:manager}
    2510             :  *                          \    /
    2511             :  *                         stud_emp {7:percent}
    2512             :  *
    2513             :  *     If the same attribute name appears multiple times, then it appears
    2514             :  *     in the result table in the proper location for its first appearance.
    2515             :  *
    2516             :  *     Constraints (including not-null constraints) for the child table
    2517             :  *     are the union of all relevant constraints, from both the child schema
    2518             :  *     and parent tables.  In addition, in legacy inheritance, each column that
    2519             :  *     appears in a primary key in any of the parents also gets a NOT NULL
    2520             :  *     constraint (partitioning doesn't need this, because the PK itself gets
    2521             :  *     inherited.)
    2522             :  *
    2523             :  *     The default value for a child column is defined as:
    2524             :  *      (1) If the child schema specifies a default, that value is used.
    2525             :  *      (2) If neither the child nor any parent specifies a default, then
    2526             :  *          the column will not have a default.
    2527             :  *      (3) If conflicting defaults are inherited from different parents
    2528             :  *          (and not overridden by the child), an error is raised.
    2529             :  *      (4) Otherwise the inherited default is used.
    2530             :  *
    2531             :  *      Note that the default-value infrastructure is used for generated
    2532             :  *      columns' expressions too, so most of the preceding paragraph applies
    2533             :  *      to generation expressions too.  We insist that a child column be
    2534             :  *      generated if and only if its parent(s) are, but it need not have
    2535             :  *      the same generation expression.
    2536             :  *----------
    2537             :  */
    2538             : static List *
    2539       63008 : MergeAttributes(List *columns, const List *supers, char relpersistence,
    2540             :                 bool is_partition, List **supconstr, List **supnotnulls)
    2541             : {
    2542       63008 :     List       *inh_columns = NIL;
    2543       63008 :     List       *constraints = NIL;
    2544       63008 :     List       *nnconstraints = NIL;
    2545       63008 :     bool        have_bogus_defaults = false;
    2546             :     int         child_attno;
    2547             :     static Node bogus_marker = {0}; /* marks conflicting defaults */
    2548       63008 :     List       *saved_columns = NIL;
    2549             :     ListCell   *lc;
    2550             : 
    2551             :     /*
    2552             :      * Check for and reject tables with too many columns. We perform this
    2553             :      * check relatively early for two reasons: (a) we don't run the risk of
    2554             :      * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
    2555             :      * okay if we're processing <= 1600 columns, but could take minutes to
    2556             :      * execute if the user attempts to create a table with hundreds of
    2557             :      * thousands of columns.
    2558             :      *
    2559             :      * Note that we also need to check that we do not exceed this figure after
    2560             :      * including columns from inherited relations.
    2561             :      */
    2562       63008 :     if (list_length(columns) > MaxHeapAttributeNumber)
    2563           0 :         ereport(ERROR,
    2564             :                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
    2565             :                  errmsg("tables can have at most %d columns",
    2566             :                         MaxHeapAttributeNumber)));
    2567             : 
    2568             :     /*
    2569             :      * Check for duplicate names in the explicit list of attributes.
    2570             :      *
    2571             :      * Although we might consider merging such entries in the same way that we
    2572             :      * handle name conflicts for inherited attributes, it seems to make more
    2573             :      * sense to assume such conflicts are errors.
    2574             :      *
    2575             :      * We don't use foreach() here because we have two nested loops over the
    2576             :      * columns list, with possible element deletions in the inner one.  If we
    2577             :      * used foreach_delete_current() it could only fix up the state of one of
    2578             :      * the loops, so it seems cleaner to use looping over list indexes for
    2579             :      * both loops.  Note that any deletion will happen beyond where the outer
    2580             :      * loop is, so its index never needs adjustment.
    2581             :      */
    2582      299322 :     for (int coldefpos = 0; coldefpos < list_length(columns); coldefpos++)
    2583             :     {
    2584      236338 :         ColumnDef  *coldef = list_nth_node(ColumnDef, columns, coldefpos);
    2585             : 
    2586      236338 :         if (!is_partition && coldef->typeName == NULL)
    2587             :         {
    2588             :             /*
    2589             :              * Typed table column option that does not belong to a column from
    2590             :              * the type.  This works because the columns from the type come
    2591             :              * first in the list.  (We omit this check for partition column
    2592             :              * lists; those are processed separately below.)
    2593             :              */
    2594           6 :             ereport(ERROR,
    2595             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    2596             :                      errmsg("column \"%s\" does not exist",
    2597             :                             coldef->colname)));
    2598             :         }
    2599             : 
    2600             :         /* restpos scans all entries beyond coldef; incr is in loop body */
    2601     6585914 :         for (int restpos = coldefpos + 1; restpos < list_length(columns);)
    2602             :         {
    2603     6349600 :             ColumnDef  *restdef = list_nth_node(ColumnDef, columns, restpos);
    2604             : 
    2605     6349600 :             if (strcmp(coldef->colname, restdef->colname) == 0)
    2606             :             {
    2607          50 :                 if (coldef->is_from_type)
    2608             :                 {
    2609             :                     /*
    2610             :                      * merge the column options into the column from the type
    2611             :                      */
    2612          32 :                     coldef->is_not_null = restdef->is_not_null;
    2613          32 :                     coldef->raw_default = restdef->raw_default;
    2614          32 :                     coldef->cooked_default = restdef->cooked_default;
    2615          32 :                     coldef->constraints = restdef->constraints;
    2616          32 :                     coldef->is_from_type = false;
    2617          32 :                     columns = list_delete_nth_cell(columns, restpos);
    2618             :                 }
    2619             :                 else
    2620          18 :                     ereport(ERROR,
    2621             :                             (errcode(ERRCODE_DUPLICATE_COLUMN),
    2622             :                              errmsg("column \"%s\" specified more than once",
    2623             :                                     coldef->colname)));
    2624             :             }
    2625             :             else
    2626     6349550 :                 restpos++;
    2627             :         }
    2628             :     }
    2629             : 
    2630             :     /*
    2631             :      * In case of a partition, there are no new column definitions, only dummy
    2632             :      * ColumnDefs created for column constraints.  Set them aside for now and
    2633             :      * process them at the end.
    2634             :      */
    2635       62984 :     if (is_partition)
    2636             :     {
    2637        8168 :         saved_columns = columns;
    2638        8168 :         columns = NIL;
    2639             :     }
    2640             : 
    2641             :     /*
    2642             :      * Scan the parents left-to-right, and merge their attributes to form a
    2643             :      * list of inherited columns (inh_columns).
    2644             :      */
    2645       62984 :     child_attno = 0;
    2646       73582 :     foreach(lc, supers)
    2647             :     {
    2648       10682 :         Oid         parent = lfirst_oid(lc);
    2649             :         Relation    relation;
    2650             :         TupleDesc   tupleDesc;
    2651             :         TupleConstr *constr;
    2652             :         AttrMap    *newattmap;
    2653             :         List       *inherited_defaults;
    2654             :         List       *cols_with_defaults;
    2655             :         List       *nnconstrs;
    2656             :         ListCell   *lc1;
    2657             :         ListCell   *lc2;
    2658       10682 :         Bitmapset  *nncols = NULL;
    2659             : 
    2660             :         /* caller already got lock */
    2661       10682 :         relation = table_open(parent, NoLock);
    2662             : 
    2663             :         /*
    2664             :          * Check for active uses of the parent partitioned table in the
    2665             :          * current transaction, such as being used in some manner by an
    2666             :          * enclosing command.
    2667             :          */
    2668       10682 :         if (is_partition)
    2669        8168 :             CheckTableNotInUse(relation, "CREATE TABLE .. PARTITION OF");
    2670             : 
    2671             :         /*
    2672             :          * We do not allow partitioned tables and partitions to participate in
    2673             :          * regular inheritance.
    2674             :          */
    2675       10676 :         if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !is_partition)
    2676           6 :             ereport(ERROR,
    2677             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2678             :                      errmsg("cannot inherit from partitioned table \"%s\"",
    2679             :                             RelationGetRelationName(relation))));
    2680       10670 :         if (relation->rd_rel->relispartition && !is_partition)
    2681           6 :             ereport(ERROR,
    2682             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2683             :                      errmsg("cannot inherit from partition \"%s\"",
    2684             :                             RelationGetRelationName(relation))));
    2685             : 
    2686       10664 :         if (relation->rd_rel->relkind != RELKIND_RELATION &&
    2687        8164 :             relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
    2688        8144 :             relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    2689           0 :             ereport(ERROR,
    2690             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2691             :                      errmsg("inherited relation \"%s\" is not a table or foreign table",
    2692             :                             RelationGetRelationName(relation))));
    2693             : 
    2694             :         /*
    2695             :          * If the parent is permanent, so must be all of its partitions.  Note
    2696             :          * that inheritance allows that case.
    2697             :          */
    2698       10664 :         if (is_partition &&
    2699        8162 :             relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
    2700             :             relpersistence == RELPERSISTENCE_TEMP)
    2701           6 :             ereport(ERROR,
    2702             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2703             :                      errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
    2704             :                             RelationGetRelationName(relation))));
    2705             : 
    2706             :         /* Permanent rels cannot inherit from temporary ones */
    2707       10658 :         if (relpersistence != RELPERSISTENCE_TEMP &&
    2708       10292 :             relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
    2709          24 :             ereport(ERROR,
    2710             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2711             :                      errmsg(!is_partition
    2712             :                             ? "cannot inherit from temporary relation \"%s\""
    2713             :                             : "cannot create a permanent relation as partition of temporary relation \"%s\"",
    2714             :                             RelationGetRelationName(relation))));
    2715             : 
    2716             :         /* If existing rel is temp, it must belong to this session */
    2717       10634 :         if (RELATION_IS_OTHER_TEMP(relation))
    2718           0 :             ereport(ERROR,
    2719             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2720             :                      errmsg(!is_partition
    2721             :                             ? "cannot inherit from temporary relation of another session"
    2722             :                             : "cannot create as partition of temporary relation of another session")));
    2723             : 
    2724             :         /*
    2725             :          * We should have an UNDER permission flag for this, but for now,
    2726             :          * demand that creator of a child table own the parent.
    2727             :          */
    2728       10634 :         if (!object_ownercheck(RelationRelationId, RelationGetRelid(relation), GetUserId()))
    2729           0 :             aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(relation->rd_rel->relkind),
    2730           0 :                            RelationGetRelationName(relation));
    2731             : 
    2732       10634 :         tupleDesc = RelationGetDescr(relation);
    2733       10634 :         constr = tupleDesc->constr;
    2734             : 
    2735             :         /*
    2736             :          * newattmap->attnums[] will contain the child-table attribute numbers
    2737             :          * for the attributes of this parent table.  (They are not the same
    2738             :          * for parents after the first one, nor if we have dropped columns.)
    2739             :          */
    2740       10634 :         newattmap = make_attrmap(tupleDesc->natts);
    2741             : 
    2742             :         /* We can't process inherited defaults until newattmap is complete. */
    2743       10634 :         inherited_defaults = cols_with_defaults = NIL;
    2744             : 
    2745             :         /*
    2746             :          * Request attnotnull on columns that have a not-null constraint
    2747             :          * that's not marked NO INHERIT (even if not valid).
    2748             :          */
    2749       10634 :         nnconstrs = RelationGetNotNullConstraints(RelationGetRelid(relation),
    2750             :                                                   true, false);
    2751       23662 :         foreach_ptr(CookedConstraint, cc, nnconstrs)
    2752        2394 :             nncols = bms_add_member(nncols, cc->attnum);
    2753             : 
    2754       32048 :         for (AttrNumber parent_attno = 1; parent_attno <= tupleDesc->natts;
    2755       21414 :              parent_attno++)
    2756             :         {
    2757       21450 :             Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
    2758             :                                                         parent_attno - 1);
    2759       21450 :             char       *attributeName = NameStr(attribute->attname);
    2760             :             int         exist_attno;
    2761             :             ColumnDef  *newdef;
    2762             :             ColumnDef  *mergeddef;
    2763             : 
    2764             :             /*
    2765             :              * Ignore dropped columns in the parent.
    2766             :              */
    2767       21450 :             if (attribute->attisdropped)
    2768         198 :                 continue;       /* leave newattmap->attnums entry as zero */
    2769             : 
    2770             :             /*
    2771             :              * Create new column definition
    2772             :              */
    2773       21252 :             newdef = makeColumnDef(attributeName, attribute->atttypid,
    2774             :                                    attribute->atttypmod, attribute->attcollation);
    2775       21252 :             newdef->storage = attribute->attstorage;
    2776       21252 :             newdef->generated = attribute->attgenerated;
    2777       21252 :             if (CompressionMethodIsValid(attribute->attcompression))
    2778          36 :                 newdef->compression =
    2779          36 :                     pstrdup(GetCompressionMethodName(attribute->attcompression));
    2780             : 
    2781             :             /*
    2782             :              * Regular inheritance children are independent enough not to
    2783             :              * inherit identity columns.  But partitions are integral part of
    2784             :              * a partitioned table and inherit identity column.
    2785             :              */
    2786       21252 :             if (is_partition)
    2787       16642 :                 newdef->identity = attribute->attidentity;
    2788             : 
    2789             :             /*
    2790             :              * Does it match some previously considered column from another
    2791             :              * parent?
    2792             :              */
    2793       21252 :             exist_attno = findAttrByName(attributeName, inh_columns);
    2794       21252 :             if (exist_attno > 0)
    2795             :             {
    2796             :                 /*
    2797             :                  * Yes, try to merge the two column definitions.
    2798             :                  */
    2799         370 :                 mergeddef = MergeInheritedAttribute(inh_columns, exist_attno, newdef);
    2800             : 
    2801         334 :                 newattmap->attnums[parent_attno - 1] = exist_attno;
    2802             : 
    2803             :                 /*
    2804             :                  * Partitions have only one parent, so conflict should never
    2805             :                  * occur.
    2806             :                  */
    2807             :                 Assert(!is_partition);
    2808             :             }
    2809             :             else
    2810             :             {
    2811             :                 /*
    2812             :                  * No, create a new inherited column
    2813             :                  */
    2814       20882 :                 newdef->inhcount = 1;
    2815       20882 :                 newdef->is_local = false;
    2816       20882 :                 inh_columns = lappend(inh_columns, newdef);
    2817             : 
    2818       20882 :                 newattmap->attnums[parent_attno - 1] = ++child_attno;
    2819       20882 :                 mergeddef = newdef;
    2820             :             }
    2821             : 
    2822             :             /*
    2823             :              * mark attnotnull if parent has it
    2824             :              */
    2825       21216 :             if (bms_is_member(parent_attno, nncols))
    2826        2394 :                 mergeddef->is_not_null = true;
    2827             : 
    2828             :             /*
    2829             :              * Locate default/generation expression if any
    2830             :              */
    2831       21216 :             if (attribute->atthasdef)
    2832             :             {
    2833             :                 Node       *this_default;
    2834             : 
    2835         716 :                 this_default = TupleDescGetDefault(tupleDesc, parent_attno);
    2836         716 :                 if (this_default == NULL)
    2837           0 :                     elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
    2838             :                          parent_attno, RelationGetRelationName(relation));
    2839             : 
    2840             :                 /*
    2841             :                  * If it's a GENERATED default, it might contain Vars that
    2842             :                  * need to be mapped to the inherited column(s)' new numbers.
    2843             :                  * We can't do that till newattmap is ready, so just remember
    2844             :                  * all the inherited default expressions for the moment.
    2845             :                  */
    2846         716 :                 inherited_defaults = lappend(inherited_defaults, this_default);
    2847         716 :                 cols_with_defaults = lappend(cols_with_defaults, mergeddef);
    2848             :             }
    2849             :         }
    2850             : 
    2851             :         /*
    2852             :          * Now process any inherited default expressions, adjusting attnos
    2853             :          * using the completed newattmap map.
    2854             :          */
    2855       11314 :         forboth(lc1, inherited_defaults, lc2, cols_with_defaults)
    2856             :         {
    2857         716 :             Node       *this_default = (Node *) lfirst(lc1);
    2858         716 :             ColumnDef  *def = (ColumnDef *) lfirst(lc2);
    2859             :             bool        found_whole_row;
    2860             : 
    2861             :             /* Adjust Vars to match new table's column numbering */
    2862         716 :             this_default = map_variable_attnos(this_default,
    2863             :                                                1, 0,
    2864             :                                                newattmap,
    2865             :                                                InvalidOid, &found_whole_row);
    2866             : 
    2867             :             /*
    2868             :              * For the moment we have to reject whole-row variables.  We could
    2869             :              * convert them, if we knew the new table's rowtype OID, but that
    2870             :              * hasn't been assigned yet.  (A variable could only appear in a
    2871             :              * generation expression, so the error message is correct.)
    2872             :              */
    2873         716 :             if (found_whole_row)
    2874           0 :                 ereport(ERROR,
    2875             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2876             :                          errmsg("cannot convert whole-row table reference"),
    2877             :                          errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
    2878             :                                    def->colname,
    2879             :                                    RelationGetRelationName(relation))));
    2880             : 
    2881             :             /*
    2882             :              * If we already had a default from some prior parent, check to
    2883             :              * see if they are the same.  If so, no problem; if not, mark the
    2884             :              * column as having a bogus default.  Below, we will complain if
    2885             :              * the bogus default isn't overridden by the child columns.
    2886             :              */
    2887             :             Assert(def->raw_default == NULL);
    2888         716 :             if (def->cooked_default == NULL)
    2889         674 :                 def->cooked_default = this_default;
    2890          42 :             else if (!equal(def->cooked_default, this_default))
    2891             :             {
    2892          36 :                 def->cooked_default = &bogus_marker;
    2893          36 :                 have_bogus_defaults = true;
    2894             :             }
    2895             :         }
    2896             : 
    2897             :         /*
    2898             :          * Now copy the CHECK constraints of this parent, adjusting attnos
    2899             :          * using the completed newattmap map.  Identically named constraints
    2900             :          * are merged if possible, else we throw error.
    2901             :          */
    2902       10598 :         if (constr && constr->num_check > 0)
    2903             :         {
    2904         334 :             ConstrCheck *check = constr->check;
    2905             : 
    2906        1070 :             for (int i = 0; i < constr->num_check; i++)
    2907             :             {
    2908         736 :                 char       *name = check[i].ccname;
    2909             :                 Node       *expr;
    2910             :                 bool        found_whole_row;
    2911             : 
    2912             :                 /* ignore if the constraint is non-inheritable */
    2913         736 :                 if (check[i].ccnoinherit)
    2914          48 :                     continue;
    2915             : 
    2916             :                 /* Adjust Vars to match new table's column numbering */
    2917         688 :                 expr = map_variable_attnos(stringToNode(check[i].ccbin),
    2918             :                                            1, 0,
    2919             :                                            newattmap,
    2920             :                                            InvalidOid, &found_whole_row);
    2921             : 
    2922             :                 /*
    2923             :                  * For the moment we have to reject whole-row variables. We
    2924             :                  * could convert them, if we knew the new table's rowtype OID,
    2925             :                  * but that hasn't been assigned yet.
    2926             :                  */
    2927         688 :                 if (found_whole_row)
    2928           0 :                     ereport(ERROR,
    2929             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2930             :                              errmsg("cannot convert whole-row table reference"),
    2931             :                              errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
    2932             :                                        name,
    2933             :                                        RelationGetRelationName(relation))));
    2934             : 
    2935         688 :                 constraints = MergeCheckConstraint(constraints, name, expr,
    2936         688 :                                                    check[i].ccenforced);
    2937             :             }
    2938             :         }
    2939             : 
    2940             :         /*
    2941             :          * Also copy the not-null constraints from this parent.  The
    2942             :          * attnotnull markings were already installed above.
    2943             :          */
    2944       23590 :         foreach_ptr(CookedConstraint, nn, nnconstrs)
    2945             :         {
    2946             :             Assert(nn->contype == CONSTR_NOTNULL);
    2947             : 
    2948        2394 :             nn->attnum = newattmap->attnums[nn->attnum - 1];
    2949             : 
    2950        2394 :             nnconstraints = lappend(nnconstraints, nn);
    2951             :         }
    2952             : 
    2953       10598 :         free_attrmap(newattmap);
    2954             : 
    2955             :         /*
    2956             :          * Close the parent rel, but keep our lock on it until xact commit.
    2957             :          * That will prevent someone else from deleting or ALTERing the parent
    2958             :          * before the child is committed.
    2959             :          */
    2960       10598 :         table_close(relation, NoLock);
    2961             :     }
    2962             : 
    2963             :     /*
    2964             :      * If we had no inherited attributes, the result columns are just the
    2965             :      * explicitly declared columns.  Otherwise, we need to merge the declared
    2966             :      * columns into the inherited column list.  Although, we never have any
    2967             :      * explicitly declared columns if the table is a partition.
    2968             :      */
    2969       62900 :     if (inh_columns != NIL)
    2970             :     {
    2971       10162 :         int         newcol_attno = 0;
    2972             : 
    2973       11136 :         foreach(lc, columns)
    2974             :         {
    2975        1052 :             ColumnDef  *newdef = lfirst_node(ColumnDef, lc);
    2976        1052 :             char       *attributeName = newdef->colname;
    2977             :             int         exist_attno;
    2978             : 
    2979             :             /*
    2980             :              * Partitions have only one parent and have no column definitions
    2981             :              * of their own, so conflict should never occur.
    2982             :              */
    2983             :             Assert(!is_partition);
    2984             : 
    2985        1052 :             newcol_attno++;
    2986             : 
    2987             :             /*
    2988             :              * Does it match some inherited column?
    2989             :              */
    2990        1052 :             exist_attno = findAttrByName(attributeName, inh_columns);
    2991        1052 :             if (exist_attno > 0)
    2992             :             {
    2993             :                 /*
    2994             :                  * Yes, try to merge the two column definitions.
    2995             :                  */
    2996         380 :                 MergeChildAttribute(inh_columns, exist_attno, newcol_attno, newdef);
    2997             :             }
    2998             :             else
    2999             :             {
    3000             :                 /*
    3001             :                  * No, attach new column unchanged to result columns.
    3002             :                  */
    3003         672 :                 inh_columns = lappend(inh_columns, newdef);
    3004             :             }
    3005             :         }
    3006             : 
    3007       10084 :         columns = inh_columns;
    3008             : 
    3009             :         /*
    3010             :          * Check that we haven't exceeded the legal # of columns after merging
    3011             :          * in inherited columns.
    3012             :          */
    3013       10084 :         if (list_length(columns) > MaxHeapAttributeNumber)
    3014           0 :             ereport(ERROR,
    3015             :                     (errcode(ERRCODE_TOO_MANY_COLUMNS),
    3016             :                      errmsg("tables can have at most %d columns",
    3017             :                             MaxHeapAttributeNumber)));
    3018             :     }
    3019             : 
    3020             :     /*
    3021             :      * Now that we have the column definition list for a partition, we can
    3022             :      * check whether the columns referenced in the column constraint specs
    3023             :      * actually exist.  Also, merge column defaults.
    3024             :      */
    3025       62822 :     if (is_partition)
    3026             :     {
    3027        8356 :         foreach(lc, saved_columns)
    3028             :         {
    3029         254 :             ColumnDef  *restdef = lfirst(lc);
    3030         254 :             bool        found = false;
    3031             :             ListCell   *l;
    3032             : 
    3033         960 :             foreach(l, columns)
    3034             :             {
    3035         742 :                 ColumnDef  *coldef = lfirst(l);
    3036             : 
    3037         742 :                 if (strcmp(coldef->colname, restdef->colname) == 0)
    3038             :                 {
    3039         254 :                     found = true;
    3040             : 
    3041             :                     /*
    3042             :                      * Check for conflicts related to generated columns.
    3043             :                      *
    3044             :                      * Same rules as above: generated-ness has to match the
    3045             :                      * parent, but the contents of the generation expression
    3046             :                      * can be different.
    3047             :                      */
    3048         254 :                     if (coldef->generated)
    3049             :                     {
    3050         146 :                         if (restdef->raw_default && !restdef->generated)
    3051          12 :                             ereport(ERROR,
    3052             :                                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3053             :                                      errmsg("column \"%s\" inherits from generated column but specifies default",
    3054             :                                             restdef->colname)));
    3055         134 :                         if (restdef->identity)
    3056           0 :                             ereport(ERROR,
    3057             :                                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3058             :                                      errmsg("column \"%s\" inherits from generated column but specifies identity",
    3059             :                                             restdef->colname)));
    3060             :                     }
    3061             :                     else
    3062             :                     {
    3063         108 :                         if (restdef->generated)
    3064          12 :                             ereport(ERROR,
    3065             :                                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3066             :                                      errmsg("child column \"%s\" specifies generation expression",
    3067             :                                             restdef->colname),
    3068             :                                      errhint("A child table column cannot be generated unless its parent column is.")));
    3069             :                     }
    3070             : 
    3071         230 :                     if (coldef->generated && restdef->generated && coldef->generated != restdef->generated)
    3072          12 :                         ereport(ERROR,
    3073             :                                 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3074             :                                  errmsg("column \"%s\" inherits from generated column of different kind",
    3075             :                                         restdef->colname),
    3076             :                                  errdetail("Parent column is %s, child column is %s.",
    3077             :                                            coldef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
    3078             :                                            restdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
    3079             : 
    3080             :                     /*
    3081             :                      * Override the parent's default value for this column
    3082             :                      * (coldef->cooked_default) with the partition's local
    3083             :                      * definition (restdef->raw_default), if there's one. It
    3084             :                      * should be physically impossible to get a cooked default
    3085             :                      * in the local definition or a raw default in the
    3086             :                      * inherited definition, but make sure they're nulls, for
    3087             :                      * future-proofing.
    3088             :                      */
    3089             :                     Assert(restdef->cooked_default == NULL);
    3090             :                     Assert(coldef->raw_default == NULL);
    3091         218 :                     if (restdef->raw_default)
    3092             :                     {
    3093         146 :                         coldef->raw_default = restdef->raw_default;
    3094         146 :                         coldef->cooked_default = NULL;
    3095             :                     }
    3096             :                 }
    3097             :             }
    3098             : 
    3099             :             /* complain for constraints on columns not in parent */
    3100         218 :             if (!found)
    3101           0 :                 ereport(ERROR,
    3102             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
    3103             :                          errmsg("column \"%s\" does not exist",
    3104             :                                 restdef->colname)));
    3105             :         }
    3106             :     }
    3107             : 
    3108             :     /*
    3109             :      * If we found any conflicting parent default values, check to make sure
    3110             :      * they were overridden by the child.
    3111             :      */
    3112       62786 :     if (have_bogus_defaults)
    3113             :     {
    3114          90 :         foreach(lc, columns)
    3115             :         {
    3116          72 :             ColumnDef  *def = lfirst(lc);
    3117             : 
    3118          72 :             if (def->cooked_default == &bogus_marker)
    3119             :             {
    3120          18 :                 if (def->generated)
    3121          12 :                     ereport(ERROR,
    3122             :                             (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3123             :                              errmsg("column \"%s\" inherits conflicting generation expressions",
    3124             :                                     def->colname),
    3125             :                              errhint("To resolve the conflict, specify a generation expression explicitly.")));
    3126             :                 else
    3127           6 :                     ereport(ERROR,
    3128             :                             (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3129             :                              errmsg("column \"%s\" inherits conflicting default values",
    3130             :                                     def->colname),
    3131             :                              errhint("To resolve the conflict, specify a default explicitly.")));
    3132             :             }
    3133             :         }
    3134             :     }
    3135             : 
    3136       62768 :     *supconstr = constraints;
    3137       62768 :     *supnotnulls = nnconstraints;
    3138             : 
    3139       62768 :     return columns;
    3140             : }
    3141             : 
    3142             : 
    3143             : /*
    3144             :  * MergeCheckConstraint
    3145             :  *      Try to merge an inherited CHECK constraint with previous ones
    3146             :  *
    3147             :  * If we inherit identically-named constraints from multiple parents, we must
    3148             :  * merge them, or throw an error if they don't have identical definitions.
    3149             :  *
    3150             :  * constraints is a list of CookedConstraint structs for previous constraints.
    3151             :  *
    3152             :  * If the new constraint matches an existing one, then the existing
    3153             :  * constraint's inheritance count is updated.  If there is a conflict (same
    3154             :  * name but different expression), throw an error.  If the constraint neither
    3155             :  * matches nor conflicts with an existing one, a new constraint is appended to
    3156             :  * the list.
    3157             :  */
    3158             : static List *
    3159         688 : MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced)
    3160             : {
    3161             :     ListCell   *lc;
    3162             :     CookedConstraint *newcon;
    3163             : 
    3164        2212 :     foreach(lc, constraints)
    3165             :     {
    3166        1674 :         CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
    3167             : 
    3168             :         Assert(ccon->contype == CONSTR_CHECK);
    3169             : 
    3170             :         /* Non-matching names never conflict */
    3171        1674 :         if (strcmp(ccon->name, name) != 0)
    3172        1524 :             continue;
    3173             : 
    3174         150 :         if (equal(expr, ccon->expr))
    3175             :         {
    3176             :             /* OK to merge constraint with existing */
    3177         150 :             if (pg_add_s16_overflow(ccon->inhcount, 1,
    3178             :                                     &ccon->inhcount))
    3179           0 :                 ereport(ERROR,
    3180             :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3181             :                         errmsg("too many inheritance parents"));
    3182             : 
    3183             :             /*
    3184             :              * When enforceability differs, the merged constraint should be
    3185             :              * marked as ENFORCED because one of the parents is ENFORCED.
    3186             :              */
    3187         150 :             if (!ccon->is_enforced && is_enforced)
    3188             :             {
    3189          48 :                 ccon->is_enforced = true;
    3190          48 :                 ccon->skip_validation = false;
    3191             :             }
    3192             : 
    3193         150 :             return constraints;
    3194             :         }
    3195             : 
    3196           0 :         ereport(ERROR,
    3197             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
    3198             :                  errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
    3199             :                         name)));
    3200             :     }
    3201             : 
    3202             :     /*
    3203             :      * Constraint couldn't be merged with an existing one and also didn't
    3204             :      * conflict with an existing one, so add it as a new one to the list.
    3205             :      */
    3206         538 :     newcon = palloc0_object(CookedConstraint);
    3207         538 :     newcon->contype = CONSTR_CHECK;
    3208         538 :     newcon->name = pstrdup(name);
    3209         538 :     newcon->expr = expr;
    3210         538 :     newcon->inhcount = 1;
    3211         538 :     newcon->is_enforced = is_enforced;
    3212         538 :     newcon->skip_validation = !is_enforced;
    3213         538 :     return lappend(constraints, newcon);
    3214             : }
    3215             : 
    3216             : /*
    3217             :  * MergeChildAttribute
    3218             :  *      Merge given child attribute definition into given inherited attribute.
    3219             :  *
    3220             :  * Input arguments:
    3221             :  * 'inh_columns' is the list of inherited ColumnDefs.
    3222             :  * 'exist_attno' is the number of the inherited attribute in inh_columns
    3223             :  * 'newcol_attno' is the attribute number in child table's schema definition
    3224             :  * 'newdef' is the column/attribute definition from the child table.
    3225             :  *
    3226             :  * The ColumnDef in 'inh_columns' list is modified.  The child attribute's
    3227             :  * ColumnDef remains unchanged.
    3228             :  *
    3229             :  * Notes:
    3230             :  * - The attribute is merged according to the rules laid out in the prologue
    3231             :  *   of MergeAttributes().
    3232             :  * - If matching inherited attribute exists but the child attribute can not be
    3233             :  *   merged into it, the function throws respective errors.
    3234             :  * - A partition can not have its own column definitions. Hence this function
    3235             :  *   is applicable only to a regular inheritance child.
    3236             :  */
    3237             : static void
    3238         380 : MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef)
    3239             : {
    3240         380 :     char       *attributeName = newdef->colname;
    3241             :     ColumnDef  *inhdef;
    3242             :     Oid         inhtypeid,
    3243             :                 newtypeid;
    3244             :     int32       inhtypmod,
    3245             :                 newtypmod;
    3246             :     Oid         inhcollid,
    3247             :                 newcollid;
    3248             : 
    3249         380 :     if (exist_attno == newcol_attno)
    3250         346 :         ereport(NOTICE,
    3251             :                 (errmsg("merging column \"%s\" with inherited definition",
    3252             :                         attributeName)));
    3253             :     else
    3254          34 :         ereport(NOTICE,
    3255             :                 (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
    3256             :                  errdetail("User-specified column moved to the position of the inherited column.")));
    3257             : 
    3258         380 :     inhdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
    3259             : 
    3260             :     /*
    3261             :      * Must have the same type and typmod
    3262             :      */
    3263         380 :     typenameTypeIdAndMod(NULL, inhdef->typeName, &inhtypeid, &inhtypmod);
    3264         380 :     typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
    3265         380 :     if (inhtypeid != newtypeid || inhtypmod != newtypmod)
    3266          12 :         ereport(ERROR,
    3267             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3268             :                  errmsg("column \"%s\" has a type conflict",
    3269             :                         attributeName),
    3270             :                  errdetail("%s versus %s",
    3271             :                            format_type_with_typemod(inhtypeid, inhtypmod),
    3272             :                            format_type_with_typemod(newtypeid, newtypmod))));
    3273             : 
    3274             :     /*
    3275             :      * Must have the same collation
    3276             :      */
    3277         368 :     inhcollid = GetColumnDefCollation(NULL, inhdef, inhtypeid);
    3278         368 :     newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
    3279         368 :     if (inhcollid != newcollid)
    3280           6 :         ereport(ERROR,
    3281             :                 (errcode(ERRCODE_COLLATION_MISMATCH),
    3282             :                  errmsg("column \"%s\" has a collation conflict",
    3283             :                         attributeName),
    3284             :                  errdetail("\"%s\" versus \"%s\"",
    3285             :                            get_collation_name(inhcollid),
    3286             :                            get_collation_name(newcollid))));
    3287             : 
    3288             :     /*
    3289             :      * Identity is never inherited by a regular inheritance child. Pick
    3290             :      * child's identity definition if there's one.
    3291             :      */
    3292         362 :     inhdef->identity = newdef->identity;
    3293             : 
    3294             :     /*
    3295             :      * Copy storage parameter
    3296             :      */
    3297         362 :     if (inhdef->storage == 0)
    3298           0 :         inhdef->storage = newdef->storage;
    3299         362 :     else if (newdef->storage != 0 && inhdef->storage != newdef->storage)
    3300           6 :         ereport(ERROR,
    3301             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3302             :                  errmsg("column \"%s\" has a storage parameter conflict",
    3303             :                         attributeName),
    3304             :                  errdetail("%s versus %s",
    3305             :                            storage_name(inhdef->storage),
    3306             :                            storage_name(newdef->storage))));
    3307             : 
    3308             :     /*
    3309             :      * Copy compression parameter
    3310             :      */
    3311         356 :     if (inhdef->compression == NULL)
    3312         350 :         inhdef->compression = newdef->compression;
    3313           6 :     else if (newdef->compression != NULL)
    3314             :     {
    3315           6 :         if (strcmp(inhdef->compression, newdef->compression) != 0)
    3316           6 :             ereport(ERROR,
    3317             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3318             :                      errmsg("column \"%s\" has a compression method conflict",
    3319             :                             attributeName),
    3320             :                      errdetail("%s versus %s", inhdef->compression, newdef->compression)));
    3321             :     }
    3322             : 
    3323             :     /*
    3324             :      * Merge of not-null constraints = OR 'em together
    3325             :      */
    3326         350 :     inhdef->is_not_null |= newdef->is_not_null;
    3327             : 
    3328             :     /*
    3329             :      * Check for conflicts related to generated columns.
    3330             :      *
    3331             :      * If the parent column is generated, the child column will be made a
    3332             :      * generated column if it isn't already.  If it is a generated column,
    3333             :      * we'll take its generation expression in preference to the parent's.  We
    3334             :      * must check that the child column doesn't specify a default value or
    3335             :      * identity, which matches the rules for a single column in
    3336             :      * parse_utilcmd.c.
    3337             :      *
    3338             :      * Conversely, if the parent column is not generated, the child column
    3339             :      * can't be either.  (We used to allow that, but it results in being able
    3340             :      * to override the generation expression via UPDATEs through the parent.)
    3341             :      */
    3342         350 :     if (inhdef->generated)
    3343             :     {
    3344          62 :         if (newdef->raw_default && !newdef->generated)
    3345          12 :             ereport(ERROR,
    3346             :                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3347             :                      errmsg("column \"%s\" inherits from generated column but specifies default",
    3348             :                             inhdef->colname)));
    3349          50 :         if (newdef->identity)
    3350          12 :             ereport(ERROR,
    3351             :                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3352             :                      errmsg("column \"%s\" inherits from generated column but specifies identity",
    3353             :                             inhdef->colname)));
    3354             :     }
    3355             :     else
    3356             :     {
    3357         288 :         if (newdef->generated)
    3358          12 :             ereport(ERROR,
    3359             :                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3360             :                      errmsg("child column \"%s\" specifies generation expression",
    3361             :                             inhdef->colname),
    3362             :                      errhint("A child table column cannot be generated unless its parent column is.")));
    3363             :     }
    3364             : 
    3365         314 :     if (inhdef->generated && newdef->generated && newdef->generated != inhdef->generated)
    3366          12 :         ereport(ERROR,
    3367             :                 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
    3368             :                  errmsg("column \"%s\" inherits from generated column of different kind",
    3369             :                         inhdef->colname),
    3370             :                  errdetail("Parent column is %s, child column is %s.",
    3371             :                            inhdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
    3372             :                            newdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
    3373             : 
    3374             :     /*
    3375             :      * If new def has a default, override previous default
    3376             :      */
    3377         302 :     if (newdef->raw_default != NULL)
    3378             :     {
    3379          30 :         inhdef->raw_default = newdef->raw_default;
    3380          30 :         inhdef->cooked_default = newdef->cooked_default;
    3381             :     }
    3382             : 
    3383             :     /* Mark the column as locally defined */
    3384         302 :     inhdef->is_local = true;
    3385         302 : }
    3386             : 
    3387             : /*
    3388             :  * MergeInheritedAttribute
    3389             :  *      Merge given parent attribute definition into specified attribute
    3390             :  *      inherited from the previous parents.
    3391             :  *
    3392             :  * Input arguments:
    3393             :  * 'inh_columns' is the list of previously inherited ColumnDefs.
    3394             :  * 'exist_attno' is the number the existing matching attribute in inh_columns.
    3395             :  * 'newdef' is the new parent column/attribute definition to be merged.
    3396             :  *
    3397             :  * The matching ColumnDef in 'inh_columns' list is modified and returned.
    3398             :  *
    3399             :  * Notes:
    3400             :  * - The attribute is merged according to the rules laid out in the prologue
    3401             :  *   of MergeAttributes().
    3402             :  * - If matching inherited attribute exists but the new attribute can not be
    3403             :  *   merged into it, the function throws respective errors.
    3404             :  * - A partition inherits from only a single parent. Hence this function is
    3405             :  *   applicable only to a regular inheritance.
    3406             :  */
    3407             : static ColumnDef *
    3408         370 : MergeInheritedAttribute(List *inh_columns,
    3409             :                         int exist_attno,
    3410             :                         const ColumnDef *newdef)
    3411             : {
    3412         370 :     char       *attributeName = newdef->colname;
    3413             :     ColumnDef  *prevdef;
    3414             :     Oid         prevtypeid,
    3415             :                 newtypeid;
    3416             :     int32       prevtypmod,
    3417             :                 newtypmod;
    3418             :     Oid         prevcollid,
    3419             :                 newcollid;
    3420             : 
    3421         370 :     ereport(NOTICE,
    3422             :             (errmsg("merging multiple inherited definitions of column \"%s\"",
    3423             :                     attributeName)));
    3424         370 :     prevdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
    3425             : 
    3426             :     /*
    3427             :      * Must have the same type and typmod
    3428             :      */
    3429         370 :     typenameTypeIdAndMod(NULL, prevdef->typeName, &prevtypeid, &prevtypmod);
    3430         370 :     typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
    3431         370 :     if (prevtypeid != newtypeid || prevtypmod != newtypmod)
    3432           0 :         ereport(ERROR,
    3433             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3434             :                  errmsg("inherited column \"%s\" has a type conflict",
    3435             :                         attributeName),
    3436             :                  errdetail("%s versus %s",
    3437             :                            format_type_with_typemod(prevtypeid, prevtypmod),
    3438             :                            format_type_with_typemod(newtypeid, newtypmod))));
    3439             : 
    3440             :     /*
    3441             :      * Must have the same collation
    3442             :      */
    3443         370 :     prevcollid = GetColumnDefCollation(NULL, prevdef, prevtypeid);
    3444         370 :     newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
    3445         370 :     if (prevcollid != newcollid)
    3446           0 :         ereport(ERROR,
    3447             :                 (errcode(ERRCODE_COLLATION_MISMATCH),
    3448             :                  errmsg("inherited column \"%s\" has a collation conflict",
    3449             :                         attributeName),
    3450             :                  errdetail("\"%s\" versus \"%s\"",
    3451             :                            get_collation_name(prevcollid),
    3452             :                            get_collation_name(newcollid))));
    3453             : 
    3454             :     /*
    3455             :      * Copy/check storage parameter
    3456             :      */
    3457         370 :     if (prevdef->storage == 0)
    3458           0 :         prevdef->storage = newdef->storage;
    3459         370 :     else if (prevdef->storage != newdef->storage)
    3460           6 :         ereport(ERROR,
    3461             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3462             :                  errmsg("inherited column \"%s\" has a storage parameter conflict",
    3463             :                         attributeName),
    3464             :                  errdetail("%s versus %s",
    3465             :                            storage_name(prevdef->storage),
    3466             :                            storage_name(newdef->storage))));
    3467             : 
    3468             :     /*
    3469             :      * Copy/check compression parameter
    3470             :      */
    3471         364 :     if (prevdef->compression == NULL)
    3472         346 :         prevdef->compression = newdef->compression;
    3473          18 :     else if (newdef->compression != NULL)
    3474             :     {
    3475           6 :         if (strcmp(prevdef->compression, newdef->compression) != 0)
    3476           6 :             ereport(ERROR,
    3477             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3478             :                      errmsg("column \"%s\" has a compression method conflict",
    3479             :                             attributeName),
    3480             :                      errdetail("%s versus %s",
    3481             :                                prevdef->compression, newdef->compression)));
    3482             :     }
    3483             : 
    3484             :     /*
    3485             :      * Check for GENERATED conflicts
    3486             :      */
    3487         358 :     if (prevdef->generated != newdef->generated)
    3488          24 :         ereport(ERROR,
    3489             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3490             :                  errmsg("inherited column \"%s\" has a generation conflict",
    3491             :                         attributeName)));
    3492             : 
    3493             :     /*
    3494             :      * Default and other constraints are handled by the caller.
    3495             :      */
    3496             : 
    3497         334 :     if (pg_add_s16_overflow(prevdef->inhcount, 1,
    3498             :                             &prevdef->inhcount))
    3499           0 :         ereport(ERROR,
    3500             :                 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3501             :                 errmsg("too many inheritance parents"));
    3502             : 
    3503         334 :     return prevdef;
    3504             : }
    3505             : 
    3506             : /*
    3507             :  * StoreCatalogInheritance
    3508             :  *      Updates the system catalogs with proper inheritance information.
    3509             :  *
    3510             :  * supers is a list of the OIDs of the new relation's direct ancestors.
    3511             :  */
    3512             : static void
    3513       62108 : StoreCatalogInheritance(Oid relationId, List *supers,
    3514             :                         bool child_is_partition)
    3515             : {
    3516             :     Relation    relation;
    3517             :     int32       seqNumber;
    3518             :     ListCell   *entry;
    3519             : 
    3520             :     /*
    3521             :      * sanity checks
    3522             :      */
    3523             :     Assert(OidIsValid(relationId));
    3524             : 
    3525       62108 :     if (supers == NIL)
    3526       52384 :         return;
    3527             : 
    3528             :     /*
    3529             :      * Store INHERITS information in pg_inherits using direct ancestors only.
    3530             :      * Also enter dependencies on the direct ancestors, and make sure they are
    3531             :      * marked with relhassubclass = true.
    3532             :      *
    3533             :      * (Once upon a time, both direct and indirect ancestors were found here
    3534             :      * and then entered into pg_ipl.  Since that catalog doesn't exist
    3535             :      * anymore, there's no need to look for indirect ancestors.)
    3536             :      */
    3537        9724 :     relation = table_open(InheritsRelationId, RowExclusiveLock);
    3538             : 
    3539        9724 :     seqNumber = 1;
    3540       19782 :     foreach(entry, supers)
    3541             :     {
    3542       10058 :         Oid         parentOid = lfirst_oid(entry);
    3543             : 
    3544       10058 :         StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
    3545             :                                  child_is_partition);
    3546       10058 :         seqNumber++;
    3547             :     }
    3548             : 
    3549        9724 :     table_close(relation, RowExclusiveLock);
    3550             : }
    3551             : 
    3552             : /*
    3553             :  * Make catalog entries showing relationId as being an inheritance child
    3554             :  * of parentOid.  inhRelation is the already-opened pg_inherits catalog.
    3555             :  */
    3556             : static void
    3557       12526 : StoreCatalogInheritance1(Oid relationId, Oid parentOid,
    3558             :                          int32 seqNumber, Relation inhRelation,
    3559             :                          bool child_is_partition)
    3560             : {
    3561             :     ObjectAddress childobject,
    3562             :                 parentobject;
    3563             : 
    3564             :     /* store the pg_inherits row */
    3565       12526 :     StoreSingleInheritance(relationId, parentOid, seqNumber);
    3566             : 
    3567             :     /*
    3568             :      * Store a dependency too
    3569             :      */
    3570       12526 :     parentobject.classId = RelationRelationId;
    3571       12526 :     parentobject.objectId = parentOid;
    3572       12526 :     parentobject.objectSubId = 0;
    3573       12526 :     childobject.classId = RelationRelationId;
    3574       12526 :     childobject.objectId = relationId;
    3575       12526 :     childobject.objectSubId = 0;
    3576             : 
    3577       12526 :     recordDependencyOn(&childobject, &parentobject,
    3578             :                        child_dependency_type(child_is_partition));
    3579             : 
    3580             :     /*
    3581             :      * Post creation hook of this inheritance. Since object_access_hook
    3582             :      * doesn't take multiple object identifiers, we relay oid of parent
    3583             :      * relation using auxiliary_id argument.
    3584             :      */
    3585       12526 :     InvokeObjectPostAlterHookArg(InheritsRelationId,
    3586             :                                  relationId, 0,
    3587             :                                  parentOid, false);
    3588             : 
    3589             :     /*
    3590             :      * Mark the parent as having subclasses.
    3591             :      */
    3592       12526 :     SetRelationHasSubclass(parentOid, true);
    3593       12526 : }
    3594             : 
    3595             : /*
    3596             :  * Look for an existing column entry with the given name.
    3597             :  *
    3598             :  * Returns the index (starting with 1) if attribute already exists in columns,
    3599             :  * 0 if it doesn't.
    3600             :  */
    3601             : static int
    3602       22304 : findAttrByName(const char *attributeName, const List *columns)
    3603             : {
    3604             :     ListCell   *lc;
    3605       22304 :     int         i = 1;
    3606             : 
    3607       39880 :     foreach(lc, columns)
    3608             :     {
    3609       18326 :         if (strcmp(attributeName, lfirst_node(ColumnDef, lc)->colname) == 0)
    3610         750 :             return i;
    3611             : 
    3612       17576 :         i++;
    3613             :     }
    3614       21554 :     return 0;
    3615             : }
    3616             : 
    3617             : 
    3618             : /*
    3619             :  * SetRelationHasSubclass
    3620             :  *      Set the value of the relation's relhassubclass field in pg_class.
    3621             :  *
    3622             :  * It's always safe to set this field to true, because all SQL commands are
    3623             :  * ready to see true and then find no children.  On the other hand, commands
    3624             :  * generally assume zero children if this is false.
    3625             :  *
    3626             :  * Caller must hold any self-exclusive lock until end of transaction.  If the
    3627             :  * new value is false, caller must have acquired that lock before reading the
    3628             :  * evidence that justified the false value.  That way, it properly waits if
    3629             :  * another backend is simultaneously concluding no need to change the tuple
    3630             :  * (new and old values are true).
    3631             :  *
    3632             :  * NOTE: an important side-effect of this operation is that an SI invalidation
    3633             :  * message is sent out to all backends --- including me --- causing plans
    3634             :  * referencing the relation to be rebuilt with the new list of children.
    3635             :  * This must happen even if we find that no change is needed in the pg_class
    3636             :  * row.
    3637             :  */
    3638             : void
    3639       15576 : SetRelationHasSubclass(Oid relationId, bool relhassubclass)
    3640             : {
    3641             :     Relation    relationRelation;
    3642             :     HeapTuple   tuple;
    3643             :     Form_pg_class classtuple;
    3644             : 
    3645             :     Assert(CheckRelationOidLockedByMe(relationId,
    3646             :                                       ShareUpdateExclusiveLock, false) ||
    3647             :            CheckRelationOidLockedByMe(relationId,
    3648             :                                       ShareRowExclusiveLock, true));
    3649             : 
    3650             :     /*
    3651             :      * Fetch a modifiable copy of the tuple, modify it, update pg_class.
    3652             :      */
    3653       15576 :     relationRelation = table_open(RelationRelationId, RowExclusiveLock);
    3654       15576 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
    3655       15576 :     if (!HeapTupleIsValid(tuple))
    3656           0 :         elog(ERROR, "cache lookup failed for relation %u", relationId);
    3657       15576 :     classtuple = (Form_pg_class) GETSTRUCT(tuple);
    3658             : 
    3659       15576 :     if (classtuple->relhassubclass != relhassubclass)
    3660             :     {
    3661        7892 :         classtuple->relhassubclass = relhassubclass;
    3662        7892 :         CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
    3663             :     }
    3664             :     else
    3665             :     {
    3666             :         /* no need to change tuple, but force relcache rebuild anyway */
    3667        7684 :         CacheInvalidateRelcacheByTuple(tuple);
    3668             :     }
    3669             : 
    3670       15576 :     heap_freetuple(tuple);
    3671       15576 :     table_close(relationRelation, RowExclusiveLock);
    3672       15576 : }
    3673             : 
    3674             : /*
    3675             :  * CheckRelationTableSpaceMove
    3676             :  *      Check if relation can be moved to new tablespace.
    3677             :  *
    3678             :  * NOTE: The caller must hold AccessExclusiveLock on the relation.
    3679             :  *
    3680             :  * Returns true if the relation can be moved to the new tablespace; raises
    3681             :  * an error if it is not possible to do the move; returns false if the move
    3682             :  * would have no effect.
    3683             :  */
    3684             : bool
    3685         226 : CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
    3686             : {
    3687             :     Oid         oldTableSpaceId;
    3688             : 
    3689             :     /*
    3690             :      * No work if no change in tablespace.  Note that MyDatabaseTableSpace is
    3691             :      * stored as 0.
    3692             :      */
    3693         226 :     oldTableSpaceId = rel->rd_rel->reltablespace;
    3694         226 :     if (newTableSpaceId == oldTableSpaceId ||
    3695         218 :         (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
    3696          10 :         return false;
    3697             : 
    3698             :     /*
    3699             :      * We cannot support moving mapped relations into different tablespaces.
    3700             :      * (In particular this eliminates all shared catalogs.)
    3701             :      */
    3702         216 :     if (RelationIsMapped(rel))
    3703           0 :         ereport(ERROR,
    3704             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3705             :                  errmsg("cannot move system relation \"%s\"",
    3706             :                         RelationGetRelationName(rel))));
    3707             : 
    3708             :     /* Cannot move a non-shared relation into pg_global */
    3709         216 :     if (newTableSpaceId == GLOBALTABLESPACE_OID)
    3710          12 :         ereport(ERROR,
    3711             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    3712             :                  errmsg("only shared relations can be placed in pg_global tablespace")));
    3713             : 
    3714             :     /*
    3715             :      * Do not allow moving temp tables of other backends ... their local
    3716             :      * buffer manager is not going to cope.
    3717             :      */
    3718         204 :     if (RELATION_IS_OTHER_TEMP(rel))
    3719           0 :         ereport(ERROR,
    3720             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3721             :                  errmsg("cannot move temporary tables of other sessions")));
    3722             : 
    3723         204 :     return true;
    3724             : }
    3725             : 
    3726             : /*
    3727             :  * SetRelationTableSpace
    3728             :  *      Set new reltablespace and relfilenumber in pg_class entry.
    3729             :  *
    3730             :  * newTableSpaceId is the new tablespace for the relation, and
    3731             :  * newRelFilenumber its new filenumber.  If newRelFilenumber is
    3732             :  * InvalidRelFileNumber, this field is not updated.
    3733             :  *
    3734             :  * NOTE: The caller must hold AccessExclusiveLock on the relation.
    3735             :  *
    3736             :  * The caller of this routine had better check if a relation can be
    3737             :  * moved to this new tablespace by calling CheckRelationTableSpaceMove()
    3738             :  * first, and is responsible for making the change visible with
    3739             :  * CommandCounterIncrement().
    3740             :  */
    3741             : void
    3742         204 : SetRelationTableSpace(Relation rel,
    3743             :                       Oid newTableSpaceId,
    3744             :                       RelFileNumber newRelFilenumber)
    3745             : {
    3746             :     Relation    pg_class;
    3747             :     HeapTuple   tuple;
    3748             :     ItemPointerData otid;
    3749             :     Form_pg_class rd_rel;
    3750         204 :     Oid         reloid = RelationGetRelid(rel);
    3751             : 
    3752             :     Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
    3753             : 
    3754             :     /* Get a modifiable copy of the relation's pg_class row. */
    3755         204 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
    3756             : 
    3757         204 :     tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
    3758         204 :     if (!HeapTupleIsValid(tuple))
    3759           0 :         elog(ERROR, "cache lookup failed for relation %u", reloid);
    3760         204 :     otid = tuple->t_self;
    3761         204 :     rd_rel = (Form_pg_class) GETSTRUCT(tuple);
    3762             : 
    3763             :     /* Update the pg_class row. */
    3764         408 :     rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
    3765         204 :         InvalidOid : newTableSpaceId;
    3766         204 :     if (RelFileNumberIsValid(newRelFilenumber))
    3767         160 :         rd_rel->relfilenode = newRelFilenumber;
    3768         204 :     CatalogTupleUpdate(pg_class, &otid, tuple);
    3769         204 :     UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
    3770             : 
    3771             :     /*
    3772             :      * Record dependency on tablespace.  This is only required for relations
    3773             :      * that have no physical storage.
    3774             :      */
    3775         204 :     if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
    3776          30 :         changeDependencyOnTablespace(RelationRelationId, reloid,
    3777             :                                      rd_rel->reltablespace);
    3778             : 
    3779         204 :     heap_freetuple(tuple);
    3780         204 :     table_close(pg_class, RowExclusiveLock);
    3781         204 : }
    3782             : 
    3783             : /*
    3784             :  *      renameatt_check         - basic sanity checks before attribute rename
    3785             :  */
    3786             : static void
    3787        1008 : renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
    3788             : {
    3789        1008 :     char        relkind = classform->relkind;
    3790             : 
    3791        1008 :     if (classform->reloftype && !recursing)
    3792           6 :         ereport(ERROR,
    3793             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3794             :                  errmsg("cannot rename column of typed table")));
    3795             : 
    3796             :     /*
    3797             :      * Renaming the columns of sequences or toast tables doesn't actually
    3798             :      * break anything from the system's point of view, since internal
    3799             :      * references are by attnum.  But it doesn't seem right to allow users to
    3800             :      * change names that are hardcoded into the system, hence the following
    3801             :      * restriction.
    3802             :      */
    3803        1002 :     if (relkind != RELKIND_RELATION &&
    3804          84 :         relkind != RELKIND_VIEW &&
    3805          84 :         relkind != RELKIND_MATVIEW &&
    3806          36 :         relkind != RELKIND_COMPOSITE_TYPE &&
    3807          36 :         relkind != RELKIND_INDEX &&
    3808          36 :         relkind != RELKIND_PARTITIONED_INDEX &&
    3809           0 :         relkind != RELKIND_FOREIGN_TABLE &&
    3810             :         relkind != RELKIND_PARTITIONED_TABLE)
    3811           0 :         ereport(ERROR,
    3812             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3813             :                  errmsg("cannot rename columns of relation \"%s\"",
    3814             :                         NameStr(classform->relname)),
    3815             :                  errdetail_relkind_not_supported(relkind)));
    3816             : 
    3817             :     /*
    3818             :      * permissions checking.  only the owner of a class can change its schema.
    3819             :      */
    3820        1002 :     if (!object_ownercheck(RelationRelationId, myrelid, GetUserId()))
    3821           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(myrelid)),
    3822           0 :                        NameStr(classform->relname));
    3823        1002 :     if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
    3824           2 :         ereport(ERROR,
    3825             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    3826             :                  errmsg("permission denied: \"%s\" is a system catalog",
    3827             :                         NameStr(classform->relname))));
    3828        1000 : }
    3829             : 
    3830             : /*
    3831             :  *      renameatt_internal      - workhorse for renameatt
    3832             :  *
    3833             :  * Return value is the attribute number in the 'myrelid' relation.
    3834             :  */
    3835             : static AttrNumber
    3836         552 : renameatt_internal(Oid myrelid,
    3837             :                    const char *oldattname,
    3838             :                    const char *newattname,
    3839             :                    bool recurse,
    3840             :                    bool recursing,
    3841             :                    int expected_parents,
    3842             :                    DropBehavior behavior)
    3843             : {
    3844             :     Relation    targetrelation;
    3845             :     Relation    attrelation;
    3846             :     HeapTuple   atttup;
    3847             :     Form_pg_attribute attform;
    3848             :     AttrNumber  attnum;
    3849             : 
    3850             :     /*
    3851             :      * Grab an exclusive lock on the target table, which we will NOT release
    3852             :      * until end of transaction.
    3853             :      */
    3854         552 :     targetrelation = relation_open(myrelid, AccessExclusiveLock);
    3855         552 :     renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
    3856             : 
    3857             :     /*
    3858             :      * if the 'recurse' flag is set then we are supposed to rename this
    3859             :      * attribute in all classes that inherit from 'relname' (as well as in
    3860             :      * 'relname').
    3861             :      *
    3862             :      * any permissions or problems with duplicate attributes will cause the
    3863             :      * whole transaction to abort, which is what we want -- all or nothing.
    3864             :      */
    3865         552 :     if (recurse)
    3866             :     {
    3867             :         List       *child_oids,
    3868             :                    *child_numparents;
    3869             :         ListCell   *lo,
    3870             :                    *li;
    3871             : 
    3872             :         /*
    3873             :          * we need the number of parents for each child so that the recursive
    3874             :          * calls to renameatt() can determine whether there are any parents
    3875             :          * outside the inheritance hierarchy being processed.
    3876             :          */
    3877         248 :         child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
    3878             :                                          &child_numparents);
    3879             : 
    3880             :         /*
    3881             :          * find_all_inheritors does the recursive search of the inheritance
    3882             :          * hierarchy, so all we have to do is process all of the relids in the
    3883             :          * list that it returns.
    3884             :          */
    3885         734 :         forboth(lo, child_oids, li, child_numparents)
    3886             :         {
    3887         516 :             Oid         childrelid = lfirst_oid(lo);
    3888         516 :             int         numparents = lfirst_int(li);
    3889             : 
    3890         516 :             if (childrelid == myrelid)
    3891         248 :                 continue;
    3892             :             /* note we need not recurse again */
    3893         268 :             renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
    3894             :         }
    3895             :     }
    3896             :     else
    3897             :     {
    3898             :         /*
    3899             :          * If we are told not to recurse, there had better not be any child
    3900             :          * tables; else the rename would put them out of step.
    3901             :          *
    3902             :          * expected_parents will only be 0 if we are not already recursing.
    3903             :          */
    3904         340 :         if (expected_parents == 0 &&
    3905          36 :             find_inheritance_children(myrelid, NoLock) != NIL)
    3906          12 :             ereport(ERROR,
    3907             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    3908             :                      errmsg("inherited column \"%s\" must be renamed in child tables too",
    3909             :                             oldattname)));
    3910             :     }
    3911             : 
    3912             :     /* rename attributes in typed tables of composite type */
    3913         510 :     if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
    3914             :     {
    3915             :         List       *child_oids;
    3916             :         ListCell   *lo;
    3917             : 
    3918          24 :         child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
    3919          24 :                                                    RelationGetRelationName(targetrelation),
    3920             :                                                    behavior);
    3921             : 
    3922          24 :         foreach(lo, child_oids)
    3923           6 :             renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
    3924             :     }
    3925             : 
    3926         504 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    3927             : 
    3928         504 :     atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
    3929         504 :     if (!HeapTupleIsValid(atttup))
    3930          24 :         ereport(ERROR,
    3931             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    3932             :                  errmsg("column \"%s\" does not exist",
    3933             :                         oldattname)));
    3934         480 :     attform = (Form_pg_attribute) GETSTRUCT(atttup);
    3935             : 
    3936         480 :     attnum = attform->attnum;
    3937         480 :     if (attnum <= 0)
    3938           0 :         ereport(ERROR,
    3939             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3940             :                  errmsg("cannot rename system column \"%s\"",
    3941             :                         oldattname)));
    3942             : 
    3943             :     /*
    3944             :      * if the attribute is inherited, forbid the renaming.  if this is a
    3945             :      * top-level call to renameatt(), then expected_parents will be 0, so the
    3946             :      * effect of this code will be to prohibit the renaming if the attribute
    3947             :      * is inherited at all.  if this is a recursive call to renameatt(),
    3948             :      * expected_parents will be the number of parents the current relation has
    3949             :      * within the inheritance hierarchy being processed, so we'll prohibit the
    3950             :      * renaming only if there are additional parents from elsewhere.
    3951             :      */
    3952         480 :     if (attform->attinhcount > expected_parents)
    3953          30 :         ereport(ERROR,
    3954             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    3955             :                  errmsg("cannot rename inherited column \"%s\"",
    3956             :                         oldattname)));
    3957             : 
    3958             :     /* new name should not already exist */
    3959         450 :     (void) check_for_column_name_collision(targetrelation, newattname, false);
    3960             : 
    3961             :     /* apply the update */
    3962         438 :     namestrcpy(&(attform->attname), newattname);
    3963             : 
    3964         438 :     CatalogTupleUpdate(attrelation, &atttup->t_self, atttup);
    3965             : 
    3966         438 :     InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
    3967             : 
    3968         438 :     heap_freetuple(atttup);
    3969             : 
    3970         438 :     table_close(attrelation, RowExclusiveLock);
    3971             : 
    3972         438 :     relation_close(targetrelation, NoLock); /* close rel but keep lock */
    3973             : 
    3974         438 :     return attnum;
    3975             : }
    3976             : 
    3977             : /*
    3978             :  * Perform permissions and integrity checks before acquiring a relation lock.
    3979             :  */
    3980             : static void
    3981         408 : RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
    3982             :                                    void *arg)
    3983             : {
    3984             :     HeapTuple   tuple;
    3985             :     Form_pg_class form;
    3986             : 
    3987         408 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    3988         408 :     if (!HeapTupleIsValid(tuple))
    3989          36 :         return;                 /* concurrently dropped */
    3990         372 :     form = (Form_pg_class) GETSTRUCT(tuple);
    3991         372 :     renameatt_check(relid, form, false);
    3992         364 :     ReleaseSysCache(tuple);
    3993             : }
    3994             : 
    3995             : /*
    3996             :  *      renameatt       - changes the name of an attribute in a relation
    3997             :  *
    3998             :  * The returned ObjectAddress is that of the renamed column.
    3999             :  */
    4000             : ObjectAddress
    4001         316 : renameatt(RenameStmt *stmt)
    4002             : {
    4003             :     Oid         relid;
    4004             :     AttrNumber  attnum;
    4005             :     ObjectAddress address;
    4006             : 
    4007             :     /* lock level taken here should match renameatt_internal */
    4008         316 :     relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
    4009         316 :                                      stmt->missing_ok ? RVR_MISSING_OK : 0,
    4010             :                                      RangeVarCallbackForRenameAttribute,
    4011             :                                      NULL);
    4012             : 
    4013         302 :     if (!OidIsValid(relid))
    4014             :     {
    4015          24 :         ereport(NOTICE,
    4016             :                 (errmsg("relation \"%s\" does not exist, skipping",
    4017             :                         stmt->relation->relname)));
    4018          24 :         return InvalidObjectAddress;
    4019             :     }
    4020             : 
    4021             :     attnum =
    4022         278 :         renameatt_internal(relid,
    4023         278 :                            stmt->subname,    /* old att name */
    4024         278 :                            stmt->newname,    /* new att name */
    4025         278 :                            stmt->relation->inh, /* recursive? */
    4026             :                            false,   /* recursing? */
    4027             :                            0,   /* expected inhcount */
    4028             :                            stmt->behavior);
    4029             : 
    4030         194 :     ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
    4031             : 
    4032         194 :     return address;
    4033             : }
    4034             : 
    4035             : /*
    4036             :  * same logic as renameatt_internal
    4037             :  */
    4038             : static ObjectAddress
    4039          90 : rename_constraint_internal(Oid myrelid,
    4040             :                            Oid mytypid,
    4041             :                            const char *oldconname,
    4042             :                            const char *newconname,
    4043             :                            bool recurse,
    4044             :                            bool recursing,
    4045             :                            int expected_parents)
    4046             : {
    4047          90 :     Relation    targetrelation = NULL;
    4048             :     Oid         constraintOid;
    4049             :     HeapTuple   tuple;
    4050             :     Form_pg_constraint con;
    4051             :     ObjectAddress address;
    4052             : 
    4053             :     Assert(!myrelid || !mytypid);
    4054             : 
    4055          90 :     if (mytypid)
    4056             :     {
    4057           6 :         constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
    4058             :     }
    4059             :     else
    4060             :     {
    4061          84 :         targetrelation = relation_open(myrelid, AccessExclusiveLock);
    4062             : 
    4063             :         /*
    4064             :          * don't tell it whether we're recursing; we allow changing typed
    4065             :          * tables here
    4066             :          */
    4067          84 :         renameatt_check(myrelid, RelationGetForm(targetrelation), false);
    4068             : 
    4069          84 :         constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
    4070             :     }
    4071             : 
    4072          90 :     tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
    4073          90 :     if (!HeapTupleIsValid(tuple))
    4074           0 :         elog(ERROR, "cache lookup failed for constraint %u",
    4075             :              constraintOid);
    4076          90 :     con = (Form_pg_constraint) GETSTRUCT(tuple);
    4077             : 
    4078          90 :     if (myrelid &&
    4079          84 :         (con->contype == CONSTRAINT_CHECK ||
    4080          24 :          con->contype == CONSTRAINT_NOTNULL) &&
    4081          66 :         !con->connoinherit)
    4082             :     {
    4083          54 :         if (recurse)
    4084             :         {
    4085             :             List       *child_oids,
    4086             :                        *child_numparents;
    4087             :             ListCell   *lo,
    4088             :                        *li;
    4089             : 
    4090          36 :             child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
    4091             :                                              &child_numparents);
    4092             : 
    4093          84 :             forboth(lo, child_oids, li, child_numparents)
    4094             :             {
    4095          48 :                 Oid         childrelid = lfirst_oid(lo);
    4096          48 :                 int         numparents = lfirst_int(li);
    4097             : 
    4098          48 :                 if (childrelid == myrelid)
    4099          36 :                     continue;
    4100             : 
    4101          12 :                 rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
    4102             :             }
    4103             :         }
    4104             :         else
    4105             :         {
    4106          24 :             if (expected_parents == 0 &&
    4107           6 :                 find_inheritance_children(myrelid, NoLock) != NIL)
    4108           6 :                 ereport(ERROR,
    4109             :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4110             :                          errmsg("inherited constraint \"%s\" must be renamed in child tables too",
    4111             :                                 oldconname)));
    4112             :         }
    4113             : 
    4114          48 :         if (con->coninhcount > expected_parents)
    4115           6 :             ereport(ERROR,
    4116             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    4117             :                      errmsg("cannot rename inherited constraint \"%s\"",
    4118             :                             oldconname)));
    4119             :     }
    4120             : 
    4121          78 :     if (con->conindid
    4122          18 :         && (con->contype == CONSTRAINT_PRIMARY
    4123           6 :             || con->contype == CONSTRAINT_UNIQUE
    4124           0 :             || con->contype == CONSTRAINT_EXCLUSION))
    4125             :         /* rename the index; this renames the constraint as well */
    4126          18 :         RenameRelationInternal(con->conindid, newconname, false, true);
    4127             :     else
    4128          60 :         RenameConstraintById(constraintOid, newconname);
    4129             : 
    4130          78 :     ObjectAddressSet(address, ConstraintRelationId, constraintOid);
    4131             : 
    4132          78 :     ReleaseSysCache(tuple);
    4133             : 
    4134          78 :     if (targetrelation)
    4135             :     {
    4136             :         /*
    4137             :          * Invalidate relcache so as others can see the new constraint name.
    4138             :          */
    4139          72 :         CacheInvalidateRelcache(targetrelation);
    4140             : 
    4141          72 :         relation_close(targetrelation, NoLock); /* close rel but keep lock */
    4142             :     }
    4143             : 
    4144          78 :     return address;
    4145             : }
    4146             : 
    4147             : ObjectAddress
    4148          84 : RenameConstraint(RenameStmt *stmt)
    4149             : {
    4150          84 :     Oid         relid = InvalidOid;
    4151          84 :     Oid         typid = InvalidOid;
    4152             : 
    4153          84 :     if (stmt->renameType == OBJECT_DOMCONSTRAINT)
    4154             :     {
    4155             :         Relation    rel;
    4156             :         HeapTuple   tup;
    4157             : 
    4158           6 :         typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
    4159           6 :         rel = table_open(TypeRelationId, RowExclusiveLock);
    4160           6 :         tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
    4161           6 :         if (!HeapTupleIsValid(tup))
    4162           0 :             elog(ERROR, "cache lookup failed for type %u", typid);
    4163           6 :         checkDomainOwner(tup);
    4164           6 :         ReleaseSysCache(tup);
    4165           6 :         table_close(rel, NoLock);
    4166             :     }
    4167             :     else
    4168             :     {
    4169             :         /* lock level taken here should match rename_constraint_internal */
    4170          78 :         relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
    4171          78 :                                          stmt->missing_ok ? RVR_MISSING_OK : 0,
    4172             :                                          RangeVarCallbackForRenameAttribute,
    4173             :                                          NULL);
    4174          78 :         if (!OidIsValid(relid))
    4175             :         {
    4176           6 :             ereport(NOTICE,
    4177             :                     (errmsg("relation \"%s\" does not exist, skipping",
    4178             :                             stmt->relation->relname)));
    4179           6 :             return InvalidObjectAddress;
    4180             :         }
    4181             :     }
    4182             : 
    4183             :     return
    4184          78 :         rename_constraint_internal(relid, typid,
    4185          78 :                                    stmt->subname,
    4186          78 :                                    stmt->newname,
    4187         150 :                                    (stmt->relation &&
    4188          72 :                                     stmt->relation->inh), /* recursive? */
    4189             :                                    false,   /* recursing? */
    4190             :                                    0 /* expected inhcount */ );
    4191             : }
    4192             : 
    4193             : /*
    4194             :  * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
    4195             :  * RENAME
    4196             :  */
    4197             : ObjectAddress
    4198         512 : RenameRelation(RenameStmt *stmt)
    4199             : {
    4200         512 :     bool        is_index_stmt = stmt->renameType == OBJECT_INDEX;
    4201             :     Oid         relid;
    4202             :     ObjectAddress address;
    4203             : 
    4204             :     /*
    4205             :      * Grab an exclusive lock on the target table, index, sequence, view,
    4206             :      * materialized view, or foreign table, which we will NOT release until
    4207             :      * end of transaction.
    4208             :      *
    4209             :      * Lock level used here should match RenameRelationInternal, to avoid lock
    4210             :      * escalation.  However, because ALTER INDEX can be used with any relation
    4211             :      * type, we mustn't believe without verification.
    4212             :      */
    4213             :     for (;;)
    4214          12 :     {
    4215             :         LOCKMODE    lockmode;
    4216             :         char        relkind;
    4217             :         bool        obj_is_index;
    4218             : 
    4219         524 :         lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
    4220             : 
    4221         524 :         relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
    4222         524 :                                          stmt->missing_ok ? RVR_MISSING_OK : 0,
    4223             :                                          RangeVarCallbackForAlterRelation,
    4224             :                                          stmt);
    4225             : 
    4226         474 :         if (!OidIsValid(relid))
    4227             :         {
    4228          18 :             ereport(NOTICE,
    4229             :                     (errmsg("relation \"%s\" does not exist, skipping",
    4230             :                             stmt->relation->relname)));
    4231          18 :             return InvalidObjectAddress;
    4232             :         }
    4233             : 
    4234             :         /*
    4235             :          * We allow mismatched statement and object types (e.g., ALTER INDEX
    4236             :          * to rename a table), but we might've used the wrong lock level.  If
    4237             :          * that happens, retry with the correct lock level.  We don't bother
    4238             :          * if we already acquired AccessExclusiveLock with an index, however.
    4239             :          */
    4240         456 :         relkind = get_rel_relkind(relid);
    4241         456 :         obj_is_index = (relkind == RELKIND_INDEX ||
    4242             :                         relkind == RELKIND_PARTITIONED_INDEX);
    4243         456 :         if (obj_is_index || is_index_stmt == obj_is_index)
    4244             :             break;
    4245             : 
    4246          12 :         UnlockRelationOid(relid, lockmode);
    4247          12 :         is_index_stmt = obj_is_index;
    4248             :     }
    4249             : 
    4250             :     /* Do the work */
    4251         444 :     RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
    4252             : 
    4253         432 :     ObjectAddressSet(address, RelationRelationId, relid);
    4254             : 
    4255         432 :     return address;
    4256             : }
    4257             : 
    4258             : /*
    4259             :  *      RenameRelationInternal - change the name of a relation
    4260             :  */
    4261             : void
    4262        1676 : RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
    4263             : {
    4264             :     Relation    targetrelation;
    4265             :     Relation    relrelation;    /* for RELATION relation */
    4266             :     ItemPointerData otid;
    4267             :     HeapTuple   reltup;
    4268             :     Form_pg_class relform;
    4269             :     Oid         namespaceId;
    4270             : 
    4271             :     /*
    4272             :      * Grab a lock on the target relation, which we will NOT release until end
    4273             :      * of transaction.  We need at least a self-exclusive lock so that
    4274             :      * concurrent DDL doesn't overwrite the rename if they start updating
    4275             :      * while still seeing the old version.  The lock also guards against
    4276             :      * triggering relcache reloads in concurrent sessions, which might not
    4277             :      * handle this information changing under them.  For indexes, we can use a
    4278             :      * reduced lock level because RelationReloadIndexInfo() handles indexes
    4279             :      * specially.
    4280             :      */
    4281        1676 :     targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
    4282        1676 :     namespaceId = RelationGetNamespace(targetrelation);
    4283             : 
    4284             :     /*
    4285             :      * Find relation's pg_class tuple, and make sure newrelname isn't in use.
    4286             :      */
    4287        1676 :     relrelation = table_open(RelationRelationId, RowExclusiveLock);
    4288             : 
    4289        1676 :     reltup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(myrelid));
    4290        1676 :     if (!HeapTupleIsValid(reltup))  /* shouldn't happen */
    4291           0 :         elog(ERROR, "cache lookup failed for relation %u", myrelid);
    4292        1676 :     otid = reltup->t_self;
    4293        1676 :     relform = (Form_pg_class) GETSTRUCT(reltup);
    4294             : 
    4295        1676 :     if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
    4296          12 :         ereport(ERROR,
    4297             :                 (errcode(ERRCODE_DUPLICATE_TABLE),
    4298             :                  errmsg("relation \"%s\" already exists",
    4299             :                         newrelname)));
    4300             : 
    4301             :     /*
    4302             :      * RenameRelation is careful not to believe the caller's idea of the
    4303             :      * relation kind being handled.  We don't have to worry about this, but
    4304             :      * let's not be totally oblivious to it.  We can process an index as
    4305             :      * not-an-index, but not the other way around.
    4306             :      */
    4307             :     Assert(!is_index ||
    4308             :            is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
    4309             :                         targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
    4310             : 
    4311             :     /*
    4312             :      * Update pg_class tuple with new relname.  (Scribbling on reltup is OK
    4313             :      * because it's a copy...)
    4314             :      */
    4315        1664 :     namestrcpy(&(relform->relname), newrelname);
    4316             : 
    4317        1664 :     CatalogTupleUpdate(relrelation, &otid, reltup);
    4318        1664 :     UnlockTuple(relrelation, &otid, InplaceUpdateTupleLock);
    4319             : 
    4320        1664 :     InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
    4321             :                                  InvalidOid, is_internal);
    4322             : 
    4323        1664 :     heap_freetuple(reltup);
    4324        1664 :     table_close(relrelation, RowExclusiveLock);
    4325             : 
    4326             :     /*
    4327             :      * Also rename the associated type, if any.
    4328             :      */
    4329        1664 :     if (OidIsValid(targetrelation->rd_rel->reltype))
    4330         126 :         RenameTypeInternal(targetrelation->rd_rel->reltype,
    4331             :                            newrelname, namespaceId);
    4332             : 
    4333             :     /*
    4334             :      * Also rename the associated constraint, if any.
    4335             :      */
    4336        1664 :     if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
    4337         874 :         targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
    4338             :     {
    4339         808 :         Oid         constraintId = get_index_constraint(myrelid);
    4340             : 
    4341         808 :         if (OidIsValid(constraintId))
    4342          36 :             RenameConstraintById(constraintId, newrelname);
    4343             :     }
    4344             : 
    4345             :     /*
    4346             :      * Close rel, but keep lock!
    4347             :      */
    4348        1664 :     relation_close(targetrelation, NoLock);
    4349        1664 : }
    4350             : 
    4351             : /*
    4352             :  *      ResetRelRewrite - reset relrewrite
    4353             :  */
    4354             : void
    4355         596 : ResetRelRewrite(Oid myrelid)
    4356             : {
    4357             :     Relation    relrelation;    /* for RELATION relation */
    4358             :     HeapTuple   reltup;
    4359             :     Form_pg_class relform;
    4360             : 
    4361             :     /*
    4362             :      * Find relation's pg_class tuple.
    4363             :      */
    4364         596 :     relrelation = table_open(RelationRelationId, RowExclusiveLock);
    4365             : 
    4366         596 :     reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
    4367         596 :     if (!HeapTupleIsValid(reltup))  /* shouldn't happen */
    4368           0 :         elog(ERROR, "cache lookup failed for relation %u", myrelid);
    4369         596 :     relform = (Form_pg_class) GETSTRUCT(reltup);
    4370             : 
    4371             :     /*
    4372             :      * Update pg_class tuple.
    4373             :      */
    4374         596 :     relform->relrewrite = InvalidOid;
    4375             : 
    4376         596 :     CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
    4377             : 
    4378         596 :     heap_freetuple(reltup);
    4379         596 :     table_close(relrelation, RowExclusiveLock);
    4380         596 : }
    4381             : 
    4382             : /*
    4383             :  * Disallow ALTER TABLE (and similar commands) when the current backend has
    4384             :  * any open reference to the target table besides the one just acquired by
    4385             :  * the calling command; this implies there's an open cursor or active plan.
    4386             :  * We need this check because our lock doesn't protect us against stomping
    4387             :  * on our own foot, only other people's feet!
    4388             :  *
    4389             :  * For ALTER TABLE, the only case known to cause serious trouble is ALTER
    4390             :  * COLUMN TYPE, and some changes are obviously pretty benign, so this could
    4391             :  * possibly be relaxed to only error out for certain types of alterations.
    4392             :  * But the use-case for allowing any of these things is not obvious, so we
    4393             :  * won't work hard at it for now.
    4394             :  *
    4395             :  * We also reject these commands if there are any pending AFTER trigger events
    4396             :  * for the rel.  This is certainly necessary for the rewriting variants of
    4397             :  * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
    4398             :  * events would try to fetch the wrong tuples.  It might be overly cautious
    4399             :  * in other cases, but again it seems better to err on the side of paranoia.
    4400             :  *
    4401             :  * REINDEX calls this with "rel" referencing the index to be rebuilt; here
    4402             :  * we are worried about active indexscans on the index.  The trigger-event
    4403             :  * check can be skipped, since we are doing no damage to the parent table.
    4404             :  *
    4405             :  * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
    4406             :  */
    4407             : void
    4408      170340 : CheckTableNotInUse(Relation rel, const char *stmt)
    4409             : {
    4410             :     int         expected_refcnt;
    4411             : 
    4412      170340 :     expected_refcnt = rel->rd_isnailed ? 2 : 1;
    4413      170340 :     if (rel->rd_refcnt != expected_refcnt)
    4414          42 :         ereport(ERROR,
    4415             :                 (errcode(ERRCODE_OBJECT_IN_USE),
    4416             :         /* translator: first %s is a SQL command, eg ALTER TABLE */
    4417             :                  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
    4418             :                         stmt, RelationGetRelationName(rel))));
    4419             : 
    4420      170298 :     if (rel->rd_rel->relkind != RELKIND_INDEX &&
    4421      277474 :         rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
    4422      137696 :         AfterTriggerPendingOnRel(RelationGetRelid(rel)))
    4423          18 :         ereport(ERROR,
    4424             :                 (errcode(ERRCODE_OBJECT_IN_USE),
    4425             :         /* translator: first %s is a SQL command, eg ALTER TABLE */
    4426             :                  errmsg("cannot %s \"%s\" because it has pending trigger events",
    4427             :                         stmt, RelationGetRelationName(rel))));
    4428      170280 : }
    4429             : 
    4430             : /*
    4431             :  * CheckAlterTableIsSafe
    4432             :  *      Verify that it's safe to allow ALTER TABLE on this relation.
    4433             :  *
    4434             :  * This consists of CheckTableNotInUse() plus a check that the relation
    4435             :  * isn't another session's temp table.  We must split out the temp-table
    4436             :  * check because there are callers of CheckTableNotInUse() that don't want
    4437             :  * that, notably DROP TABLE.  (We must allow DROP or we couldn't clean out
    4438             :  * an orphaned temp schema.)  Compare truncate_check_activity().
    4439             :  */
    4440             : static void
    4441       61316 : CheckAlterTableIsSafe(Relation rel)
    4442             : {
    4443             :     /*
    4444             :      * Don't allow ALTER on temp tables of other backends.  Their local buffer
    4445             :      * manager is not going to cope if we need to change the table's contents.
    4446             :      * Even if we don't, there may be optimizations that assume temp tables
    4447             :      * aren't subject to such interference.
    4448             :      */
    4449       61316 :     if (RELATION_IS_OTHER_TEMP(rel))
    4450           0 :         ereport(ERROR,
    4451             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4452             :                  errmsg("cannot alter temporary tables of other sessions")));
    4453             : 
    4454             :     /*
    4455             :      * Also check for active uses of the relation in the current transaction,
    4456             :      * including open scans and pending AFTER trigger events.
    4457             :      */
    4458       61316 :     CheckTableNotInUse(rel, "ALTER TABLE");
    4459       61280 : }
    4460             : 
    4461             : /*
    4462             :  * AlterTableLookupRelation
    4463             :  *      Look up, and lock, the OID for the relation named by an alter table
    4464             :  *      statement.
    4465             :  */
    4466             : Oid
    4467       32310 : AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
    4468             : {
    4469       64532 :     return RangeVarGetRelidExtended(stmt->relation, lockmode,
    4470       32310 :                                     stmt->missing_ok ? RVR_MISSING_OK : 0,
    4471             :                                     RangeVarCallbackForAlterRelation,
    4472             :                                     stmt);
    4473             : }
    4474             : 
    4475             : /*
    4476             :  * AlterTable
    4477             :  *      Execute ALTER TABLE, which can be a list of subcommands
    4478             :  *
    4479             :  * ALTER TABLE is performed in three phases:
    4480             :  *      1. Examine subcommands and perform pre-transformation checking.
    4481             :  *      2. Validate and transform subcommands, and update system catalogs.
    4482             :  *      3. Scan table(s) to check new constraints, and optionally recopy
    4483             :  *         the data into new table(s).
    4484             :  * Phase 3 is not performed unless one or more of the subcommands requires
    4485             :  * it.  The intention of this design is to allow multiple independent
    4486             :  * updates of the table schema to be performed with only one pass over the
    4487             :  * data.
    4488             :  *
    4489             :  * ATPrepCmd performs phase 1.  A "work queue" entry is created for
    4490             :  * each table to be affected (there may be multiple affected tables if the
    4491             :  * commands traverse a table inheritance hierarchy).  Also we do preliminary
    4492             :  * validation of the subcommands.  Because earlier subcommands may change
    4493             :  * the catalog state seen by later commands, there are limits to what can
    4494             :  * be done in this phase.  Generally, this phase acquires table locks,
    4495             :  * checks permissions and relkind, and recurses to find child tables.
    4496             :  *
    4497             :  * ATRewriteCatalogs performs phase 2 for each affected table.
    4498             :  * Certain subcommands need to be performed before others to avoid
    4499             :  * unnecessary conflicts; for example, DROP COLUMN should come before
    4500             :  * ADD COLUMN.  Therefore phase 1 divides the subcommands into multiple
    4501             :  * lists, one for each logical "pass" of phase 2.
    4502             :  *
    4503             :  * ATRewriteTables performs phase 3 for those tables that need it.
    4504             :  *
    4505             :  * For most subcommand types, phases 2 and 3 do no explicit recursion,
    4506             :  * since phase 1 already does it.  However, for certain subcommand types
    4507             :  * it is only possible to determine how to recurse at phase 2 time; for
    4508             :  * those cases, phase 1 sets the cmd->recurse flag.
    4509             :  *
    4510             :  * Thanks to the magic of MVCC, an error anywhere along the way rolls back
    4511             :  * the whole operation; we don't have to do anything special to clean up.
    4512             :  *
    4513             :  * The caller must lock the relation, with an appropriate lock level
    4514             :  * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
    4515             :  * or higher. We pass the lock level down
    4516             :  * so that we can apply it recursively to inherited tables. Note that the
    4517             :  * lock level we want as we recurse might well be higher than required for
    4518             :  * that specific subcommand. So we pass down the overall lock requirement,
    4519             :  * rather than reassess it at lower levels.
    4520             :  *
    4521             :  * The caller also provides a "context" which is to be passed back to
    4522             :  * utility.c when we need to execute a subcommand such as CREATE INDEX.
    4523             :  * Some of the fields therein, such as the relid, are used here as well.
    4524             :  */
    4525             : void
    4526       32084 : AlterTable(AlterTableStmt *stmt, LOCKMODE lockmode,
    4527             :            AlterTableUtilityContext *context)
    4528             : {
    4529             :     Relation    rel;
    4530             : 
    4531             :     /* Caller is required to provide an adequate lock. */
    4532       32084 :     rel = relation_open(context->relid, NoLock);
    4533             : 
    4534       32084 :     CheckAlterTableIsSafe(rel);
    4535             : 
    4536       32066 :     ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
    4537       28364 : }
    4538             : 
    4539             : /*
    4540             :  * AlterTableInternal
    4541             :  *
    4542             :  * ALTER TABLE with target specified by OID
    4543             :  *
    4544             :  * We do not reject if the relation is already open, because it's quite
    4545             :  * likely that one or more layers of caller have it open.  That means it
    4546             :  * is unsafe to use this entry point for alterations that could break
    4547             :  * existing query plans.  On the assumption it's not used for such, we
    4548             :  * don't have to reject pending AFTER triggers, either.
    4549             :  *
    4550             :  * Also, since we don't have an AlterTableUtilityContext, this cannot be
    4551             :  * used for any subcommand types that require parse transformation or
    4552             :  * could generate subcommands that have to be passed to ProcessUtility.
    4553             :  */
    4554             : void
    4555         278 : AlterTableInternal(Oid relid, List *cmds, bool recurse)
    4556             : {
    4557             :     Relation    rel;
    4558         278 :     LOCKMODE    lockmode = AlterTableGetLockLevel(cmds);
    4559             : 
    4560         278 :     rel = relation_open(relid, lockmode);
    4561             : 
    4562         278 :     EventTriggerAlterTableRelid(relid);
    4563             : 
    4564         278 :     ATController(NULL, rel, cmds, recurse, lockmode, NULL);
    4565         278 : }
    4566             : 
    4567             : /*
    4568             :  * AlterTableGetLockLevel
    4569             :  *
    4570             :  * Sets the overall lock level required for the supplied list of subcommands.
    4571             :  * Policy for doing this set according to needs of AlterTable(), see
    4572             :  * comments there for overall explanation.
    4573             :  *
    4574             :  * Function is called before and after parsing, so it must give same
    4575             :  * answer each time it is called. Some subcommands are transformed
    4576             :  * into other subcommand types, so the transform must never be made to a
    4577             :  * lower lock level than previously assigned. All transforms are noted below.
    4578             :  *
    4579             :  * Since this is called before we lock the table we cannot use table metadata
    4580             :  * to influence the type of lock we acquire.
    4581             :  *
    4582             :  * There should be no lockmodes hardcoded into the subcommand functions. All
    4583             :  * lockmode decisions for ALTER TABLE are made here only. The one exception is
    4584             :  * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
    4585             :  * and does not travel through this section of code and cannot be combined with
    4586             :  * any of the subcommands given here.
    4587             :  *
    4588             :  * Note that Hot Standby only knows about AccessExclusiveLocks on the primary
    4589             :  * so any changes that might affect SELECTs running on standbys need to use
    4590             :  * AccessExclusiveLocks even if you think a lesser lock would do, unless you
    4591             :  * have a solution for that also.
    4592             :  *
    4593             :  * Also note that pg_dump uses only an AccessShareLock, meaning that anything
    4594             :  * that takes a lock less than AccessExclusiveLock can change object definitions
    4595             :  * while pg_dump is running. Be careful to check that the appropriate data is
    4596             :  * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
    4597             :  * otherwise we might end up with an inconsistent dump that can't restore.
    4598             :  */
    4599             : LOCKMODE
    4600       32588 : AlterTableGetLockLevel(List *cmds)
    4601             : {
    4602             :     /*
    4603             :      * This only works if we read catalog tables using MVCC snapshots.
    4604             :      */
    4605             :     ListCell   *lcmd;
    4606       32588 :     LOCKMODE    lockmode = ShareUpdateExclusiveLock;
    4607             : 
    4608       66372 :     foreach(lcmd, cmds)
    4609             :     {
    4610       33784 :         AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
    4611       33784 :         LOCKMODE    cmd_lockmode = AccessExclusiveLock; /* default for compiler */
    4612             : 
    4613       33784 :         switch (cmd->subtype)
    4614             :         {
    4615             :                 /*
    4616             :                  * These subcommands rewrite the heap, so require full locks.
    4617             :                  */
    4618        3622 :             case AT_AddColumn:  /* may rewrite heap, in some cases and visible
    4619             :                                  * to SELECT */
    4620             :             case AT_SetAccessMethod:    /* must rewrite heap */
    4621             :             case AT_SetTableSpace:  /* must rewrite heap */
    4622             :             case AT_AlterColumnType:    /* must rewrite heap */
    4623        3622 :                 cmd_lockmode = AccessExclusiveLock;
    4624        3622 :                 break;
    4625             : 
    4626             :                 /*
    4627             :                  * These subcommands may require addition of toast tables. If
    4628             :                  * we add a toast table to a table currently being scanned, we
    4629             :                  * might miss data added to the new toast table by concurrent
    4630             :                  * insert transactions.
    4631             :                  */
    4632         238 :             case AT_SetStorage: /* may add toast tables, see
    4633             :                                  * ATRewriteCatalogs() */
    4634         238 :                 cmd_lockmode = AccessExclusiveLock;
    4635         238 :                 break;
    4636             : 
    4637             :                 /*
    4638             :                  * Removing constraints can affect SELECTs that have been
    4639             :                  * optimized assuming the constraint holds true. See also
    4640             :                  * CloneFkReferenced.
    4641             :                  */
    4642        1130 :             case AT_DropConstraint: /* as DROP INDEX */
    4643             :             case AT_DropNotNull:    /* may change some SQL plans */
    4644        1130 :                 cmd_lockmode = AccessExclusiveLock;
    4645        1130 :                 break;
    4646             : 
    4647             :                 /*
    4648             :                  * Subcommands that may be visible to concurrent SELECTs
    4649             :                  */
    4650        1758 :             case AT_DropColumn: /* change visible to SELECT */
    4651             :             case AT_AddColumnToView:    /* CREATE VIEW */
    4652             :             case AT_DropOids:   /* used to equiv to DropColumn */
    4653             :             case AT_EnableAlwaysRule:   /* may change SELECT rules */
    4654             :             case AT_EnableReplicaRule:  /* may change SELECT rules */
    4655             :             case AT_EnableRule: /* may change SELECT rules */
    4656             :             case AT_DisableRule:    /* may change SELECT rules */
    4657        1758 :                 cmd_lockmode = AccessExclusiveLock;
    4658        1758 :                 break;
    4659             : 
    4660             :                 /*
    4661             :                  * Changing owner may remove implicit SELECT privileges
    4662             :                  */
    4663        2024 :             case AT_ChangeOwner:    /* change visible to SELECT */
    4664        2024 :                 cmd_lockmode = AccessExclusiveLock;
    4665        2024 :                 break;
    4666             : 
    4667             :                 /*
    4668             :                  * Changing foreign table options may affect optimization.
    4669             :                  */
    4670         254 :             case AT_GenericOptions:
    4671             :             case AT_AlterColumnGenericOptions:
    4672         254 :                 cmd_lockmode = AccessExclusiveLock;
    4673         254 :                 break;
    4674             : 
    4675             :                 /*
    4676             :                  * These subcommands affect write operations only.
    4677             :                  */
    4678         342 :             case AT_EnableTrig:
    4679             :             case AT_EnableAlwaysTrig:
    4680             :             case AT_EnableReplicaTrig:
    4681             :             case AT_EnableTrigAll:
    4682             :             case AT_EnableTrigUser:
    4683             :             case AT_DisableTrig:
    4684             :             case AT_DisableTrigAll:
    4685             :             case AT_DisableTrigUser:
    4686         342 :                 cmd_lockmode = ShareRowExclusiveLock;
    4687         342 :                 break;
    4688             : 
    4689             :                 /*
    4690             :                  * These subcommands affect write operations only. XXX
    4691             :                  * Theoretically, these could be ShareRowExclusiveLock.
    4692             :                  */
    4693        2942 :             case AT_ColumnDefault:
    4694             :             case AT_CookedColumnDefault:
    4695             :             case AT_AlterConstraint:
    4696             :             case AT_AddIndex:   /* from ADD CONSTRAINT */
    4697             :             case AT_AddIndexConstraint:
    4698             :             case AT_ReplicaIdentity:
    4699             :             case AT_SetNotNull:
    4700             :             case AT_EnableRowSecurity:
    4701             :             case AT_DisableRowSecurity:
    4702             :             case AT_ForceRowSecurity:
    4703             :             case AT_NoForceRowSecurity:
    4704             :             case AT_AddIdentity:
    4705             :             case AT_DropIdentity:
    4706             :             case AT_SetIdentity:
    4707             :             case AT_SetExpression:
    4708             :             case AT_DropExpression:
    4709             :             case AT_SetCompression:
    4710        2942 :                 cmd_lockmode = AccessExclusiveLock;
    4711        2942 :                 break;
    4712             : 
    4713       15614 :             case AT_AddConstraint:
    4714             :             case AT_ReAddConstraint:    /* becomes AT_AddConstraint */
    4715             :             case AT_ReAddDomainConstraint:  /* becomes AT_AddConstraint */
    4716       15614 :                 if (IsA(cmd->def, Constraint))
    4717             :                 {
    4718       15614 :                     Constraint *con = (Constraint *) cmd->def;
    4719             : 
    4720       15614 :                     switch (con->contype)
    4721             :                     {
    4722       11900 :                         case CONSTR_EXCLUSION:
    4723             :                         case CONSTR_PRIMARY:
    4724             :                         case CONSTR_UNIQUE:
    4725             : 
    4726             :                             /*
    4727             :                              * Cases essentially the same as CREATE INDEX. We
    4728             :                              * could reduce the lock strength to ShareLock if
    4729             :                              * we can work out how to allow concurrent catalog
    4730             :                              * updates. XXX Might be set down to
    4731             :                              * ShareRowExclusiveLock but requires further
    4732             :                              * analysis.
    4733             :                              */
    4734       11900 :                             cmd_lockmode = AccessExclusiveLock;
    4735       11900 :                             break;
    4736        2594 :                         case CONSTR_FOREIGN:
    4737             : 
    4738             :                             /*
    4739             :                              * We add triggers to both tables when we add a
    4740             :                              * Foreign Key, so the lock level must be at least
    4741             :                              * as strong as CREATE TRIGGER.
    4742             :                              */
    4743        2594 :                             cmd_lockmode = ShareRowExclusiveLock;
    4744        2594 :                             break;
    4745             : 
    4746        1120 :                         default:
    4747        1120 :                             cmd_lockmode = AccessExclusiveLock;
    4748             :                     }
    4749             :                 }
    4750       15614 :                 break;
    4751             : 
    4752             :                 /*
    4753             :                  * These subcommands affect inheritance behaviour. Queries
    4754             :                  * started before us will continue to see the old inheritance
    4755             :                  * behaviour, while queries started after we commit will see
    4756             :                  * new behaviour. No need to prevent reads or writes to the
    4757             :                  * subtable while we hook it up though. Changing the TupDesc
    4758             :                  * may be a problem, so keep highest lock.
    4759             :                  */
    4760         558 :             case AT_AddInherit:
    4761             :             case AT_DropInherit:
    4762         558 :                 cmd_lockmode = AccessExclusiveLock;
    4763         558 :                 break;
    4764             : 
    4765             :                 /*
    4766             :                  * These subcommands affect implicit row type conversion. They
    4767             :                  * have affects similar to CREATE/DROP CAST on queries. don't
    4768             :                  * provide for invalidating parse trees as a result of such
    4769             :                  * changes, so we keep these at AccessExclusiveLock.
    4770             :                  */
    4771          72 :             case AT_AddOf:
    4772             :             case AT_DropOf:
    4773          72 :                 cmd_lockmode = AccessExclusiveLock;
    4774          72 :                 break;
    4775             : 
    4776             :                 /*
    4777             :                  * Only used by CREATE OR REPLACE VIEW which must conflict
    4778             :                  * with an SELECTs currently using the view.
    4779             :                  */
    4780         194 :             case AT_ReplaceRelOptions:
    4781         194 :                 cmd_lockmode = AccessExclusiveLock;
    4782         194 :                 break;
    4783             : 
    4784             :                 /*
    4785             :                  * These subcommands affect general strategies for performance
    4786             :                  * and maintenance, though don't change the semantic results
    4787             :                  * from normal data reads and writes. Delaying an ALTER TABLE
    4788             :                  * behind currently active writes only delays the point where
    4789             :                  * the new strategy begins to take effect, so there is no
    4790             :                  * benefit in waiting. In this case the minimum restriction
    4791             :                  * applies: we don't currently allow concurrent catalog
    4792             :                  * updates.
    4793             :                  */
    4794         234 :             case AT_SetStatistics:  /* Uses MVCC in getTableAttrs() */
    4795             :             case AT_ClusterOn:  /* Uses MVCC in getIndexes() */
    4796             :             case AT_DropCluster:    /* Uses MVCC in getIndexes() */
    4797             :             case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
    4798             :             case AT_ResetOptions:   /* Uses MVCC in getTableAttrs() */
    4799         234 :                 cmd_lockmode = ShareUpdateExclusiveLock;
    4800         234 :                 break;
    4801             : 
    4802         112 :             case AT_SetLogged:
    4803             :             case AT_SetUnLogged:
    4804         112 :                 cmd_lockmode = AccessExclusiveLock;
    4805         112 :                 break;
    4806             : 
    4807         476 :             case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
    4808         476 :                 cmd_lockmode = ShareUpdateExclusiveLock;
    4809         476 :                 break;
    4810             : 
    4811             :                 /*
    4812             :                  * Rel options are more complex than first appears. Options
    4813             :                  * are set here for tables, views and indexes; for historical
    4814             :                  * reasons these can all be used with ALTER TABLE, so we can't
    4815             :                  * decide between them using the basic grammar.
    4816             :                  */
    4817         770 :             case AT_SetRelOptions:  /* Uses MVCC in getIndexes() and
    4818             :                                      * getTables() */
    4819             :             case AT_ResetRelOptions:    /* Uses MVCC in getIndexes() and
    4820             :                                          * getTables() */
    4821         770 :                 cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
    4822         770 :                 break;
    4823             : 
    4824        2828 :             case AT_AttachPartition:
    4825        2828 :                 cmd_lockmode = ShareUpdateExclusiveLock;
    4826        2828 :                 break;
    4827             : 
    4828         596 :             case AT_DetachPartition:
    4829         596 :                 if (((PartitionCmd *) cmd->def)->concurrent)
    4830         164 :                     cmd_lockmode = ShareUpdateExclusiveLock;
    4831             :                 else
    4832         432 :                     cmd_lockmode = AccessExclusiveLock;
    4833         596 :                 break;
    4834             : 
    4835          20 :             case AT_DetachPartitionFinalize:
    4836          20 :                 cmd_lockmode = ShareUpdateExclusiveLock;
    4837          20 :                 break;
    4838             : 
    4839           0 :             default:            /* oops */
    4840           0 :                 elog(ERROR, "unrecognized alter table type: %d",
    4841             :                      (int) cmd->subtype);
    4842             :                 break;
    4843             :         }
    4844             : 
    4845             :         /*
    4846             :          * Take the greatest lockmode from any subcommand
    4847             :          */
    4848       33784 :         if (cmd_lockmode > lockmode)
    4849       28284 :             lockmode = cmd_lockmode;
    4850             :     }
    4851             : 
    4852       32588 :     return lockmode;
    4853             : }
    4854             : 
    4855             : /*
    4856             :  * ATController provides top level control over the phases.
    4857             :  *
    4858             :  * parsetree is passed in to allow it to be passed to event triggers
    4859             :  * when requested.
    4860             :  */
    4861             : static void
    4862       32344 : ATController(AlterTableStmt *parsetree,
    4863             :              Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
    4864             :              AlterTableUtilityContext *context)
    4865             : {
    4866       32344 :     List       *wqueue = NIL;
    4867             :     ListCell   *lcmd;
    4868             : 
    4869             :     /* Phase 1: preliminary examination of commands, create work queue */
    4870       65472 :     foreach(lcmd, cmds)
    4871             :     {
    4872       33534 :         AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
    4873             : 
    4874       33534 :         ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
    4875             :     }
    4876             : 
    4877             :     /* Close the relation, but keep lock until commit */
    4878       31938 :     relation_close(rel, NoLock);
    4879             : 
    4880             :     /* Phase 2: update system catalogs */
    4881       31938 :     ATRewriteCatalogs(&wqueue, lockmode, context);
    4882             : 
    4883             :     /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
    4884       29116 :     ATRewriteTables(parsetree, &wqueue, lockmode, context);
    4885       28642 : }
    4886             : 
    4887             : /*
    4888             :  * ATPrepCmd
    4889             :  *
    4890             :  * Traffic cop for ALTER TABLE Phase 1 operations, including simple
    4891             :  * recursion and permission checks.
    4892             :  *
    4893             :  * Caller must have acquired appropriate lock type on relation already.
    4894             :  * This lock should be held until commit.
    4895             :  */
    4896             : static void
    4897       34474 : ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
    4898             :           bool recurse, bool recursing, LOCKMODE lockmode,
    4899             :           AlterTableUtilityContext *context)
    4900             : {
    4901             :     AlteredTableInfo *tab;
    4902       34474 :     AlterTablePass pass = AT_PASS_UNSET;
    4903             : 
    4904             :     /* Find or create work queue entry for this table */
    4905       34474 :     tab = ATGetQueueEntry(wqueue, rel);
    4906             : 
    4907             :     /*
    4908             :      * Disallow any ALTER TABLE other than ALTER TABLE DETACH FINALIZE on
    4909             :      * partitions that are pending detach.
    4910             :      */
    4911       34474 :     if (rel->rd_rel->relispartition &&
    4912        2692 :         cmd->subtype != AT_DetachPartitionFinalize &&
    4913        1346 :         PartitionHasPendingDetach(RelationGetRelid(rel)))
    4914           2 :         ereport(ERROR,
    4915             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    4916             :                 errmsg("cannot alter partition \"%s\" with an incomplete detach",
    4917             :                        RelationGetRelationName(rel)),
    4918             :                 errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
    4919             : 
    4920             :     /*
    4921             :      * Copy the original subcommand for each table, so we can scribble on it.
    4922             :      * This avoids conflicts when different child tables need to make
    4923             :      * different parse transformations (for example, the same column may have
    4924             :      * different column numbers in different children).
    4925             :      */
    4926       34472 :     cmd = copyObject(cmd);
    4927             : 
    4928             :     /*
    4929             :      * Do permissions and relkind checking, recursion to child tables if
    4930             :      * needed, and any additional phase-1 processing needed.  (But beware of
    4931             :      * adding any processing that looks at table details that another
    4932             :      * subcommand could change.  In some cases we reject multiple subcommands
    4933             :      * that could try to change the same state in contrary ways.)
    4934             :      */
    4935       34472 :     switch (cmd->subtype)
    4936             :     {
    4937        2190 :         case AT_AddColumn:      /* ADD COLUMN */
    4938        2190 :             ATSimplePermissions(cmd->subtype, rel,
    4939             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    4940             :                                 ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
    4941        2190 :             ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
    4942             :                             lockmode, context);
    4943             :             /* Recursion occurs during execution phase */
    4944        2178 :             pass = AT_PASS_ADD_COL;
    4945        2178 :             break;
    4946          24 :         case AT_AddColumnToView:    /* add column via CREATE OR REPLACE VIEW */
    4947          24 :             ATSimplePermissions(cmd->subtype, rel, ATT_VIEW);
    4948          24 :             ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
    4949             :                             lockmode, context);
    4950             :             /* Recursion occurs during execution phase */
    4951          24 :             pass = AT_PASS_ADD_COL;
    4952          24 :             break;
    4953         620 :         case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
    4954             : 
    4955             :             /*
    4956             :              * We allow defaults on views so that INSERT into a view can have
    4957             :              * default-ish behavior.  This works because the rewriter
    4958             :              * substitutes default values into INSERTs before it expands
    4959             :              * rules.
    4960             :              */
    4961         620 :             ATSimplePermissions(cmd->subtype, rel,
    4962             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    4963             :                                 ATT_FOREIGN_TABLE);
    4964         620 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    4965             :             /* No command-specific prep needed */
    4966         620 :             pass = cmd->def ? AT_PASS_ADD_OTHERCONSTR : AT_PASS_DROP;
    4967         620 :             break;
    4968          80 :         case AT_CookedColumnDefault:    /* add a pre-cooked default */
    4969             :             /* This is currently used only in CREATE TABLE */
    4970             :             /* (so the permission check really isn't necessary) */
    4971          80 :             ATSimplePermissions(cmd->subtype, rel,
    4972             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    4973             :             /* This command never recurses */
    4974          80 :             pass = AT_PASS_ADD_OTHERCONSTR;
    4975          80 :             break;
    4976         166 :         case AT_AddIdentity:
    4977         166 :             ATSimplePermissions(cmd->subtype, rel,
    4978             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    4979             :                                 ATT_FOREIGN_TABLE);
    4980             :             /* Set up recursion for phase 2; no other prep needed */
    4981         166 :             if (recurse)
    4982         160 :                 cmd->recurse = true;
    4983         166 :             pass = AT_PASS_ADD_OTHERCONSTR;
    4984         166 :             break;
    4985          62 :         case AT_SetIdentity:
    4986          62 :             ATSimplePermissions(cmd->subtype, rel,
    4987             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    4988             :                                 ATT_FOREIGN_TABLE);
    4989             :             /* Set up recursion for phase 2; no other prep needed */
    4990          62 :             if (recurse)
    4991          56 :                 cmd->recurse = true;
    4992             :             /* This should run after AddIdentity, so do it in MISC pass */
    4993          62 :             pass = AT_PASS_MISC;
    4994          62 :             break;
    4995          56 :         case AT_DropIdentity:
    4996          56 :             ATSimplePermissions(cmd->subtype, rel,
    4997             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    4998             :                                 ATT_FOREIGN_TABLE);
    4999             :             /* Set up recursion for phase 2; no other prep needed */
    5000          56 :             if (recurse)
    5001          50 :                 cmd->recurse = true;
    5002          56 :             pass = AT_PASS_DROP;
    5003          56 :             break;
    5004         274 :         case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
    5005         274 :             ATSimplePermissions(cmd->subtype, rel,
    5006             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5007             :             /* Set up recursion for phase 2; no other prep needed */
    5008         268 :             if (recurse)
    5009         250 :                 cmd->recurse = true;
    5010         268 :             pass = AT_PASS_DROP;
    5011         268 :             break;
    5012         420 :         case AT_SetNotNull:     /* ALTER COLUMN SET NOT NULL */
    5013         420 :             ATSimplePermissions(cmd->subtype, rel,
    5014             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5015             :             /* Set up recursion for phase 2; no other prep needed */
    5016         414 :             if (recurse)
    5017         384 :                 cmd->recurse = true;
    5018         414 :             pass = AT_PASS_COL_ATTRS;
    5019         414 :             break;
    5020         216 :         case AT_SetExpression:  /* ALTER COLUMN SET EXPRESSION */
    5021         216 :             ATSimplePermissions(cmd->subtype, rel,
    5022             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5023         216 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    5024         216 :             pass = AT_PASS_SET_EXPRESSION;
    5025         216 :             break;
    5026          86 :         case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */
    5027          86 :             ATSimplePermissions(cmd->subtype, rel,
    5028             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5029          86 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    5030          86 :             ATPrepDropExpression(rel, cmd, recurse, recursing, lockmode);
    5031          62 :             pass = AT_PASS_DROP;
    5032          62 :             break;
    5033         164 :         case AT_SetStatistics:  /* ALTER COLUMN SET STATISTICS */
    5034         164 :             ATSimplePermissions(cmd->subtype, rel,
    5035             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW |
    5036             :                                 ATT_INDEX | ATT_PARTITIONED_INDEX | ATT_FOREIGN_TABLE);
    5037         164 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    5038             :             /* No command-specific prep needed */
    5039         164 :             pass = AT_PASS_MISC;
    5040         164 :             break;
    5041          44 :         case AT_SetOptions:     /* ALTER COLUMN SET ( options ) */
    5042             :         case AT_ResetOptions:   /* ALTER COLUMN RESET ( options ) */
    5043          44 :             ATSimplePermissions(cmd->subtype, rel,
    5044             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    5045             :                                 ATT_MATVIEW | ATT_FOREIGN_TABLE);
    5046             :             /* This command never recurses */
    5047          32 :             pass = AT_PASS_MISC;
    5048          32 :             break;
    5049         260 :         case AT_SetStorage:     /* ALTER COLUMN SET STORAGE */
    5050         260 :             ATSimplePermissions(cmd->subtype, rel,
    5051             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    5052             :                                 ATT_MATVIEW | ATT_FOREIGN_TABLE);
    5053         260 :             ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
    5054             :             /* No command-specific prep needed */
    5055         260 :             pass = AT_PASS_MISC;
    5056         260 :             break;
    5057          78 :         case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
    5058          78 :             ATSimplePermissions(cmd->subtype, rel,
    5059             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
    5060             :             /* This command never recurses */
    5061             :             /* No command-specific prep needed */
    5062          78 :             pass = AT_PASS_MISC;
    5063          78 :             break;
    5064        1664 :         case AT_DropColumn:     /* DROP COLUMN */
    5065        1664 :             ATSimplePermissions(cmd->subtype, rel,
    5066             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    5067             :                                 ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
    5068        1658 :             ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd,
    5069             :                              lockmode, context);
    5070             :             /* Recursion occurs during execution phase */
    5071        1646 :             pass = AT_PASS_DROP;
    5072        1646 :             break;
    5073           0 :         case AT_AddIndex:       /* ADD INDEX */
    5074           0 :             ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
    5075             :             /* This command never recurses */
    5076             :             /* No command-specific prep needed */
    5077           0 :             pass = AT_PASS_ADD_INDEX;
    5078           0 :             break;
    5079       16078 :         case AT_AddConstraint:  /* ADD CONSTRAINT */
    5080       16078 :             ATSimplePermissions(cmd->subtype, rel,
    5081             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5082       16078 :             ATPrepAddPrimaryKey(wqueue, rel, cmd, recurse, lockmode, context);
    5083       16048 :             if (recurse)
    5084             :             {
    5085             :                 /* recurses at exec time; lock descendants and set flag */
    5086       15680 :                 (void) find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
    5087       15680 :                 cmd->recurse = true;
    5088             :             }
    5089       16048 :             pass = AT_PASS_ADD_CONSTR;
    5090       16048 :             break;
    5091           0 :         case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
    5092           0 :             ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
    5093             :             /* This command never recurses */
    5094             :             /* No command-specific prep needed */
    5095           0 :             pass = AT_PASS_ADD_INDEXCONSTR;
    5096           0 :             break;
    5097         818 :         case AT_DropConstraint: /* DROP CONSTRAINT */
    5098         818 :             ATSimplePermissions(cmd->subtype, rel,
    5099             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5100         818 :             ATCheckPartitionsNotInUse(rel, lockmode);
    5101             :             /* Other recursion occurs during execution phase */
    5102             :             /* No command-specific prep needed except saving recurse flag */
    5103         812 :             if (recurse)
    5104         776 :                 cmd->recurse = true;
    5105         812 :             pass = AT_PASS_DROP;
    5106         812 :             break;
    5107        1318 :         case AT_AlterColumnType:    /* ALTER COLUMN TYPE */
    5108        1318 :             ATSimplePermissions(cmd->subtype, rel,
    5109             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE |
    5110             :                                 ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
    5111             :             /* See comments for ATPrepAlterColumnType */
    5112        1318 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
    5113             :                                       AT_PASS_UNSET, context);
    5114             :             Assert(cmd != NULL);
    5115             :             /* Performs own recursion */
    5116        1312 :             ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
    5117             :                                   lockmode, context);
    5118        1114 :             pass = AT_PASS_ALTER_TYPE;
    5119        1114 :             break;
    5120         172 :         case AT_AlterColumnGenericOptions:
    5121         172 :             ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
    5122             :             /* This command never recurses */
    5123             :             /* No command-specific prep needed */
    5124         172 :             pass = AT_PASS_MISC;
    5125         172 :             break;
    5126        2000 :         case AT_ChangeOwner:    /* ALTER OWNER */
    5127             :             /* This command never recurses */
    5128             :             /* No command-specific prep needed */
    5129        2000 :             pass = AT_PASS_MISC;
    5130        2000 :             break;
    5131          64 :         case AT_ClusterOn:      /* CLUSTER ON */
    5132             :         case AT_DropCluster:    /* SET WITHOUT CLUSTER */
    5133          64 :             ATSimplePermissions(cmd->subtype, rel,
    5134             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
    5135             :             /* These commands never recurse */
    5136             :             /* No command-specific prep needed */
    5137          64 :             pass = AT_PASS_MISC;
    5138          64 :             break;
    5139         112 :         case AT_SetLogged:      /* SET LOGGED */
    5140             :         case AT_SetUnLogged:    /* SET UNLOGGED */
    5141         112 :             ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_SEQUENCE);
    5142         100 :             if (tab->chgPersistence)
    5143           0 :                 ereport(ERROR,
    5144             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5145             :                          errmsg("cannot change persistence setting twice")));
    5146         100 :             ATPrepChangePersistence(tab, rel, cmd->subtype == AT_SetLogged);
    5147          88 :             pass = AT_PASS_MISC;
    5148          88 :             break;
    5149           6 :         case AT_DropOids:       /* SET WITHOUT OIDS */
    5150           6 :             ATSimplePermissions(cmd->subtype, rel,
    5151             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5152           6 :             pass = AT_PASS_DROP;
    5153           6 :             break;
    5154         128 :         case AT_SetAccessMethod:    /* SET ACCESS METHOD */
    5155         128 :             ATSimplePermissions(cmd->subtype, rel,
    5156             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
    5157             : 
    5158             :             /* check if another access method change was already requested */
    5159         128 :             if (tab->chgAccessMethod)
    5160          18 :                 ereport(ERROR,
    5161             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5162             :                          errmsg("cannot have multiple SET ACCESS METHOD subcommands")));
    5163             : 
    5164         110 :             ATPrepSetAccessMethod(tab, rel, cmd->name);
    5165         110 :             pass = AT_PASS_MISC;    /* does not matter; no work in Phase 2 */
    5166         110 :             break;
    5167         158 :         case AT_SetTableSpace:  /* SET TABLESPACE */
    5168         158 :             ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE |
    5169             :                                 ATT_MATVIEW | ATT_INDEX | ATT_PARTITIONED_INDEX);
    5170             :             /* This command never recurses */
    5171         158 :             ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
    5172         158 :             pass = AT_PASS_MISC;    /* doesn't actually matter */
    5173         158 :             break;
    5174         962 :         case AT_SetRelOptions:  /* SET (...) */
    5175             :         case AT_ResetRelOptions:    /* RESET (...) */
    5176             :         case AT_ReplaceRelOptions:  /* reset them all, then set just these */
    5177         962 :             ATSimplePermissions(cmd->subtype, rel,
    5178             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
    5179             :                                 ATT_MATVIEW | ATT_INDEX);
    5180             :             /* This command never recurses */
    5181             :             /* No command-specific prep needed */
    5182         960 :             pass = AT_PASS_MISC;
    5183         960 :             break;
    5184         464 :         case AT_AddInherit:     /* INHERIT */
    5185         464 :             ATSimplePermissions(cmd->subtype, rel,
    5186             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5187             :             /* This command never recurses */
    5188         464 :             ATPrepAddInherit(rel);
    5189         446 :             pass = AT_PASS_MISC;
    5190         446 :             break;
    5191          94 :         case AT_DropInherit:    /* NO INHERIT */
    5192          94 :             ATSimplePermissions(cmd->subtype, rel,
    5193             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5194             :             /* This command never recurses */
    5195             :             /* No command-specific prep needed */
    5196          94 :             pass = AT_PASS_MISC;
    5197          94 :             break;
    5198         294 :         case AT_AlterConstraint:    /* ALTER CONSTRAINT */
    5199         294 :             ATSimplePermissions(cmd->subtype, rel,
    5200             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE);
    5201             :             /* Recursion occurs during execution phase */
    5202         288 :             if (recurse)
    5203         288 :                 cmd->recurse = true;
    5204         288 :             pass = AT_PASS_MISC;
    5205         288 :             break;
    5206         476 :         case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
    5207         476 :             ATSimplePermissions(cmd->subtype, rel,
    5208             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5209             :             /* Recursion occurs during execution phase */
    5210             :             /* No command-specific prep needed except saving recurse flag */
    5211         476 :             if (recurse)
    5212         476 :                 cmd->recurse = true;
    5213         476 :             pass = AT_PASS_MISC;
    5214         476 :             break;
    5215         494 :         case AT_ReplicaIdentity:    /* REPLICA IDENTITY ... */
    5216         494 :             ATSimplePermissions(cmd->subtype, rel,
    5217             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
    5218         494 :             pass = AT_PASS_MISC;
    5219             :             /* This command never recurses */
    5220             :             /* No command-specific prep needed */
    5221         494 :             break;
    5222         342 :         case AT_EnableTrig:     /* ENABLE TRIGGER variants */
    5223             :         case AT_EnableAlwaysTrig:
    5224             :         case AT_EnableReplicaTrig:
    5225             :         case AT_EnableTrigAll:
    5226             :         case AT_EnableTrigUser:
    5227             :         case AT_DisableTrig:    /* DISABLE TRIGGER variants */
    5228             :         case AT_DisableTrigAll:
    5229             :         case AT_DisableTrigUser:
    5230         342 :             ATSimplePermissions(cmd->subtype, rel,
    5231             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    5232             :             /* Set up recursion for phase 2; no other prep needed */
    5233         342 :             if (recurse)
    5234         314 :                 cmd->recurse = true;
    5235         342 :             pass = AT_PASS_MISC;
    5236         342 :             break;
    5237         598 :         case AT_EnableRule:     /* ENABLE/DISABLE RULE variants */
    5238             :         case AT_EnableAlwaysRule:
    5239             :         case AT_EnableReplicaRule:
    5240             :         case AT_DisableRule:
    5241             :         case AT_AddOf:          /* OF */
    5242             :         case AT_DropOf:         /* NOT OF */
    5243             :         case AT_EnableRowSecurity:
    5244             :         case AT_DisableRowSecurity:
    5245             :         case AT_ForceRowSecurity:
    5246             :         case AT_NoForceRowSecurity:
    5247         598 :             ATSimplePermissions(cmd->subtype, rel,
    5248             :                                 ATT_TABLE | ATT_PARTITIONED_TABLE);
    5249             :             /* These commands never recurse */
    5250             :             /* No command-specific prep needed */
    5251         598 :             pass = AT_PASS_MISC;
    5252         598 :             break;
    5253          58 :         case AT_GenericOptions:
    5254          58 :             ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
    5255             :             /* No command-specific prep needed */
    5256          58 :             pass = AT_PASS_MISC;
    5257          58 :             break;
    5258        2816 :         case AT_AttachPartition:
    5259        2816 :             ATSimplePermissions(cmd->subtype, rel,
    5260             :                                 ATT_PARTITIONED_TABLE | ATT_PARTITIONED_INDEX);
    5261             :             /* No command-specific prep needed */
    5262        2810 :             pass = AT_PASS_MISC;
    5263        2810 :             break;
    5264         596 :         case AT_DetachPartition:
    5265         596 :             ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
    5266             :             /* No command-specific prep needed */
    5267         578 :             pass = AT_PASS_MISC;
    5268         578 :             break;
    5269          20 :         case AT_DetachPartitionFinalize:
    5270          20 :             ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
    5271             :             /* No command-specific prep needed */
    5272          14 :             pass = AT_PASS_MISC;
    5273          14 :             break;
    5274           0 :         default:                /* oops */
    5275           0 :             elog(ERROR, "unrecognized alter table type: %d",
    5276             :                  (int) cmd->subtype);
    5277             :             pass = AT_PASS_UNSET;   /* keep compiler quiet */
    5278             :             break;
    5279             :     }
    5280             :     Assert(pass > AT_PASS_UNSET);
    5281             : 
    5282             :     /* Add the subcommand to the appropriate list for phase 2 */
    5283       34056 :     tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
    5284       34056 : }
    5285             : 
    5286             : /*
    5287             :  * ATRewriteCatalogs
    5288             :  *
    5289             :  * Traffic cop for ALTER TABLE Phase 2 operations.  Subcommands are
    5290             :  * dispatched in a "safe" execution order (designed to avoid unnecessary
    5291             :  * conflicts).
    5292             :  */
    5293             : static void
    5294       31938 : ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
    5295             :                   AlterTableUtilityContext *context)
    5296             : {
    5297             :     ListCell   *ltab;
    5298             : 
    5299             :     /*
    5300             :      * We process all the tables "in parallel", one pass at a time.  This is
    5301             :      * needed because we may have to propagate work from one table to another
    5302             :      * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
    5303             :      * re-adding of the foreign key constraint to the other table).  Work can
    5304             :      * only be propagated into later passes, however.
    5305             :      */
    5306      402598 :     for (AlterTablePass pass = 0; pass < AT_NUM_PASSES; pass++)
    5307             :     {
    5308             :         /* Go through each table that needs to be processed */
    5309      760124 :         foreach(ltab, *wqueue)
    5310             :         {
    5311      389464 :             AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    5312      389464 :             List       *subcmds = tab->subcmds[pass];
    5313             :             ListCell   *lcmd;
    5314             : 
    5315      389464 :             if (subcmds == NIL)
    5316      333940 :                 continue;
    5317             : 
    5318             :             /*
    5319             :              * Open the relation and store it in tab.  This allows subroutines
    5320             :              * close and reopen, if necessary.  Appropriate lock was obtained
    5321             :              * by phase 1, needn't get it again.
    5322             :              */
    5323       55524 :             tab->rel = relation_open(tab->relid, NoLock);
    5324             : 
    5325      111932 :             foreach(lcmd, subcmds)
    5326       59230 :                 ATExecCmd(wqueue, tab,
    5327       59230 :                           lfirst_node(AlterTableCmd, lcmd),
    5328             :                           lockmode, pass, context);
    5329             : 
    5330             :             /*
    5331             :              * After the ALTER TYPE or SET EXPRESSION pass, do cleanup work
    5332             :              * (this is not done in ATExecAlterColumnType since it should be
    5333             :              * done only once if multiple columns of a table are altered).
    5334             :              */
    5335       52702 :             if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
    5336        1180 :                 ATPostAlterTypeCleanup(wqueue, tab, lockmode);
    5337             : 
    5338       52702 :             if (tab->rel)
    5339             :             {
    5340       52702 :                 relation_close(tab->rel, NoLock);
    5341       52702 :                 tab->rel = NULL;
    5342             :             }
    5343             :         }
    5344             :     }
    5345             : 
    5346             :     /* Check to see if a toast table must be added. */
    5347       62376 :     foreach(ltab, *wqueue)
    5348             :     {
    5349       33260 :         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    5350             : 
    5351             :         /*
    5352             :          * If the table is source table of ATTACH PARTITION command, we did
    5353             :          * not modify anything about it that will change its toasting
    5354             :          * requirement, so no need to check.
    5355             :          */
    5356       33260 :         if (((tab->relkind == RELKIND_RELATION ||
    5357        6124 :               tab->relkind == RELKIND_PARTITIONED_TABLE) &&
    5358       31358 :              tab->partition_constraint == NULL) ||
    5359        3972 :             tab->relkind == RELKIND_MATVIEW)
    5360       29338 :             AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
    5361             :     }
    5362       29116 : }
    5363             : 
    5364             : /*
    5365             :  * ATExecCmd: dispatch a subcommand to appropriate execution routine
    5366             :  */
    5367             : static void
    5368       59230 : ATExecCmd(List **wqueue, AlteredTableInfo *tab,
    5369             :           AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
    5370             :           AlterTableUtilityContext *context)
    5371             : {
    5372       59230 :     ObjectAddress address = InvalidObjectAddress;
    5373       59230 :     Relation    rel = tab->rel;
    5374             : 
    5375       59230 :     switch (cmd->subtype)
    5376             :     {
    5377        2196 :         case AT_AddColumn:      /* ADD COLUMN */
    5378             :         case AT_AddColumnToView:    /* add column via CREATE OR REPLACE VIEW */
    5379        2196 :             address = ATExecAddColumn(wqueue, tab, rel, &cmd,
    5380        2196 :                                       cmd->recurse, false,
    5381             :                                       lockmode, cur_pass, context);
    5382        2058 :             break;
    5383         584 :         case AT_ColumnDefault:  /* ALTER COLUMN DEFAULT */
    5384         584 :             address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
    5385         518 :             break;
    5386          80 :         case AT_CookedColumnDefault:    /* add a pre-cooked default */
    5387          80 :             address = ATExecCookedColumnDefault(rel, cmd->num, cmd->def);
    5388          80 :             break;
    5389         166 :         case AT_AddIdentity:
    5390         166 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5391             :                                       cur_pass, context);
    5392             :             Assert(cmd != NULL);
    5393         154 :             address = ATExecAddIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
    5394         106 :             break;
    5395          62 :         case AT_SetIdentity:
    5396          62 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5397             :                                       cur_pass, context);
    5398             :             Assert(cmd != NULL);
    5399          62 :             address = ATExecSetIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
    5400          38 :             break;
    5401          56 :         case AT_DropIdentity:
    5402          56 :             address = ATExecDropIdentity(rel, cmd->name, cmd->missing_ok, lockmode, cmd->recurse, false);
    5403          38 :             break;
    5404         268 :         case AT_DropNotNull:    /* ALTER COLUMN DROP NOT NULL */
    5405         268 :             address = ATExecDropNotNull(rel, cmd->name, cmd->recurse, lockmode);
    5406         166 :             break;
    5407         414 :         case AT_SetNotNull:     /* ALTER COLUMN SET NOT NULL */
    5408         414 :             address = ATExecSetNotNull(wqueue, rel, NULL, cmd->name,
    5409         414 :                                        cmd->recurse, false, lockmode);
    5410         384 :             break;
    5411         216 :         case AT_SetExpression:
    5412         216 :             address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode);
    5413         186 :             break;
    5414          56 :         case AT_DropExpression:
    5415          56 :             address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode);
    5416          32 :             break;
    5417         164 :         case AT_SetStatistics:  /* ALTER COLUMN SET STATISTICS */
    5418         164 :             address = ATExecSetStatistics(rel, cmd->name, cmd->num, cmd->def, lockmode);
    5419         116 :             break;
    5420          26 :         case AT_SetOptions:     /* ALTER COLUMN SET ( options ) */
    5421          26 :             address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
    5422          26 :             break;
    5423           6 :         case AT_ResetOptions:   /* ALTER COLUMN RESET ( options ) */
    5424           6 :             address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
    5425           6 :             break;
    5426         260 :         case AT_SetStorage:     /* ALTER COLUMN SET STORAGE */
    5427         260 :             address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
    5428         248 :             break;
    5429          78 :         case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
    5430          78 :             address = ATExecSetCompression(rel, cmd->name, cmd->def,
    5431             :                                            lockmode);
    5432          72 :             break;
    5433        1646 :         case AT_DropColumn:     /* DROP COLUMN */
    5434        1646 :             address = ATExecDropColumn(wqueue, rel, cmd->name,
    5435        1646 :                                        cmd->behavior, cmd->recurse, false,
    5436        1646 :                                        cmd->missing_ok, lockmode,
    5437             :                                        NULL);
    5438        1466 :             break;
    5439        1178 :         case AT_AddIndex:       /* ADD INDEX */
    5440        1178 :             address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
    5441             :                                      lockmode);
    5442        1008 :             break;
    5443         456 :         case AT_ReAddIndex:     /* ADD INDEX */
    5444         456 :             address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
    5445             :                                      lockmode);
    5446         456 :             break;
    5447          26 :         case AT_ReAddStatistics:    /* ADD STATISTICS */
    5448          26 :             address = ATExecAddStatistics(tab, rel, (CreateStatsStmt *) cmd->def,
    5449             :                                           true, lockmode);
    5450          26 :             break;
    5451       28558 :         case AT_AddConstraint:  /* ADD CONSTRAINT */
    5452             :             /* Transform the command only during initial examination */
    5453       28558 :             if (cur_pass == AT_PASS_ADD_CONSTR)
    5454       16018 :                 cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
    5455       16048 :                                           cmd->recurse, lockmode,
    5456             :                                           cur_pass, context);
    5457             :             /* Depending on constraint type, might be no more work to do now */
    5458       28528 :             if (cmd != NULL)
    5459             :                 address =
    5460       12510 :                     ATExecAddConstraint(wqueue, tab, rel,
    5461       12510 :                                         (Constraint *) cmd->def,
    5462       12510 :                                         cmd->recurse, false, lockmode);
    5463       27848 :             break;
    5464         338 :         case AT_ReAddConstraint:    /* Re-add pre-existing check constraint */
    5465             :             address =
    5466         338 :                 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
    5467             :                                     true, true, lockmode);
    5468         326 :             break;
    5469          14 :         case AT_ReAddDomainConstraint:  /* Re-add pre-existing domain check
    5470             :                                          * constraint */
    5471             :             address =
    5472          14 :                 AlterDomainAddConstraint(((AlterDomainStmt *) cmd->def)->typeName,
    5473          14 :                                          ((AlterDomainStmt *) cmd->def)->def,
    5474             :                                          NULL);
    5475           8 :             break;
    5476          78 :         case AT_ReAddComment:   /* Re-add existing comment */
    5477          78 :             address = CommentObject((CommentStmt *) cmd->def);
    5478          78 :             break;
    5479       10640 :         case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
    5480       10640 :             address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
    5481             :                                                lockmode);
    5482       10628 :             break;
    5483         288 :         case AT_AlterConstraint:    /* ALTER CONSTRAINT */
    5484         288 :             address = ATExecAlterConstraint(wqueue, rel,
    5485         288 :                                             castNode(ATAlterConstraint, cmd->def),
    5486         288 :                                             cmd->recurse, lockmode);
    5487         222 :             break;
    5488         476 :         case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
    5489         476 :             address = ATExecValidateConstraint(wqueue, rel, cmd->name, cmd->recurse,
    5490             :                                                false, lockmode);
    5491         470 :             break;
    5492         812 :         case AT_DropConstraint: /* DROP CONSTRAINT */
    5493         812 :             ATExecDropConstraint(rel, cmd->name, cmd->behavior,
    5494         812 :                                  cmd->recurse,
    5495         812 :                                  cmd->missing_ok, lockmode);
    5496         602 :             break;
    5497        1078 :         case AT_AlterColumnType:    /* ALTER COLUMN TYPE */
    5498             :             /* parse transformation was done earlier */
    5499        1078 :             address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
    5500        1036 :             break;
    5501         172 :         case AT_AlterColumnGenericOptions:  /* ALTER COLUMN OPTIONS */
    5502             :             address =
    5503         172 :                 ATExecAlterColumnGenericOptions(rel, cmd->name,
    5504         172 :                                                 (List *) cmd->def, lockmode);
    5505         166 :             break;
    5506        2000 :         case AT_ChangeOwner:    /* ALTER OWNER */
    5507        1994 :             ATExecChangeOwner(RelationGetRelid(rel),
    5508        2000 :                               get_rolespec_oid(cmd->newowner, false),
    5509             :                               false, lockmode);
    5510        1982 :             break;
    5511          64 :         case AT_ClusterOn:      /* CLUSTER ON */
    5512          64 :             address = ATExecClusterOn(rel, cmd->name, lockmode);
    5513          58 :             break;
    5514          18 :         case AT_DropCluster:    /* SET WITHOUT CLUSTER */
    5515          18 :             ATExecDropCluster(rel, lockmode);
    5516          12 :             break;
    5517          88 :         case AT_SetLogged:      /* SET LOGGED */
    5518             :         case AT_SetUnLogged:    /* SET UNLOGGED */
    5519          88 :             break;
    5520           6 :         case AT_DropOids:       /* SET WITHOUT OIDS */
    5521             :             /* nothing to do here, oid columns don't exist anymore */
    5522           6 :             break;
    5523          92 :         case AT_SetAccessMethod:    /* SET ACCESS METHOD */
    5524             : 
    5525             :             /*
    5526             :              * Only do this for partitioned tables, for which this is just a
    5527             :              * catalog change.  Tables with storage are handled by Phase 3.
    5528             :              */
    5529          92 :             if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
    5530          50 :                 tab->chgAccessMethod)
    5531          44 :                 ATExecSetAccessMethodNoStorage(rel, tab->newAccessMethod);
    5532          92 :             break;
    5533         158 :         case AT_SetTableSpace:  /* SET TABLESPACE */
    5534             : 
    5535             :             /*
    5536             :              * Only do this for partitioned tables and indexes, for which this
    5537             :              * is just a catalog change.  Other relation types which have
    5538             :              * storage are handled by Phase 3.
    5539             :              */
    5540         158 :             if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
    5541         146 :                 rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
    5542          36 :                 ATExecSetTableSpaceNoStorage(rel, tab->newTableSpace);
    5543             : 
    5544         152 :             break;
    5545         960 :         case AT_SetRelOptions:  /* SET (...) */
    5546             :         case AT_ResetRelOptions:    /* RESET (...) */
    5547             :         case AT_ReplaceRelOptions:  /* replace entire option list */
    5548         960 :             ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
    5549         908 :             break;
    5550         122 :         case AT_EnableTrig:     /* ENABLE TRIGGER name */
    5551         122 :             ATExecEnableDisableTrigger(rel, cmd->name,
    5552             :                                        TRIGGER_FIRES_ON_ORIGIN, false,
    5553         122 :                                        cmd->recurse,
    5554             :                                        lockmode);
    5555         122 :             break;
    5556          42 :         case AT_EnableAlwaysTrig:   /* ENABLE ALWAYS TRIGGER name */
    5557          42 :             ATExecEnableDisableTrigger(rel, cmd->name,
    5558             :                                        TRIGGER_FIRES_ALWAYS, false,
    5559          42 :                                        cmd->recurse,
    5560             :                                        lockmode);
    5561          42 :             break;
    5562          16 :         case AT_EnableReplicaTrig:  /* ENABLE REPLICA TRIGGER name */
    5563          16 :             ATExecEnableDisableTrigger(rel, cmd->name,
    5564             :                                        TRIGGER_FIRES_ON_REPLICA, false,
    5565          16 :                                        cmd->recurse,
    5566             :                                        lockmode);
    5567          16 :             break;
    5568         138 :         case AT_DisableTrig:    /* DISABLE TRIGGER name */
    5569         138 :             ATExecEnableDisableTrigger(rel, cmd->name,
    5570             :                                        TRIGGER_DISABLED, false,
    5571         138 :                                        cmd->recurse,
    5572             :                                        lockmode);
    5573         138 :             break;
    5574           0 :         case AT_EnableTrigAll:  /* ENABLE TRIGGER ALL */
    5575           0 :             ATExecEnableDisableTrigger(rel, NULL,
    5576             :                                        TRIGGER_FIRES_ON_ORIGIN, false,
    5577           0 :                                        cmd->recurse,
    5578             :                                        lockmode);
    5579           0 :             break;
    5580          12 :         case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
    5581          12 :             ATExecEnableDisableTrigger(rel, NULL,
    5582             :                                        TRIGGER_DISABLED, false,
    5583          12 :                                        cmd->recurse,
    5584             :                                        lockmode);
    5585          12 :             break;
    5586           0 :         case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
    5587           0 :             ATExecEnableDisableTrigger(rel, NULL,
    5588             :                                        TRIGGER_FIRES_ON_ORIGIN, true,
    5589           0 :                                        cmd->recurse,
    5590             :                                        lockmode);
    5591           0 :             break;
    5592          12 :         case AT_DisableTrigUser:    /* DISABLE TRIGGER USER */
    5593          12 :             ATExecEnableDisableTrigger(rel, NULL,
    5594             :                                        TRIGGER_DISABLED, true,
    5595          12 :                                        cmd->recurse,
    5596             :                                        lockmode);
    5597          12 :             break;
    5598             : 
    5599           8 :         case AT_EnableRule:     /* ENABLE RULE name */
    5600           8 :             ATExecEnableDisableRule(rel, cmd->name,
    5601             :                                     RULE_FIRES_ON_ORIGIN, lockmode);
    5602           8 :             break;
    5603           0 :         case AT_EnableAlwaysRule:   /* ENABLE ALWAYS RULE name */
    5604           0 :             ATExecEnableDisableRule(rel, cmd->name,
    5605             :                                     RULE_FIRES_ALWAYS, lockmode);
    5606           0 :             break;
    5607           6 :         case AT_EnableReplicaRule:  /* ENABLE REPLICA RULE name */
    5608           6 :             ATExecEnableDisableRule(rel, cmd->name,
    5609             :                                     RULE_FIRES_ON_REPLICA, lockmode);
    5610           6 :             break;
    5611          32 :         case AT_DisableRule:    /* DISABLE RULE name */
    5612          32 :             ATExecEnableDisableRule(rel, cmd->name,
    5613             :                                     RULE_DISABLED, lockmode);
    5614          32 :             break;
    5615             : 
    5616         446 :         case AT_AddInherit:
    5617         446 :             address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
    5618         326 :             break;
    5619          94 :         case AT_DropInherit:
    5620          94 :             address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
    5621          88 :             break;
    5622          66 :         case AT_AddOf:
    5623          66 :             address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
    5624          30 :             break;
    5625           6 :         case AT_DropOf:
    5626           6 :             ATExecDropOf(rel, lockmode);
    5627           6 :             break;
    5628         512 :         case AT_ReplicaIdentity:
    5629         512 :             ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
    5630         464 :             break;
    5631         338 :         case AT_EnableRowSecurity:
    5632         338 :             ATExecSetRowSecurity(rel, true);
    5633         338 :             break;
    5634          10 :         case AT_DisableRowSecurity:
    5635          10 :             ATExecSetRowSecurity(rel, false);
    5636          10 :             break;
    5637         100 :         case AT_ForceRowSecurity:
    5638         100 :             ATExecForceNoForceRowSecurity(rel, true);
    5639         100 :             break;
    5640          32 :         case AT_NoForceRowSecurity:
    5641          32 :             ATExecForceNoForceRowSecurity(rel, false);
    5642          32 :             break;
    5643          58 :         case AT_GenericOptions:
    5644          58 :             ATExecGenericOptions(rel, (List *) cmd->def);
    5645          56 :             break;
    5646        2810 :         case AT_AttachPartition:
    5647        2810 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5648             :                                       cur_pass, context);
    5649             :             Assert(cmd != NULL);
    5650        2786 :             if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    5651        2406 :                 address = ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
    5652             :                                                 context);
    5653             :             else
    5654         380 :                 address = ATExecAttachPartitionIdx(wqueue, rel,
    5655         380 :                                                    ((PartitionCmd *) cmd->def)->name);
    5656        2396 :             break;
    5657         578 :         case AT_DetachPartition:
    5658         578 :             cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
    5659             :                                       cur_pass, context);
    5660             :             Assert(cmd != NULL);
    5661             :             /* ATPrepCmd ensures it must be a table */
    5662             :             Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    5663         578 :             address = ATExecDetachPartition(wqueue, tab, rel,
    5664         578 :                                             ((PartitionCmd *) cmd->def)->name,
    5665         578 :                                             ((PartitionCmd *) cmd->def)->concurrent);
    5666         448 :             break;
    5667          14 :         case AT_DetachPartitionFinalize:
    5668          14 :             address = ATExecDetachPartitionFinalize(rel, ((PartitionCmd *) cmd->def)->name);
    5669          14 :             break;
    5670           0 :         default:                /* oops */
    5671           0 :             elog(ERROR, "unrecognized alter table type: %d",
    5672             :                  (int) cmd->subtype);
    5673             :             break;
    5674             :     }
    5675             : 
    5676             :     /*
    5677             :      * Report the subcommand to interested event triggers.
    5678             :      */
    5679       56408 :     if (cmd)
    5680       40390 :         EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
    5681             : 
    5682             :     /*
    5683             :      * Bump the command counter to ensure the next subcommand in the sequence
    5684             :      * can see the changes so far
    5685             :      */
    5686       56408 :     CommandCounterIncrement();
    5687       56408 : }
    5688             : 
    5689             : /*
    5690             :  * ATParseTransformCmd: perform parse transformation for one subcommand
    5691             :  *
    5692             :  * Returns the transformed subcommand tree, if there is one, else NULL.
    5693             :  *
    5694             :  * The parser may hand back additional AlterTableCmd(s) and/or other
    5695             :  * utility statements, either before or after the original subcommand.
    5696             :  * Other AlterTableCmds are scheduled into the appropriate slot of the
    5697             :  * AlteredTableInfo (they had better be for later passes than the current one).
    5698             :  * Utility statements that are supposed to happen before the AlterTableCmd
    5699             :  * are executed immediately.  Those that are supposed to happen afterwards
    5700             :  * are added to the tab->afterStmts list to be done at the very end.
    5701             :  */
    5702             : static AlterTableCmd *
    5703       23058 : ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
    5704             :                     AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
    5705             :                     AlterTablePass cur_pass, AlterTableUtilityContext *context)
    5706             : {
    5707       23058 :     AlterTableCmd *newcmd = NULL;
    5708       23058 :     AlterTableStmt *atstmt = makeNode(AlterTableStmt);
    5709             :     List       *beforeStmts;
    5710             :     List       *afterStmts;
    5711             :     ListCell   *lc;
    5712             : 
    5713             :     /* Gin up an AlterTableStmt with just this subcommand and this table */
    5714       23058 :     atstmt->relation =
    5715       23058 :         makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
    5716       23058 :                      pstrdup(RelationGetRelationName(rel)),
    5717             :                      -1);
    5718       23058 :     atstmt->relation->inh = recurse;
    5719       23058 :     atstmt->cmds = list_make1(cmd);
    5720       23058 :     atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
    5721       23058 :     atstmt->missing_ok = false;
    5722             : 
    5723             :     /* Transform the AlterTableStmt */
    5724       23058 :     atstmt = transformAlterTableStmt(RelationGetRelid(rel),
    5725             :                                      atstmt,
    5726             :                                      context->queryString,
    5727             :                                      &beforeStmts,
    5728             :                                      &afterStmts);
    5729             : 
    5730             :     /* Execute any statements that should happen before these subcommand(s) */
    5731       23466 :     foreach(lc, beforeStmts)
    5732             :     {
    5733         486 :         Node       *stmt = (Node *) lfirst(lc);
    5734             : 
    5735         486 :         ProcessUtilityForAlterTable(stmt, context);
    5736         474 :         CommandCounterIncrement();
    5737             :     }
    5738             : 
    5739             :     /* Examine the transformed subcommands and schedule them appropriately */
    5740       54306 :     foreach(lc, atstmt->cmds)
    5741             :     {
    5742       31326 :         AlterTableCmd *cmd2 = lfirst_node(AlterTableCmd, lc);
    5743             :         AlterTablePass pass;
    5744             : 
    5745             :         /*
    5746             :          * This switch need only cover the subcommand types that can be added
    5747             :          * by parse_utilcmd.c; otherwise, we'll use the default strategy of
    5748             :          * executing the subcommand immediately, as a substitute for the
    5749             :          * original subcommand.  (Note, however, that this does cause
    5750             :          * AT_AddConstraint subcommands to be rescheduled into later passes,
    5751             :          * which is important for index and foreign key constraints.)
    5752             :          *
    5753             :          * We assume we needn't do any phase-1 checks for added subcommands.
    5754             :          */
    5755       31326 :         switch (cmd2->subtype)
    5756             :         {
    5757        1202 :             case AT_AddIndex:
    5758        1202 :                 pass = AT_PASS_ADD_INDEX;
    5759        1202 :                 break;
    5760       10640 :             case AT_AddIndexConstraint:
    5761       10640 :                 pass = AT_PASS_ADD_INDEXCONSTR;
    5762       10640 :                 break;
    5763       12522 :             case AT_AddConstraint:
    5764             :                 /* Recursion occurs during execution phase */
    5765       12522 :                 if (recurse)
    5766       12474 :                     cmd2->recurse = true;
    5767       12522 :                 switch (castNode(Constraint, cmd2->def)->contype)
    5768             :                 {
    5769        8984 :                     case CONSTR_NOTNULL:
    5770        8984 :                         pass = AT_PASS_COL_ATTRS;
    5771        8984 :                         break;
    5772           0 :                     case CONSTR_PRIMARY:
    5773             :                     case CONSTR_UNIQUE:
    5774             :                     case CONSTR_EXCLUSION:
    5775           0 :                         pass = AT_PASS_ADD_INDEXCONSTR;
    5776           0 :                         break;
    5777        3538 :                     default:
    5778        3538 :                         pass = AT_PASS_ADD_OTHERCONSTR;
    5779        3538 :                         break;
    5780             :                 }
    5781       12522 :                 break;
    5782           0 :             case AT_AlterColumnGenericOptions:
    5783             :                 /* This command never recurses */
    5784             :                 /* No command-specific prep needed */
    5785           0 :                 pass = AT_PASS_MISC;
    5786           0 :                 break;
    5787        6962 :             default:
    5788        6962 :                 pass = cur_pass;
    5789        6962 :                 break;
    5790             :         }
    5791             : 
    5792       31326 :         if (pass < cur_pass)
    5793             :         {
    5794             :             /* Cannot schedule into a pass we already finished */
    5795           0 :             elog(ERROR, "ALTER TABLE scheduling failure: too late for pass %d",
    5796             :                  pass);
    5797             :         }
    5798       31326 :         else if (pass > cur_pass)
    5799             :         {
    5800             :             /* OK, queue it up for later */
    5801       24364 :             tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd2);
    5802             :         }
    5803             :         else
    5804             :         {
    5805             :             /*
    5806             :              * We should see at most one subcommand for the current pass,
    5807             :              * which is the transformed version of the original subcommand.
    5808             :              */
    5809        6962 :             if (newcmd == NULL && cmd->subtype == cmd2->subtype)
    5810             :             {
    5811             :                 /* Found the transformed version of our subcommand */
    5812        6962 :                 newcmd = cmd2;
    5813             :             }
    5814             :             else
    5815           0 :                 elog(ERROR, "ALTER TABLE scheduling failure: bogus item for pass %d",
    5816             :                      pass);
    5817             :         }
    5818             :     }
    5819             : 
    5820             :     /* Queue up any after-statements to happen at the end */
    5821       22980 :     tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
    5822             : 
    5823       22980 :     return newcmd;
    5824             : }
    5825             : 
    5826             : /*
    5827             :  * ATRewriteTables: ALTER TABLE phase 3
    5828             :  */
    5829             : static void
    5830       29116 : ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
    5831             :                 AlterTableUtilityContext *context)
    5832             : {
    5833             :     ListCell   *ltab;
    5834             : 
    5835             :     /* Go through each table that needs to be checked or rewritten */
    5836       61928 :     foreach(ltab, *wqueue)
    5837             :     {
    5838       33194 :         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    5839             : 
    5840             :         /* Relations without storage may be ignored here */
    5841       33194 :         if (!RELKIND_HAS_STORAGE(tab->relkind))
    5842        5816 :             continue;
    5843             : 
    5844             :         /*
    5845             :          * If we change column data types, the operation has to be propagated
    5846             :          * to tables that use this table's rowtype as a column type.
    5847             :          * tab->newvals will also be non-NULL in the case where we're adding a
    5848             :          * column with a default.  We choose to forbid that case as well,
    5849             :          * since composite types might eventually support defaults.
    5850             :          *
    5851             :          * (Eventually we'll probably need to check for composite type
    5852             :          * dependencies even when we're just scanning the table without a
    5853             :          * rewrite, but at the moment a composite type does not enforce any
    5854             :          * constraints, so it's not necessary/appropriate to enforce them just
    5855             :          * during ALTER.)
    5856             :          */
    5857       27378 :         if (tab->newvals != NIL || tab->rewrite > 0)
    5858             :         {
    5859             :             Relation    rel;
    5860             : 
    5861        1748 :             rel = table_open(tab->relid, NoLock);
    5862        1748 :             find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
    5863        1694 :             table_close(rel, NoLock);
    5864             :         }
    5865             : 
    5866             :         /*
    5867             :          * We only need to rewrite the table if at least one column needs to
    5868             :          * be recomputed, or we are changing its persistence or access method.
    5869             :          *
    5870             :          * There are two reasons for requiring a rewrite when changing
    5871             :          * persistence: on one hand, we need to ensure that the buffers
    5872             :          * belonging to each of the two relations are marked with or without
    5873             :          * BM_PERMANENT properly.  On the other hand, since rewriting creates
    5874             :          * and assigns a new relfilenumber, we automatically create or drop an
    5875             :          * init fork for the relation as appropriate.
    5876             :          */
    5877       27324 :         if (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE)
    5878         934 :         {
    5879             :             /* Build a temporary relation and copy data */
    5880             :             Relation    OldHeap;
    5881             :             Oid         OIDNewHeap;
    5882             :             Oid         NewAccessMethod;
    5883             :             Oid         NewTableSpace;
    5884             :             char        persistence;
    5885             : 
    5886         990 :             OldHeap = table_open(tab->relid, NoLock);
    5887             : 
    5888             :             /*
    5889             :              * We don't support rewriting of system catalogs; there are too
    5890             :              * many corner cases and too little benefit.  In particular this
    5891             :              * is certainly not going to work for mapped catalogs.
    5892             :              */
    5893         990 :             if (IsSystemRelation(OldHeap))
    5894           0 :                 ereport(ERROR,
    5895             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5896             :                          errmsg("cannot rewrite system relation \"%s\"",
    5897             :                                 RelationGetRelationName(OldHeap))));
    5898             : 
    5899         990 :             if (RelationIsUsedAsCatalogTable(OldHeap))
    5900           2 :                 ereport(ERROR,
    5901             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5902             :                          errmsg("cannot rewrite table \"%s\" used as a catalog table",
    5903             :                                 RelationGetRelationName(OldHeap))));
    5904             : 
    5905             :             /*
    5906             :              * Don't allow rewrite on temp tables of other backends ... their
    5907             :              * local buffer manager is not going to cope.  (This is redundant
    5908             :              * with the check in CheckAlterTableIsSafe, but for safety we'll
    5909             :              * check here too.)
    5910             :              */
    5911         988 :             if (RELATION_IS_OTHER_TEMP(OldHeap))
    5912           0 :                 ereport(ERROR,
    5913             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5914             :                          errmsg("cannot rewrite temporary tables of other sessions")));
    5915             : 
    5916             :             /*
    5917             :              * Select destination tablespace (same as original unless user
    5918             :              * requested a change)
    5919             :              */
    5920         988 :             if (tab->newTableSpace)
    5921           0 :                 NewTableSpace = tab->newTableSpace;
    5922             :             else
    5923         988 :                 NewTableSpace = OldHeap->rd_rel->reltablespace;
    5924             : 
    5925             :             /*
    5926             :              * Select destination access method (same as original unless user
    5927             :              * requested a change)
    5928             :              */
    5929         988 :             if (tab->chgAccessMethod)
    5930          36 :                 NewAccessMethod = tab->newAccessMethod;
    5931             :             else
    5932         952 :                 NewAccessMethod = OldHeap->rd_rel->relam;
    5933             : 
    5934             :             /*
    5935             :              * Select persistence of transient table (same as original unless
    5936             :              * user requested a change)
    5937             :              */
    5938         988 :             persistence = tab->chgPersistence ?
    5939         936 :                 tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
    5940             : 
    5941         988 :             table_close(OldHeap, NoLock);
    5942             : 
    5943             :             /*
    5944             :              * Fire off an Event Trigger now, before actually rewriting the
    5945             :              * table.
    5946             :              *
    5947             :              * We don't support Event Trigger for nested commands anywhere,
    5948             :              * here included, and parsetree is given NULL when coming from
    5949             :              * AlterTableInternal.
    5950             :              *
    5951             :              * And fire it only once.
    5952             :              */
    5953         988 :             if (parsetree)
    5954         988 :                 EventTriggerTableRewrite((Node *) parsetree,
    5955             :                                          tab->relid,
    5956             :                                          tab->rewrite);
    5957             : 
    5958             :             /*
    5959             :              * Create transient table that will receive the modified data.
    5960             :              *
    5961             :              * Ensure it is marked correctly as logged or unlogged.  We have
    5962             :              * to do this here so that buffers for the new relfilenumber will
    5963             :              * have the right persistence set, and at the same time ensure
    5964             :              * that the original filenumbers's buffers will get read in with
    5965             :              * the correct setting (i.e. the original one).  Otherwise a
    5966             :              * rollback after the rewrite would possibly result with buffers
    5967             :              * for the original filenumbers having the wrong persistence
    5968             :              * setting.
    5969             :              *
    5970             :              * NB: This relies on swap_relation_files() also swapping the
    5971             :              * persistence. That wouldn't work for pg_class, but that can't be
    5972             :              * unlogged anyway.
    5973             :              */
    5974         982 :             OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, NewAccessMethod,
    5975             :                                        persistence, lockmode);
    5976             : 
    5977             :             /*
    5978             :              * Copy the heap data into the new table with the desired
    5979             :              * modifications, and test the current data within the table
    5980             :              * against new constraints generated by ALTER TABLE commands.
    5981             :              */
    5982         982 :             ATRewriteTable(tab, OIDNewHeap);
    5983             : 
    5984             :             /*
    5985             :              * Swap the physical files of the old and new heaps, then rebuild
    5986             :              * indexes and discard the old heap.  We can use RecentXmin for
    5987             :              * the table's new relfrozenxid because we rewrote all the tuples
    5988             :              * in ATRewriteTable, so no older Xid remains in the table.  Also,
    5989             :              * we never try to swap toast tables by content, since we have no
    5990             :              * interest in letting this code work on system catalogs.
    5991             :              */
    5992         940 :             finish_heap_swap(tab->relid, OIDNewHeap,
    5993             :                              false, false, true,
    5994         940 :                              !OidIsValid(tab->newTableSpace),
    5995             :                              RecentXmin,
    5996             :                              ReadNextMultiXactId(),
    5997             :                              persistence);
    5998             : 
    5999         934 :             InvokeObjectPostAlterHook(RelationRelationId, tab->relid, 0);
    6000             :         }
    6001       26334 :         else if (tab->rewrite > 0 && tab->relkind == RELKIND_SEQUENCE)
    6002             :         {
    6003          24 :             if (tab->chgPersistence)
    6004          24 :                 SequenceChangePersistence(tab->relid, tab->newrelpersistence);
    6005             :         }
    6006             :         else
    6007             :         {
    6008             :             /*
    6009             :              * If required, test the current data within the table against new
    6010             :              * constraints generated by ALTER TABLE commands, but don't
    6011             :              * rebuild data.
    6012             :              */
    6013       26310 :             if (tab->constraints != NIL || tab->verify_new_notnull ||
    6014       23426 :                 tab->partition_constraint != NULL)
    6015        4800 :                 ATRewriteTable(tab, InvalidOid);
    6016             : 
    6017             :             /*
    6018             :              * If we had SET TABLESPACE but no reason to reconstruct tuples,
    6019             :              * just do a block-by-block copy.
    6020             :              */
    6021       26038 :             if (tab->newTableSpace)
    6022         122 :                 ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
    6023             :         }
    6024             : 
    6025             :         /*
    6026             :          * Also change persistence of owned sequences, so that it matches the
    6027             :          * table persistence.
    6028             :          */
    6029       26996 :         if (tab->chgPersistence)
    6030             :         {
    6031          76 :             List       *seqlist = getOwnedSequences(tab->relid);
    6032             :             ListCell   *lc;
    6033             : 
    6034         124 :             foreach(lc, seqlist)
    6035             :             {
    6036          48 :                 Oid         seq_relid = lfirst_oid(lc);
    6037             : 
    6038          48 :                 SequenceChangePersistence(seq_relid, tab->newrelpersistence);
    6039             :             }
    6040             :         }
    6041             :     }
    6042             : 
    6043             :     /*
    6044             :      * Foreign key constraints are checked in a final pass, since (a) it's
    6045             :      * generally best to examine each one separately, and (b) it's at least
    6046             :      * theoretically possible that we have changed both relations of the
    6047             :      * foreign key, and we'd better have finished both rewrites before we try
    6048             :      * to read the tables.
    6049             :      */
    6050       61288 :     foreach(ltab, *wqueue)
    6051             :     {
    6052       32646 :         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    6053       32646 :         Relation    rel = NULL;
    6054             :         ListCell   *lcon;
    6055             : 
    6056             :         /* Relations without storage may be ignored here too */
    6057       32646 :         if (!RELKIND_HAS_STORAGE(tab->relkind))
    6058        5712 :             continue;
    6059             : 
    6060       28738 :         foreach(lcon, tab->constraints)
    6061             :         {
    6062        1896 :             NewConstraint *con = lfirst(lcon);
    6063             : 
    6064        1896 :             if (con->contype == CONSTR_FOREIGN)
    6065             :             {
    6066        1166 :                 Constraint *fkconstraint = (Constraint *) con->qual;
    6067             :                 Relation    refrel;
    6068             : 
    6069        1166 :                 if (rel == NULL)
    6070             :                 {
    6071             :                     /* Long since locked, no need for another */
    6072        1154 :                     rel = table_open(tab->relid, NoLock);
    6073             :                 }
    6074             : 
    6075        1166 :                 refrel = table_open(con->refrelid, RowShareLock);
    6076             : 
    6077        1166 :                 validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
    6078             :                                              con->refindid,
    6079             :                                              con->conid,
    6080        1166 :                                              con->conwithperiod);
    6081             : 
    6082             :                 /*
    6083             :                  * No need to mark the constraint row as validated, we did
    6084             :                  * that when we inserted the row earlier.
    6085             :                  */
    6086             : 
    6087        1074 :                 table_close(refrel, NoLock);
    6088             :             }
    6089             :         }
    6090             : 
    6091       26842 :         if (rel)
    6092        1062 :             table_close(rel, NoLock);
    6093             :     }
    6094             : 
    6095             :     /* Finally, run any afterStmts that were queued up */
    6096       61152 :     foreach(ltab, *wqueue)
    6097             :     {
    6098       32510 :         AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
    6099             :         ListCell   *lc;
    6100             : 
    6101       32596 :         foreach(lc, tab->afterStmts)
    6102             :         {
    6103          86 :             Node       *stmt = (Node *) lfirst(lc);
    6104             : 
    6105          86 :             ProcessUtilityForAlterTable(stmt, context);
    6106          86 :             CommandCounterIncrement();
    6107             :         }
    6108             :     }
    6109       28642 : }
    6110             : 
    6111             : /*
    6112             :  * ATRewriteTable: scan or rewrite one table
    6113             :  *
    6114             :  * A rewrite is requested by passing a valid OIDNewHeap; in that case, caller
    6115             :  * must already hold AccessExclusiveLock on it.
    6116             :  */
    6117             : static void
    6118        5782 : ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
    6119             : {
    6120             :     Relation    oldrel;
    6121             :     Relation    newrel;
    6122             :     TupleDesc   oldTupDesc;
    6123             :     TupleDesc   newTupDesc;
    6124        5782 :     bool        needscan = false;
    6125             :     List       *notnull_attrs;
    6126             :     List       *notnull_virtual_attrs;
    6127             :     int         i;
    6128             :     ListCell   *l;
    6129             :     EState     *estate;
    6130             :     CommandId   mycid;
    6131             :     BulkInsertState bistate;
    6132             :     int         ti_options;
    6133        5782 :     ExprState  *partqualstate = NULL;
    6134             : 
    6135             :     /*
    6136             :      * Open the relation(s).  We have surely already locked the existing
    6137             :      * table.
    6138             :      */
    6139        5782 :     oldrel = table_open(tab->relid, NoLock);
    6140        5782 :     oldTupDesc = tab->oldDesc;
    6141        5782 :     newTupDesc = RelationGetDescr(oldrel);  /* includes all mods */
    6142             : 
    6143        5782 :     if (OidIsValid(OIDNewHeap))
    6144             :     {
    6145             :         Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock,
    6146             :                                           false));
    6147         982 :         newrel = table_open(OIDNewHeap, NoLock);
    6148             :     }
    6149             :     else
    6150        4800 :         newrel = NULL;
    6151             : 
    6152             :     /*
    6153             :      * Prepare a BulkInsertState and options for table_tuple_insert.  The FSM
    6154             :      * is empty, so don't bother using it.
    6155             :      */
    6156        5782 :     if (newrel)
    6157             :     {
    6158         982 :         mycid = GetCurrentCommandId(true);
    6159         982 :         bistate = GetBulkInsertState();
    6160         982 :         ti_options = TABLE_INSERT_SKIP_FSM;
    6161             :     }
    6162             :     else
    6163             :     {
    6164             :         /* keep compiler quiet about using these uninitialized */
    6165        4800 :         mycid = 0;
    6166        4800 :         bistate = NULL;
    6167        4800 :         ti_options = 0;
    6168             :     }
    6169             : 
    6170             :     /*
    6171             :      * Generate the constraint and default execution states
    6172             :      */
    6173             : 
    6174        5782 :     estate = CreateExecutorState();
    6175             : 
    6176             :     /* Build the needed expression execution states */
    6177        7798 :     foreach(l, tab->constraints)
    6178             :     {
    6179        2016 :         NewConstraint *con = lfirst(l);
    6180             : 
    6181        2016 :         switch (con->contype)
    6182             :         {
    6183         844 :             case CONSTR_CHECK:
    6184         844 :                 needscan = true;
    6185         844 :                 con->qualstate = ExecPrepareExpr((Expr *) expand_generated_columns_in_expr(con->qual, oldrel, 1), estate);
    6186         844 :                 break;
    6187        1172 :             case CONSTR_FOREIGN:
    6188             :                 /* Nothing to do here */
    6189        1172 :                 break;
    6190           0 :             default:
    6191           0 :                 elog(ERROR, "unrecognized constraint type: %d",
    6192             :                      (int) con->contype);
    6193             :         }
    6194             :     }
    6195             : 
    6196             :     /* Build expression execution states for partition check quals */
    6197        5782 :     if (tab->partition_constraint)
    6198             :     {
    6199        2064 :         needscan = true;
    6200        2064 :         partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
    6201             :     }
    6202             : 
    6203        6826 :     foreach(l, tab->newvals)
    6204             :     {
    6205        1044 :         NewColumnValue *ex = lfirst(l);
    6206             : 
    6207             :         /* expr already planned */
    6208        1044 :         ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
    6209             :     }
    6210             : 
    6211        5782 :     notnull_attrs = notnull_virtual_attrs = NIL;
    6212        5782 :     if (newrel || tab->verify_new_notnull)
    6213             :     {
    6214             :         /*
    6215             :          * If we are rebuilding the tuples OR if we added any new but not
    6216             :          * verified not-null constraints, check all *valid* not-null
    6217             :          * constraints. This is a bit of overkill but it minimizes risk of
    6218             :          * bugs.
    6219             :          *
    6220             :          * notnull_attrs does *not* collect attribute numbers for valid
    6221             :          * not-null constraints over virtual generated columns; instead, they
    6222             :          * are collected in notnull_virtual_attrs for verification elsewhere.
    6223             :          */
    6224        7514 :         for (i = 0; i < newTupDesc->natts; i++)
    6225             :         {
    6226        5494 :             CompactAttribute *attr = TupleDescCompactAttr(newTupDesc, i);
    6227             : 
    6228        5494 :             if (attr->attnullability == ATTNULLABLE_VALID &&
    6229        2118 :                 !attr->attisdropped)
    6230             :             {
    6231        2118 :                 Form_pg_attribute wholeatt = TupleDescAttr(newTupDesc, i);
    6232             : 
    6233        2118 :                 if (wholeatt->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL)
    6234        2028 :                     notnull_attrs = lappend_int(notnull_attrs, wholeatt->attnum);
    6235             :                 else
    6236          90 :                     notnull_virtual_attrs = lappend_int(notnull_virtual_attrs,
    6237          90 :                                                         wholeatt->attnum);
    6238             :             }
    6239             :         }
    6240        2020 :         if (notnull_attrs || notnull_virtual_attrs)
    6241        1556 :             needscan = true;
    6242             :     }
    6243             : 
    6244        5782 :     if (newrel || needscan)
    6245             :     {
    6246             :         ExprContext *econtext;
    6247             :         TupleTableSlot *oldslot;
    6248             :         TupleTableSlot *newslot;
    6249             :         TableScanDesc scan;
    6250             :         MemoryContext oldCxt;
    6251        4812 :         List       *dropped_attrs = NIL;
    6252             :         ListCell   *lc;
    6253             :         Snapshot    snapshot;
    6254        4812 :         ResultRelInfo *rInfo = NULL;
    6255             : 
    6256             :         /*
    6257             :          * When adding or changing a virtual generated column with a not-null
    6258             :          * constraint, we need to evaluate whether the generation expression
    6259             :          * is null.  For that, we borrow ExecRelGenVirtualNotNull().  Here, we
    6260             :          * prepare a dummy ResultRelInfo.
    6261             :          */
    6262        4812 :         if (notnull_virtual_attrs != NIL)
    6263             :         {
    6264             :             MemoryContext oldcontext;
    6265             : 
    6266             :             Assert(newTupDesc->constr->has_generated_virtual);
    6267             :             Assert(newTupDesc->constr->has_not_null);
    6268          60 :             oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
    6269          60 :             rInfo = makeNode(ResultRelInfo);
    6270          60 :             InitResultRelInfo(rInfo,
    6271             :                               oldrel,
    6272             :                               0,    /* dummy rangetable index */
    6273             :                               NULL,
    6274             :                               estate->es_instrument);
    6275          60 :             MemoryContextSwitchTo(oldcontext);
    6276             :         }
    6277             : 
    6278        4812 :         if (newrel)
    6279         982 :             ereport(DEBUG1,
    6280             :                     (errmsg_internal("rewriting table \"%s\"",
    6281             :                                      RelationGetRelationName(oldrel))));
    6282             :         else
    6283        3830 :             ereport(DEBUG1,
    6284             :                     (errmsg_internal("verifying table \"%s\"",
    6285             :                                      RelationGetRelationName(oldrel))));
    6286             : 
    6287        4812 :         if (newrel)
    6288             :         {
    6289             :             /*
    6290             :              * All predicate locks on the tuples or pages are about to be made
    6291             :              * invalid, because we move tuples around.  Promote them to
    6292             :              * relation locks.
    6293             :              */
    6294         982 :             TransferPredicateLocksToHeapRelation(oldrel);
    6295             :         }
    6296             : 
    6297        4812 :         econtext = GetPerTupleExprContext(estate);
    6298             : 
    6299             :         /*
    6300             :          * Create necessary tuple slots. When rewriting, two slots are needed,
    6301             :          * otherwise one suffices. In the case where one slot suffices, we
    6302             :          * need to use the new tuple descriptor, otherwise some constraints
    6303             :          * can't be evaluated.  Note that even when the tuple layout is the
    6304             :          * same and no rewrite is required, the tupDescs might not be
    6305             :          * (consider ADD COLUMN without a default).
    6306             :          */
    6307        4812 :         if (tab->rewrite)
    6308             :         {
    6309             :             Assert(newrel != NULL);
    6310         982 :             oldslot = MakeSingleTupleTableSlot(oldTupDesc,
    6311             :                                                table_slot_callbacks(oldrel));
    6312         982 :             newslot = MakeSingleTupleTableSlot(newTupDesc,
    6313             :                                                table_slot_callbacks(newrel));
    6314             : 
    6315             :             /*
    6316             :              * Set all columns in the new slot to NULL initially, to ensure
    6317             :              * columns added as part of the rewrite are initialized to NULL.
    6318             :              * That is necessary as tab->newvals will not contain an
    6319             :              * expression for columns with a NULL default, e.g. when adding a
    6320             :              * column without a default together with a column with a default
    6321             :              * requiring an actual rewrite.
    6322             :              */
    6323         982 :             ExecStoreAllNullTuple(newslot);
    6324             :         }
    6325             :         else
    6326             :         {
    6327        3830 :             oldslot = MakeSingleTupleTableSlot(newTupDesc,
    6328             :                                                table_slot_callbacks(oldrel));
    6329        3830 :             newslot = NULL;
    6330             :         }
    6331             : 
    6332             :         /*
    6333             :          * Any attributes that are dropped according to the new tuple
    6334             :          * descriptor can be set to NULL. We precompute the list of dropped
    6335             :          * attributes to avoid needing to do so in the per-tuple loop.
    6336             :          */
    6337       17000 :         for (i = 0; i < newTupDesc->natts; i++)
    6338             :         {
    6339       12188 :             if (TupleDescAttr(newTupDesc, i)->attisdropped)
    6340         790 :                 dropped_attrs = lappend_int(dropped_attrs, i);
    6341             :         }
    6342             : 
    6343             :         /*
    6344             :          * Scan through the rows, generating a new row if needed and then
    6345             :          * checking all the constraints.
    6346             :          */
    6347        4812 :         snapshot = RegisterSnapshot(GetLatestSnapshot());
    6348        4812 :         scan = table_beginscan(oldrel, snapshot, 0, NULL);
    6349             : 
    6350             :         /*
    6351             :          * Switch to per-tuple memory context and reset it for each tuple
    6352             :          * produced, so we don't leak memory.
    6353             :          */
    6354        4812 :         oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
    6355             : 
    6356      774538 :         while (table_scan_getnextslot(scan, ForwardScanDirection, oldslot))
    6357             :         {
    6358             :             TupleTableSlot *insertslot;
    6359             : 
    6360      765228 :             if (tab->rewrite > 0)
    6361             :             {
    6362             :                 /* Extract data from old tuple */
    6363       99834 :                 slot_getallattrs(oldslot);
    6364       99834 :                 ExecClearTuple(newslot);
    6365             : 
    6366             :                 /* copy attributes */
    6367       99834 :                 memcpy(newslot->tts_values, oldslot->tts_values,
    6368       99834 :                        sizeof(Datum) * oldslot->tts_nvalid);
    6369       99834 :                 memcpy(newslot->tts_isnull, oldslot->tts_isnull,
    6370       99834 :                        sizeof(bool) * oldslot->tts_nvalid);
    6371             : 
    6372             :                 /* Set dropped attributes to null in new tuple */
    6373       99950 :                 foreach(lc, dropped_attrs)
    6374         116 :                     newslot->tts_isnull[lfirst_int(lc)] = true;
    6375             : 
    6376             :                 /*
    6377             :                  * Constraints and GENERATED expressions might reference the
    6378             :                  * tableoid column, so fill tts_tableOid with the desired
    6379             :                  * value.  (We must do this each time, because it gets
    6380             :                  * overwritten with newrel's OID during storing.)
    6381             :                  */
    6382       99834 :                 newslot->tts_tableOid = RelationGetRelid(oldrel);
    6383             : 
    6384             :                 /*
    6385             :                  * Process supplied expressions to replace selected columns.
    6386             :                  *
    6387             :                  * First, evaluate expressions whose inputs come from the old
    6388             :                  * tuple.
    6389             :                  */
    6390       99834 :                 econtext->ecxt_scantuple = oldslot;
    6391             : 
    6392      205620 :                 foreach(l, tab->newvals)
    6393             :                 {
    6394      105798 :                     NewColumnValue *ex = lfirst(l);
    6395             : 
    6396      105798 :                     if (ex->is_generated)
    6397         312 :                         continue;
    6398             : 
    6399      105486 :                     newslot->tts_values[ex->attnum - 1]
    6400      105474 :                         = ExecEvalExpr(ex->exprstate,
    6401             :                                        econtext,
    6402      105486 :                                        &newslot->tts_isnull[ex->attnum - 1]);
    6403             :                 }
    6404             : 
    6405       99822 :                 ExecStoreVirtualTuple(newslot);
    6406             : 
    6407             :                 /*
    6408             :                  * Now, evaluate any expressions whose inputs come from the
    6409             :                  * new tuple.  We assume these columns won't reference each
    6410             :                  * other, so that there's no ordering dependency.
    6411             :                  */
    6412       99822 :                 econtext->ecxt_scantuple = newslot;
    6413             : 
    6414      205608 :                 foreach(l, tab->newvals)
    6415             :                 {
    6416      105786 :                     NewColumnValue *ex = lfirst(l);
    6417             : 
    6418      105786 :                     if (!ex->is_generated)
    6419      105474 :                         continue;
    6420             : 
    6421         312 :                     newslot->tts_values[ex->attnum - 1]
    6422         312 :                         = ExecEvalExpr(ex->exprstate,
    6423             :                                        econtext,
    6424         312 :                                        &newslot->tts_isnull[ex->attnum - 1]);
    6425             :                 }
    6426             : 
    6427       99822 :                 insertslot = newslot;
    6428             :             }
    6429             :             else
    6430             :             {
    6431             :                 /*
    6432             :                  * If there's no rewrite, old and new table are guaranteed to
    6433             :                  * have the same AM, so we can just use the old slot to verify
    6434             :                  * new constraints etc.
    6435             :                  */
    6436      665394 :                 insertslot = oldslot;
    6437             :             }
    6438             : 
    6439             :             /* Now check any constraints on the possibly-changed tuple */
    6440      765216 :             econtext->ecxt_scantuple = insertslot;
    6441             : 
    6442     4106702 :             foreach_int(attn, notnull_attrs)
    6443             :             {
    6444     2576474 :                 if (slot_attisnull(insertslot, attn))
    6445             :                 {
    6446         102 :                     Form_pg_attribute attr = TupleDescAttr(newTupDesc, attn - 1);
    6447             : 
    6448         102 :                     ereport(ERROR,
    6449             :                             (errcode(ERRCODE_NOT_NULL_VIOLATION),
    6450             :                              errmsg("column \"%s\" of relation \"%s\" contains null values",
    6451             :                                     NameStr(attr->attname),
    6452             :                                     RelationGetRelationName(oldrel)),
    6453             :                              errtablecol(oldrel, attn)));
    6454             :                 }
    6455             :             }
    6456             : 
    6457      765114 :             if (notnull_virtual_attrs != NIL)
    6458             :             {
    6459             :                 AttrNumber  attnum;
    6460             : 
    6461          84 :                 attnum = ExecRelGenVirtualNotNull(rInfo, insertslot,
    6462             :                                                   estate,
    6463             :                                                   notnull_virtual_attrs);
    6464          84 :                 if (attnum != InvalidAttrNumber)
    6465             :                 {
    6466          30 :                     Form_pg_attribute attr = TupleDescAttr(newTupDesc, attnum - 1);
    6467             : 
    6468          30 :                     ereport(ERROR,
    6469             :                             errcode(ERRCODE_NOT_NULL_VIOLATION),
    6470             :                             errmsg("column \"%s\" of relation \"%s\" contains null values",
    6471             :                                    NameStr(attr->attname),
    6472             :                                    RelationGetRelationName(oldrel)),
    6473             :                             errtablecol(oldrel, attnum));
    6474             :                 }
    6475             :             }
    6476             : 
    6477      773244 :             foreach(l, tab->constraints)
    6478             :             {
    6479        8256 :                 NewConstraint *con = lfirst(l);
    6480             : 
    6481        8256 :                 switch (con->contype)
    6482             :                 {
    6483        8150 :                     case CONSTR_CHECK:
    6484        8150 :                         if (!ExecCheck(con->qualstate, econtext))
    6485          96 :                             ereport(ERROR,
    6486             :                                     (errcode(ERRCODE_CHECK_VIOLATION),
    6487             :                                      errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
    6488             :                                             con->name,
    6489             :                                             RelationGetRelationName(oldrel)),
    6490             :                                      errtableconstraint(oldrel, con->name)));
    6491        8054 :                         break;
    6492         106 :                     case CONSTR_NOTNULL:
    6493             :                     case CONSTR_FOREIGN:
    6494             :                         /* Nothing to do here */
    6495         106 :                         break;
    6496           0 :                     default:
    6497           0 :                         elog(ERROR, "unrecognized constraint type: %d",
    6498             :                              (int) con->contype);
    6499             :                 }
    6500             :             }
    6501             : 
    6502      764988 :             if (partqualstate && !ExecCheck(partqualstate, econtext))
    6503             :             {
    6504          74 :                 if (tab->validate_default)
    6505          26 :                     ereport(ERROR,
    6506             :                             (errcode(ERRCODE_CHECK_VIOLATION),
    6507             :                              errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
    6508             :                                     RelationGetRelationName(oldrel)),
    6509             :                              errtable(oldrel)));
    6510             :                 else
    6511          48 :                     ereport(ERROR,
    6512             :                             (errcode(ERRCODE_CHECK_VIOLATION),
    6513             :                              errmsg("partition constraint of relation \"%s\" is violated by some row",
    6514             :                                     RelationGetRelationName(oldrel)),
    6515             :                              errtable(oldrel)));
    6516             :             }
    6517             : 
    6518             :             /* Write the tuple out to the new relation */
    6519      764914 :             if (newrel)
    6520       99792 :                 table_tuple_insert(newrel, insertslot, mycid,
    6521             :                                    ti_options, bistate);
    6522             : 
    6523      764914 :             ResetExprContext(econtext);
    6524             : 
    6525      764914 :             CHECK_FOR_INTERRUPTS();
    6526             :         }
    6527             : 
    6528        4498 :         MemoryContextSwitchTo(oldCxt);
    6529        4498 :         table_endscan(scan);
    6530        4498 :         UnregisterSnapshot(snapshot);
    6531             : 
    6532        4498 :         ExecDropSingleTupleTableSlot(oldslot);
    6533        4498 :         if (newslot)
    6534         940 :             ExecDropSingleTupleTableSlot(newslot);
    6535             :     }
    6536             : 
    6537        5468 :     FreeExecutorState(estate);
    6538             : 
    6539        5468 :     table_close(oldrel, NoLock);
    6540        5468 :     if (newrel)
    6541             :     {
    6542         940 :         FreeBulkInsertState(bistate);
    6543             : 
    6544         940 :         table_finish_bulk_insert(newrel, ti_options);
    6545             : 
    6546         940 :         table_close(newrel, NoLock);
    6547             :     }
    6548        5468 : }
    6549             : 
    6550             : /*
    6551             :  * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
    6552             :  */
    6553             : static AlteredTableInfo *
    6554       41510 : ATGetQueueEntry(List **wqueue, Relation rel)
    6555             : {
    6556       41510 :     Oid         relid = RelationGetRelid(rel);
    6557             :     AlteredTableInfo *tab;
    6558             :     ListCell   *ltab;
    6559             : 
    6560       51104 :     foreach(ltab, *wqueue)
    6561             :     {
    6562       14472 :         tab = (AlteredTableInfo *) lfirst(ltab);
    6563       14472 :         if (tab->relid == relid)
    6564        4878 :             return tab;
    6565             :     }
    6566             : 
    6567             :     /*
    6568             :      * Not there, so add it.  Note that we make a copy of the relation's
    6569             :      * existing descriptor before anything interesting can happen to it.
    6570             :      */
    6571       36632 :     tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
    6572       36632 :     tab->relid = relid;
    6573       36632 :     tab->rel = NULL;         /* set later */
    6574       36632 :     tab->relkind = rel->rd_rel->relkind;
    6575       36632 :     tab->oldDesc = CreateTupleDescCopyConstr(RelationGetDescr(rel));
    6576       36632 :     tab->newAccessMethod = InvalidOid;
    6577       36632 :     tab->chgAccessMethod = false;
    6578       36632 :     tab->newTableSpace = InvalidOid;
    6579       36632 :     tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
    6580       36632 :     tab->chgPersistence = false;
    6581             : 
    6582       36632 :     *wqueue = lappend(*wqueue, tab);
    6583             : 
    6584       36632 :     return tab;
    6585             : }
    6586             : 
    6587             : static const char *
    6588          80 : alter_table_type_to_string(AlterTableType cmdtype)
    6589             : {
    6590          80 :     switch (cmdtype)
    6591             :     {
    6592           0 :         case AT_AddColumn:
    6593             :         case AT_AddColumnToView:
    6594           0 :             return "ADD COLUMN";
    6595           0 :         case AT_ColumnDefault:
    6596             :         case AT_CookedColumnDefault:
    6597           0 :             return "ALTER COLUMN ... SET DEFAULT";
    6598           6 :         case AT_DropNotNull:
    6599           6 :             return "ALTER COLUMN ... DROP NOT NULL";
    6600           6 :         case AT_SetNotNull:
    6601           6 :             return "ALTER COLUMN ... SET NOT NULL";
    6602           0 :         case AT_SetExpression:
    6603           0 :             return "ALTER COLUMN ... SET EXPRESSION";
    6604           0 :         case AT_DropExpression:
    6605           0 :             return "ALTER COLUMN ... DROP EXPRESSION";
    6606           0 :         case AT_SetStatistics:
    6607           0 :             return "ALTER COLUMN ... SET STATISTICS";
    6608          12 :         case AT_SetOptions:
    6609          12 :             return "ALTER COLUMN ... SET";
    6610           0 :         case AT_ResetOptions:
    6611           0 :             return "ALTER COLUMN ... RESET";
    6612           0 :         case AT_SetStorage:
    6613           0 :             return "ALTER COLUMN ... SET STORAGE";
    6614           0 :         case AT_SetCompression:
    6615           0 :             return "ALTER COLUMN ... SET COMPRESSION";
    6616           6 :         case AT_DropColumn:
    6617           6 :             return "DROP COLUMN";
    6618           0 :         case AT_AddIndex:
    6619             :         case AT_ReAddIndex:
    6620           0 :             return NULL;        /* not real grammar */
    6621           0 :         case AT_AddConstraint:
    6622             :         case AT_ReAddConstraint:
    6623             :         case AT_ReAddDomainConstraint:
    6624             :         case AT_AddIndexConstraint:
    6625           0 :             return "ADD CONSTRAINT";
    6626           6 :         case AT_AlterConstraint:
    6627           6 :             return "ALTER CONSTRAINT";
    6628           0 :         case AT_ValidateConstraint:
    6629           0 :             return "VALIDATE CONSTRAINT";
    6630           0 :         case AT_DropConstraint:
    6631           0 :             return "DROP CONSTRAINT";
    6632           0 :         case AT_ReAddComment:
    6633           0 :             return NULL;        /* not real grammar */
    6634           0 :         case AT_AlterColumnType:
    6635           0 :             return "ALTER COLUMN ... SET DATA TYPE";
    6636           0 :         case AT_AlterColumnGenericOptions:
    6637           0 :             return "ALTER COLUMN ... OPTIONS";
    6638           0 :         case AT_ChangeOwner:
    6639           0 :             return "OWNER TO";
    6640           0 :         case AT_ClusterOn:
    6641           0 :             return "CLUSTER ON";
    6642           0 :         case AT_DropCluster:
    6643           0 :             return "SET WITHOUT CLUSTER";
    6644           0 :         case AT_SetAccessMethod:
    6645           0 :             return "SET ACCESS METHOD";
    6646           6 :         case AT_SetLogged:
    6647           6 :             return "SET LOGGED";
    6648           6 :         case AT_SetUnLogged:
    6649           6 :             return "SET UNLOGGED";
    6650           0 :         case AT_DropOids:
    6651           0 :             return "SET WITHOUT OIDS";
    6652           0 :         case AT_SetTableSpace:
    6653           0 :             return "SET TABLESPACE";
    6654           2 :         case AT_SetRelOptions:
    6655           2 :             return "SET";
    6656           0 :         case AT_ResetRelOptions:
    6657           0 :             return "RESET";
    6658           0 :         case AT_ReplaceRelOptions:
    6659           0 :             return NULL;        /* not real grammar */
    6660           0 :         case AT_EnableTrig:
    6661           0 :             return "ENABLE TRIGGER";
    6662           0 :         case AT_EnableAlwaysTrig:
    6663           0 :             return "ENABLE ALWAYS TRIGGER";
    6664           0 :         case AT_EnableReplicaTrig:
    6665           0 :             return "ENABLE REPLICA TRIGGER";
    6666           0 :         case AT_DisableTrig:
    6667           0 :             return "DISABLE TRIGGER";
    6668           0 :         case AT_EnableTrigAll:
    6669           0 :             return "ENABLE TRIGGER ALL";
    6670           0 :         case AT_DisableTrigAll:
    6671           0 :             return "DISABLE TRIGGER ALL";
    6672           0 :         case AT_EnableTrigUser:
    6673           0 :             return "ENABLE TRIGGER USER";
    6674           0 :         case AT_DisableTrigUser:
    6675           0 :             return "DISABLE TRIGGER USER";
    6676           0 :         case AT_EnableRule:
    6677           0 :             return "ENABLE RULE";
    6678           0 :         case AT_EnableAlwaysRule:
    6679           0 :             return "ENABLE ALWAYS RULE";
    6680           0 :         case AT_EnableReplicaRule:
    6681           0 :             return "ENABLE REPLICA RULE";
    6682           0 :         case AT_DisableRule:
    6683           0 :             return "DISABLE RULE";
    6684           0 :         case AT_AddInherit:
    6685           0 :             return "INHERIT";
    6686           0 :         case AT_DropInherit:
    6687           0 :             return "NO INHERIT";
    6688           0 :         case AT_AddOf:
    6689           0 :             return "OF";
    6690           0 :         case AT_DropOf:
    6691           0 :             return "NOT OF";
    6692           0 :         case AT_ReplicaIdentity:
    6693           0 :             return "REPLICA IDENTITY";
    6694           0 :         case AT_EnableRowSecurity:
    6695           0 :             return "ENABLE ROW SECURITY";
    6696           0 :         case AT_DisableRowSecurity:
    6697           0 :             return "DISABLE ROW SECURITY";
    6698           0 :         case AT_ForceRowSecurity:
    6699           0 :             return "FORCE ROW SECURITY";
    6700           0 :         case AT_NoForceRowSecurity:
    6701           0 :             return "NO FORCE ROW SECURITY";
    6702           0 :         case AT_GenericOptions:
    6703           0 :             return "OPTIONS";
    6704           6 :         case AT_AttachPartition:
    6705           6 :             return "ATTACH PARTITION";
    6706          18 :         case AT_DetachPartition:
    6707          18 :             return "DETACH PARTITION";
    6708           6 :         case AT_DetachPartitionFinalize:
    6709           6 :             return "DETACH PARTITION ... FINALIZE";
    6710           0 :         case AT_AddIdentity:
    6711           0 :             return "ALTER COLUMN ... ADD IDENTITY";
    6712           0 :         case AT_SetIdentity:
    6713           0 :             return "ALTER COLUMN ... SET";
    6714           0 :         case AT_DropIdentity:
    6715           0 :             return "ALTER COLUMN ... DROP IDENTITY";
    6716           0 :         case AT_ReAddStatistics:
    6717           0 :             return NULL;        /* not real grammar */
    6718             :     }
    6719             : 
    6720           0 :     return NULL;
    6721             : }
    6722             : 
    6723             : /*
    6724             :  * ATSimplePermissions
    6725             :  *
    6726             :  * - Ensure that it is a relation (or possibly a view)
    6727             :  * - Ensure this user is the owner
    6728             :  * - Ensure that it is not a system table
    6729             :  */
    6730             : static void
    6731       37916 : ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
    6732             : {
    6733             :     int         actual_target;
    6734             : 
    6735       37916 :     switch (rel->rd_rel->relkind)
    6736             :     {
    6737       29992 :         case RELKIND_RELATION:
    6738       29992 :             actual_target = ATT_TABLE;
    6739       29992 :             break;
    6740        5652 :         case RELKIND_PARTITIONED_TABLE:
    6741        5652 :             actual_target = ATT_PARTITIONED_TABLE;
    6742        5652 :             break;
    6743         402 :         case RELKIND_VIEW:
    6744         402 :             actual_target = ATT_VIEW;
    6745         402 :             break;
    6746          46 :         case RELKIND_MATVIEW:
    6747          46 :             actual_target = ATT_MATVIEW;
    6748          46 :             break;
    6749         228 :         case RELKIND_INDEX:
    6750         228 :             actual_target = ATT_INDEX;
    6751         228 :             break;
    6752         422 :         case RELKIND_PARTITIONED_INDEX:
    6753         422 :             actual_target = ATT_PARTITIONED_INDEX;
    6754         422 :             break;
    6755         216 :         case RELKIND_COMPOSITE_TYPE:
    6756         216 :             actual_target = ATT_COMPOSITE_TYPE;
    6757         216 :             break;
    6758         932 :         case RELKIND_FOREIGN_TABLE:
    6759         932 :             actual_target = ATT_FOREIGN_TABLE;
    6760         932 :             break;
    6761          24 :         case RELKIND_SEQUENCE:
    6762          24 :             actual_target = ATT_SEQUENCE;
    6763          24 :             break;
    6764           2 :         default:
    6765           2 :             actual_target = 0;
    6766           2 :             break;
    6767             :     }
    6768             : 
    6769             :     /* Wrong target type? */
    6770       37916 :     if ((actual_target & allowed_targets) == 0)
    6771             :     {
    6772          80 :         const char *action_str = alter_table_type_to_string(cmdtype);
    6773             : 
    6774          80 :         if (action_str)
    6775          80 :             ereport(ERROR,
    6776             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    6777             :             /* translator: %s is a group of some SQL keywords */
    6778             :                      errmsg("ALTER action %s cannot be performed on relation \"%s\"",
    6779             :                             action_str, RelationGetRelationName(rel)),
    6780             :                      errdetail_relkind_not_supported(rel->rd_rel->relkind)));
    6781             :         else
    6782             :             /* internal error? */
    6783           0 :             elog(ERROR, "invalid ALTER action attempted on relation \"%s\"",
    6784             :                  RelationGetRelationName(rel));
    6785             :     }
    6786             : 
    6787             :     /* Permissions checks */
    6788       37836 :     if (!object_ownercheck(RelationRelationId, RelationGetRelid(rel), GetUserId()))
    6789          12 :         aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
    6790          12 :                        RelationGetRelationName(rel));
    6791             : 
    6792       37824 :     if (!allowSystemTableMods && IsSystemRelation(rel))
    6793           0 :         ereport(ERROR,
    6794             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    6795             :                  errmsg("permission denied: \"%s\" is a system catalog",
    6796             :                         RelationGetRelationName(rel))));
    6797       37824 : }
    6798             : 
    6799             : /*
    6800             :  * ATSimpleRecursion
    6801             :  *
    6802             :  * Simple table recursion sufficient for most ALTER TABLE operations.
    6803             :  * All direct and indirect children are processed in an unspecified order.
    6804             :  * Note that if a child inherits from the original table via multiple
    6805             :  * inheritance paths, it will be visited just once.
    6806             :  */
    6807             : static void
    6808        1346 : ATSimpleRecursion(List **wqueue, Relation rel,
    6809             :                   AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
    6810             :                   AlterTableUtilityContext *context)
    6811             : {
    6812             :     /*
    6813             :      * Propagate to children, if desired and if there are (or might be) any
    6814             :      * children.
    6815             :      */
    6816        1346 :     if (recurse && rel->rd_rel->relhassubclass)
    6817             :     {
    6818          84 :         Oid         relid = RelationGetRelid(rel);
    6819             :         ListCell   *child;
    6820             :         List       *children;
    6821             : 
    6822          84 :         children = find_all_inheritors(relid, lockmode, NULL);
    6823             : 
    6824             :         /*
    6825             :          * find_all_inheritors does the recursive search of the inheritance
    6826             :          * hierarchy, so all we have to do is process all of the relids in the
    6827             :          * list that it returns.
    6828             :          */
    6829         366 :         foreach(child, children)
    6830             :         {
    6831         282 :             Oid         childrelid = lfirst_oid(child);
    6832             :             Relation    childrel;
    6833             : 
    6834         282 :             if (childrelid == relid)
    6835          84 :                 continue;
    6836             :             /* find_all_inheritors already got lock */
    6837         198 :             childrel = relation_open(childrelid, NoLock);
    6838         198 :             CheckAlterTableIsSafe(childrel);
    6839         198 :             ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
    6840         198 :             relation_close(childrel, NoLock);
    6841             :         }
    6842             :     }
    6843        1346 : }
    6844             : 
    6845             : /*
    6846             :  * Obtain list of partitions of the given table, locking them all at the given
    6847             :  * lockmode and ensuring that they all pass CheckAlterTableIsSafe.
    6848             :  *
    6849             :  * This function is a no-op if the given relation is not a partitioned table;
    6850             :  * in particular, nothing is done if it's a legacy inheritance parent.
    6851             :  */
    6852             : static void
    6853         818 : ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode)
    6854             : {
    6855         818 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    6856             :     {
    6857             :         List       *inh;
    6858             :         ListCell   *cell;
    6859             : 
    6860         176 :         inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
    6861             :         /* first element is the parent rel; must ignore it */
    6862         574 :         for_each_from(cell, inh, 1)
    6863             :         {
    6864             :             Relation    childrel;
    6865             : 
    6866             :             /* find_all_inheritors already got lock */
    6867         404 :             childrel = table_open(lfirst_oid(cell), NoLock);
    6868         404 :             CheckAlterTableIsSafe(childrel);
    6869         398 :             table_close(childrel, NoLock);
    6870             :         }
    6871         170 :         list_free(inh);
    6872             :     }
    6873         812 : }
    6874             : 
    6875             : /*
    6876             :  * ATTypedTableRecursion
    6877             :  *
    6878             :  * Propagate ALTER TYPE operations to the typed tables of that type.
    6879             :  * Also check the RESTRICT/CASCADE behavior.  Given CASCADE, also permit
    6880             :  * recursion to inheritance children of the typed tables.
    6881             :  */
    6882             : static void
    6883         192 : ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
    6884             :                       LOCKMODE lockmode, AlterTableUtilityContext *context)
    6885             : {
    6886             :     ListCell   *child;
    6887             :     List       *children;
    6888             : 
    6889             :     Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
    6890             : 
    6891         192 :     children = find_typed_table_dependencies(rel->rd_rel->reltype,
    6892         192 :                                              RelationGetRelationName(rel),
    6893             :                                              cmd->behavior);
    6894             : 
    6895         204 :     foreach(child, children)
    6896             :     {
    6897          30 :         Oid         childrelid = lfirst_oid(child);
    6898             :         Relation    childrel;
    6899             : 
    6900          30 :         childrel = relation_open(childrelid, lockmode);
    6901          30 :         CheckAlterTableIsSafe(childrel);
    6902          30 :         ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode, context);
    6903          30 :         relation_close(childrel, NoLock);
    6904             :     }
    6905         174 : }
    6906             : 
    6907             : 
    6908             : /*
    6909             :  * find_composite_type_dependencies
    6910             :  *
    6911             :  * Check to see if the type "typeOid" is being used as a column in some table
    6912             :  * (possibly nested several levels deep in composite types, arrays, etc!).
    6913             :  * Eventually, we'd like to propagate the check or rewrite operation
    6914             :  * into such tables, but for now, just error out if we find any.
    6915             :  *
    6916             :  * Caller should provide either the associated relation of a rowtype,
    6917             :  * or a type name (not both) for use in the error message, if any.
    6918             :  *
    6919             :  * Note that "typeOid" is not necessarily a composite type; it could also be
    6920             :  * another container type such as an array or range, or a domain over one of
    6921             :  * these things.  The name of this function is therefore somewhat historical,
    6922             :  * but it's not worth changing.
    6923             :  *
    6924             :  * We assume that functions and views depending on the type are not reasons
    6925             :  * to reject the ALTER.  (How safe is this really?)
    6926             :  */
    6927             : void
    6928        4550 : find_composite_type_dependencies(Oid typeOid, Relation origRelation,
    6929             :                                  const char *origTypeName)
    6930             : {
    6931             :     Relation    depRel;
    6932             :     ScanKeyData key[2];
    6933             :     SysScanDesc depScan;
    6934             :     HeapTuple   depTup;
    6935             : 
    6936             :     /* since this function recurses, it could be driven to stack overflow */
    6937        4550 :     check_stack_depth();
    6938             : 
    6939             :     /*
    6940             :      * We scan pg_depend to find those things that depend on the given type.
    6941             :      * (We assume we can ignore refobjsubid for a type.)
    6942             :      */
    6943        4550 :     depRel = table_open(DependRelationId, AccessShareLock);
    6944             : 
    6945        4550 :     ScanKeyInit(&key[0],
    6946             :                 Anum_pg_depend_refclassid,
    6947             :                 BTEqualStrategyNumber, F_OIDEQ,
    6948             :                 ObjectIdGetDatum(TypeRelationId));
    6949        4550 :     ScanKeyInit(&key[1],
    6950             :                 Anum_pg_depend_refobjid,
    6951             :                 BTEqualStrategyNumber, F_OIDEQ,
    6952             :                 ObjectIdGetDatum(typeOid));
    6953             : 
    6954        4550 :     depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
    6955             :                                  NULL, 2, key);
    6956             : 
    6957        6992 :     while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
    6958             :     {
    6959        2598 :         Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
    6960             :         Relation    rel;
    6961             :         TupleDesc   tupleDesc;
    6962             :         Form_pg_attribute att;
    6963             : 
    6964             :         /* Check for directly dependent types */
    6965        2598 :         if (pg_depend->classid == TypeRelationId)
    6966             :         {
    6967             :             /*
    6968             :              * This must be an array, domain, or range containing the given
    6969             :              * type, so recursively check for uses of this type.  Note that
    6970             :              * any error message will mention the original type not the
    6971             :              * container; this is intentional.
    6972             :              */
    6973        2192 :             find_composite_type_dependencies(pg_depend->objid,
    6974             :                                              origRelation, origTypeName);
    6975        2168 :             continue;
    6976             :         }
    6977             : 
    6978             :         /* Else, ignore dependees that aren't relations */
    6979         406 :         if (pg_depend->classid != RelationRelationId)
    6980         122 :             continue;
    6981             : 
    6982         284 :         rel = relation_open(pg_depend->objid, AccessShareLock);
    6983         284 :         tupleDesc = RelationGetDescr(rel);
    6984             : 
    6985             :         /*
    6986             :          * If objsubid identifies a specific column, refer to that in error
    6987             :          * messages.  Otherwise, search to see if there's a user column of the
    6988             :          * type.  (We assume system columns are never of interesting types.)
    6989             :          * The search is needed because an index containing an expression
    6990             :          * column of the target type will just be recorded as a whole-relation
    6991             :          * dependency.  If we do not find a column of the type, the dependency
    6992             :          * must indicate that the type is transiently referenced in an index
    6993             :          * expression but not stored on disk, which we assume is OK, just as
    6994             :          * we do for references in views.  (It could also be that the target
    6995             :          * type is embedded in some container type that is stored in an index
    6996             :          * column, but the previous recursion should catch such cases.)
    6997             :          */
    6998         284 :         if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
    6999         126 :             att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
    7000             :         else
    7001             :         {
    7002         158 :             att = NULL;
    7003         406 :             for (int attno = 1; attno <= tupleDesc->natts; attno++)
    7004             :             {
    7005         254 :                 att = TupleDescAttr(tupleDesc, attno - 1);
    7006         254 :                 if (att->atttypid == typeOid && !att->attisdropped)
    7007           6 :                     break;
    7008         248 :                 att = NULL;
    7009             :             }
    7010         158 :             if (att == NULL)
    7011             :             {
    7012             :                 /* No such column, so assume OK */
    7013         152 :                 relation_close(rel, AccessShareLock);
    7014         152 :                 continue;
    7015             :             }
    7016             :         }
    7017             : 
    7018             :         /*
    7019             :          * We definitely should reject if the relation has storage.  If it's
    7020             :          * partitioned, then perhaps we don't have to reject: if there are
    7021             :          * partitions then we'll fail when we find one, else there is no
    7022             :          * stored data to worry about.  However, it's possible that the type
    7023             :          * change would affect conclusions about whether the type is sortable
    7024             :          * or hashable and thus (if it's a partitioning column) break the
    7025             :          * partitioning rule.  For now, reject for partitioned rels too.
    7026             :          */
    7027         132 :         if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
    7028           0 :             RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
    7029             :         {
    7030         132 :             if (origTypeName)
    7031          30 :                 ereport(ERROR,
    7032             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7033             :                          errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
    7034             :                                 origTypeName,
    7035             :                                 RelationGetRelationName(rel),
    7036             :                                 NameStr(att->attname))));
    7037         102 :             else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
    7038          18 :                 ereport(ERROR,
    7039             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7040             :                          errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
    7041             :                                 RelationGetRelationName(origRelation),
    7042             :                                 RelationGetRelationName(rel),
    7043             :                                 NameStr(att->attname))));
    7044          84 :             else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    7045           6 :                 ereport(ERROR,
    7046             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7047             :                          errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
    7048             :                                 RelationGetRelationName(origRelation),
    7049             :                                 RelationGetRelationName(rel),
    7050             :                                 NameStr(att->attname))));
    7051             :             else
    7052          78 :                 ereport(ERROR,
    7053             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7054             :                          errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
    7055             :                                 RelationGetRelationName(origRelation),
    7056             :                                 RelationGetRelationName(rel),
    7057             :                                 NameStr(att->attname))));
    7058             :         }
    7059           0 :         else if (OidIsValid(rel->rd_rel->reltype))
    7060             :         {
    7061             :             /*
    7062             :              * A view or composite type itself isn't a problem, but we must
    7063             :              * recursively check for indirect dependencies via its rowtype.
    7064             :              */
    7065           0 :             find_composite_type_dependencies(rel->rd_rel->reltype,
    7066             :                                              origRelation, origTypeName);
    7067             :         }
    7068             : 
    7069           0 :         relation_close(rel, AccessShareLock);
    7070             :     }
    7071             : 
    7072        4394 :     systable_endscan(depScan);
    7073             : 
    7074        4394 :     relation_close(depRel, AccessShareLock);
    7075        4394 : }
    7076             : 
    7077             : 
    7078             : /*
    7079             :  * find_typed_table_dependencies
    7080             :  *
    7081             :  * Check to see if a composite type is being used as the type of a
    7082             :  * typed table.  Abort if any are found and behavior is RESTRICT.
    7083             :  * Else return the list of tables.
    7084             :  */
    7085             : static List *
    7086         216 : find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
    7087             : {
    7088             :     Relation    classRel;
    7089             :     ScanKeyData key[1];
    7090             :     TableScanDesc scan;
    7091             :     HeapTuple   tuple;
    7092         216 :     List       *result = NIL;
    7093             : 
    7094         216 :     classRel = table_open(RelationRelationId, AccessShareLock);
    7095             : 
    7096         216 :     ScanKeyInit(&key[0],
    7097             :                 Anum_pg_class_reloftype,
    7098             :                 BTEqualStrategyNumber, F_OIDEQ,
    7099             :                 ObjectIdGetDatum(typeOid));
    7100             : 
    7101         216 :     scan = table_beginscan_catalog(classRel, 1, key);
    7102             : 
    7103         252 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
    7104             :     {
    7105          60 :         Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
    7106             : 
    7107          60 :         if (behavior == DROP_RESTRICT)
    7108          24 :             ereport(ERROR,
    7109             :                     (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
    7110             :                      errmsg("cannot alter type \"%s\" because it is the type of a typed table",
    7111             :                             typeName),
    7112             :                      errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
    7113             :         else
    7114          36 :             result = lappend_oid(result, classform->oid);
    7115             :     }
    7116             : 
    7117         192 :     table_endscan(scan);
    7118         192 :     table_close(classRel, AccessShareLock);
    7119             : 
    7120         192 :     return result;
    7121             : }
    7122             : 
    7123             : 
    7124             : /*
    7125             :  * check_of_type
    7126             :  *
    7127             :  * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF.  If it
    7128             :  * isn't suitable, throw an error.  Currently, we require that the type
    7129             :  * originated with CREATE TYPE AS.  We could support any row type, but doing so
    7130             :  * would require handling a number of extra corner cases in the DDL commands.
    7131             :  * (Also, allowing domain-over-composite would open up a can of worms about
    7132             :  * whether and how the domain's constraints should apply to derived tables.)
    7133             :  */
    7134             : void
    7135         182 : check_of_type(HeapTuple typetuple)
    7136             : {
    7137         182 :     Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
    7138         182 :     bool        typeOk = false;
    7139             : 
    7140         182 :     if (typ->typtype == TYPTYPE_COMPOSITE)
    7141             :     {
    7142             :         Relation    typeRelation;
    7143             : 
    7144             :         Assert(OidIsValid(typ->typrelid));
    7145         176 :         typeRelation = relation_open(typ->typrelid, AccessShareLock);
    7146         176 :         typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
    7147             : 
    7148             :         /*
    7149             :          * Close the parent rel, but keep our AccessShareLock on it until xact
    7150             :          * commit.  That will prevent someone else from deleting or ALTERing
    7151             :          * the type before the typed table creation/conversion commits.
    7152             :          */
    7153         176 :         relation_close(typeRelation, NoLock);
    7154             : 
    7155         176 :         if (!typeOk)
    7156           6 :             ereport(ERROR,
    7157             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    7158             :                      errmsg("type %s is the row type of another table",
    7159             :                             format_type_be(typ->oid)),
    7160             :                      errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
    7161             :     }
    7162             :     else
    7163           6 :         ereport(ERROR,
    7164             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    7165             :                  errmsg("type %s is not a composite type",
    7166             :                         format_type_be(typ->oid))));
    7167         170 : }
    7168             : 
    7169             : 
    7170             : /*
    7171             :  * ALTER TABLE ADD COLUMN
    7172             :  *
    7173             :  * Adds an additional attribute to a relation making the assumption that
    7174             :  * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
    7175             :  * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
    7176             :  * AlterTableCmd's.
    7177             :  *
    7178             :  * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
    7179             :  * have to decide at runtime whether to recurse or not depending on whether we
    7180             :  * actually add a column or merely merge with an existing column.  (We can't
    7181             :  * check this in a static pre-pass because it won't handle multiple inheritance
    7182             :  * situations correctly.)
    7183             :  */
    7184             : static void
    7185        2214 : ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
    7186             :                 bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
    7187             :                 AlterTableUtilityContext *context)
    7188             : {
    7189        2214 :     if (rel->rd_rel->reloftype && !recursing)
    7190           6 :         ereport(ERROR,
    7191             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    7192             :                  errmsg("cannot add column to typed table")));
    7193             : 
    7194        2208 :     if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
    7195          58 :         ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
    7196             : 
    7197        2202 :     if (recurse && !is_view)
    7198        2102 :         cmd->recurse = true;
    7199        2202 : }
    7200             : 
    7201             : /*
    7202             :  * Add a column to a table.  The return value is the address of the
    7203             :  * new column in the parent relation.
    7204             :  *
    7205             :  * cmd is pass-by-ref so that we can replace it with the parse-transformed
    7206             :  * copy (but that happens only after we check for IF NOT EXISTS).
    7207             :  */
    7208             : static ObjectAddress
    7209        2934 : ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
    7210             :                 AlterTableCmd **cmd, bool recurse, bool recursing,
    7211             :                 LOCKMODE lockmode, AlterTablePass cur_pass,
    7212             :                 AlterTableUtilityContext *context)
    7213             : {
    7214        2934 :     Oid         myrelid = RelationGetRelid(rel);
    7215        2934 :     ColumnDef  *colDef = castNode(ColumnDef, (*cmd)->def);
    7216        2934 :     bool        if_not_exists = (*cmd)->missing_ok;
    7217             :     Relation    pgclass,
    7218             :                 attrdesc;
    7219             :     HeapTuple   reltup;
    7220             :     Form_pg_class relform;
    7221             :     Form_pg_attribute attribute;
    7222             :     int         newattnum;
    7223             :     char        relkind;
    7224             :     Expr       *defval;
    7225             :     List       *children;
    7226             :     ListCell   *child;
    7227             :     AlterTableCmd *childcmd;
    7228             :     ObjectAddress address;
    7229             :     TupleDesc   tupdesc;
    7230             : 
    7231             :     /* since this function recurses, it could be driven to stack overflow */
    7232        2934 :     check_stack_depth();
    7233             : 
    7234             :     /* At top level, permission check was done in ATPrepCmd, else do it */
    7235        2934 :     if (recursing)
    7236         738 :         ATSimplePermissions((*cmd)->subtype, rel,
    7237             :                             ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    7238             : 
    7239        2934 :     if (rel->rd_rel->relispartition && !recursing)
    7240          12 :         ereport(ERROR,
    7241             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    7242             :                  errmsg("cannot add column to a partition")));
    7243             : 
    7244        2922 :     attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
    7245             : 
    7246             :     /*
    7247             :      * Are we adding the column to a recursion child?  If so, check whether to
    7248             :      * merge with an existing definition for the column.  If we do merge, we
    7249             :      * must not recurse.  Children will already have the column, and recursing
    7250             :      * into them would mess up attinhcount.
    7251             :      */
    7252        2922 :     if (colDef->inhcount > 0)
    7253             :     {
    7254             :         HeapTuple   tuple;
    7255             : 
    7256             :         /* Does child already have a column by this name? */
    7257         738 :         tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
    7258         738 :         if (HeapTupleIsValid(tuple))
    7259             :         {
    7260          60 :             Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
    7261             :             Oid         ctypeId;
    7262             :             int32       ctypmod;
    7263             :             Oid         ccollid;
    7264             : 
    7265             :             /* Child column must match on type, typmod, and collation */
    7266          60 :             typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
    7267          60 :             if (ctypeId != childatt->atttypid ||
    7268          60 :                 ctypmod != childatt->atttypmod)
    7269           0 :                 ereport(ERROR,
    7270             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    7271             :                          errmsg("child table \"%s\" has different type for column \"%s\"",
    7272             :                                 RelationGetRelationName(rel), colDef->colname)));
    7273          60 :             ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
    7274          60 :             if (ccollid != childatt->attcollation)
    7275           0 :                 ereport(ERROR,
    7276             :                         (errcode(ERRCODE_COLLATION_MISMATCH),
    7277             :                          errmsg("child table \"%s\" has different collation for column \"%s\"",
    7278             :                                 RelationGetRelationName(rel), colDef->colname),
    7279             :                          errdetail("\"%s\" versus \"%s\"",
    7280             :                                    get_collation_name(ccollid),
    7281             :                                    get_collation_name(childatt->attcollation))));
    7282             : 
    7283             :             /* Bump the existing child att's inhcount */
    7284          60 :             if (pg_add_s16_overflow(childatt->attinhcount, 1,
    7285             :                                     &childatt->attinhcount))
    7286           0 :                 ereport(ERROR,
    7287             :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    7288             :                         errmsg("too many inheritance parents"));
    7289          60 :             CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
    7290             : 
    7291          60 :             heap_freetuple(tuple);
    7292             : 
    7293             :             /* Inform the user about the merge */
    7294          60 :             ereport(NOTICE,
    7295             :                     (errmsg("merging definition of column \"%s\" for child \"%s\"",
    7296             :                             colDef->colname, RelationGetRelationName(rel))));
    7297             : 
    7298          60 :             table_close(attrdesc, RowExclusiveLock);
    7299             : 
    7300             :             /* Make the child column change visible */
    7301          60 :             CommandCounterIncrement();
    7302             : 
    7303          60 :             return InvalidObjectAddress;
    7304             :         }
    7305             :     }
    7306             : 
    7307             :     /* skip if the name already exists and if_not_exists is true */
    7308        2862 :     if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
    7309             :     {
    7310          54 :         table_close(attrdesc, RowExclusiveLock);
    7311          54 :         return InvalidObjectAddress;
    7312             :     }
    7313             : 
    7314             :     /*
    7315             :      * Okay, we need to add the column, so go ahead and do parse
    7316             :      * transformation.  This can result in queueing up, or even immediately
    7317             :      * executing, subsidiary operations (such as creation of unique indexes);
    7318             :      * so we mustn't do it until we have made the if_not_exists check.
    7319             :      *
    7320             :      * When recursing, the command was already transformed and we needn't do
    7321             :      * so again.  Also, if context isn't given we can't transform.  (That
    7322             :      * currently happens only for AT_AddColumnToView; we expect that view.c
    7323             :      * passed us a ColumnDef that doesn't need work.)
    7324             :      */
    7325        2778 :     if (context != NULL && !recursing)
    7326             :     {
    7327        2076 :         *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
    7328             :                                    cur_pass, context);
    7329             :         Assert(*cmd != NULL);
    7330        2070 :         colDef = castNode(ColumnDef, (*cmd)->def);
    7331             :     }
    7332             : 
    7333             :     /*
    7334             :      * Regular inheritance children are independent enough not to inherit the
    7335             :      * identity column from parent hence cannot recursively add identity
    7336             :      * column if the table has inheritance children.
    7337             :      *
    7338             :      * Partitions, on the other hand, are integral part of a partitioned table
    7339             :      * and inherit identity column.  Hence propagate identity column down the
    7340             :      * partition hierarchy.
    7341             :      */
    7342        2772 :     if (colDef->identity &&
    7343          54 :         recurse &&
    7344         102 :         rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
    7345          48 :         find_inheritance_children(myrelid, NoLock) != NIL)
    7346           6 :         ereport(ERROR,
    7347             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    7348             :                  errmsg("cannot recursively add identity column to table that has child tables")));
    7349             : 
    7350        2766 :     pgclass = table_open(RelationRelationId, RowExclusiveLock);
    7351             : 
    7352        2766 :     reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
    7353        2766 :     if (!HeapTupleIsValid(reltup))
    7354           0 :         elog(ERROR, "cache lookup failed for relation %u", myrelid);
    7355        2766 :     relform = (Form_pg_class) GETSTRUCT(reltup);
    7356        2766 :     relkind = relform->relkind;
    7357             : 
    7358             :     /* Determine the new attribute's number */
    7359        2766 :     newattnum = relform->relnatts + 1;
    7360        2766 :     if (newattnum > MaxHeapAttributeNumber)
    7361           0 :         ereport(ERROR,
    7362             :                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
    7363             :                  errmsg("tables can have at most %d columns",
    7364             :                         MaxHeapAttributeNumber)));
    7365             : 
    7366             :     /*
    7367             :      * Construct new attribute's pg_attribute entry.
    7368             :      */
    7369        2766 :     tupdesc = BuildDescForRelation(list_make1(colDef));
    7370             : 
    7371        2754 :     attribute = TupleDescAttr(tupdesc, 0);
    7372             : 
    7373             :     /* Fix up attribute number */
    7374        2754 :     attribute->attnum = newattnum;
    7375             : 
    7376             :     /* make sure datatype is legal for a column */
    7377        5508 :     CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
    7378        2754 :                        list_make1_oid(rel->rd_rel->reltype),
    7379        2754 :                        (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
    7380             : 
    7381        2718 :     InsertPgAttributeTuples(attrdesc, tupdesc, myrelid, NULL, NULL);
    7382             : 
    7383        2718 :     table_close(attrdesc, RowExclusiveLock);
    7384             : 
    7385             :     /*
    7386             :      * Update pg_class tuple as appropriate
    7387             :      */
    7388        2718 :     relform->relnatts = newattnum;
    7389             : 
    7390        2718 :     CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
    7391             : 
    7392        2718 :     heap_freetuple(reltup);
    7393             : 
    7394             :     /* Post creation hook for new attribute */
    7395        2718 :     InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
    7396             : 
    7397        2718 :     table_close(pgclass, RowExclusiveLock);
    7398             : 
    7399             :     /* Make the attribute's catalog entry visible */
    7400        2718 :     CommandCounterIncrement();
    7401             : 
    7402             :     /*
    7403             :      * Store the DEFAULT, if any, in the catalogs
    7404             :      */
    7405        2718 :     if (colDef->raw_default)
    7406             :     {
    7407             :         RawColumnDefault *rawEnt;
    7408             : 
    7409         950 :         rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
    7410         950 :         rawEnt->attnum = attribute->attnum;
    7411         950 :         rawEnt->raw_default = copyObject(colDef->raw_default);
    7412         950 :         rawEnt->generated = colDef->generated;
    7413             : 
    7414             :         /*
    7415             :          * This function is intended for CREATE TABLE, so it processes a
    7416             :          * _list_ of defaults, but we just do one.
    7417             :          */
    7418         950 :         AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
    7419             :                                   false, true, false, NULL);
    7420             : 
    7421             :         /* Make the additional catalog changes visible */
    7422         926 :         CommandCounterIncrement();
    7423             :     }
    7424             : 
    7425             :     /*
    7426             :      * Tell Phase 3 to fill in the default expression, if there is one.
    7427             :      *
    7428             :      * If there is no default, Phase 3 doesn't have to do anything, because
    7429             :      * that effectively means that the default is NULL.  The heap tuple access
    7430             :      * routines always check for attnum > # of attributes in tuple, and return
    7431             :      * NULL if so, so without any modification of the tuple data we will get
    7432             :      * the effect of NULL values in the new column.
    7433             :      *
    7434             :      * An exception occurs when the new column is of a domain type: the domain
    7435             :      * might have a not-null constraint, or a check constraint that indirectly
    7436             :      * rejects nulls.  If there are any domain constraints then we construct
    7437             :      * an explicit NULL default value that will be passed through
    7438             :      * CoerceToDomain processing.  (This is a tad inefficient, since it causes
    7439             :      * rewriting the table which we really wouldn't have to do; but we do it
    7440             :      * to preserve the historical behavior that such a failure will be raised
    7441             :      * only if the table currently contains some rows.)
    7442             :      *
    7443             :      * Note: we use build_column_default, and not just the cooked default
    7444             :      * returned by AddRelationNewConstraints, so that the right thing happens
    7445             :      * when a datatype's default applies.
    7446             :      *
    7447             :      * Note: it might seem that this should happen at the end of Phase 2, so
    7448             :      * that the effects of subsequent subcommands can be taken into account.
    7449             :      * It's intentional that we do it now, though.  The new column should be
    7450             :      * filled according to what is said in the ADD COLUMN subcommand, so that
    7451             :      * the effects are the same as if this subcommand had been run by itself
    7452             :      * and the later subcommands had been issued in new ALTER TABLE commands.
    7453             :      *
    7454             :      * We can skip this entirely for relations without storage, since Phase 3
    7455             :      * is certainly not going to touch them.
    7456             :      */
    7457        2694 :     if (RELKIND_HAS_STORAGE(relkind))
    7458             :     {
    7459             :         bool        has_domain_constraints;
    7460        2318 :         bool        has_missing = false;
    7461             : 
    7462             :         /*
    7463             :          * For an identity column, we can't use build_column_default(),
    7464             :          * because the sequence ownership isn't set yet.  So do it manually.
    7465             :          */
    7466        2318 :         if (colDef->identity)
    7467             :         {
    7468          42 :             NextValueExpr *nve = makeNode(NextValueExpr);
    7469             : 
    7470          42 :             nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
    7471          42 :             nve->typeId = attribute->atttypid;
    7472             : 
    7473          42 :             defval = (Expr *) nve;
    7474             :         }
    7475             :         else
    7476        2276 :             defval = (Expr *) build_column_default(rel, attribute->attnum);
    7477             : 
    7478             :         /* Build CoerceToDomain(NULL) expression if needed */
    7479        2318 :         has_domain_constraints = DomainHasConstraints(attribute->atttypid);
    7480        2318 :         if (!defval && has_domain_constraints)
    7481             :         {
    7482             :             Oid         baseTypeId;
    7483             :             int32       baseTypeMod;
    7484             :             Oid         baseTypeColl;
    7485             : 
    7486           6 :             baseTypeMod = attribute->atttypmod;
    7487           6 :             baseTypeId = getBaseTypeAndTypmod(attribute->atttypid, &baseTypeMod);
    7488           6 :             baseTypeColl = get_typcollation(baseTypeId);
    7489           6 :             defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
    7490           6 :             defval = (Expr *) coerce_to_target_type(NULL,
    7491             :                                                     (Node *) defval,
    7492             :                                                     baseTypeId,
    7493             :                                                     attribute->atttypid,
    7494             :                                                     attribute->atttypmod,
    7495             :                                                     COERCION_ASSIGNMENT,
    7496             :                                                     COERCE_IMPLICIT_CAST,
    7497             :                                                     -1);
    7498           6 :             if (defval == NULL) /* should not happen */
    7499           0 :                 elog(ERROR, "failed to coerce base type to domain");
    7500             :         }
    7501             : 
    7502        2318 :         if (defval)
    7503             :         {
    7504             :             NewColumnValue *newval;
    7505             : 
    7506             :             /* Prepare defval for execution, either here or in Phase 3 */
    7507         822 :             defval = expression_planner(defval);
    7508             : 
    7509             :             /* Add the new default to the newvals list */
    7510         822 :             newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
    7511         822 :             newval->attnum = attribute->attnum;
    7512         822 :             newval->expr = defval;
    7513         822 :             newval->is_generated = (colDef->generated != '\0');
    7514             : 
    7515         822 :             tab->newvals = lappend(tab->newvals, newval);
    7516             : 
    7517             :             /*
    7518             :              * Attempt to skip a complete table rewrite by storing the
    7519             :              * specified DEFAULT value outside of the heap.  This is only
    7520             :              * allowed for plain relations and non-generated columns, and the
    7521             :              * default expression can't be volatile (stable is OK).  Note that
    7522             :              * contain_volatile_functions deems CoerceToDomain immutable, but
    7523             :              * here we consider that coercion to a domain with constraints is
    7524             :              * volatile; else it might fail even when the table is empty.
    7525             :              */
    7526         822 :             if (rel->rd_rel->relkind == RELKIND_RELATION &&
    7527         822 :                 !colDef->generated &&
    7528         694 :                 !has_domain_constraints &&
    7529         682 :                 !contain_volatile_functions((Node *) defval))
    7530         514 :             {
    7531             :                 EState     *estate;
    7532             :                 ExprState  *exprState;
    7533             :                 Datum       missingval;
    7534             :                 bool        missingIsNull;
    7535             : 
    7536             :                 /* Evaluate the default expression */
    7537         514 :                 estate = CreateExecutorState();
    7538         514 :                 exprState = ExecPrepareExpr(defval, estate);
    7539         514 :                 missingval = ExecEvalExpr(exprState,
    7540         514 :                                           GetPerTupleExprContext(estate),
    7541             :                                           &missingIsNull);
    7542             :                 /* If it turns out NULL, nothing to do; else store it */
    7543         514 :                 if (!missingIsNull)
    7544             :                 {
    7545         514 :                     StoreAttrMissingVal(rel, attribute->attnum, missingval);
    7546             :                     /* Make the additional catalog change visible */
    7547         514 :                     CommandCounterIncrement();
    7548         514 :                     has_missing = true;
    7549             :                 }
    7550         514 :                 FreeExecutorState(estate);
    7551             :             }
    7552             :             else
    7553             :             {
    7554             :                 /*
    7555             :                  * Failed to use missing mode.  We have to do a table rewrite
    7556             :                  * to install the value --- unless it's a virtual generated
    7557             :                  * column.
    7558             :                  */
    7559         308 :                 if (colDef->generated != ATTRIBUTE_GENERATED_VIRTUAL)
    7560         216 :                     tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
    7561             :             }
    7562             :         }
    7563             : 
    7564        2318 :         if (!has_missing)
    7565             :         {
    7566             :             /*
    7567             :              * If the new column is NOT NULL, and there is no missing value,
    7568             :              * tell Phase 3 it needs to check for NULLs.
    7569             :              */
    7570        1804 :             tab->verify_new_notnull |= colDef->is_not_null;
    7571             :         }
    7572             :     }
    7573             : 
    7574             :     /*
    7575             :      * Add needed dependency entries for the new column.
    7576             :      */
    7577        2694 :     add_column_datatype_dependency(myrelid, newattnum, attribute->atttypid);
    7578        2694 :     add_column_collation_dependency(myrelid, newattnum, attribute->attcollation);
    7579             : 
    7580             :     /*
    7581             :      * Propagate to children as appropriate.  Unlike most other ALTER
    7582             :      * routines, we have to do this one level of recursion at a time; we can't
    7583             :      * use find_all_inheritors to do it in one pass.
    7584             :      */
    7585             :     children =
    7586        2694 :         find_inheritance_children(RelationGetRelid(rel), lockmode);
    7587             : 
    7588             :     /*
    7589             :      * If we are told not to recurse, there had better not be any child
    7590             :      * tables; else the addition would put them out of step.
    7591             :      */
    7592        2694 :     if (children && !recurse)
    7593          12 :         ereport(ERROR,
    7594             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    7595             :                  errmsg("column must be added to child tables too")));
    7596             : 
    7597             :     /* Children should see column as singly inherited */
    7598        2682 :     if (!recursing)
    7599             :     {
    7600        2004 :         childcmd = copyObject(*cmd);
    7601        2004 :         colDef = castNode(ColumnDef, childcmd->def);
    7602        2004 :         colDef->inhcount = 1;
    7603        2004 :         colDef->is_local = false;
    7604             :     }
    7605             :     else
    7606         678 :         childcmd = *cmd;        /* no need to copy again */
    7607             : 
    7608        3420 :     foreach(child, children)
    7609             :     {
    7610         738 :         Oid         childrelid = lfirst_oid(child);
    7611             :         Relation    childrel;
    7612             :         AlteredTableInfo *childtab;
    7613             : 
    7614             :         /* find_inheritance_children already got lock */
    7615         738 :         childrel = table_open(childrelid, NoLock);
    7616         738 :         CheckAlterTableIsSafe(childrel);
    7617             : 
    7618             :         /* Find or create work queue entry for this table */
    7619         738 :         childtab = ATGetQueueEntry(wqueue, childrel);
    7620             : 
    7621             :         /* Recurse to child; return value is ignored */
    7622         738 :         ATExecAddColumn(wqueue, childtab, childrel,
    7623             :                         &childcmd, recurse, true,
    7624             :                         lockmode, cur_pass, context);
    7625             : 
    7626         738 :         table_close(childrel, NoLock);
    7627             :     }
    7628             : 
    7629        2682 :     ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
    7630        2682 :     return address;
    7631             : }
    7632             : 
    7633             : /*
    7634             :  * If a new or renamed column will collide with the name of an existing
    7635             :  * column and if_not_exists is false then error out, else do nothing.
    7636             :  */
    7637             : static bool
    7638        3312 : check_for_column_name_collision(Relation rel, const char *colname,
    7639             :                                 bool if_not_exists)
    7640             : {
    7641             :     HeapTuple   attTuple;
    7642             :     int         attnum;
    7643             : 
    7644             :     /*
    7645             :      * this test is deliberately not attisdropped-aware, since if one tries to
    7646             :      * add a column matching a dropped column name, it's gonna fail anyway.
    7647             :      */
    7648        3312 :     attTuple = SearchSysCache2(ATTNAME,
    7649             :                                ObjectIdGetDatum(RelationGetRelid(rel)),
    7650             :                                PointerGetDatum(colname));
    7651        3312 :     if (!HeapTupleIsValid(attTuple))
    7652        3216 :         return true;
    7653             : 
    7654          96 :     attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
    7655          96 :     ReleaseSysCache(attTuple);
    7656             : 
    7657             :     /*
    7658             :      * We throw a different error message for conflicts with system column
    7659             :      * names, since they are normally not shown and the user might otherwise
    7660             :      * be confused about the reason for the conflict.
    7661             :      */
    7662          96 :     if (attnum <= 0)
    7663          12 :         ereport(ERROR,
    7664             :                 (errcode(ERRCODE_DUPLICATE_COLUMN),
    7665             :                  errmsg("column name \"%s\" conflicts with a system column name",
    7666             :                         colname)));
    7667             :     else
    7668             :     {
    7669          84 :         if (if_not_exists)
    7670             :         {
    7671          54 :             ereport(NOTICE,
    7672             :                     (errcode(ERRCODE_DUPLICATE_COLUMN),
    7673             :                      errmsg("column \"%s\" of relation \"%s\" already exists, skipping",
    7674             :                             colname, RelationGetRelationName(rel))));
    7675          54 :             return false;
    7676             :         }
    7677             : 
    7678          30 :         ereport(ERROR,
    7679             :                 (errcode(ERRCODE_DUPLICATE_COLUMN),
    7680             :                  errmsg("column \"%s\" of relation \"%s\" already exists",
    7681             :                         colname, RelationGetRelationName(rel))));
    7682             :     }
    7683             : 
    7684             :     return true;
    7685             : }
    7686             : 
    7687             : /*
    7688             :  * Install a column's dependency on its datatype.
    7689             :  */
    7690             : static void
    7691        3730 : add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
    7692             : {
    7693             :     ObjectAddress myself,
    7694             :                 referenced;
    7695             : 
    7696        3730 :     myself.classId = RelationRelationId;
    7697        3730 :     myself.objectId = relid;
    7698        3730 :     myself.objectSubId = attnum;
    7699        3730 :     referenced.classId = TypeRelationId;
    7700        3730 :     referenced.objectId = typid;
    7701        3730 :     referenced.objectSubId = 0;
    7702        3730 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
    7703        3730 : }
    7704             : 
    7705             : /*
    7706             :  * Install a column's dependency on its collation.
    7707             :  */
    7708             : static void
    7709        3730 : add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
    7710             : {
    7711             :     ObjectAddress myself,
    7712             :                 referenced;
    7713             : 
    7714             :     /* We know the default collation is pinned, so don't bother recording it */
    7715        3730 :     if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
    7716             :     {
    7717          18 :         myself.classId = RelationRelationId;
    7718          18 :         myself.objectId = relid;
    7719          18 :         myself.objectSubId = attnum;
    7720          18 :         referenced.classId = CollationRelationId;
    7721          18 :         referenced.objectId = collid;
    7722          18 :         referenced.objectSubId = 0;
    7723          18 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
    7724             :     }
    7725        3730 : }
    7726             : 
    7727             : /*
    7728             :  * ALTER TABLE ALTER COLUMN DROP NOT NULL
    7729             :  *
    7730             :  * Return the address of the modified column.  If the column was already
    7731             :  * nullable, InvalidObjectAddress is returned.
    7732             :  */
    7733             : static ObjectAddress
    7734         268 : ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
    7735             :                   LOCKMODE lockmode)
    7736             : {
    7737             :     HeapTuple   tuple;
    7738             :     HeapTuple   conTup;
    7739             :     Form_pg_attribute attTup;
    7740             :     AttrNumber  attnum;
    7741             :     Relation    attr_rel;
    7742             :     ObjectAddress address;
    7743             : 
    7744             :     /*
    7745             :      * lookup the attribute
    7746             :      */
    7747         268 :     attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    7748             : 
    7749         268 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    7750         268 :     if (!HeapTupleIsValid(tuple))
    7751          18 :         ereport(ERROR,
    7752             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    7753             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    7754             :                         colName, RelationGetRelationName(rel))));
    7755         250 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    7756         250 :     attnum = attTup->attnum;
    7757         250 :     ObjectAddressSubSet(address, RelationRelationId,
    7758             :                         RelationGetRelid(rel), attnum);
    7759             : 
    7760             :     /* If the column is already nullable there's nothing to do. */
    7761         250 :     if (!attTup->attnotnull)
    7762             :     {
    7763           0 :         table_close(attr_rel, RowExclusiveLock);
    7764           0 :         return InvalidObjectAddress;
    7765             :     }
    7766             : 
    7767             :     /* Prevent them from altering a system attribute */
    7768         250 :     if (attnum <= 0)
    7769           0 :         ereport(ERROR,
    7770             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7771             :                  errmsg("cannot alter system column \"%s\"",
    7772             :                         colName)));
    7773             : 
    7774         250 :     if (attTup->attidentity)
    7775          18 :         ereport(ERROR,
    7776             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    7777             :                  errmsg("column \"%s\" of relation \"%s\" is an identity column",
    7778             :                         colName, RelationGetRelationName(rel))));
    7779             : 
    7780             :     /*
    7781             :      * If rel is partition, shouldn't drop NOT NULL if parent has the same.
    7782             :      */
    7783         232 :     if (rel->rd_rel->relispartition)
    7784             :     {
    7785          12 :         Oid         parentId = get_partition_parent(RelationGetRelid(rel), false);
    7786          12 :         Relation    parent = table_open(parentId, AccessShareLock);
    7787          12 :         TupleDesc   tupDesc = RelationGetDescr(parent);
    7788             :         AttrNumber  parent_attnum;
    7789             : 
    7790          12 :         parent_attnum = get_attnum(parentId, colName);
    7791          12 :         if (TupleDescAttr(tupDesc, parent_attnum - 1)->attnotnull)
    7792          12 :             ereport(ERROR,
    7793             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    7794             :                      errmsg("column \"%s\" is marked NOT NULL in parent table",
    7795             :                             colName)));
    7796           0 :         table_close(parent, AccessShareLock);
    7797             :     }
    7798             : 
    7799             :     /*
    7800             :      * Find the constraint that makes this column NOT NULL, and drop it.
    7801             :      * dropconstraint_internal() resets attnotnull.
    7802             :      */
    7803         220 :     conTup = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
    7804         220 :     if (conTup == NULL)
    7805           0 :         elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
    7806             :              colName, RelationGetRelationName(rel));
    7807             : 
    7808             :     /* The normal case: we have a pg_constraint row, remove it */
    7809         220 :     dropconstraint_internal(rel, conTup, DROP_RESTRICT, recurse, false,
    7810             :                             false, lockmode);
    7811         166 :     heap_freetuple(conTup);
    7812             : 
    7813         166 :     InvokeObjectPostAlterHook(RelationRelationId,
    7814             :                               RelationGetRelid(rel), attnum);
    7815             : 
    7816         166 :     table_close(attr_rel, RowExclusiveLock);
    7817             : 
    7818         166 :     return address;
    7819             : }
    7820             : 
    7821             : /*
    7822             :  * set_attnotnull
    7823             :  *      Helper to update/validate the pg_attribute status of a not-null
    7824             :  *      constraint
    7825             :  *
    7826             :  * pg_attribute.attnotnull is set true, if it isn't already.
    7827             :  * If queue_validation is true, also set up wqueue to validate the constraint.
    7828             :  * wqueue may be given as NULL when validation is not needed (e.g., on table
    7829             :  * creation).
    7830             :  */
    7831             : static void
    7832       25302 : set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
    7833             :                bool is_valid, bool queue_validation)
    7834             : {
    7835             :     Form_pg_attribute attr;
    7836             :     CompactAttribute *thisatt;
    7837             : 
    7838             :     Assert(!queue_validation || wqueue);
    7839             : 
    7840       25302 :     CheckAlterTableIsSafe(rel);
    7841             : 
    7842             :     /*
    7843             :      * Exit quickly by testing attnotnull from the tupledesc's copy of the
    7844             :      * attribute.
    7845             :      */
    7846       25302 :     attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
    7847       25302 :     if (attr->attisdropped)
    7848           0 :         return;
    7849             : 
    7850       25302 :     if (!attr->attnotnull)
    7851             :     {
    7852             :         Relation    attr_rel;
    7853             :         HeapTuple   tuple;
    7854             : 
    7855        1462 :         attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    7856             : 
    7857        1462 :         tuple = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
    7858        1462 :         if (!HeapTupleIsValid(tuple))
    7859           0 :             elog(ERROR, "cache lookup failed for attribute %d of relation %u",
    7860             :                  attnum, RelationGetRelid(rel));
    7861             : 
    7862        1462 :         thisatt = TupleDescCompactAttr(RelationGetDescr(rel), attnum - 1);
    7863        1462 :         thisatt->attnullability = ATTNULLABLE_VALID;
    7864             : 
    7865        1462 :         attr = (Form_pg_attribute) GETSTRUCT(tuple);
    7866             : 
    7867        1462 :         attr->attnotnull = true;
    7868        1462 :         CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
    7869             : 
    7870             :         /*
    7871             :          * If the nullness isn't already proven by validated constraints, have
    7872             :          * ALTER TABLE phase 3 test for it.
    7873             :          */
    7874        1462 :         if (queue_validation && wqueue &&
    7875        1244 :             !NotNullImpliedByRelConstraints(rel, attr))
    7876             :         {
    7877             :             AlteredTableInfo *tab;
    7878             : 
    7879        1194 :             tab = ATGetQueueEntry(wqueue, rel);
    7880        1194 :             tab->verify_new_notnull = true;
    7881             :         }
    7882             : 
    7883        1462 :         CommandCounterIncrement();
    7884             : 
    7885        1462 :         table_close(attr_rel, RowExclusiveLock);
    7886        1462 :         heap_freetuple(tuple);
    7887             :     }
    7888             :     else
    7889             :     {
    7890       23840 :         CacheInvalidateRelcache(rel);
    7891             :     }
    7892             : }
    7893             : 
    7894             : /*
    7895             :  * ALTER TABLE ALTER COLUMN SET NOT NULL
    7896             :  *
    7897             :  * Add a not-null constraint to a single table and its children.  Returns
    7898             :  * the address of the constraint added to the parent relation, if one gets
    7899             :  * added, or InvalidObjectAddress otherwise.
    7900             :  *
    7901             :  * We must recurse to child tables during execution, rather than using
    7902             :  * ALTER TABLE's normal prep-time recursion.
    7903             :  */
    7904             : static ObjectAddress
    7905         712 : ATExecSetNotNull(List **wqueue, Relation rel, char *conName, char *colName,
    7906             :                  bool recurse, bool recursing, LOCKMODE lockmode)
    7907             : {
    7908             :     HeapTuple   tuple;
    7909             :     AttrNumber  attnum;
    7910             :     ObjectAddress address;
    7911             :     Constraint *constraint;
    7912             :     CookedConstraint *ccon;
    7913             :     List       *cooked;
    7914         712 :     bool        is_no_inherit = false;
    7915             : 
    7916             :     /* Guard against stack overflow due to overly deep inheritance tree. */
    7917         712 :     check_stack_depth();
    7918             : 
    7919             :     /* At top level, permission check was done in ATPrepCmd, else do it */
    7920         712 :     if (recursing)
    7921             :     {
    7922         298 :         ATSimplePermissions(AT_AddConstraint, rel,
    7923             :                             ATT_PARTITIONED_TABLE | ATT_TABLE | ATT_FOREIGN_TABLE);
    7924             :         Assert(conName != NULL);
    7925             :     }
    7926             : 
    7927         712 :     attnum = get_attnum(RelationGetRelid(rel), colName);
    7928         712 :     if (attnum == InvalidAttrNumber)
    7929          18 :         ereport(ERROR,
    7930             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    7931             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    7932             :                         colName, RelationGetRelationName(rel))));
    7933             : 
    7934             :     /* Prevent them from altering a system attribute */
    7935         694 :     if (attnum <= 0)
    7936           0 :         ereport(ERROR,
    7937             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7938             :                  errmsg("cannot alter system column \"%s\"",
    7939             :                         colName)));
    7940             : 
    7941             :     /* See if there's already a constraint */
    7942         694 :     tuple = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
    7943         694 :     if (HeapTupleIsValid(tuple))
    7944             :     {
    7945         158 :         Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
    7946         158 :         bool        changed = false;
    7947             : 
    7948             :         /*
    7949             :          * Don't let a NO INHERIT constraint be changed into inherit.
    7950             :          */
    7951         158 :         if (conForm->connoinherit && recurse)
    7952          12 :             ereport(ERROR,
    7953             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7954             :                     errmsg("cannot change NO INHERIT status of NOT NULL constraint \"%s\" on relation \"%s\"",
    7955             :                            NameStr(conForm->conname),
    7956             :                            RelationGetRelationName(rel)));
    7957             : 
    7958             :         /*
    7959             :          * If we find an appropriate constraint, we're almost done, but just
    7960             :          * need to change some properties on it: if we're recursing, increment
    7961             :          * coninhcount; if not, set conislocal if not already set.
    7962             :          */
    7963         146 :         if (recursing)
    7964             :         {
    7965         102 :             if (pg_add_s16_overflow(conForm->coninhcount, 1,
    7966             :                                     &conForm->coninhcount))
    7967           0 :                 ereport(ERROR,
    7968             :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    7969             :                         errmsg("too many inheritance parents"));
    7970         102 :             changed = true;
    7971             :         }
    7972          44 :         else if (!conForm->conislocal)
    7973             :         {
    7974           0 :             conForm->conislocal = true;
    7975           0 :             changed = true;
    7976             :         }
    7977          44 :         else if (!conForm->convalidated)
    7978             :         {
    7979             :             /*
    7980             :              * Flip attnotnull and convalidated, and also validate the
    7981             :              * constraint.
    7982             :              */
    7983          24 :             return ATExecValidateConstraint(wqueue, rel, NameStr(conForm->conname),
    7984             :                                             recurse, recursing, lockmode);
    7985             :         }
    7986             : 
    7987         122 :         if (changed)
    7988             :         {
    7989             :             Relation    constr_rel;
    7990             : 
    7991         102 :             constr_rel = table_open(ConstraintRelationId, RowExclusiveLock);
    7992             : 
    7993         102 :             CatalogTupleUpdate(constr_rel, &tuple->t_self, tuple);
    7994         102 :             ObjectAddressSet(address, ConstraintRelationId, conForm->oid);
    7995         102 :             table_close(constr_rel, RowExclusiveLock);
    7996             :         }
    7997             : 
    7998         122 :         if (changed)
    7999         102 :             return address;
    8000             :         else
    8001          20 :             return InvalidObjectAddress;
    8002             :     }
    8003             : 
    8004             :     /*
    8005             :      * If we're asked not to recurse, and children exist, raise an error for
    8006             :      * partitioned tables.  For inheritance, we act as if NO INHERIT had been
    8007             :      * specified.
    8008             :      */
    8009         566 :     if (!recurse &&
    8010          30 :         find_inheritance_children(RelationGetRelid(rel),
    8011             :                                   NoLock) != NIL)
    8012             :     {
    8013          18 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    8014           6 :             ereport(ERROR,
    8015             :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8016             :                     errmsg("constraint must be added to child tables too"),
    8017             :                     errhint("Do not specify the ONLY keyword."));
    8018             :         else
    8019          12 :             is_no_inherit = true;
    8020             :     }
    8021             : 
    8022             :     /*
    8023             :      * No constraint exists; we must add one.  First determine a name to use,
    8024             :      * if we haven't already.
    8025             :      */
    8026         530 :     if (!recursing)
    8027             :     {
    8028             :         Assert(conName == NULL);
    8029         340 :         conName = ChooseConstraintName(RelationGetRelationName(rel),
    8030             :                                        colName, "not_null",
    8031         340 :                                        RelationGetNamespace(rel),
    8032             :                                        NIL);
    8033             :     }
    8034             : 
    8035         530 :     constraint = makeNotNullConstraint(makeString(colName));
    8036         530 :     constraint->is_no_inherit = is_no_inherit;
    8037         530 :     constraint->conname = conName;
    8038             : 
    8039             :     /* and do it */
    8040         530 :     cooked = AddRelationNewConstraints(rel, NIL, list_make1(constraint),
    8041         530 :                                        false, !recursing, false, NULL);
    8042         530 :     ccon = linitial(cooked);
    8043         530 :     ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
    8044             : 
    8045         530 :     InvokeObjectPostAlterHook(RelationRelationId,
    8046             :                               RelationGetRelid(rel), attnum);
    8047             : 
    8048             :     /* Mark pg_attribute.attnotnull for the column and queue validation */
    8049         530 :     set_attnotnull(wqueue, rel, attnum, true, true);
    8050             : 
    8051             :     /*
    8052             :      * Recurse to propagate the constraint to children that don't have one.
    8053             :      */
    8054         530 :     if (recurse)
    8055             :     {
    8056             :         List       *children;
    8057             : 
    8058         506 :         children = find_inheritance_children(RelationGetRelid(rel),
    8059             :                                              lockmode);
    8060             : 
    8061        1244 :         foreach_oid(childoid, children)
    8062             :         {
    8063         244 :             Relation    childrel = table_open(childoid, NoLock);
    8064             : 
    8065         244 :             CommandCounterIncrement();
    8066             : 
    8067         244 :             ATExecSetNotNull(wqueue, childrel, conName, colName,
    8068             :                              recurse, true, lockmode);
    8069         238 :             table_close(childrel, NoLock);
    8070             :         }
    8071             :     }
    8072             : 
    8073         524 :     return address;
    8074             : }
    8075             : 
    8076             : /*
    8077             :  * NotNullImpliedByRelConstraints
    8078             :  *      Does rel's existing constraints imply NOT NULL for the given attribute?
    8079             :  */
    8080             : static bool
    8081        1244 : NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr)
    8082             : {
    8083        1244 :     NullTest   *nnulltest = makeNode(NullTest);
    8084             : 
    8085        2488 :     nnulltest->arg = (Expr *) makeVar(1,
    8086        1244 :                                       attr->attnum,
    8087             :                                       attr->atttypid,
    8088             :                                       attr->atttypmod,
    8089             :                                       attr->attcollation,
    8090             :                                       0);
    8091        1244 :     nnulltest->nulltesttype = IS_NOT_NULL;
    8092             : 
    8093             :     /*
    8094             :      * argisrow = false is correct even for a composite column, because
    8095             :      * attnotnull does not represent a SQL-spec IS NOT NULL test in such a
    8096             :      * case, just IS DISTINCT FROM NULL.
    8097             :      */
    8098        1244 :     nnulltest->argisrow = false;
    8099        1244 :     nnulltest->location = -1;
    8100             : 
    8101        1244 :     if (ConstraintImpliedByRelConstraint(rel, list_make1(nnulltest), NIL))
    8102             :     {
    8103          50 :         ereport(DEBUG1,
    8104             :                 (errmsg_internal("existing constraints on column \"%s.%s\" are sufficient to prove that it does not contain nulls",
    8105             :                                  RelationGetRelationName(rel), NameStr(attr->attname))));
    8106          50 :         return true;
    8107             :     }
    8108             : 
    8109        1194 :     return false;
    8110             : }
    8111             : 
    8112             : /*
    8113             :  * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
    8114             :  *
    8115             :  * Return the address of the affected column.
    8116             :  */
    8117             : static ObjectAddress
    8118         584 : ATExecColumnDefault(Relation rel, const char *colName,
    8119             :                     Node *newDefault, LOCKMODE lockmode)
    8120             : {
    8121         584 :     TupleDesc   tupdesc = RelationGetDescr(rel);
    8122             :     AttrNumber  attnum;
    8123             :     ObjectAddress address;
    8124             : 
    8125             :     /*
    8126             :      * get the number of the attribute
    8127             :      */
    8128         584 :     attnum = get_attnum(RelationGetRelid(rel), colName);
    8129         584 :     if (attnum == InvalidAttrNumber)
    8130          30 :         ereport(ERROR,
    8131             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8132             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8133             :                         colName, RelationGetRelationName(rel))));
    8134             : 
    8135             :     /* Prevent them from altering a system attribute */
    8136         554 :     if (attnum <= 0)
    8137           0 :         ereport(ERROR,
    8138             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8139             :                  errmsg("cannot alter system column \"%s\"",
    8140             :                         colName)));
    8141             : 
    8142         554 :     if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
    8143          18 :         ereport(ERROR,
    8144             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    8145             :                  errmsg("column \"%s\" of relation \"%s\" is an identity column",
    8146             :                         colName, RelationGetRelationName(rel)),
    8147             :         /* translator: %s is an SQL ALTER command */
    8148             :                  newDefault ? 0 : errhint("Use %s instead.",
    8149             :                                           "ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY")));
    8150             : 
    8151         536 :     if (TupleDescAttr(tupdesc, attnum - 1)->attgenerated)
    8152          12 :         ereport(ERROR,
    8153             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    8154             :                  errmsg("column \"%s\" of relation \"%s\" is a generated column",
    8155             :                         colName, RelationGetRelationName(rel)),
    8156             :                  newDefault ?
    8157             :         /* translator: %s is an SQL ALTER command */
    8158             :                  errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... SET EXPRESSION") :
    8159             :                  (TupleDescAttr(tupdesc, attnum - 1)->attgenerated == ATTRIBUTE_GENERATED_STORED ?
    8160             :                   errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION") : 0)));
    8161             : 
    8162             :     /*
    8163             :      * Remove any old default for the column.  We use RESTRICT here for
    8164             :      * safety, but at present we do not expect anything to depend on the
    8165             :      * default.
    8166             :      *
    8167             :      * We treat removing the existing default as an internal operation when it
    8168             :      * is preparatory to adding a new default, but as a user-initiated
    8169             :      * operation when the user asked for a drop.
    8170             :      */
    8171         524 :     RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
    8172             :                       newDefault != NULL);
    8173             : 
    8174         524 :     if (newDefault)
    8175             :     {
    8176             :         /* SET DEFAULT */
    8177             :         RawColumnDefault *rawEnt;
    8178             : 
    8179         350 :         rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
    8180         350 :         rawEnt->attnum = attnum;
    8181         350 :         rawEnt->raw_default = newDefault;
    8182         350 :         rawEnt->generated = '\0';
    8183             : 
    8184             :         /*
    8185             :          * This function is intended for CREATE TABLE, so it processes a
    8186             :          * _list_ of defaults, but we just do one.
    8187             :          */
    8188         350 :         AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
    8189             :                                   false, true, false, NULL);
    8190             :     }
    8191             : 
    8192         518 :     ObjectAddressSubSet(address, RelationRelationId,
    8193             :                         RelationGetRelid(rel), attnum);
    8194         518 :     return address;
    8195             : }
    8196             : 
    8197             : /*
    8198             :  * Add a pre-cooked default expression.
    8199             :  *
    8200             :  * Return the address of the affected column.
    8201             :  */
    8202             : static ObjectAddress
    8203          80 : ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
    8204             :                           Node *newDefault)
    8205             : {
    8206             :     ObjectAddress address;
    8207             : 
    8208             :     /* We assume no checking is required */
    8209             : 
    8210             :     /*
    8211             :      * Remove any old default for the column.  We use RESTRICT here for
    8212             :      * safety, but at present we do not expect anything to depend on the
    8213             :      * default.  (In ordinary cases, there could not be a default in place
    8214             :      * anyway, but it's possible when combining LIKE with inheritance.)
    8215             :      */
    8216          80 :     RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
    8217             :                       true);
    8218             : 
    8219          80 :     (void) StoreAttrDefault(rel, attnum, newDefault, true);
    8220             : 
    8221          80 :     ObjectAddressSubSet(address, RelationRelationId,
    8222             :                         RelationGetRelid(rel), attnum);
    8223          80 :     return address;
    8224             : }
    8225             : 
    8226             : /*
    8227             :  * ALTER TABLE ALTER COLUMN ADD IDENTITY
    8228             :  *
    8229             :  * Return the address of the affected column.
    8230             :  */
    8231             : static ObjectAddress
    8232         160 : ATExecAddIdentity(Relation rel, const char *colName,
    8233             :                   Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
    8234             : {
    8235             :     Relation    attrelation;
    8236             :     HeapTuple   tuple;
    8237             :     Form_pg_attribute attTup;
    8238             :     AttrNumber  attnum;
    8239             :     ObjectAddress address;
    8240         160 :     ColumnDef  *cdef = castNode(ColumnDef, def);
    8241             :     bool        ispartitioned;
    8242             : 
    8243         160 :     ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    8244         160 :     if (ispartitioned && !recurse)
    8245           6 :         ereport(ERROR,
    8246             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8247             :                  errmsg("cannot add identity to a column of only the partitioned table"),
    8248             :                  errhint("Do not specify the ONLY keyword.")));
    8249             : 
    8250         154 :     if (rel->rd_rel->relispartition && !recursing)
    8251          12 :         ereport(ERROR,
    8252             :                 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8253             :                 errmsg("cannot add identity to a column of a partition"));
    8254             : 
    8255         142 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    8256             : 
    8257         142 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    8258         142 :     if (!HeapTupleIsValid(tuple))
    8259           0 :         ereport(ERROR,
    8260             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8261             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8262             :                         colName, RelationGetRelationName(rel))));
    8263         142 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8264         142 :     attnum = attTup->attnum;
    8265             : 
    8266             :     /* Can't alter a system attribute */
    8267         142 :     if (attnum <= 0)
    8268           0 :         ereport(ERROR,
    8269             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8270             :                  errmsg("cannot alter system column \"%s\"",
    8271             :                         colName)));
    8272             : 
    8273             :     /*
    8274             :      * Creating a column as identity implies NOT NULL, so adding the identity
    8275             :      * to an existing column that is not NOT NULL would create a state that
    8276             :      * cannot be reproduced without contortions.
    8277             :      */
    8278         142 :     if (!attTup->attnotnull)
    8279           6 :         ereport(ERROR,
    8280             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8281             :                  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
    8282             :                         colName, RelationGetRelationName(rel))));
    8283             : 
    8284         136 :     if (attTup->attidentity)
    8285          18 :         ereport(ERROR,
    8286             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8287             :                  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
    8288             :                         colName, RelationGetRelationName(rel))));
    8289             : 
    8290         118 :     if (attTup->atthasdef)
    8291           6 :         ereport(ERROR,
    8292             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8293             :                  errmsg("column \"%s\" of relation \"%s\" already has a default value",
    8294             :                         colName, RelationGetRelationName(rel))));
    8295             : 
    8296         112 :     attTup->attidentity = cdef->identity;
    8297         112 :     CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    8298             : 
    8299         112 :     InvokeObjectPostAlterHook(RelationRelationId,
    8300             :                               RelationGetRelid(rel),
    8301             :                               attTup->attnum);
    8302         112 :     ObjectAddressSubSet(address, RelationRelationId,
    8303             :                         RelationGetRelid(rel), attnum);
    8304         112 :     heap_freetuple(tuple);
    8305             : 
    8306         112 :     table_close(attrelation, RowExclusiveLock);
    8307             : 
    8308             :     /*
    8309             :      * Recurse to propagate the identity column to partitions.  Identity is
    8310             :      * not inherited in regular inheritance children.
    8311             :      */
    8312         112 :     if (recurse && ispartitioned)
    8313             :     {
    8314             :         List       *children;
    8315             :         ListCell   *lc;
    8316             : 
    8317          10 :         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
    8318             : 
    8319          16 :         foreach(lc, children)
    8320             :         {
    8321             :             Relation    childrel;
    8322             : 
    8323           6 :             childrel = table_open(lfirst_oid(lc), NoLock);
    8324           6 :             ATExecAddIdentity(childrel, colName, def, lockmode, recurse, true);
    8325           6 :             table_close(childrel, NoLock);
    8326             :         }
    8327             :     }
    8328             : 
    8329         112 :     return address;
    8330             : }
    8331             : 
    8332             : /*
    8333             :  * ALTER TABLE ALTER COLUMN SET { GENERATED or sequence options }
    8334             :  *
    8335             :  * Return the address of the affected column.
    8336             :  */
    8337             : static ObjectAddress
    8338          74 : ATExecSetIdentity(Relation rel, const char *colName, Node *def,
    8339             :                   LOCKMODE lockmode, bool recurse, bool recursing)
    8340             : {
    8341             :     ListCell   *option;
    8342          74 :     DefElem    *generatedEl = NULL;
    8343             :     HeapTuple   tuple;
    8344             :     Form_pg_attribute attTup;
    8345             :     AttrNumber  attnum;
    8346             :     Relation    attrelation;
    8347             :     ObjectAddress address;
    8348             :     bool        ispartitioned;
    8349             : 
    8350          74 :     ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    8351          74 :     if (ispartitioned && !recurse)
    8352           6 :         ereport(ERROR,
    8353             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8354             :                  errmsg("cannot change identity column of only the partitioned table"),
    8355             :                  errhint("Do not specify the ONLY keyword.")));
    8356             : 
    8357          68 :     if (rel->rd_rel->relispartition && !recursing)
    8358          12 :         ereport(ERROR,
    8359             :                 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8360             :                 errmsg("cannot change identity column of a partition"));
    8361             : 
    8362         100 :     foreach(option, castNode(List, def))
    8363             :     {
    8364          44 :         DefElem    *defel = lfirst_node(DefElem, option);
    8365             : 
    8366          44 :         if (strcmp(defel->defname, "generated") == 0)
    8367             :         {
    8368          44 :             if (generatedEl)
    8369           0 :                 ereport(ERROR,
    8370             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    8371             :                          errmsg("conflicting or redundant options")));
    8372          44 :             generatedEl = defel;
    8373             :         }
    8374             :         else
    8375           0 :             elog(ERROR, "option \"%s\" not recognized",
    8376             :                  defel->defname);
    8377             :     }
    8378             : 
    8379             :     /*
    8380             :      * Even if there is nothing to change here, we run all the checks.  There
    8381             :      * will be a subsequent ALTER SEQUENCE that relies on everything being
    8382             :      * there.
    8383             :      */
    8384             : 
    8385          56 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    8386          56 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    8387          56 :     if (!HeapTupleIsValid(tuple))
    8388           0 :         ereport(ERROR,
    8389             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8390             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8391             :                         colName, RelationGetRelationName(rel))));
    8392             : 
    8393          56 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8394          56 :     attnum = attTup->attnum;
    8395             : 
    8396          56 :     if (attnum <= 0)
    8397           0 :         ereport(ERROR,
    8398             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8399             :                  errmsg("cannot alter system column \"%s\"",
    8400             :                         colName)));
    8401             : 
    8402          56 :     if (!attTup->attidentity)
    8403           6 :         ereport(ERROR,
    8404             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8405             :                  errmsg("column \"%s\" of relation \"%s\" is not an identity column",
    8406             :                         colName, RelationGetRelationName(rel))));
    8407             : 
    8408          50 :     if (generatedEl)
    8409             :     {
    8410          44 :         attTup->attidentity = defGetInt32(generatedEl);
    8411          44 :         CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    8412             : 
    8413          44 :         InvokeObjectPostAlterHook(RelationRelationId,
    8414             :                                   RelationGetRelid(rel),
    8415             :                                   attTup->attnum);
    8416          44 :         ObjectAddressSubSet(address, RelationRelationId,
    8417             :                             RelationGetRelid(rel), attnum);
    8418             :     }
    8419             :     else
    8420           6 :         address = InvalidObjectAddress;
    8421             : 
    8422          50 :     heap_freetuple(tuple);
    8423          50 :     table_close(attrelation, RowExclusiveLock);
    8424             : 
    8425             :     /*
    8426             :      * Recurse to propagate the identity change to partitions. Identity is not
    8427             :      * inherited in regular inheritance children.
    8428             :      */
    8429          50 :     if (generatedEl && recurse && ispartitioned)
    8430             :     {
    8431             :         List       *children;
    8432             :         ListCell   *lc;
    8433             : 
    8434           6 :         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
    8435             : 
    8436          18 :         foreach(lc, children)
    8437             :         {
    8438             :             Relation    childrel;
    8439             : 
    8440          12 :             childrel = table_open(lfirst_oid(lc), NoLock);
    8441          12 :             ATExecSetIdentity(childrel, colName, def, lockmode, recurse, true);
    8442          12 :             table_close(childrel, NoLock);
    8443             :         }
    8444             :     }
    8445             : 
    8446          50 :     return address;
    8447             : }
    8448             : 
    8449             : /*
    8450             :  * ALTER TABLE ALTER COLUMN DROP IDENTITY
    8451             :  *
    8452             :  * Return the address of the affected column.
    8453             :  */
    8454             : static ObjectAddress
    8455          68 : ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
    8456             :                    bool recurse, bool recursing)
    8457             : {
    8458             :     HeapTuple   tuple;
    8459             :     Form_pg_attribute attTup;
    8460             :     AttrNumber  attnum;
    8461             :     Relation    attrelation;
    8462             :     ObjectAddress address;
    8463             :     Oid         seqid;
    8464             :     ObjectAddress seqaddress;
    8465             :     bool        ispartitioned;
    8466             : 
    8467          68 :     ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    8468          68 :     if (ispartitioned && !recurse)
    8469           6 :         ereport(ERROR,
    8470             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8471             :                  errmsg("cannot drop identity from a column of only the partitioned table"),
    8472             :                  errhint("Do not specify the ONLY keyword.")));
    8473             : 
    8474          62 :     if (rel->rd_rel->relispartition && !recursing)
    8475           6 :         ereport(ERROR,
    8476             :                 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8477             :                 errmsg("cannot drop identity from a column of a partition"));
    8478             : 
    8479          56 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    8480          56 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    8481          56 :     if (!HeapTupleIsValid(tuple))
    8482           0 :         ereport(ERROR,
    8483             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8484             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8485             :                         colName, RelationGetRelationName(rel))));
    8486             : 
    8487          56 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8488          56 :     attnum = attTup->attnum;
    8489             : 
    8490          56 :     if (attnum <= 0)
    8491           0 :         ereport(ERROR,
    8492             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8493             :                  errmsg("cannot alter system column \"%s\"",
    8494             :                         colName)));
    8495             : 
    8496          56 :     if (!attTup->attidentity)
    8497             :     {
    8498          12 :         if (!missing_ok)
    8499           6 :             ereport(ERROR,
    8500             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8501             :                      errmsg("column \"%s\" of relation \"%s\" is not an identity column",
    8502             :                             colName, RelationGetRelationName(rel))));
    8503             :         else
    8504             :         {
    8505           6 :             ereport(NOTICE,
    8506             :                     (errmsg("column \"%s\" of relation \"%s\" is not an identity column, skipping",
    8507             :                             colName, RelationGetRelationName(rel))));
    8508           6 :             heap_freetuple(tuple);
    8509           6 :             table_close(attrelation, RowExclusiveLock);
    8510           6 :             return InvalidObjectAddress;
    8511             :         }
    8512             :     }
    8513             : 
    8514          44 :     attTup->attidentity = '\0';
    8515          44 :     CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    8516             : 
    8517          44 :     InvokeObjectPostAlterHook(RelationRelationId,
    8518             :                               RelationGetRelid(rel),
    8519             :                               attTup->attnum);
    8520          44 :     ObjectAddressSubSet(address, RelationRelationId,
    8521             :                         RelationGetRelid(rel), attnum);
    8522          44 :     heap_freetuple(tuple);
    8523             : 
    8524          44 :     table_close(attrelation, RowExclusiveLock);
    8525             : 
    8526             :     /*
    8527             :      * Recurse to drop the identity from column in partitions.  Identity is
    8528             :      * not inherited in regular inheritance children so ignore them.
    8529             :      */
    8530          44 :     if (recurse && ispartitioned)
    8531             :     {
    8532             :         List       *children;
    8533             :         ListCell   *lc;
    8534             : 
    8535           6 :         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
    8536             : 
    8537          12 :         foreach(lc, children)
    8538             :         {
    8539             :             Relation    childrel;
    8540             : 
    8541           6 :             childrel = table_open(lfirst_oid(lc), NoLock);
    8542           6 :             ATExecDropIdentity(childrel, colName, false, lockmode, recurse, true);
    8543           6 :             table_close(childrel, NoLock);
    8544             :         }
    8545             :     }
    8546             : 
    8547          44 :     if (!recursing)
    8548             :     {
    8549             :         /* drop the internal sequence */
    8550          32 :         seqid = getIdentitySequence(rel, attnum, false);
    8551          32 :         deleteDependencyRecordsForClass(RelationRelationId, seqid,
    8552             :                                         RelationRelationId, DEPENDENCY_INTERNAL);
    8553          32 :         CommandCounterIncrement();
    8554          32 :         seqaddress.classId = RelationRelationId;
    8555          32 :         seqaddress.objectId = seqid;
    8556          32 :         seqaddress.objectSubId = 0;
    8557          32 :         performDeletion(&seqaddress, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
    8558             :     }
    8559             : 
    8560          44 :     return address;
    8561             : }
    8562             : 
    8563             : /*
    8564             :  * ALTER TABLE ALTER COLUMN SET EXPRESSION
    8565             :  *
    8566             :  * Return the address of the affected column.
    8567             :  */
    8568             : static ObjectAddress
    8569         216 : ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
    8570             :                     Node *newExpr, LOCKMODE lockmode)
    8571             : {
    8572             :     HeapTuple   tuple;
    8573             :     Form_pg_attribute attTup;
    8574             :     AttrNumber  attnum;
    8575             :     char        attgenerated;
    8576             :     bool        rewrite;
    8577             :     Oid         attrdefoid;
    8578             :     ObjectAddress address;
    8579             :     Expr       *defval;
    8580             :     NewColumnValue *newval;
    8581             :     RawColumnDefault *rawEnt;
    8582             : 
    8583         216 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
    8584         216 :     if (!HeapTupleIsValid(tuple))
    8585           0 :         ereport(ERROR,
    8586             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8587             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8588             :                         colName, RelationGetRelationName(rel))));
    8589             : 
    8590         216 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8591             : 
    8592         216 :     attnum = attTup->attnum;
    8593         216 :     if (attnum <= 0)
    8594           0 :         ereport(ERROR,
    8595             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8596             :                  errmsg("cannot alter system column \"%s\"",
    8597             :                         colName)));
    8598             : 
    8599         216 :     attgenerated = attTup->attgenerated;
    8600         216 :     if (!attgenerated)
    8601          12 :         ereport(ERROR,
    8602             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8603             :                  errmsg("column \"%s\" of relation \"%s\" is not a generated column",
    8604             :                         colName, RelationGetRelationName(rel))));
    8605             : 
    8606             :     /*
    8607             :      * TODO: This could be done, just need to recheck any constraints
    8608             :      * afterwards.
    8609             :      */
    8610         204 :     if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
    8611         108 :         rel->rd_att->constr && rel->rd_att->constr->num_check > 0)
    8612          12 :         ereport(ERROR,
    8613             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8614             :                  errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables with check constraints"),
    8615             :                  errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
    8616             :                            colName, RelationGetRelationName(rel))));
    8617             : 
    8618         192 :     if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull)
    8619          24 :         tab->verify_new_notnull = true;
    8620             : 
    8621             :     /*
    8622             :      * We need to prevent this because a change of expression could affect a
    8623             :      * row filter and inject expressions that are not permitted in a row
    8624             :      * filter.  XXX We could try to have a more precise check to catch only
    8625             :      * publications with row filters, or even re-verify the row filter
    8626             :      * expressions.
    8627             :      */
    8628         288 :     if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
    8629          96 :         GetRelationPublications(RelationGetRelid(rel)) != NIL)
    8630           6 :         ereport(ERROR,
    8631             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8632             :                  errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables that are part of a publication"),
    8633             :                  errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
    8634             :                            colName, RelationGetRelationName(rel))));
    8635             : 
    8636         186 :     rewrite = (attgenerated == ATTRIBUTE_GENERATED_STORED);
    8637             : 
    8638         186 :     ReleaseSysCache(tuple);
    8639             : 
    8640         186 :     if (rewrite)
    8641             :     {
    8642             :         /*
    8643             :          * Clear all the missing values if we're rewriting the table, since
    8644             :          * this renders them pointless.
    8645             :          */
    8646          96 :         RelationClearMissing(rel);
    8647             : 
    8648             :         /* make sure we don't conflict with later attribute modifications */
    8649          96 :         CommandCounterIncrement();
    8650             : 
    8651             :         /*
    8652             :          * Find everything that depends on the column (constraints, indexes,
    8653             :          * etc), and record enough information to let us recreate the objects
    8654             :          * after rewrite.
    8655             :          */
    8656          96 :         RememberAllDependentForRebuilding(tab, AT_SetExpression, rel, attnum, colName);
    8657             :     }
    8658             : 
    8659             :     /*
    8660             :      * Drop the dependency records of the GENERATED expression, in particular
    8661             :      * its INTERNAL dependency on the column, which would otherwise cause
    8662             :      * dependency.c to refuse to perform the deletion.
    8663             :      */
    8664         186 :     attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
    8665         186 :     if (!OidIsValid(attrdefoid))
    8666           0 :         elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
    8667             :              RelationGetRelid(rel), attnum);
    8668         186 :     (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
    8669             : 
    8670             :     /* Make above changes visible */
    8671         186 :     CommandCounterIncrement();
    8672             : 
    8673             :     /*
    8674             :      * Get rid of the GENERATED expression itself.  We use RESTRICT here for
    8675             :      * safety, but at present we do not expect anything to depend on the
    8676             :      * expression.
    8677             :      */
    8678         186 :     RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
    8679             :                       false, false);
    8680             : 
    8681             :     /* Prepare to store the new expression, in the catalogs */
    8682         186 :     rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
    8683         186 :     rawEnt->attnum = attnum;
    8684         186 :     rawEnt->raw_default = newExpr;
    8685         186 :     rawEnt->generated = attgenerated;
    8686             : 
    8687             :     /* Store the generated expression */
    8688         186 :     AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
    8689             :                               false, true, false, NULL);
    8690             : 
    8691             :     /* Make above new expression visible */
    8692         186 :     CommandCounterIncrement();
    8693             : 
    8694         186 :     if (rewrite)
    8695             :     {
    8696             :         /* Prepare for table rewrite */
    8697          96 :         defval = (Expr *) build_column_default(rel, attnum);
    8698             : 
    8699          96 :         newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
    8700          96 :         newval->attnum = attnum;
    8701          96 :         newval->expr = expression_planner(defval);
    8702          96 :         newval->is_generated = true;
    8703             : 
    8704          96 :         tab->newvals = lappend(tab->newvals, newval);
    8705          96 :         tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
    8706             :     }
    8707             : 
    8708             :     /* Drop any pg_statistic entry for the column */
    8709         186 :     RemoveStatistics(RelationGetRelid(rel), attnum);
    8710             : 
    8711         186 :     InvokeObjectPostAlterHook(RelationRelationId,
    8712             :                               RelationGetRelid(rel), attnum);
    8713             : 
    8714         186 :     ObjectAddressSubSet(address, RelationRelationId,
    8715             :                         RelationGetRelid(rel), attnum);
    8716         186 :     return address;
    8717             : }
    8718             : 
    8719             : /*
    8720             :  * ALTER TABLE ALTER COLUMN DROP EXPRESSION
    8721             :  */
    8722             : static void
    8723          86 : ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
    8724             : {
    8725             :     /*
    8726             :      * Reject ONLY if there are child tables.  We could implement this, but it
    8727             :      * is a bit complicated.  GENERATED clauses must be attached to the column
    8728             :      * definition and cannot be added later like DEFAULT, so if a child table
    8729             :      * has a generation expression that the parent does not have, the child
    8730             :      * column will necessarily be an attislocal column.  So to implement ONLY
    8731             :      * here, we'd need extra code to update attislocal of the direct child
    8732             :      * tables, somewhat similar to how DROP COLUMN does it, so that the
    8733             :      * resulting state can be properly dumped and restored.
    8734             :      */
    8735         110 :     if (!recurse &&
    8736          24 :         find_inheritance_children(RelationGetRelid(rel), lockmode))
    8737          12 :         ereport(ERROR,
    8738             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8739             :                  errmsg("ALTER TABLE / DROP EXPRESSION must be applied to child tables too")));
    8740             : 
    8741             :     /*
    8742             :      * Cannot drop generation expression from inherited columns.
    8743             :      */
    8744          74 :     if (!recursing)
    8745             :     {
    8746             :         HeapTuple   tuple;
    8747             :         Form_pg_attribute attTup;
    8748             : 
    8749          62 :         tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), cmd->name);
    8750          62 :         if (!HeapTupleIsValid(tuple))
    8751           0 :             ereport(ERROR,
    8752             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    8753             :                      errmsg("column \"%s\" of relation \"%s\" does not exist",
    8754             :                             cmd->name, RelationGetRelationName(rel))));
    8755             : 
    8756          62 :         attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8757             : 
    8758          62 :         if (attTup->attinhcount > 0)
    8759          12 :             ereport(ERROR,
    8760             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    8761             :                      errmsg("cannot drop generation expression from inherited column")));
    8762             :     }
    8763          62 : }
    8764             : 
    8765             : /*
    8766             :  * Return the address of the affected column.
    8767             :  */
    8768             : static ObjectAddress
    8769          56 : ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
    8770             : {
    8771             :     HeapTuple   tuple;
    8772             :     Form_pg_attribute attTup;
    8773             :     AttrNumber  attnum;
    8774             :     Relation    attrelation;
    8775             :     Oid         attrdefoid;
    8776             :     ObjectAddress address;
    8777             : 
    8778          56 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    8779          56 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    8780          56 :     if (!HeapTupleIsValid(tuple))
    8781           0 :         ereport(ERROR,
    8782             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    8783             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    8784             :                         colName, RelationGetRelationName(rel))));
    8785             : 
    8786          56 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
    8787          56 :     attnum = attTup->attnum;
    8788             : 
    8789          56 :     if (attnum <= 0)
    8790           0 :         ereport(ERROR,
    8791             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8792             :                  errmsg("cannot alter system column \"%s\"",
    8793             :                         colName)));
    8794             : 
    8795             :     /*
    8796             :      * TODO: This could be done, but it would need a table rewrite to
    8797             :      * materialize the generated values.  Note that for the time being, we
    8798             :      * still error with missing_ok, so that we don't silently leave the column
    8799             :      * as generated.
    8800             :      */
    8801          56 :     if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
    8802          12 :         ereport(ERROR,
    8803             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8804             :                  errmsg("ALTER TABLE / DROP EXPRESSION is not supported for virtual generated columns"),
    8805             :                  errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
    8806             :                            colName, RelationGetRelationName(rel))));
    8807             : 
    8808          44 :     if (!attTup->attgenerated)
    8809             :     {
    8810          24 :         if (!missing_ok)
    8811          12 :             ereport(ERROR,
    8812             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8813             :                      errmsg("column \"%s\" of relation \"%s\" is not a generated column",
    8814             :                             colName, RelationGetRelationName(rel))));
    8815             :         else
    8816             :         {
    8817          12 :             ereport(NOTICE,
    8818             :                     (errmsg("column \"%s\" of relation \"%s\" is not a generated column, skipping",
    8819             :                             colName, RelationGetRelationName(rel))));
    8820          12 :             heap_freetuple(tuple);
    8821          12 :             table_close(attrelation, RowExclusiveLock);
    8822          12 :             return InvalidObjectAddress;
    8823             :         }
    8824             :     }
    8825             : 
    8826             :     /*
    8827             :      * Mark the column as no longer generated.  (The atthasdef flag needs to
    8828             :      * get cleared too, but RemoveAttrDefault will handle that.)
    8829             :      */
    8830          20 :     attTup->attgenerated = '\0';
    8831          20 :     CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    8832             : 
    8833          20 :     InvokeObjectPostAlterHook(RelationRelationId,
    8834             :                               RelationGetRelid(rel),
    8835             :                               attnum);
    8836          20 :     heap_freetuple(tuple);
    8837             : 
    8838          20 :     table_close(attrelation, RowExclusiveLock);
    8839             : 
    8840             :     /*
    8841             :      * Drop the dependency records of the GENERATED expression, in particular
    8842             :      * its INTERNAL dependency on the column, which would otherwise cause
    8843             :      * dependency.c to refuse to perform the deletion.
    8844             :      */
    8845          20 :     attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
    8846          20 :     if (!OidIsValid(attrdefoid))
    8847           0 :         elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
    8848             :              RelationGetRelid(rel), attnum);
    8849          20 :     (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
    8850             : 
    8851             :     /* Make above changes visible */
    8852          20 :     CommandCounterIncrement();
    8853             : 
    8854             :     /*
    8855             :      * Get rid of the GENERATED expression itself.  We use RESTRICT here for
    8856             :      * safety, but at present we do not expect anything to depend on the
    8857             :      * default.
    8858             :      */
    8859          20 :     RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
    8860             :                       false, false);
    8861             : 
    8862          20 :     ObjectAddressSubSet(address, RelationRelationId,
    8863             :                         RelationGetRelid(rel), attnum);
    8864          20 :     return address;
    8865             : }
    8866             : 
    8867             : /*
    8868             :  * ALTER TABLE ALTER COLUMN SET STATISTICS
    8869             :  *
    8870             :  * Return value is the address of the modified column
    8871             :  */
    8872             : static ObjectAddress
    8873         164 : ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
    8874             : {
    8875         164 :     int         newtarget = 0;
    8876             :     bool        newtarget_default;
    8877             :     Relation    attrelation;
    8878             :     HeapTuple   tuple,
    8879             :                 newtuple;
    8880             :     Form_pg_attribute attrtuple;
    8881             :     AttrNumber  attnum;
    8882             :     ObjectAddress address;
    8883             :     Datum       repl_val[Natts_pg_attribute];
    8884             :     bool        repl_null[Natts_pg_attribute];
    8885             :     bool        repl_repl[Natts_pg_attribute];
    8886             : 
    8887             :     /*
    8888             :      * We allow referencing columns by numbers only for indexes, since table
    8889             :      * column numbers could contain gaps if columns are later dropped.
    8890             :      */
    8891         164 :     if (rel->rd_rel->relkind != RELKIND_INDEX &&
    8892         100 :         rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
    8893             :         !colName)
    8894           0 :         ereport(ERROR,
    8895             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8896             :                  errmsg("cannot refer to non-index column by number")));
    8897             : 
    8898             :     /* -1 was used in previous versions for the default setting */
    8899         164 :     if (newValue && intVal(newValue) != -1)
    8900             :     {
    8901         120 :         newtarget = intVal(newValue);
    8902         120 :         newtarget_default = false;
    8903             :     }
    8904             :     else
    8905          44 :         newtarget_default = true;
    8906             : 
    8907         164 :     if (!newtarget_default)
    8908             :     {
    8909             :         /*
    8910             :          * Limit target to a sane range
    8911             :          */
    8912         120 :         if (newtarget < 0)
    8913             :         {
    8914           0 :             ereport(ERROR,
    8915             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    8916             :                      errmsg("statistics target %d is too low",
    8917             :                             newtarget)));
    8918             :         }
    8919         120 :         else if (newtarget > MAX_STATISTICS_TARGET)
    8920             :         {
    8921           0 :             newtarget = MAX_STATISTICS_TARGET;
    8922           0 :             ereport(WARNING,
    8923             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    8924             :                      errmsg("lowering statistics target to %d",
    8925             :                             newtarget)));
    8926             :         }
    8927             :     }
    8928             : 
    8929         164 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    8930             : 
    8931         164 :     if (colName)
    8932             :     {
    8933         100 :         tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
    8934             : 
    8935         100 :         if (!HeapTupleIsValid(tuple))
    8936          12 :             ereport(ERROR,
    8937             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    8938             :                      errmsg("column \"%s\" of relation \"%s\" does not exist",
    8939             :                             colName, RelationGetRelationName(rel))));
    8940             :     }
    8941             :     else
    8942             :     {
    8943          64 :         tuple = SearchSysCacheAttNum(RelationGetRelid(rel), colNum);
    8944             : 
    8945          64 :         if (!HeapTupleIsValid(tuple))
    8946          12 :             ereport(ERROR,
    8947             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    8948             :                      errmsg("column number %d of relation \"%s\" does not exist",
    8949             :                             colNum, RelationGetRelationName(rel))));
    8950             :     }
    8951             : 
    8952         140 :     attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    8953             : 
    8954         140 :     attnum = attrtuple->attnum;
    8955         140 :     if (attnum <= 0)
    8956           0 :         ereport(ERROR,
    8957             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8958             :                  errmsg("cannot alter system column \"%s\"",
    8959             :                         colName)));
    8960             : 
    8961             :     /*
    8962             :      * Prevent this as long as the ANALYZE code skips virtual generated
    8963             :      * columns.
    8964             :      */
    8965         140 :     if (attrtuple->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
    8966           0 :         ereport(ERROR,
    8967             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8968             :                  errmsg("cannot alter statistics on virtual generated column \"%s\"",
    8969             :                         colName)));
    8970             : 
    8971         140 :     if (rel->rd_rel->relkind == RELKIND_INDEX ||
    8972          88 :         rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
    8973             :     {
    8974          52 :         if (attnum > rel->rd_index->indnkeyatts)
    8975           6 :             ereport(ERROR,
    8976             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8977             :                      errmsg("cannot alter statistics on included column \"%s\" of index \"%s\"",
    8978             :                             NameStr(attrtuple->attname), RelationGetRelationName(rel))));
    8979          46 :         else if (rel->rd_index->indkey.values[attnum - 1] != 0)
    8980          18 :             ereport(ERROR,
    8981             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    8982             :                      errmsg("cannot alter statistics on non-expression column \"%s\" of index \"%s\"",
    8983             :                             NameStr(attrtuple->attname), RelationGetRelationName(rel)),
    8984             :                      errhint("Alter statistics on table column instead.")));
    8985             :     }
    8986             : 
    8987             :     /* Build new tuple. */
    8988         116 :     memset(repl_null, false, sizeof(repl_null));
    8989         116 :     memset(repl_repl, false, sizeof(repl_repl));
    8990         116 :     if (!newtarget_default)
    8991          72 :         repl_val[Anum_pg_attribute_attstattarget - 1] = Int16GetDatum(newtarget);
    8992             :     else
    8993          44 :         repl_null[Anum_pg_attribute_attstattarget - 1] = true;
    8994         116 :     repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
    8995         116 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
    8996             :                                  repl_val, repl_null, repl_repl);
    8997         116 :     CatalogTupleUpdate(attrelation, &tuple->t_self, newtuple);
    8998             : 
    8999         116 :     InvokeObjectPostAlterHook(RelationRelationId,
    9000             :                               RelationGetRelid(rel),
    9001             :                               attrtuple->attnum);
    9002         116 :     ObjectAddressSubSet(address, RelationRelationId,
    9003             :                         RelationGetRelid(rel), attnum);
    9004             : 
    9005         116 :     heap_freetuple(newtuple);
    9006             : 
    9007         116 :     ReleaseSysCache(tuple);
    9008             : 
    9009         116 :     table_close(attrelation, RowExclusiveLock);
    9010             : 
    9011         116 :     return address;
    9012             : }
    9013             : 
    9014             : /*
    9015             :  * Return value is the address of the modified column
    9016             :  */
    9017             : static ObjectAddress
    9018          32 : ATExecSetOptions(Relation rel, const char *colName, Node *options,
    9019             :                  bool isReset, LOCKMODE lockmode)
    9020             : {
    9021             :     Relation    attrelation;
    9022             :     HeapTuple   tuple,
    9023             :                 newtuple;
    9024             :     Form_pg_attribute attrtuple;
    9025             :     AttrNumber  attnum;
    9026             :     Datum       datum,
    9027             :                 newOptions;
    9028             :     bool        isnull;
    9029             :     ObjectAddress address;
    9030             :     Datum       repl_val[Natts_pg_attribute];
    9031             :     bool        repl_null[Natts_pg_attribute];
    9032             :     bool        repl_repl[Natts_pg_attribute];
    9033             : 
    9034          32 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    9035             : 
    9036          32 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
    9037             : 
    9038          32 :     if (!HeapTupleIsValid(tuple))
    9039           0 :         ereport(ERROR,
    9040             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    9041             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    9042             :                         colName, RelationGetRelationName(rel))));
    9043          32 :     attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    9044             : 
    9045          32 :     attnum = attrtuple->attnum;
    9046          32 :     if (attnum <= 0)
    9047           0 :         ereport(ERROR,
    9048             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9049             :                  errmsg("cannot alter system column \"%s\"",
    9050             :                         colName)));
    9051             : 
    9052             :     /* Generate new proposed attoptions (text array) */
    9053          32 :     datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
    9054             :                             &isnull);
    9055          32 :     newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
    9056             :                                      castNode(List, options), NULL, NULL,
    9057             :                                      false, isReset);
    9058             :     /* Validate new options */
    9059          32 :     (void) attribute_reloptions(newOptions, true);
    9060             : 
    9061             :     /* Build new tuple. */
    9062          32 :     memset(repl_null, false, sizeof(repl_null));
    9063          32 :     memset(repl_repl, false, sizeof(repl_repl));
    9064          32 :     if (newOptions != (Datum) 0)
    9065          32 :         repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
    9066             :     else
    9067           0 :         repl_null[Anum_pg_attribute_attoptions - 1] = true;
    9068          32 :     repl_repl[Anum_pg_attribute_attoptions - 1] = true;
    9069          32 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
    9070             :                                  repl_val, repl_null, repl_repl);
    9071             : 
    9072             :     /* Update system catalog. */
    9073          32 :     CatalogTupleUpdate(attrelation, &newtuple->t_self, newtuple);
    9074             : 
    9075          32 :     InvokeObjectPostAlterHook(RelationRelationId,
    9076             :                               RelationGetRelid(rel),
    9077             :                               attrtuple->attnum);
    9078          32 :     ObjectAddressSubSet(address, RelationRelationId,
    9079             :                         RelationGetRelid(rel), attnum);
    9080             : 
    9081          32 :     heap_freetuple(newtuple);
    9082             : 
    9083          32 :     ReleaseSysCache(tuple);
    9084             : 
    9085          32 :     table_close(attrelation, RowExclusiveLock);
    9086             : 
    9087          32 :     return address;
    9088             : }
    9089             : 
    9090             : /*
    9091             :  * Helper function for ATExecSetStorage and ATExecSetCompression
    9092             :  *
    9093             :  * Set the attstorage and/or attcompression fields for index columns
    9094             :  * associated with the specified table column.
    9095             :  */
    9096             : static void
    9097         320 : SetIndexStorageProperties(Relation rel, Relation attrelation,
    9098             :                           AttrNumber attnum,
    9099             :                           bool setstorage, char newstorage,
    9100             :                           bool setcompression, char newcompression,
    9101             :                           LOCKMODE lockmode)
    9102             : {
    9103             :     ListCell   *lc;
    9104             : 
    9105         412 :     foreach(lc, RelationGetIndexList(rel))
    9106             :     {
    9107          92 :         Oid         indexoid = lfirst_oid(lc);
    9108             :         Relation    indrel;
    9109          92 :         AttrNumber  indattnum = 0;
    9110             :         HeapTuple   tuple;
    9111             : 
    9112          92 :         indrel = index_open(indexoid, lockmode);
    9113             : 
    9114         154 :         for (int i = 0; i < indrel->rd_index->indnatts; i++)
    9115             :         {
    9116          98 :             if (indrel->rd_index->indkey.values[i] == attnum)
    9117             :             {
    9118          36 :                 indattnum = i + 1;
    9119          36 :                 break;
    9120             :             }
    9121             :         }
    9122             : 
    9123          92 :         if (indattnum == 0)
    9124             :         {
    9125          56 :             index_close(indrel, lockmode);
    9126          56 :             continue;
    9127             :         }
    9128             : 
    9129          36 :         tuple = SearchSysCacheCopyAttNum(RelationGetRelid(indrel), indattnum);
    9130             : 
    9131          36 :         if (HeapTupleIsValid(tuple))
    9132             :         {
    9133          36 :             Form_pg_attribute attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    9134             : 
    9135          36 :             if (setstorage)
    9136          24 :                 attrtuple->attstorage = newstorage;
    9137             : 
    9138          36 :             if (setcompression)
    9139          12 :                 attrtuple->attcompression = newcompression;
    9140             : 
    9141          36 :             CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    9142             : 
    9143          36 :             InvokeObjectPostAlterHook(RelationRelationId,
    9144             :                                       RelationGetRelid(rel),
    9145             :                                       attrtuple->attnum);
    9146             : 
    9147          36 :             heap_freetuple(tuple);
    9148             :         }
    9149             : 
    9150          36 :         index_close(indrel, lockmode);
    9151             :     }
    9152         320 : }
    9153             : 
    9154             : /*
    9155             :  * ALTER TABLE ALTER COLUMN SET STORAGE
    9156             :  *
    9157             :  * Return value is the address of the modified column
    9158             :  */
    9159             : static ObjectAddress
    9160         260 : ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
    9161             : {
    9162             :     Relation    attrelation;
    9163             :     HeapTuple   tuple;
    9164             :     Form_pg_attribute attrtuple;
    9165             :     AttrNumber  attnum;
    9166             :     ObjectAddress address;
    9167             : 
    9168         260 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
    9169             : 
    9170         260 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
    9171             : 
    9172         260 :     if (!HeapTupleIsValid(tuple))
    9173          12 :         ereport(ERROR,
    9174             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    9175             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    9176             :                         colName, RelationGetRelationName(rel))));
    9177         248 :     attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
    9178             : 
    9179         248 :     attnum = attrtuple->attnum;
    9180         248 :     if (attnum <= 0)
    9181           0 :         ereport(ERROR,
    9182             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9183             :                  errmsg("cannot alter system column \"%s\"",
    9184             :                         colName)));
    9185             : 
    9186         248 :     attrtuple->attstorage = GetAttributeStorage(attrtuple->atttypid, strVal(newValue));
    9187             : 
    9188         248 :     CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
    9189             : 
    9190         248 :     InvokeObjectPostAlterHook(RelationRelationId,
    9191             :                               RelationGetRelid(rel),
    9192             :                               attrtuple->attnum);
    9193             : 
    9194             :     /*
    9195             :      * Apply the change to indexes as well (only for simple index columns,
    9196             :      * matching behavior of index.c ConstructTupleDescriptor()).
    9197             :      */
    9198         248 :     SetIndexStorageProperties(rel, attrelation, attnum,
    9199         248 :                               true, attrtuple->attstorage,
    9200             :                               false, 0,
    9201             :                               lockmode);
    9202             : 
    9203         248 :     heap_freetuple(tuple);
    9204             : 
    9205         248 :     table_close(attrelation, RowExclusiveLock);
    9206             : 
    9207         248 :     ObjectAddressSubSet(address, RelationRelationId,
    9208             :                         RelationGetRelid(rel), attnum);
    9209         248 :     return address;
    9210             : }
    9211             : 
    9212             : 
    9213             : /*
    9214             :  * ALTER TABLE DROP COLUMN
    9215             :  *
    9216             :  * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
    9217             :  * because we have to decide at runtime whether to recurse or not depending
    9218             :  * on whether attinhcount goes to zero or not.  (We can't check this in a
    9219             :  * static pre-pass because it won't handle multiple inheritance situations
    9220             :  * correctly.)
    9221             :  */
    9222             : static void
    9223        1658 : ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
    9224             :                  AlterTableCmd *cmd, LOCKMODE lockmode,
    9225             :                  AlterTableUtilityContext *context)
    9226             : {
    9227        1658 :     if (rel->rd_rel->reloftype && !recursing)
    9228           6 :         ereport(ERROR,
    9229             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    9230             :                  errmsg("cannot drop column from typed table")));
    9231             : 
    9232        1652 :     if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
    9233          84 :         ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
    9234             : 
    9235        1646 :     if (recurse)
    9236        1366 :         cmd->recurse = true;
    9237        1646 : }
    9238             : 
    9239             : /*
    9240             :  * Drops column 'colName' from relation 'rel' and returns the address of the
    9241             :  * dropped column.  The column is also dropped (or marked as no longer
    9242             :  * inherited from relation) from the relation's inheritance children, if any.
    9243             :  *
    9244             :  * In the recursive invocations for inheritance child relations, instead of
    9245             :  * dropping the column directly (if to be dropped at all), its object address
    9246             :  * is added to 'addrs', which must be non-NULL in such invocations.  All
    9247             :  * columns are dropped at the same time after all the children have been
    9248             :  * checked recursively.
    9249             :  */
    9250             : static ObjectAddress
    9251        2208 : ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
    9252             :                  DropBehavior behavior,
    9253             :                  bool recurse, bool recursing,
    9254             :                  bool missing_ok, LOCKMODE lockmode,
    9255             :                  ObjectAddresses *addrs)
    9256             : {
    9257             :     HeapTuple   tuple;
    9258             :     Form_pg_attribute targetatt;
    9259             :     AttrNumber  attnum;
    9260             :     List       *children;
    9261             :     ObjectAddress object;
    9262             :     bool        is_expr;
    9263             : 
    9264             :     /* At top level, permission check was done in ATPrepCmd, else do it */
    9265        2208 :     if (recursing)
    9266         562 :         ATSimplePermissions(AT_DropColumn, rel,
    9267             :                             ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    9268             : 
    9269             :     /* Initialize addrs on the first invocation */
    9270             :     Assert(!recursing || addrs != NULL);
    9271             : 
    9272             :     /* since this function recurses, it could be driven to stack overflow */
    9273        2208 :     check_stack_depth();
    9274             : 
    9275        2208 :     if (!recursing)
    9276        1646 :         addrs = new_object_addresses();
    9277             : 
    9278             :     /*
    9279             :      * get the number of the attribute
    9280             :      */
    9281        2208 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
    9282        2208 :     if (!HeapTupleIsValid(tuple))
    9283             :     {
    9284          54 :         if (!missing_ok)
    9285             :         {
    9286          36 :             ereport(ERROR,
    9287             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    9288             :                      errmsg("column \"%s\" of relation \"%s\" does not exist",
    9289             :                             colName, RelationGetRelationName(rel))));
    9290             :         }
    9291             :         else
    9292             :         {
    9293          18 :             ereport(NOTICE,
    9294             :                     (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
    9295             :                             colName, RelationGetRelationName(rel))));
    9296          18 :             return InvalidObjectAddress;
    9297             :         }
    9298             :     }
    9299        2154 :     targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
    9300             : 
    9301        2154 :     attnum = targetatt->attnum;
    9302             : 
    9303             :     /* Can't drop a system attribute */
    9304        2154 :     if (attnum <= 0)
    9305           6 :         ereport(ERROR,
    9306             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9307             :                  errmsg("cannot drop system column \"%s\"",
    9308             :                         colName)));
    9309             : 
    9310             :     /*
    9311             :      * Don't drop inherited columns, unless recursing (presumably from a drop
    9312             :      * of the parent column)
    9313             :      */
    9314        2148 :     if (targetatt->attinhcount > 0 && !recursing)
    9315          48 :         ereport(ERROR,
    9316             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    9317             :                  errmsg("cannot drop inherited column \"%s\"",
    9318             :                         colName)));
    9319             : 
    9320             :     /*
    9321             :      * Don't drop columns used in the partition key, either.  (If we let this
    9322             :      * go through, the key column's dependencies would cause a cascaded drop
    9323             :      * of the whole table, which is surely not what the user expected.)
    9324             :      */
    9325        2100 :     if (has_partition_attrs(rel,
    9326             :                             bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
    9327             :                             &is_expr))
    9328          30 :         ereport(ERROR,
    9329             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    9330             :                  errmsg("cannot drop column \"%s\" because it is part of the partition key of relation \"%s\"",
    9331             :                         colName, RelationGetRelationName(rel))));
    9332             : 
    9333        2070 :     ReleaseSysCache(tuple);
    9334             : 
    9335             :     /*
    9336             :      * Propagate to children as appropriate.  Unlike most other ALTER
    9337             :      * routines, we have to do this one level of recursion at a time; we can't
    9338             :      * use find_all_inheritors to do it in one pass.
    9339             :      */
    9340             :     children =
    9341        2070 :         find_inheritance_children(RelationGetRelid(rel), lockmode);
    9342             : 
    9343        2070 :     if (children)
    9344             :     {
    9345             :         Relation    attr_rel;
    9346             :         ListCell   *child;
    9347             : 
    9348             :         /*
    9349             :          * In case of a partitioned table, the column must be dropped from the
    9350             :          * partitions as well.
    9351             :          */
    9352         308 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
    9353           6 :             ereport(ERROR,
    9354             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    9355             :                      errmsg("cannot drop column from only the partitioned table when partitions exist"),
    9356             :                      errhint("Do not specify the ONLY keyword.")));
    9357             : 
    9358         302 :         attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
    9359         894 :         foreach(child, children)
    9360             :         {
    9361         598 :             Oid         childrelid = lfirst_oid(child);
    9362             :             Relation    childrel;
    9363             :             Form_pg_attribute childatt;
    9364             : 
    9365             :             /* find_inheritance_children already got lock */
    9366         598 :             childrel = table_open(childrelid, NoLock);
    9367         598 :             CheckAlterTableIsSafe(childrel);
    9368             : 
    9369         598 :             tuple = SearchSysCacheCopyAttName(childrelid, colName);
    9370         598 :             if (!HeapTupleIsValid(tuple))   /* shouldn't happen */
    9371           0 :                 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
    9372             :                      colName, childrelid);
    9373         598 :             childatt = (Form_pg_attribute) GETSTRUCT(tuple);
    9374             : 
    9375         598 :             if (childatt->attinhcount <= 0) /* shouldn't happen */
    9376           0 :                 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
    9377             :                      childrelid, colName);
    9378             : 
    9379         598 :             if (recurse)
    9380             :             {
    9381             :                 /*
    9382             :                  * If the child column has other definition sources, just
    9383             :                  * decrement its inheritance count; if not, recurse to delete
    9384             :                  * it.
    9385             :                  */
    9386         574 :                 if (childatt->attinhcount == 1 && !childatt->attislocal)
    9387             :                 {
    9388             :                     /* Time to delete this child column, too */
    9389         562 :                     ATExecDropColumn(wqueue, childrel, colName,
    9390             :                                      behavior, true, true,
    9391             :                                      false, lockmode, addrs);
    9392             :                 }
    9393             :                 else
    9394             :                 {
    9395             :                     /* Child column must survive my deletion */
    9396          12 :                     childatt->attinhcount--;
    9397             : 
    9398          12 :                     CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
    9399             : 
    9400             :                     /* Make update visible */
    9401          12 :                     CommandCounterIncrement();
    9402             :                 }
    9403             :             }
    9404             :             else
    9405             :             {
    9406             :                 /*
    9407             :                  * If we were told to drop ONLY in this table (no recursion),
    9408             :                  * we need to mark the inheritors' attributes as locally
    9409             :                  * defined rather than inherited.
    9410             :                  */
    9411          24 :                 childatt->attinhcount--;
    9412          24 :                 childatt->attislocal = true;
    9413             : 
    9414          24 :                 CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
    9415             : 
    9416             :                 /* Make update visible */
    9417          24 :                 CommandCounterIncrement();
    9418             :             }
    9419             : 
    9420         592 :             heap_freetuple(tuple);
    9421             : 
    9422         592 :             table_close(childrel, NoLock);
    9423             :         }
    9424         296 :         table_close(attr_rel, RowExclusiveLock);
    9425             :     }
    9426             : 
    9427             :     /* Add object to delete */
    9428        2058 :     object.classId = RelationRelationId;
    9429        2058 :     object.objectId = RelationGetRelid(rel);
    9430        2058 :     object.objectSubId = attnum;
    9431        2058 :     add_exact_object_address(&object, addrs);
    9432             : 
    9433        2058 :     if (!recursing)
    9434             :     {
    9435             :         /* Recursion has ended, drop everything that was collected */
    9436        1502 :         performMultipleDeletions(addrs, behavior, 0);
    9437        1448 :         free_object_addresses(addrs);
    9438             :     }
    9439             : 
    9440        2004 :     return object;
    9441             : }
    9442             : 
    9443             : /*
    9444             :  * Prepare to add a primary key on a table, by adding not-null constraints
    9445             :  * on all columns.
    9446             :  *
    9447             :  * The not-null constraints for a primary key must cover the whole inheritance
    9448             :  * hierarchy (failing to ensure that leads to funny corner cases).  For the
    9449             :  * normal case where we're asked to recurse, this routine checks if the
    9450             :  * not-null constraints exist already, and if not queues a requirement for
    9451             :  * them to be created by phase 2.
    9452             :  *
    9453             :  * For the case where we're asked not to recurse, we verify that a not-null
    9454             :  * constraint exists on each column of each (direct) child table, throwing an
    9455             :  * error if not.  Not throwing an error would also work, because a not-null
    9456             :  * constraint would be created anyway, but it'd cause a silent scan of the
    9457             :  * child table to verify absence of nulls.  We prefer to let the user know so
    9458             :  * that they can add the constraint manually without having to hold
    9459             :  * AccessExclusiveLock while at it.
    9460             :  *
    9461             :  * However, it's also important that we do not acquire locks on children if
    9462             :  * the not-null constraints already exist on the parent, to avoid risking
    9463             :  * deadlocks during parallel pg_restore of PKs on partitioned tables.
    9464             :  */
    9465             : static void
    9466       16078 : ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
    9467             :                     bool recurse, LOCKMODE lockmode,
    9468             :                     AlterTableUtilityContext *context)
    9469             : {
    9470             :     Constraint *pkconstr;
    9471       16078 :     List       *children = NIL;
    9472       16078 :     bool        got_children = false;
    9473             : 
    9474       16078 :     pkconstr = castNode(Constraint, cmd->def);
    9475       16078 :     if (pkconstr->contype != CONSTR_PRIMARY)
    9476        9224 :         return;
    9477             : 
    9478             :     /* Verify that columns are not-null, or request that they be made so */
    9479       14676 :     foreach_node(String, column, pkconstr->keys)
    9480             :     {
    9481             :         AlterTableCmd *newcmd;
    9482             :         Constraint *nnconstr;
    9483             :         HeapTuple   tuple;
    9484             : 
    9485             :         /*
    9486             :          * First check if a suitable constraint exists.  If it does, we don't
    9487             :          * need to request another one.  We do need to bail out if it's not
    9488             :          * valid, though.
    9489             :          */
    9490        1028 :         tuple = findNotNullConstraint(RelationGetRelid(rel), strVal(column));
    9491        1028 :         if (tuple != NULL)
    9492             :         {
    9493         518 :             verifyNotNullPKCompatible(tuple, strVal(column));
    9494             : 
    9495             :             /* All good with this one; don't request another */
    9496         506 :             heap_freetuple(tuple);
    9497         506 :             continue;
    9498             :         }
    9499         510 :         else if (!recurse)
    9500             :         {
    9501             :             /*
    9502             :              * No constraint on this column.  Asked not to recurse, we won't
    9503             :              * create one here, but verify that all children have one.
    9504             :              */
    9505          36 :             if (!got_children)
    9506             :             {
    9507          36 :                 children = find_inheritance_children(RelationGetRelid(rel),
    9508             :                                                      lockmode);
    9509             :                 /* only search for children on the first time through */
    9510          36 :                 got_children = true;
    9511             :             }
    9512             : 
    9513          72 :             foreach_oid(childrelid, children)
    9514             :             {
    9515             :                 HeapTuple   tup;
    9516             : 
    9517          36 :                 tup = findNotNullConstraint(childrelid, strVal(column));
    9518          36 :                 if (!tup)
    9519           6 :                     ereport(ERROR,
    9520             :                             errmsg("column \"%s\" of table \"%s\" is not marked NOT NULL",
    9521             :                                    strVal(column), get_rel_name(childrelid)));
    9522             :                 /* verify it's good enough */
    9523          30 :                 verifyNotNullPKCompatible(tup, strVal(column));
    9524             :             }
    9525             :         }
    9526             : 
    9527             :         /* This column is not already not-null, so add it to the queue */
    9528         492 :         nnconstr = makeNotNullConstraint(column);
    9529             : 
    9530         492 :         newcmd = makeNode(AlterTableCmd);
    9531         492 :         newcmd->subtype = AT_AddConstraint;
    9532             :         /* note we force recurse=true here; see above */
    9533         492 :         newcmd->recurse = true;
    9534         492 :         newcmd->def = (Node *) nnconstr;
    9535             : 
    9536         492 :         ATPrepCmd(wqueue, rel, newcmd, true, false, lockmode, context);
    9537             :     }
    9538             : }
    9539             : 
    9540             : /*
    9541             :  * Verify whether the given not-null constraint is compatible with a
    9542             :  * primary key.  If not, an error is thrown.
    9543             :  */
    9544             : static void
    9545         548 : verifyNotNullPKCompatible(HeapTuple tuple, const char *colname)
    9546             : {
    9547         548 :     Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
    9548             : 
    9549         548 :     if (conForm->contype != CONSTRAINT_NOTNULL)
    9550           0 :         elog(ERROR, "constraint %u is not a not-null constraint", conForm->oid);
    9551             : 
    9552             :     /* a NO INHERIT constraint is no good */
    9553         548 :     if (conForm->connoinherit)
    9554          12 :         ereport(ERROR,
    9555             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    9556             :                 errmsg("cannot create primary key on column \"%s\"", colname),
    9557             :         /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
    9558             :                 errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
    9559             :                           NameStr(conForm->conname), colname,
    9560             :                           get_rel_name(conForm->conrelid), "NO INHERIT"),
    9561             :                 errhint("You might need to make the existing constraint inheritable using %s.",
    9562             :                         "ALTER TABLE ... ALTER CONSTRAINT ... INHERIT"));
    9563             : 
    9564             :     /* an unvalidated constraint is no good */
    9565         536 :     if (!conForm->convalidated)
    9566          12 :         ereport(ERROR,
    9567             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    9568             :                 errmsg("cannot create primary key on column \"%s\"", colname),
    9569             :         /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
    9570             :                 errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
    9571             :                           NameStr(conForm->conname), colname,
    9572             :                           get_rel_name(conForm->conrelid), "NOT VALID"),
    9573             :                 errhint("You might need to validate it using %s.",
    9574             :                         "ALTER TABLE ... VALIDATE CONSTRAINT"));
    9575         524 : }
    9576             : 
    9577             : /*
    9578             :  * ALTER TABLE ADD INDEX
    9579             :  *
    9580             :  * There is no such command in the grammar, but parse_utilcmd.c converts
    9581             :  * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands.  This lets
    9582             :  * us schedule creation of the index at the appropriate time during ALTER.
    9583             :  *
    9584             :  * Return value is the address of the new index.
    9585             :  */
    9586             : static ObjectAddress
    9587        1634 : ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
    9588             :                IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
    9589             : {
    9590             :     bool        check_rights;
    9591             :     bool        skip_build;
    9592             :     bool        quiet;
    9593             :     ObjectAddress address;
    9594             : 
    9595             :     Assert(IsA(stmt, IndexStmt));
    9596             :     Assert(!stmt->concurrent);
    9597             : 
    9598             :     /* The IndexStmt has already been through transformIndexStmt */
    9599             :     Assert(stmt->transformed);
    9600             : 
    9601             :     /* suppress schema rights check when rebuilding existing index */
    9602        1634 :     check_rights = !is_rebuild;
    9603             :     /* skip index build if phase 3 will do it or we're reusing an old one */
    9604        1634 :     skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
    9605             :     /* suppress notices when rebuilding existing index */
    9606        1634 :     quiet = is_rebuild;
    9607             : 
    9608        1634 :     address = DefineIndex(RelationGetRelid(rel),
    9609             :                           stmt,
    9610             :                           InvalidOid,   /* no predefined OID */
    9611             :                           InvalidOid,   /* no parent index */
    9612             :                           InvalidOid,   /* no parent constraint */
    9613             :                           -1,   /* total_parts unknown */
    9614             :                           true, /* is_alter_table */
    9615             :                           check_rights,
    9616             :                           false,    /* check_not_in_use - we did it already */
    9617             :                           skip_build,
    9618             :                           quiet);
    9619             : 
    9620             :     /*
    9621             :      * If TryReuseIndex() stashed a relfilenumber for us, we used it for the
    9622             :      * new index instead of building from scratch.  Restore associated fields.
    9623             :      * This may store InvalidSubTransactionId in both fields, in which case
    9624             :      * relcache.c will assume it can rebuild the relcache entry.  Hence, do
    9625             :      * this after the CCI that made catalog rows visible to any rebuild.  The
    9626             :      * DROP of the old edition of this index will have scheduled the storage
    9627             :      * for deletion at commit, so cancel that pending deletion.
    9628             :      */
    9629        1464 :     if (RelFileNumberIsValid(stmt->oldNumber))
    9630             :     {
    9631          74 :         Relation    irel = index_open(address.objectId, NoLock);
    9632             : 
    9633          74 :         irel->rd_createSubid = stmt->oldCreateSubid;
    9634          74 :         irel->rd_firstRelfilelocatorSubid = stmt->oldFirstRelfilelocatorSubid;
    9635          74 :         RelationPreserveStorage(irel->rd_locator, true);
    9636          74 :         index_close(irel, NoLock);
    9637             :     }
    9638             : 
    9639        1464 :     return address;
    9640             : }
    9641             : 
    9642             : /*
    9643             :  * ALTER TABLE ADD STATISTICS
    9644             :  *
    9645             :  * This is no such command in the grammar, but we use this internally to add
    9646             :  * AT_ReAddStatistics subcommands to rebuild extended statistics after a table
    9647             :  * column type change.
    9648             :  */
    9649             : static ObjectAddress
    9650          26 : ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
    9651             :                     CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
    9652             : {
    9653             :     ObjectAddress address;
    9654             : 
    9655             :     Assert(IsA(stmt, CreateStatsStmt));
    9656             : 
    9657             :     /* The CreateStatsStmt has already been through transformStatsStmt */
    9658             :     Assert(stmt->transformed);
    9659             : 
    9660          26 :     address = CreateStatistics(stmt);
    9661             : 
    9662          26 :     return address;
    9663             : }
    9664             : 
    9665             : /*
    9666             :  * ALTER TABLE ADD CONSTRAINT USING INDEX
    9667             :  *
    9668             :  * Returns the address of the new constraint.
    9669             :  */
    9670             : static ObjectAddress
    9671       10640 : ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
    9672             :                          IndexStmt *stmt, LOCKMODE lockmode)
    9673             : {
    9674       10640 :     Oid         index_oid = stmt->indexOid;
    9675             :     Relation    indexRel;
    9676             :     char       *indexName;
    9677             :     IndexInfo  *indexInfo;
    9678             :     char       *constraintName;
    9679             :     char        constraintType;
    9680             :     ObjectAddress address;
    9681             :     bits16      flags;
    9682             : 
    9683             :     Assert(IsA(stmt, IndexStmt));
    9684             :     Assert(OidIsValid(index_oid));
    9685             :     Assert(stmt->isconstraint);
    9686             : 
    9687             :     /*
    9688             :      * Doing this on partitioned tables is not a simple feature to implement,
    9689             :      * so let's punt for now.
    9690             :      */
    9691       10640 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    9692           6 :         ereport(ERROR,
    9693             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    9694             :                  errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
    9695             : 
    9696       10634 :     indexRel = index_open(index_oid, AccessShareLock);
    9697             : 
    9698       10634 :     indexName = pstrdup(RelationGetRelationName(indexRel));
    9699             : 
    9700       10634 :     indexInfo = BuildIndexInfo(indexRel);
    9701             : 
    9702             :     /* this should have been checked at parse time */
    9703       10634 :     if (!indexInfo->ii_Unique)
    9704           0 :         elog(ERROR, "index \"%s\" is not unique", indexName);
    9705             : 
    9706             :     /*
    9707             :      * Determine name to assign to constraint.  We require a constraint to
    9708             :      * have the same name as the underlying index; therefore, use the index's
    9709             :      * existing name as the default constraint name, and if the user
    9710             :      * explicitly gives some other name for the constraint, rename the index
    9711             :      * to match.
    9712             :      */
    9713       10634 :     constraintName = stmt->idxname;
    9714       10634 :     if (constraintName == NULL)
    9715       10608 :         constraintName = indexName;
    9716          26 :     else if (strcmp(constraintName, indexName) != 0)
    9717             :     {
    9718          20 :         ereport(NOTICE,
    9719             :                 (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
    9720             :                         indexName, constraintName)));
    9721          20 :         RenameRelationInternal(index_oid, constraintName, false, true);
    9722             :     }
    9723             : 
    9724             :     /* Extra checks needed if making primary key */
    9725       10634 :     if (stmt->primary)
    9726        6006 :         index_check_primary_key(rel, indexInfo, true, stmt);
    9727             : 
    9728             :     /* Note we currently don't support EXCLUSION constraints here */
    9729       10628 :     if (stmt->primary)
    9730        6000 :         constraintType = CONSTRAINT_PRIMARY;
    9731             :     else
    9732        4628 :         constraintType = CONSTRAINT_UNIQUE;
    9733             : 
    9734             :     /* Create the catalog entries for the constraint */
    9735       10628 :     flags = INDEX_CONSTR_CREATE_UPDATE_INDEX |
    9736             :         INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS |
    9737       21256 :         (stmt->initdeferred ? INDEX_CONSTR_CREATE_INIT_DEFERRED : 0) |
    9738       10628 :         (stmt->deferrable ? INDEX_CONSTR_CREATE_DEFERRABLE : 0) |
    9739       10628 :         (stmt->primary ? INDEX_CONSTR_CREATE_MARK_AS_PRIMARY : 0);
    9740             : 
    9741       10628 :     address = index_constraint_create(rel,
    9742             :                                       index_oid,
    9743             :                                       InvalidOid,
    9744             :                                       indexInfo,
    9745             :                                       constraintName,
    9746             :                                       constraintType,
    9747             :                                       flags,
    9748             :                                       allowSystemTableMods,
    9749             :                                       false);   /* is_internal */
    9750             : 
    9751       10628 :     index_close(indexRel, NoLock);
    9752             : 
    9753       10628 :     return address;
    9754             : }
    9755             : 
    9756             : /*
    9757             :  * ALTER TABLE ADD CONSTRAINT
    9758             :  *
    9759             :  * Return value is the address of the new constraint; if no constraint was
    9760             :  * added, InvalidObjectAddress is returned.
    9761             :  */
    9762             : static ObjectAddress
    9763       12848 : ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
    9764             :                     Constraint *newConstraint, bool recurse, bool is_readd,
    9765             :                     LOCKMODE lockmode)
    9766             : {
    9767       12848 :     ObjectAddress address = InvalidObjectAddress;
    9768             : 
    9769             :     Assert(IsA(newConstraint, Constraint));
    9770             : 
    9771             :     /*
    9772             :      * Currently, we only expect to see CONSTR_CHECK, CONSTR_NOTNULL and
    9773             :      * CONSTR_FOREIGN nodes arriving here (see the preprocessing done in
    9774             :      * parse_utilcmd.c).
    9775             :      */
    9776       12848 :     switch (newConstraint->contype)
    9777             :     {
    9778       10176 :         case CONSTR_CHECK:
    9779             :         case CONSTR_NOTNULL:
    9780             :             address =
    9781       10176 :                 ATAddCheckNNConstraint(wqueue, tab, rel,
    9782             :                                        newConstraint, recurse, false, is_readd,
    9783             :                                        lockmode);
    9784       10032 :             break;
    9785             : 
    9786        2672 :         case CONSTR_FOREIGN:
    9787             : 
    9788             :             /*
    9789             :              * Assign or validate constraint name
    9790             :              */
    9791        2672 :             if (newConstraint->conname)
    9792             :             {
    9793        1200 :                 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
    9794             :                                          RelationGetRelid(rel),
    9795        1200 :                                          newConstraint->conname))
    9796           0 :                     ereport(ERROR,
    9797             :                             (errcode(ERRCODE_DUPLICATE_OBJECT),
    9798             :                              errmsg("constraint \"%s\" for relation \"%s\" already exists",
    9799             :                                     newConstraint->conname,
    9800             :                                     RelationGetRelationName(rel))));
    9801             :             }
    9802             :             else
    9803        1472 :                 newConstraint->conname =
    9804        1472 :                     ChooseConstraintName(RelationGetRelationName(rel),
    9805        1472 :                                          ChooseForeignKeyConstraintNameAddition(newConstraint->fk_attrs),
    9806             :                                          "fkey",
    9807        1472 :                                          RelationGetNamespace(rel),
    9808             :                                          NIL);
    9809             : 
    9810        2672 :             address = ATAddForeignKeyConstraint(wqueue, tab, rel,
    9811             :                                                 newConstraint,
    9812             :                                                 recurse, false,
    9813             :                                                 lockmode);
    9814        2124 :             break;
    9815             : 
    9816           0 :         default:
    9817           0 :             elog(ERROR, "unrecognized constraint type: %d",
    9818             :                  (int) newConstraint->contype);
    9819             :     }
    9820             : 
    9821       12156 :     return address;
    9822             : }
    9823             : 
    9824             : /*
    9825             :  * Generate the column-name portion of the constraint name for a new foreign
    9826             :  * key given the list of column names that reference the referenced
    9827             :  * table.  This will be passed to ChooseConstraintName along with the parent
    9828             :  * table name and the "fkey" suffix.
    9829             :  *
    9830             :  * We know that less than NAMEDATALEN characters will actually be used, so we
    9831             :  * can truncate the result once we've generated that many.
    9832             :  *
    9833             :  * XXX see also ChooseExtendedStatisticNameAddition and
    9834             :  * ChooseIndexNameAddition.
    9835             :  */
    9836             : static char *
    9837        1472 : ChooseForeignKeyConstraintNameAddition(List *colnames)
    9838             : {
    9839             :     char        buf[NAMEDATALEN * 2];
    9840        1472 :     int         buflen = 0;
    9841             :     ListCell   *lc;
    9842             : 
    9843        1472 :     buf[0] = '\0';
    9844        3372 :     foreach(lc, colnames)
    9845             :     {
    9846        1900 :         const char *name = strVal(lfirst(lc));
    9847             : 
    9848        1900 :         if (buflen > 0)
    9849         428 :             buf[buflen++] = '_';    /* insert _ between names */
    9850             : 
    9851             :         /*
    9852             :          * At this point we have buflen <= NAMEDATALEN.  name should be less
    9853             :          * than NAMEDATALEN already, but use strlcpy for paranoia.
    9854             :          */
    9855        1900 :         strlcpy(buf + buflen, name, NAMEDATALEN);
    9856        1900 :         buflen += strlen(buf + buflen);
    9857        1900 :         if (buflen >= NAMEDATALEN)
    9858           0 :             break;
    9859             :     }
    9860        1472 :     return pstrdup(buf);
    9861             : }
    9862             : 
    9863             : /*
    9864             :  * Add a check or not-null constraint to a single table and its children.
    9865             :  * Returns the address of the constraint added to the parent relation,
    9866             :  * if one gets added, or InvalidObjectAddress otherwise.
    9867             :  *
    9868             :  * Subroutine for ATExecAddConstraint.
    9869             :  *
    9870             :  * We must recurse to child tables during execution, rather than using
    9871             :  * ALTER TABLE's normal prep-time recursion.  The reason is that all the
    9872             :  * constraints *must* be given the same name, else they won't be seen as
    9873             :  * related later.  If the user didn't explicitly specify a name, then
    9874             :  * AddRelationNewConstraints would normally assign different names to the
    9875             :  * child constraints.  To fix that, we must capture the name assigned at
    9876             :  * the parent table and pass that down.
    9877             :  */
    9878             : static ObjectAddress
    9879       10966 : ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
    9880             :                        Constraint *constr, bool recurse, bool recursing,
    9881             :                        bool is_readd, LOCKMODE lockmode)
    9882             : {
    9883             :     List       *newcons;
    9884             :     ListCell   *lcon;
    9885             :     List       *children;
    9886             :     ListCell   *child;
    9887       10966 :     ObjectAddress address = InvalidObjectAddress;
    9888             : 
    9889             :     /* Guard against stack overflow due to overly deep inheritance tree. */
    9890       10966 :     check_stack_depth();
    9891             : 
    9892             :     /* At top level, permission check was done in ATPrepCmd, else do it */
    9893       10966 :     if (recursing)
    9894         790 :         ATSimplePermissions(AT_AddConstraint, rel,
    9895             :                             ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
    9896             : 
    9897             :     /*
    9898             :      * Call AddRelationNewConstraints to do the work, making sure it works on
    9899             :      * a copy of the Constraint so transformExpr can't modify the original. It
    9900             :      * returns a list of cooked constraints.
    9901             :      *
    9902             :      * If the constraint ends up getting merged with a pre-existing one, it's
    9903             :      * omitted from the returned list, which is what we want: we do not need
    9904             :      * to do any validation work.  That can only happen at child tables,
    9905             :      * though, since we disallow merging at the top level.
    9906             :      */
    9907       10966 :     newcons = AddRelationNewConstraints(rel, NIL,
    9908       10966 :                                         list_make1(copyObject(constr)),
    9909       10966 :                                         recursing || is_readd,  /* allow_merge */
    9910       10966 :                                         !recursing, /* is_local */
    9911             :                                         is_readd,   /* is_internal */
    9912       10966 :                                         NULL);  /* queryString not available
    9913             :                                                  * here */
    9914             : 
    9915             :     /* we don't expect more than one constraint here */
    9916             :     Assert(list_length(newcons) <= 1);
    9917             : 
    9918             :     /* Add each to-be-validated constraint to Phase 3's queue */
    9919       21456 :     foreach(lcon, newcons)
    9920             :     {
    9921       10628 :         CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
    9922             : 
    9923       10628 :         if (!ccon->skip_validation && ccon->contype != CONSTR_NOTNULL)
    9924             :         {
    9925             :             NewConstraint *newcon;
    9926             : 
    9927         910 :             newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
    9928         910 :             newcon->name = ccon->name;
    9929         910 :             newcon->contype = ccon->contype;
    9930         910 :             newcon->qual = ccon->expr;
    9931             : 
    9932         910 :             tab->constraints = lappend(tab->constraints, newcon);
    9933             :         }
    9934             : 
    9935             :         /* Save the actually assigned name if it was defaulted */
    9936       10628 :         if (constr->conname == NULL)
    9937        8898 :             constr->conname = ccon->name;
    9938             : 
    9939             :         /*
    9940             :          * If adding a valid not-null constraint, set the pg_attribute flag
    9941             :          * and tell phase 3 to verify existing rows, if needed.  For an
    9942             :          * invalid constraint, just set attnotnull, without queueing
    9943             :          * verification.
    9944             :          */
    9945       10628 :         if (constr->contype == CONSTR_NOTNULL)
    9946        9314 :             set_attnotnull(wqueue, rel, ccon->attnum,
    9947        9314 :                            !constr->skip_validation,
    9948        9314 :                            !constr->skip_validation);
    9949             : 
    9950       10628 :         ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
    9951             :     }
    9952             : 
    9953             :     /* At this point we must have a locked-down name to use */
    9954             :     Assert(newcons == NIL || constr->conname != NULL);
    9955             : 
    9956             :     /* Advance command counter in case same table is visited multiple times */
    9957       10828 :     CommandCounterIncrement();
    9958             : 
    9959             :     /*
    9960             :      * If the constraint got merged with an existing constraint, we're done.
    9961             :      * We mustn't recurse to child tables in this case, because they've
    9962             :      * already got the constraint, and visiting them again would lead to an
    9963             :      * incorrect value for coninhcount.
    9964             :      */
    9965       10828 :     if (newcons == NIL)
    9966         200 :         return address;
    9967             : 
    9968             :     /*
    9969             :      * If adding a NO INHERIT constraint, no need to find our children.
    9970             :      */
    9971       10628 :     if (constr->is_no_inherit)
    9972          84 :         return address;
    9973             : 
    9974             :     /*
    9975             :      * Propagate to children as appropriate.  Unlike most other ALTER
    9976             :      * routines, we have to do this one level of recursion at a time; we can't
    9977             :      * use find_all_inheritors to do it in one pass.
    9978             :      */
    9979             :     children =
    9980       10544 :         find_inheritance_children(RelationGetRelid(rel), lockmode);
    9981             : 
    9982             :     /*
    9983             :      * Check if ONLY was specified with ALTER TABLE.  If so, allow the
    9984             :      * constraint creation only if there are no children currently. Error out
    9985             :      * otherwise.
    9986             :      */
    9987       10544 :     if (!recurse && children != NIL)
    9988           6 :         ereport(ERROR,
    9989             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    9990             :                  errmsg("constraint must be added to child tables too")));
    9991             : 
    9992             :     /*
    9993             :      * Recurse to create the constraint on each child.
    9994             :      */
    9995       11298 :     foreach(child, children)
    9996             :     {
    9997         790 :         Oid         childrelid = lfirst_oid(child);
    9998             :         Relation    childrel;
    9999             :         AlteredTableInfo *childtab;
   10000             : 
   10001             :         /* find_inheritance_children already got lock */
   10002         790 :         childrel = table_open(childrelid, NoLock);
   10003         790 :         CheckAlterTableIsSafe(childrel);
   10004             : 
   10005             :         /* Find or create work queue entry for this table */
   10006         790 :         childtab = ATGetQueueEntry(wqueue, childrel);
   10007             : 
   10008             :         /* Recurse to this child */
   10009         790 :         ATAddCheckNNConstraint(wqueue, childtab, childrel,
   10010             :                                constr, recurse, true, is_readd, lockmode);
   10011             : 
   10012         760 :         table_close(childrel, NoLock);
   10013             :     }
   10014             : 
   10015       10508 :     return address;
   10016             : }
   10017             : 
   10018             : /*
   10019             :  * Add a foreign-key constraint to a single table; return the new constraint's
   10020             :  * address.
   10021             :  *
   10022             :  * Subroutine for ATExecAddConstraint.  Must already hold exclusive
   10023             :  * lock on the rel, and have done appropriate validity checks for it.
   10024             :  * We do permissions checks here, however.
   10025             :  *
   10026             :  * When the referenced or referencing tables (or both) are partitioned,
   10027             :  * multiple pg_constraint rows are required -- one for each partitioned table
   10028             :  * and each partition on each side (fortunately, not one for every combination
   10029             :  * thereof).  We also need action triggers on each leaf partition on the
   10030             :  * referenced side, and check triggers on each leaf partition on the
   10031             :  * referencing side.
   10032             :  */
   10033             : static ObjectAddress
   10034        2672 : ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
   10035             :                           Constraint *fkconstraint,
   10036             :                           bool recurse, bool recursing, LOCKMODE lockmode)
   10037             : {
   10038             :     Relation    pkrel;
   10039        2672 :     int16       pkattnum[INDEX_MAX_KEYS] = {0};
   10040        2672 :     int16       fkattnum[INDEX_MAX_KEYS] = {0};
   10041        2672 :     Oid         pktypoid[INDEX_MAX_KEYS] = {0};
   10042        2672 :     Oid         fktypoid[INDEX_MAX_KEYS] = {0};
   10043        2672 :     Oid         pkcolloid[INDEX_MAX_KEYS] = {0};
   10044        2672 :     Oid         fkcolloid[INDEX_MAX_KEYS] = {0};
   10045        2672 :     Oid         opclasses[INDEX_MAX_KEYS] = {0};
   10046        2672 :     Oid         pfeqoperators[INDEX_MAX_KEYS] = {0};
   10047        2672 :     Oid         ppeqoperators[INDEX_MAX_KEYS] = {0};
   10048        2672 :     Oid         ffeqoperators[INDEX_MAX_KEYS] = {0};
   10049        2672 :     int16       fkdelsetcols[INDEX_MAX_KEYS] = {0};
   10050             :     bool        with_period;
   10051             :     bool        pk_has_without_overlaps;
   10052             :     int         i;
   10053             :     int         numfks,
   10054             :                 numpks,
   10055             :                 numfkdelsetcols;
   10056             :     Oid         indexOid;
   10057             :     bool        old_check_ok;
   10058             :     ObjectAddress address;
   10059        2672 :     ListCell   *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
   10060             : 
   10061             :     /*
   10062             :      * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
   10063             :      * delete rows out from under us.
   10064             :      */
   10065        2672 :     if (OidIsValid(fkconstraint->old_pktable_oid))
   10066          72 :         pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
   10067             :     else
   10068        2600 :         pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
   10069             : 
   10070             :     /*
   10071             :      * Validity checks (permission checks wait till we have the column
   10072             :      * numbers)
   10073             :      */
   10074        2666 :     if (!recurse && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   10075           6 :         ereport(ERROR,
   10076             :                 errcode(ERRCODE_WRONG_OBJECT_TYPE),
   10077             :                 errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
   10078             :                        RelationGetRelationName(rel),
   10079             :                        RelationGetRelationName(pkrel)));
   10080             : 
   10081        2660 :     if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
   10082         350 :         pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
   10083           0 :         ereport(ERROR,
   10084             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   10085             :                  errmsg("referenced relation \"%s\" is not a table",
   10086             :                         RelationGetRelationName(pkrel))));
   10087             : 
   10088        2660 :     if (!allowSystemTableMods && IsSystemRelation(pkrel))
   10089           2 :         ereport(ERROR,
   10090             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
   10091             :                  errmsg("permission denied: \"%s\" is a system catalog",
   10092             :                         RelationGetRelationName(pkrel))));
   10093             : 
   10094             :     /*
   10095             :      * References from permanent or unlogged tables to temp tables, and from
   10096             :      * permanent tables to unlogged tables, are disallowed because the
   10097             :      * referenced data can vanish out from under us.  References from temp
   10098             :      * tables to any other table type are also disallowed, because other
   10099             :      * backends might need to run the RI triggers on the perm table, but they
   10100             :      * can't reliably see tuples in the local buffers of other backends.
   10101             :      */
   10102        2658 :     switch (rel->rd_rel->relpersistence)
   10103             :     {
   10104        2368 :         case RELPERSISTENCE_PERMANENT:
   10105        2368 :             if (!RelationIsPermanent(pkrel))
   10106           0 :                 ereport(ERROR,
   10107             :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   10108             :                          errmsg("constraints on permanent tables may reference only permanent tables")));
   10109        2368 :             break;
   10110          12 :         case RELPERSISTENCE_UNLOGGED:
   10111          12 :             if (!RelationIsPermanent(pkrel)
   10112          12 :                 && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
   10113           0 :                 ereport(ERROR,
   10114             :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   10115             :                          errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
   10116          12 :             break;
   10117         278 :         case RELPERSISTENCE_TEMP:
   10118         278 :             if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
   10119           0 :                 ereport(ERROR,
   10120             :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   10121             :                          errmsg("constraints on temporary tables may reference only temporary tables")));
   10122         278 :             if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
   10123           0 :                 ereport(ERROR,
   10124             :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   10125             :                          errmsg("constraints on temporary tables must involve temporary tables of this session")));
   10126         278 :             break;
   10127             :     }
   10128             : 
   10129             :     /*
   10130             :      * Look up the referencing attributes to make sure they exist, and record
   10131             :      * their attnums and type and collation OIDs.
   10132             :      */
   10133        2658 :     numfks = transformColumnNameList(RelationGetRelid(rel),
   10134             :                                      fkconstraint->fk_attrs,
   10135             :                                      fkattnum, fktypoid, fkcolloid);
   10136        2628 :     with_period = fkconstraint->fk_with_period || fkconstraint->pk_with_period;
   10137        2628 :     if (with_period && !fkconstraint->fk_with_period)
   10138          24 :         ereport(ERROR,
   10139             :                 errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10140             :                 errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
   10141             : 
   10142        2604 :     numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
   10143             :                                               fkconstraint->fk_del_set_cols,
   10144             :                                               fkdelsetcols, NULL, NULL);
   10145        2598 :     numfkdelsetcols = validateFkOnDeleteSetColumns(numfks, fkattnum,
   10146             :                                                    numfkdelsetcols,
   10147             :                                                    fkdelsetcols,
   10148             :                                                    fkconstraint->fk_del_set_cols);
   10149             : 
   10150             :     /*
   10151             :      * If the attribute list for the referenced table was omitted, lookup the
   10152             :      * definition of the primary key and use it.  Otherwise, validate the
   10153             :      * supplied attribute list.  In either case, discover the index OID and
   10154             :      * index opclasses, and the attnums and type and collation OIDs of the
   10155             :      * attributes.
   10156             :      */
   10157        2592 :     if (fkconstraint->pk_attrs == NIL)
   10158             :     {
   10159        1256 :         numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
   10160             :                                             &fkconstraint->pk_attrs,
   10161             :                                             pkattnum, pktypoid, pkcolloid,
   10162             :                                             opclasses, &pk_has_without_overlaps);
   10163             : 
   10164             :         /* If the primary key uses WITHOUT OVERLAPS, the fk must use PERIOD */
   10165        1256 :         if (pk_has_without_overlaps && !fkconstraint->fk_with_period)
   10166          24 :             ereport(ERROR,
   10167             :                     errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10168             :                     errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
   10169             :     }
   10170             :     else
   10171             :     {
   10172        1336 :         numpks = transformColumnNameList(RelationGetRelid(pkrel),
   10173             :                                          fkconstraint->pk_attrs,
   10174             :                                          pkattnum, pktypoid, pkcolloid);
   10175             : 
   10176             :         /* Since we got pk_attrs, one should be a period. */
   10177        1306 :         if (with_period && !fkconstraint->pk_with_period)
   10178          24 :             ereport(ERROR,
   10179             :                     errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10180             :                     errmsg("foreign key uses PERIOD on the referencing table but not the referenced table"));
   10181             : 
   10182             :         /* Look for an index matching the column list */
   10183        1282 :         indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
   10184             :                                            with_period, opclasses, &pk_has_without_overlaps);
   10185             :     }
   10186             : 
   10187             :     /*
   10188             :      * If the referenced primary key has WITHOUT OVERLAPS, the foreign key
   10189             :      * must use PERIOD.
   10190             :      */
   10191        2478 :     if (pk_has_without_overlaps && !with_period)
   10192          12 :         ereport(ERROR,
   10193             :                 errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10194             :                 errmsg("foreign key must use PERIOD when referencing a primary key using WITHOUT OVERLAPS"));
   10195             : 
   10196             :     /*
   10197             :      * Now we can check permissions.
   10198             :      */
   10199        2466 :     checkFkeyPermissions(pkrel, pkattnum, numpks);
   10200             : 
   10201             :     /*
   10202             :      * Check some things for generated columns.
   10203             :      */
   10204        5796 :     for (i = 0; i < numfks; i++)
   10205             :     {
   10206        3360 :         char        attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
   10207             : 
   10208        3360 :         if (attgenerated)
   10209             :         {
   10210             :             /*
   10211             :              * Check restrictions on UPDATE/DELETE actions, per SQL standard
   10212             :              */
   10213          48 :             if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
   10214          48 :                 fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
   10215          48 :                 fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
   10216          12 :                 ereport(ERROR,
   10217             :                         (errcode(ERRCODE_SYNTAX_ERROR),
   10218             :                          errmsg("invalid %s action for foreign key constraint containing generated column",
   10219             :                                 "ON UPDATE")));
   10220          36 :             if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
   10221          24 :                 fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
   10222          12 :                 ereport(ERROR,
   10223             :                         (errcode(ERRCODE_SYNTAX_ERROR),
   10224             :                          errmsg("invalid %s action for foreign key constraint containing generated column",
   10225             :                                 "ON DELETE")));
   10226             :         }
   10227             : 
   10228             :         /*
   10229             :          * FKs on virtual columns are not supported.  This would require
   10230             :          * various additional support in ri_triggers.c, including special
   10231             :          * handling in ri_NullCheck(), ri_KeysEqual(),
   10232             :          * RI_FKey_fk_upd_check_required() (since all virtual columns appear
   10233             :          * as NULL there).  Also not really practical as long as you can't
   10234             :          * index virtual columns.
   10235             :          */
   10236        3336 :         if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
   10237           6 :             ereport(ERROR,
   10238             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   10239             :                      errmsg("foreign key constraints on virtual generated columns are not supported")));
   10240             :     }
   10241             : 
   10242             :     /*
   10243             :      * Some actions are currently unsupported for foreign keys using PERIOD.
   10244             :      */
   10245        2436 :     if (fkconstraint->fk_with_period)
   10246             :     {
   10247         278 :         if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_RESTRICT ||
   10248         266 :             fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE ||
   10249         248 :             fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
   10250         230 :             fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT)
   10251          66 :             ereport(ERROR,
   10252             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   10253             :                     errmsg("unsupported %s action for foreign key constraint using PERIOD",
   10254             :                            "ON UPDATE"));
   10255             : 
   10256         212 :         if (fkconstraint->fk_del_action == FKCONSTR_ACTION_RESTRICT ||
   10257         206 :             fkconstraint->fk_del_action == FKCONSTR_ACTION_CASCADE ||
   10258         206 :             fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
   10259         206 :             fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
   10260           6 :             ereport(ERROR,
   10261             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   10262             :                     errmsg("unsupported %s action for foreign key constraint using PERIOD",
   10263             :                            "ON DELETE"));
   10264             :     }
   10265             : 
   10266             :     /*
   10267             :      * Look up the equality operators to use in the constraint.
   10268             :      *
   10269             :      * Note that we have to be careful about the difference between the actual
   10270             :      * PK column type and the opclass' declared input type, which might be
   10271             :      * only binary-compatible with it.  The declared opcintype is the right
   10272             :      * thing to probe pg_amop with.
   10273             :      */
   10274        2364 :     if (numfks != numpks)
   10275           0 :         ereport(ERROR,
   10276             :                 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
   10277             :                  errmsg("number of referencing and referenced columns for foreign key disagree")));
   10278             : 
   10279             :     /*
   10280             :      * On the strength of a previous constraint, we might avoid scanning
   10281             :      * tables to validate this one.  See below.
   10282             :      */
   10283        2364 :     old_check_ok = (fkconstraint->old_conpfeqop != NIL);
   10284             :     Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
   10285             : 
   10286        5166 :     for (i = 0; i < numpks; i++)
   10287             :     {
   10288        3042 :         Oid         pktype = pktypoid[i];
   10289        3042 :         Oid         fktype = fktypoid[i];
   10290             :         Oid         fktyped;
   10291        3042 :         Oid         pkcoll = pkcolloid[i];
   10292        3042 :         Oid         fkcoll = fkcolloid[i];
   10293             :         HeapTuple   cla_ht;
   10294             :         Form_pg_opclass cla_tup;
   10295             :         Oid         amid;
   10296             :         Oid         opfamily;
   10297             :         Oid         opcintype;
   10298             :         bool        for_overlaps;
   10299             :         CompareType cmptype;
   10300             :         Oid         pfeqop;
   10301             :         Oid         ppeqop;
   10302             :         Oid         ffeqop;
   10303             :         int16       eqstrategy;
   10304             :         Oid         pfeqop_right;
   10305             : 
   10306             :         /* We need several fields out of the pg_opclass entry */
   10307        3042 :         cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
   10308        3042 :         if (!HeapTupleIsValid(cla_ht))
   10309           0 :             elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
   10310        3042 :         cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
   10311        3042 :         amid = cla_tup->opcmethod;
   10312        3042 :         opfamily = cla_tup->opcfamily;
   10313        3042 :         opcintype = cla_tup->opcintype;
   10314        3042 :         ReleaseSysCache(cla_ht);
   10315             : 
   10316             :         /*
   10317             :          * Get strategy number from index AM.
   10318             :          *
   10319             :          * For a normal foreign-key constraint, this should not fail, since we
   10320             :          * already checked that the index is unique and should therefore have
   10321             :          * appropriate equal operators.  For a period foreign key, this could
   10322             :          * fail if we selected a non-matching exclusion constraint earlier.
   10323             :          * (XXX Maybe we should do these lookups earlier so we don't end up
   10324             :          * doing that.)
   10325             :          */
   10326        3042 :         for_overlaps = with_period && i == numpks - 1;
   10327        3042 :         cmptype = for_overlaps ? COMPARE_OVERLAP : COMPARE_EQ;
   10328        3042 :         eqstrategy = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
   10329        3042 :         if (eqstrategy == InvalidStrategy)
   10330           0 :             ereport(ERROR,
   10331             :                     errcode(ERRCODE_UNDEFINED_OBJECT),
   10332             :                     for_overlaps
   10333             :                     ? errmsg("could not identify an overlaps operator for foreign key")
   10334             :                     : errmsg("could not identify an equality operator for foreign key"),
   10335             :                     errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
   10336             :                               cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
   10337             : 
   10338             :         /*
   10339             :          * There had better be a primary equality operator for the index.
   10340             :          * We'll use it for PK = PK comparisons.
   10341             :          */
   10342        3042 :         ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
   10343             :                                      eqstrategy);
   10344             : 
   10345        3042 :         if (!OidIsValid(ppeqop))
   10346           0 :             elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
   10347             :                  eqstrategy, opcintype, opcintype, opfamily);
   10348             : 
   10349             :         /*
   10350             :          * Are there equality operators that take exactly the FK type? Assume
   10351             :          * we should look through any domain here.
   10352             :          */
   10353        3042 :         fktyped = getBaseType(fktype);
   10354             : 
   10355        3042 :         pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
   10356             :                                      eqstrategy);
   10357        3042 :         if (OidIsValid(pfeqop))
   10358             :         {
   10359        2346 :             pfeqop_right = fktyped;
   10360        2346 :             ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
   10361             :                                          eqstrategy);
   10362             :         }
   10363             :         else
   10364             :         {
   10365             :             /* keep compiler quiet */
   10366         696 :             pfeqop_right = InvalidOid;
   10367         696 :             ffeqop = InvalidOid;
   10368             :         }
   10369             : 
   10370        3042 :         if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
   10371             :         {
   10372             :             /*
   10373             :              * Otherwise, look for an implicit cast from the FK type to the
   10374             :              * opcintype, and if found, use the primary equality operator.
   10375             :              * This is a bit tricky because opcintype might be a polymorphic
   10376             :              * type such as ANYARRAY or ANYENUM; so what we have to test is
   10377             :              * whether the two actual column types can be concurrently cast to
   10378             :              * that type.  (Otherwise, we'd fail to reject combinations such
   10379             :              * as int[] and point[].)
   10380             :              */
   10381             :             Oid         input_typeids[2];
   10382             :             Oid         target_typeids[2];
   10383             : 
   10384         696 :             input_typeids[0] = pktype;
   10385         696 :             input_typeids[1] = fktype;
   10386         696 :             target_typeids[0] = opcintype;
   10387         696 :             target_typeids[1] = opcintype;
   10388         696 :             if (can_coerce_type(2, input_typeids, target_typeids,
   10389             :                                 COERCION_IMPLICIT))
   10390             :             {
   10391         468 :                 pfeqop = ffeqop = ppeqop;
   10392         468 :                 pfeqop_right = opcintype;
   10393             :             }
   10394             :         }
   10395             : 
   10396        3042 :         if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
   10397         228 :             ereport(ERROR,
   10398             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   10399             :                      errmsg("foreign key constraint \"%s\" cannot be implemented",
   10400             :                             fkconstraint->conname),
   10401             :                      errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
   10402             :                                "are of incompatible types: %s and %s.",
   10403             :                                strVal(list_nth(fkconstraint->fk_attrs, i)),
   10404             :                                strVal(list_nth(fkconstraint->pk_attrs, i)),
   10405             :                                format_type_be(fktype),
   10406             :                                format_type_be(pktype))));
   10407             : 
   10408             :         /*
   10409             :          * This shouldn't be possible, but better check to make sure we have a
   10410             :          * consistent state for the check below.
   10411             :          */
   10412        2814 :         if ((OidIsValid(pkcoll) && !OidIsValid(fkcoll)) || (!OidIsValid(pkcoll) && OidIsValid(fkcoll)))
   10413           0 :             elog(ERROR, "key columns are not both collatable");
   10414             : 
   10415        2814 :         if (OidIsValid(pkcoll) && OidIsValid(fkcoll))
   10416             :         {
   10417             :             bool        pkcolldet;
   10418             :             bool        fkcolldet;
   10419             : 
   10420         104 :             pkcolldet = get_collation_isdeterministic(pkcoll);
   10421         104 :             fkcolldet = get_collation_isdeterministic(fkcoll);
   10422             : 
   10423             :             /*
   10424             :              * SQL requires that both collations are the same.  This is
   10425             :              * because we need a consistent notion of equality on both
   10426             :              * columns.  We relax this by allowing different collations if
   10427             :              * they are both deterministic.  (This is also for backward
   10428             :              * compatibility, because PostgreSQL has always allowed this.)
   10429             :              */
   10430         104 :             if ((!pkcolldet || !fkcolldet) && pkcoll != fkcoll)
   10431          12 :                 ereport(ERROR,
   10432             :                         (errcode(ERRCODE_COLLATION_MISMATCH),
   10433             :                          errmsg("foreign key constraint \"%s\" cannot be implemented", fkconstraint->conname),
   10434             :                          errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
   10435             :                                    "have incompatible collations: \"%s\" and \"%s\".  "
   10436             :                                    "If either collation is nondeterministic, then both collations have to be the same.",
   10437             :                                    strVal(list_nth(fkconstraint->fk_attrs, i)),
   10438             :                                    strVal(list_nth(fkconstraint->pk_attrs, i)),
   10439             :                                    get_collation_name(fkcoll),
   10440             :                                    get_collation_name(pkcoll))));
   10441             :         }
   10442             : 
   10443        2802 :         if (old_check_ok)
   10444             :         {
   10445             :             /*
   10446             :              * When a pfeqop changes, revalidate the constraint.  We could
   10447             :              * permit intra-opfamily changes, but that adds subtle complexity
   10448             :              * without any concrete benefit for core types.  We need not
   10449             :              * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
   10450             :              */
   10451           6 :             old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
   10452           6 :             old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
   10453             :                                     old_pfeqop_item);
   10454             :         }
   10455        2802 :         if (old_check_ok)
   10456             :         {
   10457             :             Oid         old_fktype;
   10458             :             Oid         new_fktype;
   10459             :             CoercionPathType old_pathtype;
   10460             :             CoercionPathType new_pathtype;
   10461             :             Oid         old_castfunc;
   10462             :             Oid         new_castfunc;
   10463             :             Oid         old_fkcoll;
   10464             :             Oid         new_fkcoll;
   10465           6 :             Form_pg_attribute attr = TupleDescAttr(tab->oldDesc,
   10466           6 :                                                    fkattnum[i] - 1);
   10467             : 
   10468             :             /*
   10469             :              * Identify coercion pathways from each of the old and new FK-side
   10470             :              * column types to the right (foreign) operand type of the pfeqop.
   10471             :              * We may assume that pg_constraint.conkey is not changing.
   10472             :              */
   10473           6 :             old_fktype = attr->atttypid;
   10474           6 :             new_fktype = fktype;
   10475           6 :             old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
   10476             :                                         &old_castfunc);
   10477           6 :             new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
   10478             :                                         &new_castfunc);
   10479             : 
   10480           6 :             old_fkcoll = attr->attcollation;
   10481           6 :             new_fkcoll = fkcoll;
   10482             : 
   10483             :             /*
   10484             :              * Upon a change to the cast from the FK column to its pfeqop
   10485             :              * operand, revalidate the constraint.  For this evaluation, a
   10486             :              * binary coercion cast is equivalent to no cast at all.  While
   10487             :              * type implementors should design implicit casts with an eye
   10488             :              * toward consistency of operations like equality, we cannot
   10489             :              * assume here that they have done so.
   10490             :              *
   10491             :              * A function with a polymorphic argument could change behavior
   10492             :              * arbitrarily in response to get_fn_expr_argtype().  Therefore,
   10493             :              * when the cast destination is polymorphic, we only avoid
   10494             :              * revalidation if the input type has not changed at all.  Given
   10495             :              * just the core data types and operator classes, this requirement
   10496             :              * prevents no would-be optimizations.
   10497             :              *
   10498             :              * If the cast converts from a base type to a domain thereon, then
   10499             :              * that domain type must be the opcintype of the unique index.
   10500             :              * Necessarily, the primary key column must then be of the domain
   10501             :              * type.  Since the constraint was previously valid, all values on
   10502             :              * the foreign side necessarily exist on the primary side and in
   10503             :              * turn conform to the domain.  Consequently, we need not treat
   10504             :              * domains specially here.
   10505             :              *
   10506             :              * If the collation changes, revalidation is required, unless both
   10507             :              * collations are deterministic, because those share the same
   10508             :              * notion of equality (because texteq reduces to bitwise
   10509             :              * equality).
   10510             :              *
   10511             :              * We need not directly consider the PK type.  It's necessarily
   10512             :              * binary coercible to the opcintype of the unique index column,
   10513             :              * and ri_triggers.c will only deal with PK datums in terms of
   10514             :              * that opcintype.  Changing the opcintype also changes pfeqop.
   10515             :              */
   10516           6 :             old_check_ok = (new_pathtype == old_pathtype &&
   10517           6 :                             new_castfunc == old_castfunc &&
   10518           6 :                             (!IsPolymorphicType(pfeqop_right) ||
   10519          12 :                              new_fktype == old_fktype) &&
   10520           0 :                             (new_fkcoll == old_fkcoll ||
   10521           0 :                              (get_collation_isdeterministic(old_fkcoll) && get_collation_isdeterministic(new_fkcoll))));
   10522             :         }
   10523             : 
   10524        2802 :         pfeqoperators[i] = pfeqop;
   10525        2802 :         ppeqoperators[i] = ppeqop;
   10526        2802 :         ffeqoperators[i] = ffeqop;
   10527             :     }
   10528             : 
   10529             :     /*
   10530             :      * For FKs with PERIOD we need additional operators to check whether the
   10531             :      * referencing row's range is contained by the aggregated ranges of the
   10532             :      * referenced row(s). For rangetypes and multirangetypes this is
   10533             :      * fk.periodatt <@ range_agg(pk.periodatt). Those are the only types we
   10534             :      * support for now. FKs will look these up at "runtime", but we should
   10535             :      * make sure the lookup works here, even if we don't use the values.
   10536             :      */
   10537        2124 :     if (with_period)
   10538             :     {
   10539             :         Oid         periodoperoid;
   10540             :         Oid         aggedperiodoperoid;
   10541             :         Oid         intersectoperoid;
   10542             : 
   10543         188 :         FindFKPeriodOpers(opclasses[numpks - 1], &periodoperoid, &aggedperiodoperoid,
   10544             :                           &intersectoperoid);
   10545             :     }
   10546             : 
   10547             :     /* First, create the constraint catalog entry itself. */
   10548        2124 :     address = addFkConstraint(addFkBothSides,
   10549             :                               fkconstraint->conname, fkconstraint, rel, pkrel,
   10550             :                               indexOid,
   10551             :                               InvalidOid,   /* no parent constraint */
   10552             :                               numfks,
   10553             :                               pkattnum,
   10554             :                               fkattnum,
   10555             :                               pfeqoperators,
   10556             :                               ppeqoperators,
   10557             :                               ffeqoperators,
   10558             :                               numfkdelsetcols,
   10559             :                               fkdelsetcols,
   10560             :                               false,
   10561             :                               with_period);
   10562             : 
   10563             :     /* Next process the action triggers at the referenced side and recurse */
   10564        2124 :     addFkRecurseReferenced(fkconstraint, rel, pkrel,
   10565             :                            indexOid,
   10566             :                            address.objectId,
   10567             :                            numfks,
   10568             :                            pkattnum,
   10569             :                            fkattnum,
   10570             :                            pfeqoperators,
   10571             :                            ppeqoperators,
   10572             :                            ffeqoperators,
   10573             :                            numfkdelsetcols,
   10574             :                            fkdelsetcols,
   10575             :                            old_check_ok,
   10576             :                            InvalidOid, InvalidOid,
   10577             :                            with_period);
   10578             : 
   10579             :     /* Lastly create the check triggers at the referencing side and recurse */
   10580        2124 :     addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
   10581             :                             indexOid,
   10582             :                             address.objectId,
   10583             :                             numfks,
   10584             :                             pkattnum,
   10585             :                             fkattnum,
   10586             :                             pfeqoperators,
   10587             :                             ppeqoperators,
   10588             :                             ffeqoperators,
   10589             :                             numfkdelsetcols,
   10590             :                             fkdelsetcols,
   10591             :                             old_check_ok,
   10592             :                             lockmode,
   10593             :                             InvalidOid, InvalidOid,
   10594             :                             with_period);
   10595             : 
   10596             :     /*
   10597             :      * Done.  Close pk table, but keep lock until we've committed.
   10598             :      */
   10599        2124 :     table_close(pkrel, NoLock);
   10600             : 
   10601        2124 :     return address;
   10602             : }
   10603             : 
   10604             : /*
   10605             :  * validateFkOnDeleteSetColumns
   10606             :  *      Verifies that columns used in ON DELETE SET NULL/DEFAULT (...)
   10607             :  *      column lists are valid.
   10608             :  *
   10609             :  * If there are duplicates in the fksetcolsattnums[] array, this silently
   10610             :  * removes the dups.  The new count of numfksetcols is returned.
   10611             :  */
   10612             : static int
   10613        2598 : validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
   10614             :                              int numfksetcols, int16 *fksetcolsattnums,
   10615             :                              List *fksetcols)
   10616             : {
   10617        2598 :     int         numcolsout = 0;
   10618             : 
   10619        2628 :     for (int i = 0; i < numfksetcols; i++)
   10620             :     {
   10621          36 :         int16       setcol_attnum = fksetcolsattnums[i];
   10622          36 :         bool        seen = false;
   10623             : 
   10624             :         /* Make sure it's in fkattnums[] */
   10625          66 :         for (int j = 0; j < numfks; j++)
   10626             :         {
   10627          60 :             if (fkattnums[j] == setcol_attnum)
   10628             :             {
   10629          30 :                 seen = true;
   10630          30 :                 break;
   10631             :             }
   10632             :         }
   10633             : 
   10634          36 :         if (!seen)
   10635             :         {
   10636           6 :             char       *col = strVal(list_nth(fksetcols, i));
   10637             : 
   10638           6 :             ereport(ERROR,
   10639             :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
   10640             :                      errmsg("column \"%s\" referenced in ON DELETE SET action must be part of foreign key", col)));
   10641             :         }
   10642             : 
   10643             :         /* Now check for dups */
   10644          30 :         seen = false;
   10645          30 :         for (int j = 0; j < numcolsout; j++)
   10646             :         {
   10647           6 :             if (fksetcolsattnums[j] == setcol_attnum)
   10648             :             {
   10649           6 :                 seen = true;
   10650           6 :                 break;
   10651             :             }
   10652             :         }
   10653          30 :         if (!seen)
   10654          24 :             fksetcolsattnums[numcolsout++] = setcol_attnum;
   10655             :     }
   10656        2592 :     return numcolsout;
   10657             : }
   10658             : 
   10659             : /*
   10660             :  * addFkConstraint
   10661             :  *      Install pg_constraint entries to implement a foreign key constraint.
   10662             :  *      Caller must separately invoke addFkRecurseReferenced and
   10663             :  *      addFkRecurseReferencing, as appropriate, to install pg_trigger entries
   10664             :  *      and (for partitioned tables) recurse to partitions.
   10665             :  *
   10666             :  * fkside: the side of the FK (or both) to create.  Caller should
   10667             :  *      call addFkRecurseReferenced if this is addFkReferencedSide,
   10668             :  *      addFkRecurseReferencing if it's addFkReferencingSide, or both if it's
   10669             :  *      addFkBothSides.
   10670             :  * constraintname: the base name for the constraint being added,
   10671             :  *      copied to fkconstraint->conname if the latter is not set
   10672             :  * fkconstraint: the constraint being added
   10673             :  * rel: the root referencing relation
   10674             :  * pkrel: the referenced relation; might be a partition, if recursing
   10675             :  * indexOid: the OID of the index (on pkrel) implementing this constraint
   10676             :  * parentConstr: the OID of a parent constraint; InvalidOid if this is a
   10677             :  *      top-level constraint
   10678             :  * numfks: the number of columns in the foreign key
   10679             :  * pkattnum: the attnum array of referenced attributes
   10680             :  * fkattnum: the attnum array of referencing attributes
   10681             :  * pf/pp/ffeqoperators: OID array of operators between columns
   10682             :  * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
   10683             :  *      (...) clause
   10684             :  * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
   10685             :  *      NULL/DEFAULT clause
   10686             :  * with_period: true if this is a temporal FK
   10687             :  */
   10688             : static ObjectAddress
   10689        4100 : addFkConstraint(addFkConstraintSides fkside,
   10690             :                 char *constraintname, Constraint *fkconstraint,
   10691             :                 Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
   10692             :                 int numfks, int16 *pkattnum,
   10693             :                 int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators,
   10694             :                 Oid *ffeqoperators, int numfkdelsetcols, int16 *fkdelsetcols,
   10695             :                 bool is_internal, bool with_period)
   10696             : {
   10697             :     ObjectAddress address;
   10698             :     Oid         constrOid;
   10699             :     char       *conname;
   10700             :     bool        conislocal;
   10701             :     int16       coninhcount;
   10702             :     bool        connoinherit;
   10703             : 
   10704             :     /*
   10705             :      * Verify relkind for each referenced partition.  At the top level, this
   10706             :      * is redundant with a previous check, but we need it when recursing.
   10707             :      */
   10708        4100 :     if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
   10709         868 :         pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
   10710           0 :         ereport(ERROR,
   10711             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   10712             :                  errmsg("referenced relation \"%s\" is not a table",
   10713             :                         RelationGetRelationName(pkrel))));
   10714             : 
   10715             :     /*
   10716             :      * Caller supplies us with a constraint name; however, it may be used in
   10717             :      * this partition, so come up with a different one in that case.  Unless
   10718             :      * truncation to NAMEDATALEN dictates otherwise, the new name will be the
   10719             :      * supplied name with an underscore and digit(s) appended.
   10720             :      */
   10721        4100 :     if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
   10722             :                              RelationGetRelid(rel),
   10723             :                              constraintname))
   10724        1176 :         conname = ChooseConstraintName(constraintname,
   10725             :                                        NULL,
   10726             :                                        "",
   10727        1176 :                                        RelationGetNamespace(rel), NIL);
   10728             :     else
   10729        2924 :         conname = constraintname;
   10730             : 
   10731        4100 :     if (fkconstraint->conname == NULL)
   10732         436 :         fkconstraint->conname = pstrdup(conname);
   10733             : 
   10734        4100 :     if (OidIsValid(parentConstr))
   10735             :     {
   10736        1976 :         conislocal = false;
   10737        1976 :         coninhcount = 1;
   10738        1976 :         connoinherit = false;
   10739             :     }
   10740             :     else
   10741             :     {
   10742        2124 :         conislocal = true;
   10743        2124 :         coninhcount = 0;
   10744             : 
   10745             :         /*
   10746             :          * always inherit for partitioned tables, never for legacy inheritance
   10747             :          */
   10748        2124 :         connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
   10749             :     }
   10750             : 
   10751             :     /*
   10752             :      * Record the FK constraint in pg_constraint.
   10753             :      */
   10754        4100 :     constrOid = CreateConstraintEntry(conname,
   10755        4100 :                                       RelationGetNamespace(rel),
   10756             :                                       CONSTRAINT_FOREIGN,
   10757        4100 :                                       fkconstraint->deferrable,
   10758        4100 :                                       fkconstraint->initdeferred,
   10759        4100 :                                       fkconstraint->is_enforced,
   10760        4100 :                                       fkconstraint->initially_valid,
   10761             :                                       parentConstr,
   10762             :                                       RelationGetRelid(rel),
   10763             :                                       fkattnum,
   10764             :                                       numfks,
   10765             :                                       numfks,
   10766             :                                       InvalidOid,   /* not a domain constraint */
   10767             :                                       indexOid,
   10768             :                                       RelationGetRelid(pkrel),
   10769             :                                       pkattnum,
   10770             :                                       pfeqoperators,
   10771             :                                       ppeqoperators,
   10772             :                                       ffeqoperators,
   10773             :                                       numfks,
   10774        4100 :                                       fkconstraint->fk_upd_action,
   10775        4100 :                                       fkconstraint->fk_del_action,
   10776             :                                       fkdelsetcols,
   10777             :                                       numfkdelsetcols,
   10778        4100 :                                       fkconstraint->fk_matchtype,
   10779             :                                       NULL, /* no exclusion constraint */
   10780             :                                       NULL, /* no check constraint */
   10781             :                                       NULL,
   10782             :                                       conislocal,   /* islocal */
   10783             :                                       coninhcount,  /* inhcount */
   10784             :                                       connoinherit, /* conNoInherit */
   10785             :                                       with_period,  /* conPeriod */
   10786             :                                       is_internal); /* is_internal */
   10787             : 
   10788        4100 :     ObjectAddressSet(address, ConstraintRelationId, constrOid);
   10789             : 
   10790             :     /*
   10791             :      * In partitioning cases, create the dependency entries for this
   10792             :      * constraint.  (For non-partitioned cases, relevant entries were created
   10793             :      * by CreateConstraintEntry.)
   10794             :      *
   10795             :      * On the referenced side, we need the constraint to have an internal
   10796             :      * dependency on its parent constraint; this means that this constraint
   10797             :      * cannot be dropped on its own -- only through the parent constraint. It
   10798             :      * also means the containing partition cannot be dropped on its own, but
   10799             :      * it can be detached, at which point this dependency is removed (after
   10800             :      * verifying that no rows are referenced via this FK.)
   10801             :      *
   10802             :      * When processing the referencing side, we link the constraint via the
   10803             :      * special partitioning dependencies: the parent constraint is the primary
   10804             :      * dependent, and the partition on which the foreign key exists is the
   10805             :      * secondary dependency.  That way, this constraint is dropped if either
   10806             :      * of these objects is.
   10807             :      *
   10808             :      * Note that this is only necessary for the subsidiary pg_constraint rows
   10809             :      * in partitions; the topmost row doesn't need any of this.
   10810             :      */
   10811        4100 :     if (OidIsValid(parentConstr))
   10812             :     {
   10813             :         ObjectAddress referenced;
   10814             : 
   10815        1976 :         ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
   10816             : 
   10817             :         Assert(fkside != addFkBothSides);
   10818        1976 :         if (fkside == addFkReferencedSide)
   10819        1170 :             recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
   10820             :         else
   10821             :         {
   10822         806 :             recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
   10823         806 :             ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
   10824         806 :             recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
   10825             :         }
   10826             :     }
   10827             : 
   10828             :     /* make new constraint visible, in case we add more */
   10829        4100 :     CommandCounterIncrement();
   10830             : 
   10831        4100 :     return address;
   10832             : }
   10833             : 
   10834             : /*
   10835             :  * addFkRecurseReferenced
   10836             :  *      Recursive helper for the referenced side of foreign key creation,
   10837             :  *      which creates the action triggers and recurses
   10838             :  *
   10839             :  * If the referenced relation is a plain relation, create the necessary action
   10840             :  * triggers that implement the constraint.  If the referenced relation is a
   10841             :  * partitioned table, then we create a pg_constraint row referencing the parent
   10842             :  * of the referencing side for it and recurse on this routine for each
   10843             :  * partition.
   10844             :  *
   10845             :  * fkconstraint: the constraint being added
   10846             :  * rel: the root referencing relation
   10847             :  * pkrel: the referenced relation; might be a partition, if recursing
   10848             :  * indexOid: the OID of the index (on pkrel) implementing this constraint
   10849             :  * parentConstr: the OID of a parent constraint; InvalidOid if this is a
   10850             :  *      top-level constraint
   10851             :  * numfks: the number of columns in the foreign key
   10852             :  * pkattnum: the attnum array of referenced attributes
   10853             :  * fkattnum: the attnum array of referencing attributes
   10854             :  * numfkdelsetcols: the number of columns in the ON DELETE SET
   10855             :  *      NULL/DEFAULT (...) clause
   10856             :  * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
   10857             :  *      NULL/DEFAULT clause
   10858             :  * pf/pp/ffeqoperators: OID array of operators between columns
   10859             :  * old_check_ok: true if this constraint replaces an existing one that
   10860             :  *      was already validated (thus this one doesn't need validation)
   10861             :  * parentDelTrigger and parentUpdTrigger: when recursively called on a
   10862             :  *      partition, the OIDs of the parent action triggers for DELETE and
   10863             :  *      UPDATE respectively.
   10864             :  * with_period: true if this is a temporal FK
   10865             :  */
   10866             : static void
   10867        3396 : addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
   10868             :                        Relation pkrel, Oid indexOid, Oid parentConstr,
   10869             :                        int numfks,
   10870             :                        int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators,
   10871             :                        Oid *ppeqoperators, Oid *ffeqoperators,
   10872             :                        int numfkdelsetcols, int16 *fkdelsetcols,
   10873             :                        bool old_check_ok,
   10874             :                        Oid parentDelTrigger, Oid parentUpdTrigger,
   10875             :                        bool with_period)
   10876             : {
   10877        3396 :     Oid         deleteTriggerOid = InvalidOid,
   10878        3396 :                 updateTriggerOid = InvalidOid;
   10879             : 
   10880             :     Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
   10881             :     Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
   10882             : 
   10883             :     /*
   10884             :      * Create action triggers to enforce the constraint, or skip them if the
   10885             :      * constraint is NOT ENFORCED.
   10886             :      */
   10887        3396 :     if (fkconstraint->is_enforced)
   10888        3348 :         createForeignKeyActionTriggers(RelationGetRelid(rel),
   10889             :                                        RelationGetRelid(pkrel),
   10890             :                                        fkconstraint,
   10891             :                                        parentConstr, indexOid,
   10892             :                                        parentDelTrigger, parentUpdTrigger,
   10893             :                                        &deleteTriggerOid, &updateTriggerOid);
   10894             : 
   10895             :     /*
   10896             :      * If the referenced table is partitioned, recurse on ourselves to handle
   10897             :      * each partition.  We need one pg_constraint row created for each
   10898             :      * partition in addition to the pg_constraint row for the parent table.
   10899             :      */
   10900        3396 :     if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   10901             :     {
   10902         558 :         PartitionDesc pd = RelationGetPartitionDesc(pkrel, true);
   10903             : 
   10904        1506 :         for (int i = 0; i < pd->nparts; i++)
   10905             :         {
   10906             :             Relation    partRel;
   10907             :             AttrMap    *map;
   10908             :             AttrNumber *mapped_pkattnum;
   10909             :             Oid         partIndexId;
   10910             :             ObjectAddress address;
   10911             : 
   10912             :             /* XXX would it be better to acquire these locks beforehand? */
   10913         948 :             partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
   10914             : 
   10915             :             /*
   10916             :              * Map the attribute numbers in the referenced side of the FK
   10917             :              * definition to match the partition's column layout.
   10918             :              */
   10919         948 :             map = build_attrmap_by_name_if_req(RelationGetDescr(partRel),
   10920             :                                                RelationGetDescr(pkrel),
   10921             :                                                false);
   10922         948 :             if (map)
   10923             :             {
   10924         136 :                 mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
   10925         284 :                 for (int j = 0; j < numfks; j++)
   10926         148 :                     mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
   10927             :             }
   10928             :             else
   10929         812 :                 mapped_pkattnum = pkattnum;
   10930             : 
   10931             :             /* Determine the index to use at this level */
   10932         948 :             partIndexId = index_get_partition(partRel, indexOid);
   10933         948 :             if (!OidIsValid(partIndexId))
   10934           0 :                 elog(ERROR, "index for %u not found in partition %s",
   10935             :                      indexOid, RelationGetRelationName(partRel));
   10936             : 
   10937             :             /* Create entry at this level ... */
   10938         948 :             address = addFkConstraint(addFkReferencedSide,
   10939             :                                       fkconstraint->conname, fkconstraint, rel,
   10940             :                                       partRel, partIndexId, parentConstr,
   10941             :                                       numfks, mapped_pkattnum,
   10942             :                                       fkattnum, pfeqoperators, ppeqoperators,
   10943             :                                       ffeqoperators, numfkdelsetcols,
   10944             :                                       fkdelsetcols, true, with_period);
   10945             :             /* ... and recurse to our children */
   10946         948 :             addFkRecurseReferenced(fkconstraint, rel, partRel,
   10947             :                                    partIndexId, address.objectId, numfks,
   10948             :                                    mapped_pkattnum, fkattnum,
   10949             :                                    pfeqoperators, ppeqoperators, ffeqoperators,
   10950             :                                    numfkdelsetcols, fkdelsetcols,
   10951             :                                    old_check_ok,
   10952             :                                    deleteTriggerOid, updateTriggerOid,
   10953             :                                    with_period);
   10954             : 
   10955             :             /* Done -- clean up (but keep the lock) */
   10956         948 :             table_close(partRel, NoLock);
   10957         948 :             if (map)
   10958             :             {
   10959         136 :                 pfree(mapped_pkattnum);
   10960         136 :                 free_attrmap(map);
   10961             :             }
   10962             :         }
   10963             :     }
   10964        3396 : }
   10965             : 
   10966             : /*
   10967             :  * addFkRecurseReferencing
   10968             :  *      Recursive helper for the referencing side of foreign key creation,
   10969             :  *      which creates the check triggers and recurses
   10970             :  *
   10971             :  * If the referencing relation is a plain relation, create the necessary check
   10972             :  * triggers that implement the constraint, and set up for Phase 3 constraint
   10973             :  * verification.  If the referencing relation is a partitioned table, then
   10974             :  * we create a pg_constraint row for it and recurse on this routine for each
   10975             :  * partition.
   10976             :  *
   10977             :  * We assume that the referenced relation is locked against concurrent
   10978             :  * deletions.  If it's a partitioned relation, every partition must be so
   10979             :  * locked.
   10980             :  *
   10981             :  * wqueue: the ALTER TABLE work queue; NULL when not running as part
   10982             :  *      of an ALTER TABLE sequence.
   10983             :  * fkconstraint: the constraint being added
   10984             :  * rel: the referencing relation; might be a partition, if recursing
   10985             :  * pkrel: the root referenced relation
   10986             :  * indexOid: the OID of the index (on pkrel) implementing this constraint
   10987             :  * parentConstr: the OID of the parent constraint (there is always one)
   10988             :  * numfks: the number of columns in the foreign key
   10989             :  * pkattnum: the attnum array of referenced attributes
   10990             :  * fkattnum: the attnum array of referencing attributes
   10991             :  * pf/pp/ffeqoperators: OID array of operators between columns
   10992             :  * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
   10993             :  *      (...) clause
   10994             :  * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
   10995             :  *      NULL/DEFAULT clause
   10996             :  * old_check_ok: true if this constraint replaces an existing one that
   10997             :  *      was already validated (thus this one doesn't need validation)
   10998             :  * lockmode: the lockmode to acquire on partitions when recursing
   10999             :  * parentInsTrigger and parentUpdTrigger: when being recursively called on
   11000             :  *      a partition, the OIDs of the parent check triggers for INSERT and
   11001             :  *      UPDATE respectively.
   11002             :  * with_period: true if this is a temporal FK
   11003             :  */
   11004             : static void
   11005        2930 : addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
   11006             :                         Relation pkrel, Oid indexOid, Oid parentConstr,
   11007             :                         int numfks, int16 *pkattnum, int16 *fkattnum,
   11008             :                         Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
   11009             :                         int numfkdelsetcols, int16 *fkdelsetcols,
   11010             :                         bool old_check_ok, LOCKMODE lockmode,
   11011             :                         Oid parentInsTrigger, Oid parentUpdTrigger,
   11012             :                         bool with_period)
   11013             : {
   11014        2930 :     Oid         insertTriggerOid = InvalidOid,
   11015        2930 :                 updateTriggerOid = InvalidOid;
   11016             : 
   11017             :     Assert(OidIsValid(parentConstr));
   11018             :     Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
   11019             :     Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
   11020             : 
   11021        2930 :     if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
   11022           0 :         ereport(ERROR,
   11023             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   11024             :                  errmsg("foreign key constraints are not supported on foreign tables")));
   11025             : 
   11026             :     /*
   11027             :      * Add check triggers if the constraint is ENFORCED, and if needed,
   11028             :      * schedule them to be checked in Phase 3.
   11029             :      *
   11030             :      * If the relation is partitioned, drill down to do it to its partitions.
   11031             :      */
   11032        2930 :     if (fkconstraint->is_enforced)
   11033        2888 :         createForeignKeyCheckTriggers(RelationGetRelid(rel),
   11034             :                                       RelationGetRelid(pkrel),
   11035             :                                       fkconstraint,
   11036             :                                       parentConstr,
   11037             :                                       indexOid,
   11038             :                                       parentInsTrigger, parentUpdTrigger,
   11039             :                                       &insertTriggerOid, &updateTriggerOid);
   11040             : 
   11041        2930 :     if (rel->rd_rel->relkind == RELKIND_RELATION)
   11042             :     {
   11043             :         /*
   11044             :          * Tell Phase 3 to check that the constraint is satisfied by existing
   11045             :          * rows. We can skip this during table creation, when constraint is
   11046             :          * specified as NOT ENFORCED, or when requested explicitly by
   11047             :          * specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
   11048             :          * recreating a constraint following a SET DATA TYPE operation that
   11049             :          * did not impugn its validity.
   11050             :          */
   11051        2446 :         if (wqueue && !old_check_ok && !fkconstraint->skip_validation &&
   11052         772 :             fkconstraint->is_enforced)
   11053             :         {
   11054             :             NewConstraint *newcon;
   11055             :             AlteredTableInfo *tab;
   11056             : 
   11057         772 :             tab = ATGetQueueEntry(wqueue, rel);
   11058             : 
   11059         772 :             newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
   11060         772 :             newcon->name = get_constraint_name(parentConstr);
   11061         772 :             newcon->contype = CONSTR_FOREIGN;
   11062         772 :             newcon->refrelid = RelationGetRelid(pkrel);
   11063         772 :             newcon->refindid = indexOid;
   11064         772 :             newcon->conid = parentConstr;
   11065         772 :             newcon->conwithperiod = fkconstraint->fk_with_period;
   11066         772 :             newcon->qual = (Node *) fkconstraint;
   11067             : 
   11068         772 :             tab->constraints = lappend(tab->constraints, newcon);
   11069             :         }
   11070             :     }
   11071         484 :     else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   11072             :     {
   11073         484 :         PartitionDesc pd = RelationGetPartitionDesc(rel, true);
   11074             :         Relation    trigrel;
   11075             : 
   11076             :         /*
   11077             :          * Triggers of the foreign keys will be manipulated a bunch of times
   11078             :          * in the loop below.  To avoid repeatedly opening/closing the trigger
   11079             :          * catalog relation, we open it here and pass it to the subroutines
   11080             :          * called below.
   11081             :          */
   11082         484 :         trigrel = table_open(TriggerRelationId, RowExclusiveLock);
   11083             : 
   11084             :         /*
   11085             :          * Recurse to take appropriate action on each partition; either we
   11086             :          * find an existing constraint to reparent to ours, or we create a new
   11087             :          * one.
   11088             :          */
   11089         866 :         for (int i = 0; i < pd->nparts; i++)
   11090             :         {
   11091         388 :             Relation    partition = table_open(pd->oids[i], lockmode);
   11092             :             List       *partFKs;
   11093             :             AttrMap    *attmap;
   11094             :             AttrNumber  mapped_fkattnum[INDEX_MAX_KEYS];
   11095             :             bool        attached;
   11096             :             ObjectAddress address;
   11097             : 
   11098         388 :             CheckAlterTableIsSafe(partition);
   11099             : 
   11100         382 :             attmap = build_attrmap_by_name(RelationGetDescr(partition),
   11101             :                                            RelationGetDescr(rel),
   11102             :                                            false);
   11103         986 :             for (int j = 0; j < numfks; j++)
   11104         604 :                 mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
   11105             : 
   11106             :             /* Check whether an existing constraint can be repurposed */
   11107         382 :             partFKs = copyObject(RelationGetFKeyList(partition));
   11108         382 :             attached = false;
   11109         782 :             foreach_node(ForeignKeyCacheInfo, fk, partFKs)
   11110             :             {
   11111          30 :                 if (tryAttachPartitionForeignKey(wqueue,
   11112             :                                                  fk,
   11113             :                                                  partition,
   11114             :                                                  parentConstr,
   11115             :                                                  numfks,
   11116             :                                                  mapped_fkattnum,
   11117             :                                                  pkattnum,
   11118             :                                                  pfeqoperators,
   11119             :                                                  insertTriggerOid,
   11120             :                                                  updateTriggerOid,
   11121             :                                                  trigrel))
   11122             :                 {
   11123          12 :                     attached = true;
   11124          12 :                     break;
   11125             :                 }
   11126             :             }
   11127         382 :             if (attached)
   11128             :             {
   11129          12 :                 table_close(partition, NoLock);
   11130          12 :                 continue;
   11131             :             }
   11132             : 
   11133             :             /*
   11134             :              * No luck finding a good constraint to reuse; create our own.
   11135             :              */
   11136         370 :             address = addFkConstraint(addFkReferencingSide,
   11137             :                                       fkconstraint->conname, fkconstraint,
   11138             :                                       partition, pkrel, indexOid, parentConstr,
   11139             :                                       numfks, pkattnum,
   11140             :                                       mapped_fkattnum, pfeqoperators,
   11141             :                                       ppeqoperators, ffeqoperators,
   11142             :                                       numfkdelsetcols, fkdelsetcols, true,
   11143             :                                       with_period);
   11144             : 
   11145             :             /* call ourselves to finalize the creation and we're done */
   11146         370 :             addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
   11147             :                                     indexOid,
   11148             :                                     address.objectId,
   11149             :                                     numfks,
   11150             :                                     pkattnum,
   11151             :                                     mapped_fkattnum,
   11152             :                                     pfeqoperators,
   11153             :                                     ppeqoperators,
   11154             :                                     ffeqoperators,
   11155             :                                     numfkdelsetcols,
   11156             :                                     fkdelsetcols,
   11157             :                                     old_check_ok,
   11158             :                                     lockmode,
   11159             :                                     insertTriggerOid,
   11160             :                                     updateTriggerOid,
   11161             :                                     with_period);
   11162             : 
   11163         370 :             table_close(partition, NoLock);
   11164             :         }
   11165             : 
   11166         478 :         table_close(trigrel, RowExclusiveLock);
   11167             :     }
   11168        2924 : }
   11169             : 
   11170             : /*
   11171             :  * CloneForeignKeyConstraints
   11172             :  *      Clone foreign keys from a partitioned table to a newly acquired
   11173             :  *      partition.
   11174             :  *
   11175             :  * partitionRel is a partition of parentRel, so we can be certain that it has
   11176             :  * the same columns with the same datatypes.  The columns may be in different
   11177             :  * order, though.
   11178             :  *
   11179             :  * wqueue must be passed to set up phase 3 constraint checking, unless the
   11180             :  * referencing-side partition is known to be empty (such as in CREATE TABLE /
   11181             :  * PARTITION OF).
   11182             :  */
   11183             : static void
   11184        9830 : CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
   11185             :                            Relation partitionRel)
   11186             : {
   11187             :     /* This only works for declarative partitioning */
   11188             :     Assert(parentRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
   11189             : 
   11190             :     /*
   11191             :      * First, clone constraints where the parent is on the referencing side.
   11192             :      */
   11193        9830 :     CloneFkReferencing(wqueue, parentRel, partitionRel);
   11194             : 
   11195             :     /*
   11196             :      * Clone constraints for which the parent is on the referenced side.
   11197             :      */
   11198        9812 :     CloneFkReferenced(parentRel, partitionRel);
   11199        9812 : }
   11200             : 
   11201             : /*
   11202             :  * CloneFkReferenced
   11203             :  *      Subroutine for CloneForeignKeyConstraints
   11204             :  *
   11205             :  * Find all the FKs that have the parent relation on the referenced side;
   11206             :  * clone those constraints to the given partition.  This is to be called
   11207             :  * when the partition is being created or attached.
   11208             :  *
   11209             :  * This recurses to partitions, if the relation being attached is partitioned.
   11210             :  * Recursion is done by calling addFkRecurseReferenced.
   11211             :  */
   11212             : static void
   11213        9812 : CloneFkReferenced(Relation parentRel, Relation partitionRel)
   11214             : {
   11215             :     Relation    pg_constraint;
   11216             :     AttrMap    *attmap;
   11217             :     ListCell   *cell;
   11218             :     SysScanDesc scan;
   11219             :     ScanKeyData key[2];
   11220             :     HeapTuple   tuple;
   11221        9812 :     List       *clone = NIL;
   11222             :     Relation    trigrel;
   11223             : 
   11224             :     /*
   11225             :      * Search for any constraints where this partition's parent is in the
   11226             :      * referenced side.  However, we must not clone any constraint whose
   11227             :      * parent constraint is also going to be cloned, to avoid duplicates.  So
   11228             :      * do it in two steps: first construct the list of constraints to clone,
   11229             :      * then go over that list cloning those whose parents are not in the list.
   11230             :      * (We must not rely on the parent being seen first, since the catalog
   11231             :      * scan could return children first.)
   11232             :      */
   11233        9812 :     pg_constraint = table_open(ConstraintRelationId, RowShareLock);
   11234        9812 :     ScanKeyInit(&key[0],
   11235             :                 Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
   11236             :                 F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parentRel)));
   11237        9812 :     ScanKeyInit(&key[1],
   11238             :                 Anum_pg_constraint_contype, BTEqualStrategyNumber,
   11239             :                 F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
   11240             :     /* This is a seqscan, as we don't have a usable index ... */
   11241        9812 :     scan = systable_beginscan(pg_constraint, InvalidOid, true,
   11242             :                               NULL, 2, key);
   11243       10256 :     while ((tuple = systable_getnext(scan)) != NULL)
   11244             :     {
   11245         444 :         Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   11246             : 
   11247         444 :         clone = lappend_oid(clone, constrForm->oid);
   11248             :     }
   11249        9812 :     systable_endscan(scan);
   11250        9812 :     table_close(pg_constraint, RowShareLock);
   11251             : 
   11252             :     /*
   11253             :      * Triggers of the foreign keys will be manipulated a bunch of times in
   11254             :      * the loop below.  To avoid repeatedly opening/closing the trigger
   11255             :      * catalog relation, we open it here and pass it to the subroutines called
   11256             :      * below.
   11257             :      */
   11258        9812 :     trigrel = table_open(TriggerRelationId, RowExclusiveLock);
   11259             : 
   11260        9812 :     attmap = build_attrmap_by_name(RelationGetDescr(partitionRel),
   11261             :                                    RelationGetDescr(parentRel),
   11262             :                                    false);
   11263       10256 :     foreach(cell, clone)
   11264             :     {
   11265         444 :         Oid         constrOid = lfirst_oid(cell);
   11266             :         Form_pg_constraint constrForm;
   11267             :         Relation    fkRel;
   11268             :         Oid         indexOid;
   11269             :         Oid         partIndexId;
   11270             :         int         numfks;
   11271             :         AttrNumber  conkey[INDEX_MAX_KEYS];
   11272             :         AttrNumber  mapped_confkey[INDEX_MAX_KEYS];
   11273             :         AttrNumber  confkey[INDEX_MAX_KEYS];
   11274             :         Oid         conpfeqop[INDEX_MAX_KEYS];
   11275             :         Oid         conppeqop[INDEX_MAX_KEYS];
   11276             :         Oid         conffeqop[INDEX_MAX_KEYS];
   11277             :         int         numfkdelsetcols;
   11278             :         AttrNumber  confdelsetcols[INDEX_MAX_KEYS];
   11279             :         Constraint *fkconstraint;
   11280             :         ObjectAddress address;
   11281         444 :         Oid         deleteTriggerOid = InvalidOid,
   11282         444 :                     updateTriggerOid = InvalidOid;
   11283             : 
   11284         444 :         tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
   11285         444 :         if (!HeapTupleIsValid(tuple))
   11286           0 :             elog(ERROR, "cache lookup failed for constraint %u", constrOid);
   11287         444 :         constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   11288             : 
   11289             :         /*
   11290             :          * As explained above: don't try to clone a constraint for which we're
   11291             :          * going to clone the parent.
   11292             :          */
   11293         444 :         if (list_member_oid(clone, constrForm->conparentid))
   11294             :         {
   11295         222 :             ReleaseSysCache(tuple);
   11296         222 :             continue;
   11297             :         }
   11298             : 
   11299             :         /* We need the same lock level that CreateTrigger will acquire */
   11300         222 :         fkRel = table_open(constrForm->conrelid, ShareRowExclusiveLock);
   11301             : 
   11302         222 :         indexOid = constrForm->conindid;
   11303         222 :         DeconstructFkConstraintRow(tuple,
   11304             :                                    &numfks,
   11305             :                                    conkey,
   11306             :                                    confkey,
   11307             :                                    conpfeqop,
   11308             :                                    conppeqop,
   11309             :                                    conffeqop,
   11310             :                                    &numfkdelsetcols,
   11311             :                                    confdelsetcols);
   11312             : 
   11313         486 :         for (int i = 0; i < numfks; i++)
   11314         264 :             mapped_confkey[i] = attmap->attnums[confkey[i] - 1];
   11315             : 
   11316         222 :         fkconstraint = makeNode(Constraint);
   11317         222 :         fkconstraint->contype = CONSTRAINT_FOREIGN;
   11318         222 :         fkconstraint->conname = NameStr(constrForm->conname);
   11319         222 :         fkconstraint->deferrable = constrForm->condeferrable;
   11320         222 :         fkconstraint->initdeferred = constrForm->condeferred;
   11321         222 :         fkconstraint->location = -1;
   11322         222 :         fkconstraint->pktable = NULL;
   11323             :         /* ->fk_attrs determined below */
   11324         222 :         fkconstraint->pk_attrs = NIL;
   11325         222 :         fkconstraint->fk_matchtype = constrForm->confmatchtype;
   11326         222 :         fkconstraint->fk_upd_action = constrForm->confupdtype;
   11327         222 :         fkconstraint->fk_del_action = constrForm->confdeltype;
   11328         222 :         fkconstraint->fk_del_set_cols = NIL;
   11329         222 :         fkconstraint->old_conpfeqop = NIL;
   11330         222 :         fkconstraint->old_pktable_oid = InvalidOid;
   11331         222 :         fkconstraint->is_enforced = constrForm->conenforced;
   11332         222 :         fkconstraint->skip_validation = false;
   11333         222 :         fkconstraint->initially_valid = constrForm->convalidated;
   11334             : 
   11335             :         /* set up colnames that are used to generate the constraint name */
   11336         486 :         for (int i = 0; i < numfks; i++)
   11337             :         {
   11338             :             Form_pg_attribute att;
   11339             : 
   11340         264 :             att = TupleDescAttr(RelationGetDescr(fkRel),
   11341         264 :                                 conkey[i] - 1);
   11342         264 :             fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
   11343         264 :                                              makeString(NameStr(att->attname)));
   11344             :         }
   11345             : 
   11346             :         /*
   11347             :          * Add the new foreign key constraint pointing to the new partition.
   11348             :          * Because this new partition appears in the referenced side of the
   11349             :          * constraint, we don't need to set up for Phase 3 check.
   11350             :          */
   11351         222 :         partIndexId = index_get_partition(partitionRel, indexOid);
   11352         222 :         if (!OidIsValid(partIndexId))
   11353           0 :             elog(ERROR, "index for %u not found in partition %s",
   11354             :                  indexOid, RelationGetRelationName(partitionRel));
   11355             : 
   11356             :         /*
   11357             :          * Get the "action" triggers belonging to the constraint to pass as
   11358             :          * parent OIDs for similar triggers that will be created on the
   11359             :          * partition in addFkRecurseReferenced().
   11360             :          */
   11361         222 :         if (constrForm->conenforced)
   11362         222 :             GetForeignKeyActionTriggers(trigrel, constrOid,
   11363             :                                         constrForm->confrelid, constrForm->conrelid,
   11364             :                                         &deleteTriggerOid, &updateTriggerOid);
   11365             : 
   11366             :         /* Add this constraint ... */
   11367         222 :         address = addFkConstraint(addFkReferencedSide,
   11368             :                                   fkconstraint->conname, fkconstraint, fkRel,
   11369             :                                   partitionRel, partIndexId, constrOid,
   11370             :                                   numfks, mapped_confkey,
   11371             :                                   conkey, conpfeqop, conppeqop, conffeqop,
   11372             :                                   numfkdelsetcols, confdelsetcols, false,
   11373         222 :                                   constrForm->conperiod);
   11374             :         /* ... and recurse */
   11375         222 :         addFkRecurseReferenced(fkconstraint,
   11376             :                                fkRel,
   11377             :                                partitionRel,
   11378             :                                partIndexId,
   11379             :                                address.objectId,
   11380             :                                numfks,
   11381             :                                mapped_confkey,
   11382             :                                conkey,
   11383             :                                conpfeqop,
   11384             :                                conppeqop,
   11385             :                                conffeqop,
   11386             :                                numfkdelsetcols,
   11387             :                                confdelsetcols,
   11388             :                                true,
   11389             :                                deleteTriggerOid,
   11390             :                                updateTriggerOid,
   11391         222 :                                constrForm->conperiod);
   11392             : 
   11393         222 :         table_close(fkRel, NoLock);
   11394         222 :         ReleaseSysCache(tuple);
   11395             :     }
   11396             : 
   11397        9812 :     table_close(trigrel, RowExclusiveLock);
   11398        9812 : }
   11399             : 
   11400             : /*
   11401             :  * CloneFkReferencing
   11402             :  *      Subroutine for CloneForeignKeyConstraints
   11403             :  *
   11404             :  * For each FK constraint of the parent relation in the given list, find an
   11405             :  * equivalent constraint in its partition relation that can be reparented;
   11406             :  * if one cannot be found, create a new constraint in the partition as its
   11407             :  * child.
   11408             :  *
   11409             :  * If wqueue is given, it is used to set up phase-3 verification for each
   11410             :  * cloned constraint; omit it if such verification is not needed
   11411             :  * (example: the partition is being created anew).
   11412             :  */
   11413             : static void
   11414        9830 : CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
   11415             : {
   11416             :     AttrMap    *attmap;
   11417             :     List       *partFKs;
   11418        9830 :     List       *clone = NIL;
   11419             :     ListCell   *cell;
   11420             :     Relation    trigrel;
   11421             : 
   11422             :     /* obtain a list of constraints that we need to clone */
   11423       11146 :     foreach(cell, RelationGetFKeyList(parentRel))
   11424             :     {
   11425        1322 :         ForeignKeyCacheInfo *fk = lfirst(cell);
   11426             : 
   11427             :         /*
   11428             :          * Refuse to attach a table as partition that this partitioned table
   11429             :          * already has a foreign key to.  This isn't useful schema, which is
   11430             :          * proven by the fact that there have been no user complaints that
   11431             :          * it's already impossible to achieve this in the opposite direction,
   11432             :          * i.e., creating a foreign key that references a partition.  This
   11433             :          * restriction allows us to dodge some complexities around
   11434             :          * pg_constraint and pg_trigger row creations that would be needed
   11435             :          * during ATTACH/DETACH for this kind of relationship.
   11436             :          */
   11437        1322 :         if (fk->confrelid == RelationGetRelid(partRel))
   11438           6 :             ereport(ERROR,
   11439             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   11440             :                      errmsg("cannot attach table \"%s\" as a partition because it is referenced by foreign key \"%s\"",
   11441             :                             RelationGetRelationName(partRel),
   11442             :                             get_constraint_name(fk->conoid))));
   11443             : 
   11444        1316 :         clone = lappend_oid(clone, fk->conoid);
   11445             :     }
   11446             : 
   11447             :     /*
   11448             :      * Silently do nothing if there's nothing to do.  In particular, this
   11449             :      * avoids throwing a spurious error for foreign tables.
   11450             :      */
   11451        9824 :     if (clone == NIL)
   11452        9268 :         return;
   11453             : 
   11454         556 :     if (partRel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
   11455           0 :         ereport(ERROR,
   11456             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   11457             :                  errmsg("foreign key constraints are not supported on foreign tables")));
   11458             : 
   11459             :     /*
   11460             :      * Triggers of the foreign keys will be manipulated a bunch of times in
   11461             :      * the loop below.  To avoid repeatedly opening/closing the trigger
   11462             :      * catalog relation, we open it here and pass it to the subroutines called
   11463             :      * below.
   11464             :      */
   11465         556 :     trigrel = table_open(TriggerRelationId, RowExclusiveLock);
   11466             : 
   11467             :     /*
   11468             :      * The constraint key may differ, if the columns in the partition are
   11469             :      * different.  This map is used to convert them.
   11470             :      */
   11471         556 :     attmap = build_attrmap_by_name(RelationGetDescr(partRel),
   11472             :                                    RelationGetDescr(parentRel),
   11473             :                                    false);
   11474             : 
   11475         556 :     partFKs = copyObject(RelationGetFKeyList(partRel));
   11476             : 
   11477        1860 :     foreach(cell, clone)
   11478             :     {
   11479        1316 :         Oid         parentConstrOid = lfirst_oid(cell);
   11480             :         Form_pg_constraint constrForm;
   11481             :         Relation    pkrel;
   11482             :         HeapTuple   tuple;
   11483             :         int         numfks;
   11484             :         AttrNumber  conkey[INDEX_MAX_KEYS];
   11485             :         AttrNumber  mapped_conkey[INDEX_MAX_KEYS];
   11486             :         AttrNumber  confkey[INDEX_MAX_KEYS];
   11487             :         Oid         conpfeqop[INDEX_MAX_KEYS];
   11488             :         Oid         conppeqop[INDEX_MAX_KEYS];
   11489             :         Oid         conffeqop[INDEX_MAX_KEYS];
   11490             :         int         numfkdelsetcols;
   11491             :         AttrNumber  confdelsetcols[INDEX_MAX_KEYS];
   11492             :         Constraint *fkconstraint;
   11493             :         bool        attached;
   11494             :         Oid         indexOid;
   11495             :         ObjectAddress address;
   11496             :         ListCell   *lc;
   11497        1316 :         Oid         insertTriggerOid = InvalidOid,
   11498        1316 :                     updateTriggerOid = InvalidOid;
   11499             :         bool        with_period;
   11500             : 
   11501        1316 :         tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parentConstrOid));
   11502        1316 :         if (!HeapTupleIsValid(tuple))
   11503           0 :             elog(ERROR, "cache lookup failed for constraint %u",
   11504             :                  parentConstrOid);
   11505        1316 :         constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   11506             : 
   11507             :         /* Don't clone constraints whose parents are being cloned */
   11508        1316 :         if (list_member_oid(clone, constrForm->conparentid))
   11509             :         {
   11510         724 :             ReleaseSysCache(tuple);
   11511         874 :             continue;
   11512             :         }
   11513             : 
   11514             :         /*
   11515             :          * Need to prevent concurrent deletions.  If pkrel is a partitioned
   11516             :          * relation, that means to lock all partitions.
   11517             :          */
   11518         592 :         pkrel = table_open(constrForm->confrelid, ShareRowExclusiveLock);
   11519         592 :         if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   11520         250 :             (void) find_all_inheritors(RelationGetRelid(pkrel),
   11521             :                                        ShareRowExclusiveLock, NULL);
   11522             : 
   11523         592 :         DeconstructFkConstraintRow(tuple, &numfks, conkey, confkey,
   11524             :                                    conpfeqop, conppeqop, conffeqop,
   11525             :                                    &numfkdelsetcols, confdelsetcols);
   11526        1418 :         for (int i = 0; i < numfks; i++)
   11527         826 :             mapped_conkey[i] = attmap->attnums[conkey[i] - 1];
   11528             : 
   11529             :         /*
   11530             :          * Get the "check" triggers belonging to the constraint, if it is
   11531             :          * ENFORCED, to pass as parent OIDs for similar triggers that will be
   11532             :          * created on the partition in addFkRecurseReferencing().  They are
   11533             :          * also passed to tryAttachPartitionForeignKey() below to simply
   11534             :          * assign as parents to the partition's existing "check" triggers,
   11535             :          * that is, if the corresponding constraints is deemed attachable to
   11536             :          * the parent constraint.
   11537             :          */
   11538         592 :         if (constrForm->conenforced)
   11539         580 :             GetForeignKeyCheckTriggers(trigrel, constrForm->oid,
   11540             :                                        constrForm->confrelid, constrForm->conrelid,
   11541             :                                        &insertTriggerOid, &updateTriggerOid);
   11542             : 
   11543             :         /*
   11544             :          * Before creating a new constraint, see whether any existing FKs are
   11545             :          * fit for the purpose.  If one is, attach the parent constraint to
   11546             :          * it, and don't clone anything.  This way we avoid the expensive
   11547             :          * verification step and don't end up with a duplicate FK, and we
   11548             :          * don't need to recurse to partitions for this constraint.
   11549             :          */
   11550         592 :         attached = false;
   11551         682 :         foreach(lc, partFKs)
   11552             :         {
   11553         246 :             ForeignKeyCacheInfo *fk = lfirst_node(ForeignKeyCacheInfo, lc);
   11554             : 
   11555         246 :             if (tryAttachPartitionForeignKey(wqueue,
   11556             :                                              fk,
   11557             :                                              partRel,
   11558             :                                              parentConstrOid,
   11559             :                                              numfks,
   11560             :                                              mapped_conkey,
   11561             :                                              confkey,
   11562             :                                              conpfeqop,
   11563             :                                              insertTriggerOid,
   11564             :                                              updateTriggerOid,
   11565             :                                              trigrel))
   11566             :             {
   11567         150 :                 attached = true;
   11568         150 :                 table_close(pkrel, NoLock);
   11569         150 :                 break;
   11570             :             }
   11571             :         }
   11572         586 :         if (attached)
   11573             :         {
   11574         150 :             ReleaseSysCache(tuple);
   11575         150 :             continue;
   11576             :         }
   11577             : 
   11578             :         /* No dice.  Set up to create our own constraint */
   11579         436 :         fkconstraint = makeNode(Constraint);
   11580         436 :         fkconstraint->contype = CONSTRAINT_FOREIGN;
   11581             :         /* ->conname determined below */
   11582         436 :         fkconstraint->deferrable = constrForm->condeferrable;
   11583         436 :         fkconstraint->initdeferred = constrForm->condeferred;
   11584         436 :         fkconstraint->location = -1;
   11585         436 :         fkconstraint->pktable = NULL;
   11586             :         /* ->fk_attrs determined below */
   11587         436 :         fkconstraint->pk_attrs = NIL;
   11588         436 :         fkconstraint->fk_matchtype = constrForm->confmatchtype;
   11589         436 :         fkconstraint->fk_upd_action = constrForm->confupdtype;
   11590         436 :         fkconstraint->fk_del_action = constrForm->confdeltype;
   11591         436 :         fkconstraint->fk_del_set_cols = NIL;
   11592         436 :         fkconstraint->old_conpfeqop = NIL;
   11593         436 :         fkconstraint->old_pktable_oid = InvalidOid;
   11594         436 :         fkconstraint->is_enforced = constrForm->conenforced;
   11595         436 :         fkconstraint->skip_validation = false;
   11596         436 :         fkconstraint->initially_valid = constrForm->convalidated;
   11597         992 :         for (int i = 0; i < numfks; i++)
   11598             :         {
   11599             :             Form_pg_attribute att;
   11600             : 
   11601         556 :             att = TupleDescAttr(RelationGetDescr(partRel),
   11602         556 :                                 mapped_conkey[i] - 1);
   11603         556 :             fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
   11604         556 :                                              makeString(NameStr(att->attname)));
   11605             :         }
   11606             : 
   11607         436 :         indexOid = constrForm->conindid;
   11608         436 :         with_period = constrForm->conperiod;
   11609             : 
   11610             :         /* Create the pg_constraint entry at this level */
   11611         436 :         address = addFkConstraint(addFkReferencingSide,
   11612         436 :                                   NameStr(constrForm->conname), fkconstraint,
   11613             :                                   partRel, pkrel, indexOid, parentConstrOid,
   11614             :                                   numfks, confkey,
   11615             :                                   mapped_conkey, conpfeqop,
   11616             :                                   conppeqop, conffeqop,
   11617             :                                   numfkdelsetcols, confdelsetcols,
   11618             :                                   false, with_period);
   11619             : 
   11620             :         /* Done with the cloned constraint's tuple */
   11621         436 :         ReleaseSysCache(tuple);
   11622             : 
   11623             :         /* Create the check triggers, and recurse to partitions, if any */
   11624         436 :         addFkRecurseReferencing(wqueue,
   11625             :                                 fkconstraint,
   11626             :                                 partRel,
   11627             :                                 pkrel,
   11628             :                                 indexOid,
   11629             :                                 address.objectId,
   11630             :                                 numfks,
   11631             :                                 confkey,
   11632             :                                 mapped_conkey,
   11633             :                                 conpfeqop,
   11634             :                                 conppeqop,
   11635             :                                 conffeqop,
   11636             :                                 numfkdelsetcols,
   11637             :                                 confdelsetcols,
   11638             :                                 false,  /* no old check exists */
   11639             :                                 AccessExclusiveLock,
   11640             :                                 insertTriggerOid,
   11641             :                                 updateTriggerOid,
   11642             :                                 with_period);
   11643         430 :         table_close(pkrel, NoLock);
   11644             :     }
   11645             : 
   11646         544 :     table_close(trigrel, RowExclusiveLock);
   11647             : }
   11648             : 
   11649             : /*
   11650             :  * When the parent of a partition receives [the referencing side of] a foreign
   11651             :  * key, we must propagate that foreign key to the partition.  However, the
   11652             :  * partition might already have an equivalent foreign key; this routine
   11653             :  * compares the given ForeignKeyCacheInfo (in the partition) to the FK defined
   11654             :  * by the other parameters.  If they are equivalent, create the link between
   11655             :  * the two constraints and return true.
   11656             :  *
   11657             :  * If the given FK does not match the one defined by rest of the params,
   11658             :  * return false.
   11659             :  */
   11660             : static bool
   11661         276 : tryAttachPartitionForeignKey(List **wqueue,
   11662             :                              ForeignKeyCacheInfo *fk,
   11663             :                              Relation partition,
   11664             :                              Oid parentConstrOid,
   11665             :                              int numfks,
   11666             :                              AttrNumber *mapped_conkey,
   11667             :                              AttrNumber *confkey,
   11668             :                              Oid *conpfeqop,
   11669             :                              Oid parentInsTrigger,
   11670             :                              Oid parentUpdTrigger,
   11671             :                              Relation trigrel)
   11672             : {
   11673             :     HeapTuple   parentConstrTup;
   11674             :     Form_pg_constraint parentConstr;
   11675             :     HeapTuple   partcontup;
   11676             :     Form_pg_constraint partConstr;
   11677             : 
   11678         276 :     parentConstrTup = SearchSysCache1(CONSTROID,
   11679             :                                       ObjectIdGetDatum(parentConstrOid));
   11680         276 :     if (!HeapTupleIsValid(parentConstrTup))
   11681           0 :         elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
   11682         276 :     parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
   11683             : 
   11684             :     /*
   11685             :      * Do some quick & easy initial checks.  If any of these fail, we cannot
   11686             :      * use this constraint.
   11687             :      */
   11688         276 :     if (fk->confrelid != parentConstr->confrelid || fk->nkeys != numfks)
   11689             :     {
   11690           0 :         ReleaseSysCache(parentConstrTup);
   11691           0 :         return false;
   11692             :     }
   11693         768 :     for (int i = 0; i < numfks; i++)
   11694             :     {
   11695         492 :         if (fk->conkey[i] != mapped_conkey[i] ||
   11696         492 :             fk->confkey[i] != confkey[i] ||
   11697         492 :             fk->conpfeqop[i] != conpfeqop[i])
   11698             :         {
   11699           0 :             ReleaseSysCache(parentConstrTup);
   11700           0 :             return false;
   11701             :         }
   11702             :     }
   11703             : 
   11704             :     /* Looks good so far; perform more extensive checks. */
   11705         276 :     partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
   11706         276 :     if (!HeapTupleIsValid(partcontup))
   11707           0 :         elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
   11708         276 :     partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
   11709             : 
   11710             :     /*
   11711             :      * An error should be raised if the constraint enforceability is
   11712             :      * different. Returning false without raising an error, as we do for other
   11713             :      * attributes, could lead to a duplicate constraint with the same
   11714             :      * enforceability as the parent. While this may be acceptable, it may not
   11715             :      * be ideal. Therefore, it's better to raise an error and allow the user
   11716             :      * to correct the enforceability before proceeding.
   11717             :      */
   11718         276 :     if (partConstr->conenforced != parentConstr->conenforced)
   11719           6 :         ereport(ERROR,
   11720             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   11721             :                  errmsg("constraint \"%s\" enforceability conflicts with constraint \"%s\" on relation \"%s\"",
   11722             :                         NameStr(parentConstr->conname),
   11723             :                         NameStr(partConstr->conname),
   11724             :                         RelationGetRelationName(partition))));
   11725             : 
   11726         270 :     if (OidIsValid(partConstr->conparentid) ||
   11727         240 :         partConstr->condeferrable != parentConstr->condeferrable ||
   11728         212 :         partConstr->condeferred != parentConstr->condeferred ||
   11729         212 :         partConstr->confupdtype != parentConstr->confupdtype ||
   11730         176 :         partConstr->confdeltype != parentConstr->confdeltype ||
   11731         176 :         partConstr->confmatchtype != parentConstr->confmatchtype)
   11732             :     {
   11733         108 :         ReleaseSysCache(parentConstrTup);
   11734         108 :         ReleaseSysCache(partcontup);
   11735         108 :         return false;
   11736             :     }
   11737             : 
   11738         162 :     ReleaseSysCache(parentConstrTup);
   11739         162 :     ReleaseSysCache(partcontup);
   11740             : 
   11741             :     /* Looks good!  Attach this constraint. */
   11742         162 :     AttachPartitionForeignKey(wqueue, partition, fk->conoid,
   11743             :                               parentConstrOid, parentInsTrigger,
   11744             :                               parentUpdTrigger, trigrel);
   11745             : 
   11746         162 :     return true;
   11747             : }
   11748             : 
   11749             : /*
   11750             :  * AttachPartitionForeignKey
   11751             :  *
   11752             :  * The subroutine for tryAttachPartitionForeignKey performs the final tasks of
   11753             :  * attaching the constraint, removing redundant triggers and entries from
   11754             :  * pg_constraint, and setting the constraint's parent.
   11755             :  */
   11756             : static void
   11757         162 : AttachPartitionForeignKey(List **wqueue,
   11758             :                           Relation partition,
   11759             :                           Oid partConstrOid,
   11760             :                           Oid parentConstrOid,
   11761             :                           Oid parentInsTrigger,
   11762             :                           Oid parentUpdTrigger,
   11763             :                           Relation trigrel)
   11764             : {
   11765             :     HeapTuple   parentConstrTup;
   11766             :     Form_pg_constraint parentConstr;
   11767             :     HeapTuple   partcontup;
   11768             :     Form_pg_constraint partConstr;
   11769             :     bool        queueValidation;
   11770             :     Oid         partConstrFrelid;
   11771             :     Oid         partConstrRelid;
   11772             :     bool        parentConstrIsEnforced;
   11773             : 
   11774             :     /* Fetch the parent constraint tuple */
   11775         162 :     parentConstrTup = SearchSysCache1(CONSTROID,
   11776             :                                       ObjectIdGetDatum(parentConstrOid));
   11777         162 :     if (!HeapTupleIsValid(parentConstrTup))
   11778           0 :         elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
   11779         162 :     parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
   11780         162 :     parentConstrIsEnforced = parentConstr->conenforced;
   11781             : 
   11782             :     /* Fetch the child constraint tuple */
   11783         162 :     partcontup = SearchSysCache1(CONSTROID,
   11784             :                                  ObjectIdGetDatum(partConstrOid));
   11785         162 :     if (!HeapTupleIsValid(partcontup))
   11786           0 :         elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
   11787         162 :     partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
   11788         162 :     partConstrFrelid = partConstr->confrelid;
   11789         162 :     partConstrRelid = partConstr->conrelid;
   11790             : 
   11791             :     /*
   11792             :      * If the referenced table is partitioned, then the partition we're
   11793             :      * attaching now has extra pg_constraint rows and action triggers that are
   11794             :      * no longer needed.  Remove those.
   11795             :      */
   11796         162 :     if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
   11797             :     {
   11798          36 :         Relation    pg_constraint = table_open(ConstraintRelationId, RowShareLock);
   11799             : 
   11800          36 :         RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
   11801             :                                   partConstrRelid);
   11802             : 
   11803          36 :         table_close(pg_constraint, RowShareLock);
   11804             :     }
   11805             : 
   11806             :     /*
   11807             :      * Will we need to validate this constraint?   A valid parent constraint
   11808             :      * implies that all child constraints have been validated, so if this one
   11809             :      * isn't, we must trigger phase 3 validation.
   11810             :      */
   11811         162 :     queueValidation = parentConstr->convalidated && !partConstr->convalidated;
   11812             : 
   11813         162 :     ReleaseSysCache(partcontup);
   11814         162 :     ReleaseSysCache(parentConstrTup);
   11815             : 
   11816             :     /*
   11817             :      * The action triggers in the new partition become redundant -- the parent
   11818             :      * table already has equivalent ones, and those will be able to reach the
   11819             :      * partition.  Remove the ones in the partition.  We identify them because
   11820             :      * they have our constraint OID, as well as being on the referenced rel.
   11821             :      */
   11822         162 :     DropForeignKeyConstraintTriggers(trigrel, partConstrOid, partConstrFrelid,
   11823             :                                      partConstrRelid);
   11824             : 
   11825         162 :     ConstraintSetParentConstraint(partConstrOid, parentConstrOid,
   11826             :                                   RelationGetRelid(partition));
   11827             : 
   11828             :     /*
   11829             :      * Like the constraint, attach partition's "check" triggers to the
   11830             :      * corresponding parent triggers if the constraint is ENFORCED. NOT
   11831             :      * ENFORCED constraints do not have these triggers.
   11832             :      */
   11833         162 :     if (parentConstrIsEnforced)
   11834             :     {
   11835             :         Oid         insertTriggerOid,
   11836             :                     updateTriggerOid;
   11837             : 
   11838         150 :         GetForeignKeyCheckTriggers(trigrel,
   11839             :                                    partConstrOid, partConstrFrelid, partConstrRelid,
   11840             :                                    &insertTriggerOid, &updateTriggerOid);
   11841             :         Assert(OidIsValid(insertTriggerOid) && OidIsValid(parentInsTrigger));
   11842         150 :         TriggerSetParentTrigger(trigrel, insertTriggerOid, parentInsTrigger,
   11843             :                                 RelationGetRelid(partition));
   11844             :         Assert(OidIsValid(updateTriggerOid) && OidIsValid(parentUpdTrigger));
   11845         150 :         TriggerSetParentTrigger(trigrel, updateTriggerOid, parentUpdTrigger,
   11846             :                                 RelationGetRelid(partition));
   11847             :     }
   11848             : 
   11849             :     /*
   11850             :      * We updated this pg_constraint row above to set its parent; validating
   11851             :      * it will cause its convalidated flag to change, so we need CCI here.  In
   11852             :      * addition, we need it unconditionally for the rare case where the parent
   11853             :      * table has *two* identical constraints; when reaching this function for
   11854             :      * the second one, we must have made our changes visible, otherwise we
   11855             :      * would try to attach both to this one.
   11856             :      */
   11857         162 :     CommandCounterIncrement();
   11858             : 
   11859             :     /* If validation is needed, put it in the queue now. */
   11860         162 :     if (queueValidation)
   11861             :     {
   11862             :         Relation    conrel;
   11863             :         Oid         confrelid;
   11864             : 
   11865          18 :         conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   11866             : 
   11867          18 :         partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(partConstrOid));
   11868          18 :         if (!HeapTupleIsValid(partcontup))
   11869           0 :             elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
   11870             : 
   11871          18 :         confrelid = ((Form_pg_constraint) GETSTRUCT(partcontup))->confrelid;
   11872             : 
   11873             :         /* Use the same lock as for AT_ValidateConstraint */
   11874          18 :         QueueFKConstraintValidation(wqueue, conrel, partition, confrelid,
   11875             :                                     partcontup, ShareUpdateExclusiveLock);
   11876          18 :         ReleaseSysCache(partcontup);
   11877          18 :         table_close(conrel, RowExclusiveLock);
   11878             :     }
   11879         162 : }
   11880             : 
   11881             : /*
   11882             :  * RemoveInheritedConstraint
   11883             :  *
   11884             :  * Removes the constraint and its associated trigger from the specified
   11885             :  * relation, which inherited the given constraint.
   11886             :  */
   11887             : static void
   11888          36 : RemoveInheritedConstraint(Relation conrel, Relation trigrel, Oid conoid,
   11889             :                           Oid conrelid)
   11890             : {
   11891             :     ObjectAddresses *objs;
   11892             :     HeapTuple   consttup;
   11893             :     ScanKeyData key;
   11894             :     SysScanDesc scan;
   11895             :     HeapTuple   trigtup;
   11896             : 
   11897          36 :     ScanKeyInit(&key,
   11898             :                 Anum_pg_constraint_conrelid,
   11899             :                 BTEqualStrategyNumber, F_OIDEQ,
   11900             :                 ObjectIdGetDatum(conrelid));
   11901             : 
   11902          36 :     scan = systable_beginscan(conrel,
   11903             :                               ConstraintRelidTypidNameIndexId,
   11904             :                               true, NULL, 1, &key);
   11905          36 :     objs = new_object_addresses();
   11906         324 :     while ((consttup = systable_getnext(scan)) != NULL)
   11907             :     {
   11908         288 :         Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(consttup);
   11909             : 
   11910         288 :         if (conform->conparentid != conoid)
   11911         210 :             continue;
   11912             :         else
   11913             :         {
   11914             :             ObjectAddress addr;
   11915             :             SysScanDesc scan2;
   11916             :             ScanKeyData key2;
   11917             :             int         n PG_USED_FOR_ASSERTS_ONLY;
   11918             : 
   11919          78 :             ObjectAddressSet(addr, ConstraintRelationId, conform->oid);
   11920          78 :             add_exact_object_address(&addr, objs);
   11921             : 
   11922             :             /*
   11923             :              * First we must delete the dependency record that binds the
   11924             :              * constraint records together.
   11925             :              */
   11926          78 :             n = deleteDependencyRecordsForSpecific(ConstraintRelationId,
   11927             :                                                    conform->oid,
   11928             :                                                    DEPENDENCY_INTERNAL,
   11929             :                                                    ConstraintRelationId,
   11930             :                                                    conoid);
   11931             :             Assert(n == 1);     /* actually only one is expected */
   11932             : 
   11933             :             /*
   11934             :              * Now search for the triggers for this constraint and set them up
   11935             :              * for deletion too
   11936             :              */
   11937          78 :             ScanKeyInit(&key2,
   11938             :                         Anum_pg_trigger_tgconstraint,
   11939             :                         BTEqualStrategyNumber, F_OIDEQ,
   11940             :                         ObjectIdGetDatum(conform->oid));
   11941          78 :             scan2 = systable_beginscan(trigrel, TriggerConstraintIndexId,
   11942             :                                        true, NULL, 1, &key2);
   11943         234 :             while ((trigtup = systable_getnext(scan2)) != NULL)
   11944             :             {
   11945         156 :                 ObjectAddressSet(addr, TriggerRelationId,
   11946             :                                  ((Form_pg_trigger) GETSTRUCT(trigtup))->oid);
   11947         156 :                 add_exact_object_address(&addr, objs);
   11948             :             }
   11949          78 :             systable_endscan(scan2);
   11950             :         }
   11951             :     }
   11952             :     /* make the dependency deletions visible */
   11953          36 :     CommandCounterIncrement();
   11954          36 :     performMultipleDeletions(objs, DROP_RESTRICT,
   11955             :                              PERFORM_DELETION_INTERNAL);
   11956          36 :     systable_endscan(scan);
   11957          36 : }
   11958             : 
   11959             : /*
   11960             :  * DropForeignKeyConstraintTriggers
   11961             :  *
   11962             :  * The subroutine for tryAttachPartitionForeignKey handles the deletion of
   11963             :  * action triggers for the foreign key constraint.
   11964             :  *
   11965             :  * If valid confrelid and conrelid values are not provided, the respective
   11966             :  * trigger check will be skipped, and the trigger will be considered for
   11967             :  * removal.
   11968             :  */
   11969             : static void
   11970         234 : DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid, Oid confrelid,
   11971             :                                  Oid conrelid)
   11972             : {
   11973             :     ScanKeyData key;
   11974             :     SysScanDesc scan;
   11975             :     HeapTuple   trigtup;
   11976             : 
   11977         234 :     ScanKeyInit(&key,
   11978             :                 Anum_pg_trigger_tgconstraint,
   11979             :                 BTEqualStrategyNumber, F_OIDEQ,
   11980             :                 ObjectIdGetDatum(conoid));
   11981         234 :     scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
   11982             :                               NULL, 1, &key);
   11983        1014 :     while ((trigtup = systable_getnext(scan)) != NULL)
   11984             :     {
   11985         780 :         Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
   11986             :         ObjectAddress trigger;
   11987             : 
   11988             :         /* Invalid if trigger is not for a referential integrity constraint */
   11989         780 :         if (!OidIsValid(trgform->tgconstrrelid))
   11990         300 :             continue;
   11991         780 :         if (OidIsValid(conrelid) && trgform->tgconstrrelid != conrelid)
   11992         300 :             continue;
   11993         480 :         if (OidIsValid(confrelid) && trgform->tgrelid != confrelid)
   11994           0 :             continue;
   11995             : 
   11996             :         /* We should be dropping trigger related to foreign key constraint */
   11997             :         Assert(trgform->tgfoid == F_RI_FKEY_CHECK_INS ||
   11998             :                trgform->tgfoid == F_RI_FKEY_CHECK_UPD ||
   11999             :                trgform->tgfoid == F_RI_FKEY_CASCADE_DEL ||
   12000             :                trgform->tgfoid == F_RI_FKEY_CASCADE_UPD ||
   12001             :                trgform->tgfoid == F_RI_FKEY_RESTRICT_DEL ||
   12002             :                trgform->tgfoid == F_RI_FKEY_RESTRICT_UPD ||
   12003             :                trgform->tgfoid == F_RI_FKEY_SETNULL_DEL ||
   12004             :                trgform->tgfoid == F_RI_FKEY_SETNULL_UPD ||
   12005             :                trgform->tgfoid == F_RI_FKEY_SETDEFAULT_DEL ||
   12006             :                trgform->tgfoid == F_RI_FKEY_SETDEFAULT_UPD ||
   12007             :                trgform->tgfoid == F_RI_FKEY_NOACTION_DEL ||
   12008             :                trgform->tgfoid == F_RI_FKEY_NOACTION_UPD);
   12009             : 
   12010             :         /*
   12011             :          * The constraint is originally set up to contain this trigger as an
   12012             :          * implementation object, so there's a dependency record that links
   12013             :          * the two; however, since the trigger is no longer needed, we remove
   12014             :          * the dependency link in order to be able to drop the trigger while
   12015             :          * keeping the constraint intact.
   12016             :          */
   12017         480 :         deleteDependencyRecordsFor(TriggerRelationId,
   12018             :                                    trgform->oid,
   12019             :                                    false);
   12020             :         /* make dependency deletion visible to performDeletion */
   12021         480 :         CommandCounterIncrement();
   12022         480 :         ObjectAddressSet(trigger, TriggerRelationId,
   12023             :                          trgform->oid);
   12024         480 :         performDeletion(&trigger, DROP_RESTRICT, 0);
   12025             :         /* make trigger drop visible, in case the loop iterates */
   12026         480 :         CommandCounterIncrement();
   12027             :     }
   12028             : 
   12029         234 :     systable_endscan(scan);
   12030         234 : }
   12031             : 
   12032             : /*
   12033             :  * GetForeignKeyActionTriggers
   12034             :  *      Returns delete and update "action" triggers of the given relation
   12035             :  *      belonging to the given constraint
   12036             :  */
   12037             : static void
   12038         222 : GetForeignKeyActionTriggers(Relation trigrel,
   12039             :                             Oid conoid, Oid confrelid, Oid conrelid,
   12040             :                             Oid *deleteTriggerOid,
   12041             :                             Oid *updateTriggerOid)
   12042             : {
   12043             :     ScanKeyData key;
   12044             :     SysScanDesc scan;
   12045             :     HeapTuple   trigtup;
   12046             : 
   12047         222 :     *deleteTriggerOid = *updateTriggerOid = InvalidOid;
   12048         222 :     ScanKeyInit(&key,
   12049             :                 Anum_pg_trigger_tgconstraint,
   12050             :                 BTEqualStrategyNumber, F_OIDEQ,
   12051             :                 ObjectIdGetDatum(conoid));
   12052             : 
   12053         222 :     scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
   12054             :                               NULL, 1, &key);
   12055         450 :     while ((trigtup = systable_getnext(scan)) != NULL)
   12056             :     {
   12057         450 :         Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
   12058             : 
   12059         450 :         if (trgform->tgconstrrelid != conrelid)
   12060           6 :             continue;
   12061         444 :         if (trgform->tgrelid != confrelid)
   12062           0 :             continue;
   12063             :         /* Only ever look at "action" triggers on the PK side. */
   12064         444 :         if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_PK)
   12065           0 :             continue;
   12066         444 :         if (TRIGGER_FOR_DELETE(trgform->tgtype))
   12067             :         {
   12068             :             Assert(*deleteTriggerOid == InvalidOid);
   12069         222 :             *deleteTriggerOid = trgform->oid;
   12070             :         }
   12071         222 :         else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
   12072             :         {
   12073             :             Assert(*updateTriggerOid == InvalidOid);
   12074         222 :             *updateTriggerOid = trgform->oid;
   12075             :         }
   12076             : #ifndef USE_ASSERT_CHECKING
   12077             :         /* In an assert-enabled build, continue looking to find duplicates */
   12078         444 :         if (OidIsValid(*deleteTriggerOid) && OidIsValid(*updateTriggerOid))
   12079         222 :             break;
   12080             : #endif
   12081             :     }
   12082             : 
   12083         222 :     if (!OidIsValid(*deleteTriggerOid))
   12084           0 :         elog(ERROR, "could not find ON DELETE action trigger of foreign key constraint %u",
   12085             :              conoid);
   12086         222 :     if (!OidIsValid(*updateTriggerOid))
   12087           0 :         elog(ERROR, "could not find ON UPDATE action trigger of foreign key constraint %u",
   12088             :              conoid);
   12089             : 
   12090         222 :     systable_endscan(scan);
   12091         222 : }
   12092             : 
   12093             : /*
   12094             :  * GetForeignKeyCheckTriggers
   12095             :  *      Returns insert and update "check" triggers of the given relation
   12096             :  *      belonging to the given constraint
   12097             :  */
   12098             : static void
   12099         832 : GetForeignKeyCheckTriggers(Relation trigrel,
   12100             :                            Oid conoid, Oid confrelid, Oid conrelid,
   12101             :                            Oid *insertTriggerOid,
   12102             :                            Oid *updateTriggerOid)
   12103             : {
   12104             :     ScanKeyData key;
   12105             :     SysScanDesc scan;
   12106             :     HeapTuple   trigtup;
   12107             : 
   12108         832 :     *insertTriggerOid = *updateTriggerOid = InvalidOid;
   12109         832 :     ScanKeyInit(&key,
   12110             :                 Anum_pg_trigger_tgconstraint,
   12111             :                 BTEqualStrategyNumber, F_OIDEQ,
   12112             :                 ObjectIdGetDatum(conoid));
   12113             : 
   12114         832 :     scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
   12115             :                               NULL, 1, &key);
   12116        2672 :     while ((trigtup = systable_getnext(scan)) != NULL)
   12117             :     {
   12118        2672 :         Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
   12119             : 
   12120        2672 :         if (trgform->tgconstrrelid != confrelid)
   12121         900 :             continue;
   12122        1772 :         if (trgform->tgrelid != conrelid)
   12123           0 :             continue;
   12124             :         /* Only ever look at "check" triggers on the FK side. */
   12125        1772 :         if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_FK)
   12126         108 :             continue;
   12127        1664 :         if (TRIGGER_FOR_INSERT(trgform->tgtype))
   12128             :         {
   12129             :             Assert(*insertTriggerOid == InvalidOid);
   12130         832 :             *insertTriggerOid = trgform->oid;
   12131             :         }
   12132         832 :         else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
   12133             :         {
   12134             :             Assert(*updateTriggerOid == InvalidOid);
   12135         832 :             *updateTriggerOid = trgform->oid;
   12136             :         }
   12137             : #ifndef USE_ASSERT_CHECKING
   12138             :         /* In an assert-enabled build, continue looking to find duplicates. */
   12139        1664 :         if (OidIsValid(*insertTriggerOid) && OidIsValid(*updateTriggerOid))
   12140         832 :             break;
   12141             : #endif
   12142             :     }
   12143             : 
   12144         832 :     if (!OidIsValid(*insertTriggerOid))
   12145           0 :         elog(ERROR, "could not find ON INSERT check triggers of foreign key constraint %u",
   12146             :              conoid);
   12147         832 :     if (!OidIsValid(*updateTriggerOid))
   12148           0 :         elog(ERROR, "could not find ON UPDATE check triggers of foreign key constraint %u",
   12149             :              conoid);
   12150             : 
   12151         832 :     systable_endscan(scan);
   12152         832 : }
   12153             : 
   12154             : /*
   12155             :  * ALTER TABLE ALTER CONSTRAINT
   12156             :  *
   12157             :  * Update the attributes of a constraint.
   12158             :  *
   12159             :  * Currently only works for Foreign Key and not null constraints.
   12160             :  *
   12161             :  * If the constraint is modified, returns its address; otherwise, return
   12162             :  * InvalidObjectAddress.
   12163             :  */
   12164             : static ObjectAddress
   12165         288 : ATExecAlterConstraint(List **wqueue, Relation rel, ATAlterConstraint *cmdcon,
   12166             :                       bool recurse, LOCKMODE lockmode)
   12167             : {
   12168             :     Relation    conrel;
   12169             :     Relation    tgrel;
   12170             :     SysScanDesc scan;
   12171             :     ScanKeyData skey[3];
   12172             :     HeapTuple   contuple;
   12173             :     Form_pg_constraint currcon;
   12174             :     ObjectAddress address;
   12175             : 
   12176             :     /*
   12177             :      * Disallow altering ONLY a partitioned table, as it would make no sense.
   12178             :      * This is okay for legacy inheritance.
   12179             :      */
   12180         288 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
   12181           0 :         ereport(ERROR,
   12182             :                 errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   12183             :                 errmsg("constraint must be altered in child tables too"),
   12184             :                 errhint("Do not specify the ONLY keyword."));
   12185             : 
   12186             : 
   12187         288 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   12188         288 :     tgrel = table_open(TriggerRelationId, RowExclusiveLock);
   12189             : 
   12190             :     /*
   12191             :      * Find and check the target constraint
   12192             :      */
   12193         288 :     ScanKeyInit(&skey[0],
   12194             :                 Anum_pg_constraint_conrelid,
   12195             :                 BTEqualStrategyNumber, F_OIDEQ,
   12196             :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   12197         288 :     ScanKeyInit(&skey[1],
   12198             :                 Anum_pg_constraint_contypid,
   12199             :                 BTEqualStrategyNumber, F_OIDEQ,
   12200             :                 ObjectIdGetDatum(InvalidOid));
   12201         288 :     ScanKeyInit(&skey[2],
   12202             :                 Anum_pg_constraint_conname,
   12203             :                 BTEqualStrategyNumber, F_NAMEEQ,
   12204         288 :                 CStringGetDatum(cmdcon->conname));
   12205         288 :     scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
   12206             :                               true, NULL, 3, skey);
   12207             : 
   12208             :     /* There can be at most one matching row */
   12209         288 :     if (!HeapTupleIsValid(contuple = systable_getnext(scan)))
   12210           6 :         ereport(ERROR,
   12211             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   12212             :                  errmsg("constraint \"%s\" of relation \"%s\" does not exist",
   12213             :                         cmdcon->conname, RelationGetRelationName(rel))));
   12214             : 
   12215         282 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12216         282 :     if (cmdcon->alterDeferrability && currcon->contype != CONSTRAINT_FOREIGN)
   12217           0 :         ereport(ERROR,
   12218             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   12219             :                  errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
   12220             :                         cmdcon->conname, RelationGetRelationName(rel))));
   12221         282 :     if (cmdcon->alterEnforceability && currcon->contype != CONSTRAINT_FOREIGN)
   12222          12 :         ereport(ERROR,
   12223             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   12224             :                  errmsg("cannot alter enforceability of constraint \"%s\" of relation \"%s\"",
   12225             :                         cmdcon->conname, RelationGetRelationName(rel))));
   12226         270 :     if (cmdcon->alterInheritability &&
   12227          90 :         currcon->contype != CONSTRAINT_NOTNULL)
   12228          24 :         ereport(ERROR,
   12229             :                 errcode(ERRCODE_WRONG_OBJECT_TYPE),
   12230             :                 errmsg("constraint \"%s\" of relation \"%s\" is not a not-null constraint",
   12231             :                        cmdcon->conname, RelationGetRelationName(rel)));
   12232             : 
   12233             :     /* Refuse to modify inheritability of inherited constraints */
   12234         246 :     if (cmdcon->alterInheritability &&
   12235          66 :         cmdcon->noinherit && currcon->coninhcount > 0)
   12236           6 :         ereport(ERROR,
   12237             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   12238             :                 errmsg("cannot alter inherited constraint \"%s\" on relation \"%s\"",
   12239             :                        NameStr(currcon->conname),
   12240             :                        RelationGetRelationName(rel)));
   12241             : 
   12242             :     /*
   12243             :      * If it's not the topmost constraint, raise an error.
   12244             :      *
   12245             :      * Altering a non-topmost constraint leaves some triggers untouched, since
   12246             :      * they are not directly connected to this constraint; also, pg_dump would
   12247             :      * ignore the deferrability status of the individual constraint, since it
   12248             :      * only dumps topmost constraints.  Avoid these problems by refusing this
   12249             :      * operation and telling the user to alter the parent constraint instead.
   12250             :      */
   12251         240 :     if (OidIsValid(currcon->conparentid))
   12252             :     {
   12253             :         HeapTuple   tp;
   12254          12 :         Oid         parent = currcon->conparentid;
   12255          12 :         char       *ancestorname = NULL;
   12256          12 :         char       *ancestortable = NULL;
   12257             : 
   12258             :         /* Loop to find the topmost constraint */
   12259          24 :         while (HeapTupleIsValid(tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parent))))
   12260             :         {
   12261          24 :             Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
   12262             : 
   12263             :             /* If no parent, this is the constraint we want */
   12264          24 :             if (!OidIsValid(contup->conparentid))
   12265             :             {
   12266          12 :                 ancestorname = pstrdup(NameStr(contup->conname));
   12267          12 :                 ancestortable = get_rel_name(contup->conrelid);
   12268          12 :                 ReleaseSysCache(tp);
   12269          12 :                 break;
   12270             :             }
   12271             : 
   12272          12 :             parent = contup->conparentid;
   12273          12 :             ReleaseSysCache(tp);
   12274             :         }
   12275             : 
   12276          12 :         ereport(ERROR,
   12277             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   12278             :                  errmsg("cannot alter constraint \"%s\" on relation \"%s\"",
   12279             :                         cmdcon->conname, RelationGetRelationName(rel)),
   12280             :                  ancestorname && ancestortable ?
   12281             :                  errdetail("Constraint \"%s\" is derived from constraint \"%s\" of relation \"%s\".",
   12282             :                            cmdcon->conname, ancestorname, ancestortable) : 0,
   12283             :                  errhint("You may alter the constraint it derives from instead.")));
   12284             :     }
   12285             : 
   12286         228 :     address = InvalidObjectAddress;
   12287             : 
   12288             :     /*
   12289             :      * Do the actual catalog work, and recurse if necessary.
   12290             :      */
   12291         228 :     if (ATExecAlterConstraintInternal(wqueue, cmdcon, conrel, tgrel, rel,
   12292             :                                       contuple, recurse, lockmode))
   12293         216 :         ObjectAddressSet(address, ConstraintRelationId, currcon->oid);
   12294             : 
   12295         222 :     systable_endscan(scan);
   12296             : 
   12297         222 :     table_close(tgrel, RowExclusiveLock);
   12298         222 :     table_close(conrel, RowExclusiveLock);
   12299             : 
   12300         222 :     return address;
   12301             : }
   12302             : 
   12303             : /*
   12304             :  * A subroutine of ATExecAlterConstraint that calls the respective routines for
   12305             :  * altering constraint's enforceability, deferrability or inheritability.
   12306             :  */
   12307             : static bool
   12308         228 : ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon,
   12309             :                               Relation conrel, Relation tgrel, Relation rel,
   12310             :                               HeapTuple contuple, bool recurse,
   12311             :                               LOCKMODE lockmode)
   12312             : {
   12313             :     Form_pg_constraint currcon;
   12314         228 :     bool        changed = false;
   12315         228 :     List       *otherrelids = NIL;
   12316             : 
   12317         228 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12318             : 
   12319             :     /*
   12320             :      * Do the catalog work for the enforceability or deferrability change,
   12321             :      * recurse if necessary.
   12322             :      *
   12323             :      * Note that even if deferrability is requested to be altered along with
   12324             :      * enforceability, we don't need to explicitly update multiple entries in
   12325             :      * pg_trigger related to deferrability.
   12326             :      *
   12327             :      * Modifying enforceability involves either creating or dropping the
   12328             :      * trigger, during which the deferrability setting will be adjusted
   12329             :      * automatically.
   12330             :      */
   12331         300 :     if (cmdcon->alterEnforceability &&
   12332          72 :         ATExecAlterConstrEnforceability(wqueue, cmdcon, conrel, tgrel,
   12333             :                                         currcon->conrelid, currcon->confrelid,
   12334             :                                         contuple, lockmode, InvalidOid,
   12335             :                                         InvalidOid, InvalidOid, InvalidOid))
   12336          66 :         changed = true;
   12337             : 
   12338         258 :     else if (cmdcon->alterDeferrability &&
   12339          96 :              ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel,
   12340             :                                             contuple, recurse, &otherrelids,
   12341             :                                             lockmode))
   12342             :     {
   12343             :         /*
   12344             :          * AlterConstrUpdateConstraintEntry already invalidated relcache for
   12345             :          * the relations having the constraint itself; here we also invalidate
   12346             :          * for relations that have any triggers that are part of the
   12347             :          * constraint.
   12348             :          */
   12349         306 :         foreach_oid(relid, otherrelids)
   12350         114 :             CacheInvalidateRelcacheByRelid(relid);
   12351             : 
   12352          96 :         changed = true;
   12353             :     }
   12354             : 
   12355             :     /*
   12356             :      * Do the catalog work for the inheritability change.
   12357             :      */
   12358         282 :     if (cmdcon->alterInheritability &&
   12359          60 :         ATExecAlterConstrInheritability(wqueue, cmdcon, conrel, rel, contuple,
   12360             :                                         lockmode))
   12361          54 :         changed = true;
   12362             : 
   12363         222 :     return changed;
   12364             : }
   12365             : 
   12366             : /*
   12367             :  * Returns true if the constraint's enforceability is altered.
   12368             :  *
   12369             :  * Depending on whether the constraint is being set to ENFORCED or NOT
   12370             :  * ENFORCED, it creates or drops the trigger accordingly.
   12371             :  *
   12372             :  * Note that we must recurse even when trying to change a constraint to not
   12373             :  * enforced if it is already not enforced, in case descendant constraints
   12374             :  * might be enforced and need to be changed to not enforced. Conversely, we
   12375             :  * should do nothing if a constraint is being set to enforced and is already
   12376             :  * enforced, as descendant constraints cannot be different in that case.
   12377             :  */
   12378             : static bool
   12379         168 : ATExecAlterConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
   12380             :                                 Relation conrel, Relation tgrel,
   12381             :                                 Oid fkrelid, Oid pkrelid,
   12382             :                                 HeapTuple contuple, LOCKMODE lockmode,
   12383             :                                 Oid ReferencedParentDelTrigger,
   12384             :                                 Oid ReferencedParentUpdTrigger,
   12385             :                                 Oid ReferencingParentInsTrigger,
   12386             :                                 Oid ReferencingParentUpdTrigger)
   12387             : {
   12388             :     Form_pg_constraint currcon;
   12389             :     Oid         conoid;
   12390             :     Relation    rel;
   12391         168 :     bool        changed = false;
   12392             : 
   12393             :     /* Since this function recurses, it could be driven to stack overflow */
   12394         168 :     check_stack_depth();
   12395             : 
   12396             :     Assert(cmdcon->alterEnforceability);
   12397             : 
   12398         168 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12399         168 :     conoid = currcon->oid;
   12400             : 
   12401             :     /* Should be foreign key constraint */
   12402             :     Assert(currcon->contype == CONSTRAINT_FOREIGN);
   12403             : 
   12404         168 :     rel = table_open(currcon->conrelid, lockmode);
   12405             : 
   12406         168 :     if (currcon->conenforced != cmdcon->is_enforced)
   12407             :     {
   12408         162 :         AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
   12409         162 :         changed = true;
   12410             :     }
   12411             : 
   12412             :     /* Drop triggers */
   12413         168 :     if (!cmdcon->is_enforced)
   12414             :     {
   12415             :         /*
   12416             :          * When setting a constraint to NOT ENFORCED, the constraint triggers
   12417             :          * need to be dropped. Therefore, we must process the child relations
   12418             :          * first, followed by the parent, to account for dependencies.
   12419             :          */
   12420         126 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
   12421          54 :             get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
   12422          18 :             AlterConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
   12423             :                                              fkrelid, pkrelid, contuple,
   12424             :                                              lockmode, InvalidOid, InvalidOid,
   12425             :                                              InvalidOid, InvalidOid);
   12426             : 
   12427             :         /* Drop all the triggers */
   12428          72 :         DropForeignKeyConstraintTriggers(tgrel, conoid, InvalidOid, InvalidOid);
   12429             :     }
   12430          96 :     else if (changed)           /* Create triggers */
   12431             :     {
   12432          96 :         Oid         ReferencedDelTriggerOid = InvalidOid,
   12433          96 :                     ReferencedUpdTriggerOid = InvalidOid,
   12434          96 :                     ReferencingInsTriggerOid = InvalidOid,
   12435          96 :                     ReferencingUpdTriggerOid = InvalidOid;
   12436             : 
   12437             :         /* Prepare the minimal information required for trigger creation. */
   12438          96 :         Constraint *fkconstraint = makeNode(Constraint);
   12439             : 
   12440          96 :         fkconstraint->conname = pstrdup(NameStr(currcon->conname));
   12441          96 :         fkconstraint->fk_matchtype = currcon->confmatchtype;
   12442          96 :         fkconstraint->fk_upd_action = currcon->confupdtype;
   12443          96 :         fkconstraint->fk_del_action = currcon->confdeltype;
   12444             : 
   12445             :         /* Create referenced triggers */
   12446          96 :         if (currcon->conrelid == fkrelid)
   12447          54 :             createForeignKeyActionTriggers(currcon->conrelid,
   12448             :                                            currcon->confrelid,
   12449             :                                            fkconstraint,
   12450             :                                            conoid,
   12451             :                                            currcon->conindid,
   12452             :                                            ReferencedParentDelTrigger,
   12453             :                                            ReferencedParentUpdTrigger,
   12454             :                                            &ReferencedDelTriggerOid,
   12455             :                                            &ReferencedUpdTriggerOid);
   12456             : 
   12457             :         /* Create referencing triggers */
   12458          96 :         if (currcon->confrelid == pkrelid)
   12459          84 :             createForeignKeyCheckTriggers(currcon->conrelid,
   12460             :                                           pkrelid,
   12461             :                                           fkconstraint,
   12462             :                                           conoid,
   12463             :                                           currcon->conindid,
   12464             :                                           ReferencingParentInsTrigger,
   12465             :                                           ReferencingParentUpdTrigger,
   12466             :                                           &ReferencingInsTriggerOid,
   12467             :                                           &ReferencingUpdTriggerOid);
   12468             : 
   12469             :         /*
   12470             :          * Tell Phase 3 to check that the constraint is satisfied by existing
   12471             :          * rows.  Only applies to leaf partitions, and (for constraints that
   12472             :          * reference a partitioned table) only if this is not one of the
   12473             :          * pg_constraint rows that exist solely to support action triggers.
   12474             :          */
   12475          96 :         if (rel->rd_rel->relkind == RELKIND_RELATION &&
   12476          78 :             currcon->confrelid == pkrelid)
   12477             :         {
   12478             :             AlteredTableInfo *tab;
   12479             :             NewConstraint *newcon;
   12480             : 
   12481          66 :             newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
   12482          66 :             newcon->name = fkconstraint->conname;
   12483          66 :             newcon->contype = CONSTR_FOREIGN;
   12484          66 :             newcon->refrelid = currcon->confrelid;
   12485          66 :             newcon->refindid = currcon->conindid;
   12486          66 :             newcon->conid = currcon->oid;
   12487          66 :             newcon->qual = (Node *) fkconstraint;
   12488             : 
   12489             :             /* Find or create work queue entry for this table */
   12490          66 :             tab = ATGetQueueEntry(wqueue, rel);
   12491          66 :             tab->constraints = lappend(tab->constraints, newcon);
   12492             :         }
   12493             : 
   12494             :         /*
   12495             :          * If the table at either end of the constraint is partitioned, we
   12496             :          * need to recurse and create triggers for each constraint that is a
   12497             :          * child of this one.
   12498             :          */
   12499         174 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
   12500          78 :             get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
   12501          24 :             AlterConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
   12502             :                                              fkrelid, pkrelid, contuple,
   12503             :                                              lockmode, ReferencedDelTriggerOid,
   12504             :                                              ReferencedUpdTriggerOid,
   12505             :                                              ReferencingInsTriggerOid,
   12506             :                                              ReferencingUpdTriggerOid);
   12507             :     }
   12508             : 
   12509         168 :     table_close(rel, NoLock);
   12510             : 
   12511         168 :     return changed;
   12512             : }
   12513             : 
   12514             : /*
   12515             :  * Returns true if the constraint's deferrability is altered.
   12516             :  *
   12517             :  * *otherrelids is appended OIDs of relations containing affected triggers.
   12518             :  *
   12519             :  * Note that we must recurse even when the values are correct, in case
   12520             :  * indirect descendants have had their constraints altered locally.
   12521             :  * (This could be avoided if we forbade altering constraints in partitions
   12522             :  * but existing releases don't do that.)
   12523             :  */
   12524             : static bool
   12525         162 : ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
   12526             :                                Relation conrel, Relation tgrel, Relation rel,
   12527             :                                HeapTuple contuple, bool recurse,
   12528             :                                List **otherrelids, LOCKMODE lockmode)
   12529             : {
   12530             :     Form_pg_constraint currcon;
   12531             :     Oid         refrelid;
   12532         162 :     bool        changed = false;
   12533             : 
   12534             :     /* since this function recurses, it could be driven to stack overflow */
   12535         162 :     check_stack_depth();
   12536             : 
   12537             :     Assert(cmdcon->alterDeferrability);
   12538             : 
   12539         162 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12540         162 :     refrelid = currcon->confrelid;
   12541             : 
   12542             :     /* Should be foreign key constraint */
   12543             :     Assert(currcon->contype == CONSTRAINT_FOREIGN);
   12544             : 
   12545             :     /*
   12546             :      * If called to modify a constraint that's already in the desired state,
   12547             :      * silently do nothing.
   12548             :      */
   12549         162 :     if (currcon->condeferrable != cmdcon->deferrable ||
   12550           6 :         currcon->condeferred != cmdcon->initdeferred)
   12551             :     {
   12552         162 :         AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
   12553         162 :         changed = true;
   12554             : 
   12555             :         /*
   12556             :          * Now we need to update the multiple entries in pg_trigger that
   12557             :          * implement the constraint.
   12558             :          */
   12559         162 :         AlterConstrTriggerDeferrability(currcon->oid, tgrel, rel,
   12560         162 :                                         cmdcon->deferrable,
   12561         162 :                                         cmdcon->initdeferred, otherrelids);
   12562             :     }
   12563             : 
   12564             :     /*
   12565             :      * If the table at either end of the constraint is partitioned, we need to
   12566             :      * handle every constraint that is a child of this one.
   12567             :      */
   12568         162 :     if (recurse && changed &&
   12569         300 :         (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
   12570         138 :          get_rel_relkind(refrelid) == RELKIND_PARTITIONED_TABLE))
   12571          42 :         AlterConstrDeferrabilityRecurse(wqueue, cmdcon, conrel, tgrel, rel,
   12572             :                                         contuple, recurse, otherrelids,
   12573             :                                         lockmode);
   12574             : 
   12575         162 :     return changed;
   12576             : }
   12577             : 
   12578             : /*
   12579             :  * Returns true if the constraint's inheritability is altered.
   12580             :  */
   12581             : static bool
   12582          60 : ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
   12583             :                                 Relation conrel, Relation rel,
   12584             :                                 HeapTuple contuple, LOCKMODE lockmode)
   12585             : {
   12586             :     Form_pg_constraint currcon;
   12587             :     AttrNumber  colNum;
   12588             :     char       *colName;
   12589             :     List       *children;
   12590             : 
   12591             :     Assert(cmdcon->alterInheritability);
   12592             : 
   12593          60 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12594             : 
   12595             :     /* The current implementation only works for NOT NULL constraints */
   12596             :     Assert(currcon->contype == CONSTRAINT_NOTNULL);
   12597             : 
   12598             :     /*
   12599             :      * If called to modify a constraint that's already in the desired state,
   12600             :      * silently do nothing.
   12601             :      */
   12602          60 :     if (cmdcon->noinherit == currcon->connoinherit)
   12603           0 :         return false;
   12604             : 
   12605          60 :     AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
   12606          60 :     CommandCounterIncrement();
   12607             : 
   12608             :     /* Fetch the column number and name */
   12609          60 :     colNum = extractNotNullColumn(contuple);
   12610          60 :     colName = get_attname(currcon->conrelid, colNum, false);
   12611             : 
   12612             :     /*
   12613             :      * Propagate the change to children.  For this subcommand type we don't
   12614             :      * recursively affect children, just the immediate level.
   12615             :      */
   12616          60 :     children = find_inheritance_children(RelationGetRelid(rel),
   12617             :                                          lockmode);
   12618         192 :     foreach_oid(childoid, children)
   12619             :     {
   12620             :         ObjectAddress addr;
   12621             : 
   12622          84 :         if (cmdcon->noinherit)
   12623             :         {
   12624             :             HeapTuple   childtup;
   12625             :             Form_pg_constraint childcon;
   12626             : 
   12627          30 :             childtup = findNotNullConstraint(childoid, colName);
   12628          30 :             if (!childtup)
   12629           0 :                 elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
   12630             :                      colName, childoid);
   12631          30 :             childcon = (Form_pg_constraint) GETSTRUCT(childtup);
   12632             :             Assert(childcon->coninhcount > 0);
   12633          30 :             childcon->coninhcount--;
   12634          30 :             childcon->conislocal = true;
   12635          30 :             CatalogTupleUpdate(conrel, &childtup->t_self, childtup);
   12636          30 :             heap_freetuple(childtup);
   12637             :         }
   12638             :         else
   12639             :         {
   12640          54 :             Relation    childrel = table_open(childoid, NoLock);
   12641             : 
   12642          54 :             addr = ATExecSetNotNull(wqueue, childrel, NameStr(currcon->conname),
   12643             :                                     colName, true, true, lockmode);
   12644          48 :             if (OidIsValid(addr.objectId))
   12645          48 :                 CommandCounterIncrement();
   12646          48 :             table_close(childrel, NoLock);
   12647             :         }
   12648             :     }
   12649             : 
   12650          54 :     return true;
   12651             : }
   12652             : 
   12653             : /*
   12654             :  * A subroutine of ATExecAlterConstrDeferrability that updated constraint
   12655             :  * trigger's deferrability.
   12656             :  *
   12657             :  * The arguments to this function have the same meaning as the arguments to
   12658             :  * ATExecAlterConstrDeferrability.
   12659             :  */
   12660             : static void
   12661         162 : AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
   12662             :                                 bool deferrable, bool initdeferred,
   12663             :                                 List **otherrelids)
   12664             : {
   12665             :     HeapTuple   tgtuple;
   12666             :     ScanKeyData tgkey;
   12667             :     SysScanDesc tgscan;
   12668             : 
   12669         162 :     ScanKeyInit(&tgkey,
   12670             :                 Anum_pg_trigger_tgconstraint,
   12671             :                 BTEqualStrategyNumber, F_OIDEQ,
   12672             :                 ObjectIdGetDatum(conoid));
   12673         162 :     tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
   12674             :                                 NULL, 1, &tgkey);
   12675         630 :     while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
   12676             :     {
   12677         468 :         Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
   12678             :         Form_pg_trigger copy_tg;
   12679             :         HeapTuple   tgCopyTuple;
   12680             : 
   12681             :         /*
   12682             :          * Remember OIDs of other relation(s) involved in FK constraint.
   12683             :          * (Note: it's likely that we could skip forcing a relcache inval for
   12684             :          * other rels that don't have a trigger whose properties change, but
   12685             :          * let's be conservative.)
   12686             :          */
   12687         468 :         if (tgform->tgrelid != RelationGetRelid(rel))
   12688         228 :             *otherrelids = list_append_unique_oid(*otherrelids,
   12689             :                                                   tgform->tgrelid);
   12690             : 
   12691             :         /*
   12692             :          * Update enable status and deferrability of RI_FKey_noaction_del,
   12693             :          * RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
   12694             :          * triggers, but not others; see createForeignKeyActionTriggers and
   12695             :          * CreateFKCheckTrigger.
   12696             :          */
   12697         468 :         if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
   12698         372 :             tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
   12699         258 :             tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
   12700         138 :             tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
   12701          18 :             continue;
   12702             : 
   12703         450 :         tgCopyTuple = heap_copytuple(tgtuple);
   12704         450 :         copy_tg = (Form_pg_trigger) GETSTRUCT(tgCopyTuple);
   12705             : 
   12706         450 :         copy_tg->tgdeferrable = deferrable;
   12707         450 :         copy_tg->tginitdeferred = initdeferred;
   12708         450 :         CatalogTupleUpdate(tgrel, &tgCopyTuple->t_self, tgCopyTuple);
   12709             : 
   12710         450 :         InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
   12711             : 
   12712         450 :         heap_freetuple(tgCopyTuple);
   12713             :     }
   12714             : 
   12715         162 :     systable_endscan(tgscan);
   12716         162 : }
   12717             : 
   12718             : /*
   12719             :  * Invokes ATExecAlterConstrEnforceability for each constraint that is a child of
   12720             :  * the specified constraint.
   12721             :  *
   12722             :  * Note that this doesn't handle recursion the normal way, viz. by scanning the
   12723             :  * list of child relations and recursing; instead it uses the conparentid
   12724             :  * relationships.  This may need to be reconsidered.
   12725             :  *
   12726             :  * The arguments to this function have the same meaning as the arguments to
   12727             :  * ATExecAlterConstrEnforceability.
   12728             :  */
   12729             : static void
   12730          42 : AlterConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
   12731             :                                  Relation conrel, Relation tgrel,
   12732             :                                  Oid fkrelid, Oid pkrelid,
   12733             :                                  HeapTuple contuple, LOCKMODE lockmode,
   12734             :                                  Oid ReferencedParentDelTrigger,
   12735             :                                  Oid ReferencedParentUpdTrigger,
   12736             :                                  Oid ReferencingParentInsTrigger,
   12737             :                                  Oid ReferencingParentUpdTrigger)
   12738             : {
   12739             :     Form_pg_constraint currcon;
   12740             :     Oid         conoid;
   12741             :     ScanKeyData pkey;
   12742             :     SysScanDesc pscan;
   12743             :     HeapTuple   childtup;
   12744             : 
   12745          42 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12746          42 :     conoid = currcon->oid;
   12747             : 
   12748          42 :     ScanKeyInit(&pkey,
   12749             :                 Anum_pg_constraint_conparentid,
   12750             :                 BTEqualStrategyNumber, F_OIDEQ,
   12751             :                 ObjectIdGetDatum(conoid));
   12752             : 
   12753          42 :     pscan = systable_beginscan(conrel, ConstraintParentIndexId,
   12754             :                                true, NULL, 1, &pkey);
   12755             : 
   12756         138 :     while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
   12757          96 :         ATExecAlterConstrEnforceability(wqueue, cmdcon, conrel, tgrel, fkrelid,
   12758             :                                         pkrelid, childtup, lockmode,
   12759             :                                         ReferencedParentDelTrigger,
   12760             :                                         ReferencedParentUpdTrigger,
   12761             :                                         ReferencingParentInsTrigger,
   12762             :                                         ReferencingParentUpdTrigger);
   12763             : 
   12764          42 :     systable_endscan(pscan);
   12765          42 : }
   12766             : 
   12767             : /*
   12768             :  * Invokes ATExecAlterConstrDeferrability for each constraint that is a child of
   12769             :  * the specified constraint.
   12770             :  *
   12771             :  * Note that this doesn't handle recursion the normal way, viz. by scanning the
   12772             :  * list of child relations and recursing; instead it uses the conparentid
   12773             :  * relationships.  This may need to be reconsidered.
   12774             :  *
   12775             :  * The arguments to this function have the same meaning as the arguments to
   12776             :  * ATExecAlterConstrDeferrability.
   12777             :  */
   12778             : static void
   12779          42 : AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
   12780             :                                 Relation conrel, Relation tgrel, Relation rel,
   12781             :                                 HeapTuple contuple, bool recurse,
   12782             :                                 List **otherrelids, LOCKMODE lockmode)
   12783             : {
   12784             :     Form_pg_constraint currcon;
   12785             :     Oid         conoid;
   12786             :     ScanKeyData pkey;
   12787             :     SysScanDesc pscan;
   12788             :     HeapTuple   childtup;
   12789             : 
   12790          42 :     currcon = (Form_pg_constraint) GETSTRUCT(contuple);
   12791          42 :     conoid = currcon->oid;
   12792             : 
   12793          42 :     ScanKeyInit(&pkey,
   12794             :                 Anum_pg_constraint_conparentid,
   12795             :                 BTEqualStrategyNumber, F_OIDEQ,
   12796             :                 ObjectIdGetDatum(conoid));
   12797             : 
   12798          42 :     pscan = systable_beginscan(conrel, ConstraintParentIndexId,
   12799             :                                true, NULL, 1, &pkey);
   12800             : 
   12801         108 :     while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
   12802             :     {
   12803          66 :         Form_pg_constraint childcon = (Form_pg_constraint) GETSTRUCT(childtup);
   12804             :         Relation    childrel;
   12805             : 
   12806          66 :         childrel = table_open(childcon->conrelid, lockmode);
   12807             : 
   12808          66 :         ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, childrel,
   12809             :                                        childtup, recurse, otherrelids, lockmode);
   12810          66 :         table_close(childrel, NoLock);
   12811             :     }
   12812             : 
   12813          42 :     systable_endscan(pscan);
   12814          42 : }
   12815             : 
   12816             : /*
   12817             :  * Update the constraint entry for the given ATAlterConstraint command, and
   12818             :  * invoke the appropriate hooks.
   12819             :  */
   12820             : static void
   12821         384 : AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
   12822             :                                  HeapTuple contuple)
   12823             : {
   12824             :     HeapTuple   copyTuple;
   12825             :     Form_pg_constraint copy_con;
   12826             : 
   12827             :     Assert(cmdcon->alterEnforceability || cmdcon->alterDeferrability ||
   12828             :            cmdcon->alterInheritability);
   12829             : 
   12830         384 :     copyTuple = heap_copytuple(contuple);
   12831         384 :     copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   12832             : 
   12833         384 :     if (cmdcon->alterEnforceability)
   12834             :     {
   12835         162 :         copy_con->conenforced = cmdcon->is_enforced;
   12836             : 
   12837             :         /*
   12838             :          * NB: The convalidated status is irrelevant when the constraint is
   12839             :          * set to NOT ENFORCED, but for consistency, it should still be set
   12840             :          * appropriately. Similarly, if the constraint is later changed to
   12841             :          * ENFORCED, validation will be performed during phase 3, so it makes
   12842             :          * sense to mark it as valid in that case.
   12843             :          */
   12844         162 :         copy_con->convalidated = cmdcon->is_enforced;
   12845             :     }
   12846         384 :     if (cmdcon->alterDeferrability)
   12847             :     {
   12848         168 :         copy_con->condeferrable = cmdcon->deferrable;
   12849         168 :         copy_con->condeferred = cmdcon->initdeferred;
   12850             :     }
   12851         384 :     if (cmdcon->alterInheritability)
   12852          60 :         copy_con->connoinherit = cmdcon->noinherit;
   12853             : 
   12854         384 :     CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
   12855         384 :     InvokeObjectPostAlterHook(ConstraintRelationId, copy_con->oid, 0);
   12856             : 
   12857             :     /* Make new constraint flags visible to others */
   12858         384 :     CacheInvalidateRelcacheByRelid(copy_con->conrelid);
   12859             : 
   12860         384 :     heap_freetuple(copyTuple);
   12861         384 : }
   12862             : 
   12863             : /*
   12864             :  * ALTER TABLE VALIDATE CONSTRAINT
   12865             :  *
   12866             :  * XXX The reason we handle recursion here rather than at Phase 1 is because
   12867             :  * there's no good way to skip recursing when handling foreign keys: there is
   12868             :  * no need to lock children in that case, yet we wouldn't be able to avoid
   12869             :  * doing so at that level.
   12870             :  *
   12871             :  * Return value is the address of the validated constraint.  If the constraint
   12872             :  * was already validated, InvalidObjectAddress is returned.
   12873             :  */
   12874             : static ObjectAddress
   12875         584 : ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName,
   12876             :                          bool recurse, bool recursing, LOCKMODE lockmode)
   12877             : {
   12878             :     Relation    conrel;
   12879             :     SysScanDesc scan;
   12880             :     ScanKeyData skey[3];
   12881             :     HeapTuple   tuple;
   12882             :     Form_pg_constraint con;
   12883             :     ObjectAddress address;
   12884             : 
   12885         584 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   12886             : 
   12887             :     /*
   12888             :      * Find and check the target constraint
   12889             :      */
   12890         584 :     ScanKeyInit(&skey[0],
   12891             :                 Anum_pg_constraint_conrelid,
   12892             :                 BTEqualStrategyNumber, F_OIDEQ,
   12893             :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   12894         584 :     ScanKeyInit(&skey[1],
   12895             :                 Anum_pg_constraint_contypid,
   12896             :                 BTEqualStrategyNumber, F_OIDEQ,
   12897             :                 ObjectIdGetDatum(InvalidOid));
   12898         584 :     ScanKeyInit(&skey[2],
   12899             :                 Anum_pg_constraint_conname,
   12900             :                 BTEqualStrategyNumber, F_NAMEEQ,
   12901             :                 CStringGetDatum(constrName));
   12902         584 :     scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
   12903             :                               true, NULL, 3, skey);
   12904             : 
   12905             :     /* There can be at most one matching row */
   12906         584 :     if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
   12907           0 :         ereport(ERROR,
   12908             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   12909             :                  errmsg("constraint \"%s\" of relation \"%s\" does not exist",
   12910             :                         constrName, RelationGetRelationName(rel))));
   12911             : 
   12912         584 :     con = (Form_pg_constraint) GETSTRUCT(tuple);
   12913         584 :     if (con->contype != CONSTRAINT_FOREIGN &&
   12914         256 :         con->contype != CONSTRAINT_CHECK &&
   12915         112 :         con->contype != CONSTRAINT_NOTNULL)
   12916           0 :         ereport(ERROR,
   12917             :                 errcode(ERRCODE_WRONG_OBJECT_TYPE),
   12918             :                 errmsg("cannot validate constraint \"%s\" of relation \"%s\"",
   12919             :                        constrName, RelationGetRelationName(rel)),
   12920             :                 errdetail("This operation is not supported for this type of constraint."));
   12921             : 
   12922         584 :     if (!con->conenforced)
   12923           6 :         ereport(ERROR,
   12924             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   12925             :                  errmsg("cannot validate NOT ENFORCED constraint")));
   12926             : 
   12927         578 :     if (!con->convalidated)
   12928             :     {
   12929         560 :         if (con->contype == CONSTRAINT_FOREIGN)
   12930             :         {
   12931         322 :             QueueFKConstraintValidation(wqueue, conrel, rel, con->confrelid,
   12932             :                                         tuple, lockmode);
   12933             :         }
   12934         238 :         else if (con->contype == CONSTRAINT_CHECK)
   12935             :         {
   12936         126 :             QueueCheckConstraintValidation(wqueue, conrel, rel, constrName,
   12937             :                                            tuple, recurse, recursing, lockmode);
   12938             :         }
   12939         112 :         else if (con->contype == CONSTRAINT_NOTNULL)
   12940             :         {
   12941         112 :             QueueNNConstraintValidation(wqueue, conrel, rel,
   12942             :                                         tuple, recurse, recursing, lockmode);
   12943             :         }
   12944             : 
   12945         560 :         ObjectAddressSet(address, ConstraintRelationId, con->oid);
   12946             :     }
   12947             :     else
   12948          18 :         address = InvalidObjectAddress; /* already validated */
   12949             : 
   12950         578 :     systable_endscan(scan);
   12951             : 
   12952         578 :     table_close(conrel, RowExclusiveLock);
   12953             : 
   12954         578 :     return address;
   12955             : }
   12956             : 
   12957             : /*
   12958             :  * QueueFKConstraintValidation
   12959             :  *
   12960             :  * Add an entry to the wqueue to validate the given foreign key constraint in
   12961             :  * Phase 3 and update the convalidated field in the pg_constraint catalog
   12962             :  * for the specified relation and all its children.
   12963             :  */
   12964             : static void
   12965         394 : QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
   12966             :                             Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode)
   12967             : {
   12968             :     Form_pg_constraint con;
   12969             :     AlteredTableInfo *tab;
   12970             :     HeapTuple   copyTuple;
   12971             :     Form_pg_constraint copy_con;
   12972             : 
   12973         394 :     con = (Form_pg_constraint) GETSTRUCT(contuple);
   12974             :     Assert(con->contype == CONSTRAINT_FOREIGN);
   12975             :     Assert(!con->convalidated);
   12976             : 
   12977             :     /*
   12978             :      * Add the validation to phase 3's queue; not needed for partitioned
   12979             :      * tables themselves, only for their partitions.
   12980             :      *
   12981             :      * When the referenced table (pkrelid) is partitioned, the referencing
   12982             :      * table (fkrel) has one pg_constraint row pointing to each partition
   12983             :      * thereof.  These rows are there only to support action triggers and no
   12984             :      * table scan is needed, therefore skip this for them as well.
   12985             :      */
   12986         394 :     if (fkrel->rd_rel->relkind == RELKIND_RELATION &&
   12987         346 :         con->confrelid == pkrelid)
   12988             :     {
   12989             :         NewConstraint *newcon;
   12990             :         Constraint *fkconstraint;
   12991             : 
   12992             :         /* Queue validation for phase 3 */
   12993         334 :         fkconstraint = makeNode(Constraint);
   12994             :         /* for now this is all we need */
   12995         334 :         fkconstraint->conname = pstrdup(NameStr(con->conname));
   12996             : 
   12997         334 :         newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
   12998         334 :         newcon->name = fkconstraint->conname;
   12999         334 :         newcon->contype = CONSTR_FOREIGN;
   13000         334 :         newcon->refrelid = con->confrelid;
   13001         334 :         newcon->refindid = con->conindid;
   13002         334 :         newcon->conid = con->oid;
   13003         334 :         newcon->qual = (Node *) fkconstraint;
   13004             : 
   13005             :         /* Find or create work queue entry for this table */
   13006         334 :         tab = ATGetQueueEntry(wqueue, fkrel);
   13007         334 :         tab->constraints = lappend(tab->constraints, newcon);
   13008             :     }
   13009             : 
   13010             :     /*
   13011             :      * If the table at either end of the constraint is partitioned, we need to
   13012             :      * recurse and handle every unvalidate constraint that is a child of this
   13013             :      * constraint.
   13014             :      */
   13015         740 :     if (fkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
   13016         346 :         get_rel_relkind(con->confrelid) == RELKIND_PARTITIONED_TABLE)
   13017             :     {
   13018             :         ScanKeyData pkey;
   13019             :         SysScanDesc pscan;
   13020             :         HeapTuple   childtup;
   13021             : 
   13022          72 :         ScanKeyInit(&pkey,
   13023             :                     Anum_pg_constraint_conparentid,
   13024             :                     BTEqualStrategyNumber, F_OIDEQ,
   13025             :                     ObjectIdGetDatum(con->oid));
   13026             : 
   13027          72 :         pscan = systable_beginscan(conrel, ConstraintParentIndexId,
   13028             :                                    true, NULL, 1, &pkey);
   13029             : 
   13030         144 :         while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
   13031             :         {
   13032             :             Form_pg_constraint childcon;
   13033             :             Relation    childrel;
   13034             : 
   13035          72 :             childcon = (Form_pg_constraint) GETSTRUCT(childtup);
   13036             : 
   13037             :             /*
   13038             :              * If the child constraint has already been validated, no further
   13039             :              * action is required for it or its descendants, as they are all
   13040             :              * valid.
   13041             :              */
   13042          72 :             if (childcon->convalidated)
   13043          18 :                 continue;
   13044             : 
   13045          54 :             childrel = table_open(childcon->conrelid, lockmode);
   13046             : 
   13047             :             /*
   13048             :              * NB: Note that pkrelid should be passed as-is during recursion,
   13049             :              * as it is required to identify the root referenced table.
   13050             :              */
   13051          54 :             QueueFKConstraintValidation(wqueue, conrel, childrel, pkrelid,
   13052             :                                         childtup, lockmode);
   13053          54 :             table_close(childrel, NoLock);
   13054             :         }
   13055             : 
   13056          72 :         systable_endscan(pscan);
   13057             :     }
   13058             : 
   13059             :     /*
   13060             :      * Now mark the pg_constraint row as validated (even if we didn't check,
   13061             :      * notably the ones for partitions on the referenced side).
   13062             :      *
   13063             :      * We rely on transaction abort to roll back this change if phase 3
   13064             :      * ultimately finds violating rows.  This is a bit ugly.
   13065             :      */
   13066         394 :     copyTuple = heap_copytuple(contuple);
   13067         394 :     copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   13068         394 :     copy_con->convalidated = true;
   13069         394 :     CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
   13070             : 
   13071         394 :     InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
   13072             : 
   13073         394 :     heap_freetuple(copyTuple);
   13074         394 : }
   13075             : 
   13076             : /*
   13077             :  * QueueCheckConstraintValidation
   13078             :  *
   13079             :  * Add an entry to the wqueue to validate the given check constraint in Phase 3
   13080             :  * and update the convalidated field in the pg_constraint catalog for the
   13081             :  * specified relation and all its inheriting children.
   13082             :  */
   13083             : static void
   13084         126 : QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
   13085             :                                char *constrName, HeapTuple contuple,
   13086             :                                bool recurse, bool recursing, LOCKMODE lockmode)
   13087             : {
   13088             :     Form_pg_constraint con;
   13089             :     AlteredTableInfo *tab;
   13090             :     HeapTuple   copyTuple;
   13091             :     Form_pg_constraint copy_con;
   13092             : 
   13093         126 :     List       *children = NIL;
   13094             :     ListCell   *child;
   13095             :     NewConstraint *newcon;
   13096             :     Datum       val;
   13097             :     char       *conbin;
   13098             : 
   13099         126 :     con = (Form_pg_constraint) GETSTRUCT(contuple);
   13100             :     Assert(con->contype == CONSTRAINT_CHECK);
   13101             : 
   13102             :     /*
   13103             :      * If we're recursing, the parent has already done this, so skip it. Also,
   13104             :      * if the constraint is a NO INHERIT constraint, we shouldn't try to look
   13105             :      * for it in the children.
   13106             :      */
   13107         126 :     if (!recursing && !con->connoinherit)
   13108          72 :         children = find_all_inheritors(RelationGetRelid(rel),
   13109             :                                        lockmode, NULL);
   13110             : 
   13111             :     /*
   13112             :      * For CHECK constraints, we must ensure that we only mark the constraint
   13113             :      * as validated on the parent if it's already validated on the children.
   13114             :      *
   13115             :      * We recurse before validating on the parent, to reduce risk of
   13116             :      * deadlocks.
   13117             :      */
   13118         246 :     foreach(child, children)
   13119             :     {
   13120         120 :         Oid         childoid = lfirst_oid(child);
   13121             :         Relation    childrel;
   13122             : 
   13123         120 :         if (childoid == RelationGetRelid(rel))
   13124          72 :             continue;
   13125             : 
   13126             :         /*
   13127             :          * If we are told not to recurse, there had better not be any child
   13128             :          * tables, because we can't mark the constraint on the parent valid
   13129             :          * unless it is valid for all child tables.
   13130             :          */
   13131          48 :         if (!recurse)
   13132           0 :             ereport(ERROR,
   13133             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   13134             :                      errmsg("constraint must be validated on child tables too")));
   13135             : 
   13136             :         /* find_all_inheritors already got lock */
   13137          48 :         childrel = table_open(childoid, NoLock);
   13138             : 
   13139          48 :         ATExecValidateConstraint(wqueue, childrel, constrName, false,
   13140             :                                  true, lockmode);
   13141          48 :         table_close(childrel, NoLock);
   13142             :     }
   13143             : 
   13144             :     /* Queue validation for phase 3 */
   13145         126 :     newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
   13146         126 :     newcon->name = constrName;
   13147         126 :     newcon->contype = CONSTR_CHECK;
   13148         126 :     newcon->refrelid = InvalidOid;
   13149         126 :     newcon->refindid = InvalidOid;
   13150         126 :     newcon->conid = con->oid;
   13151             : 
   13152         126 :     val = SysCacheGetAttrNotNull(CONSTROID, contuple,
   13153             :                                  Anum_pg_constraint_conbin);
   13154         126 :     conbin = TextDatumGetCString(val);
   13155         126 :     newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
   13156             : 
   13157             :     /* Find or create work queue entry for this table */
   13158         126 :     tab = ATGetQueueEntry(wqueue, rel);
   13159         126 :     tab->constraints = lappend(tab->constraints, newcon);
   13160             : 
   13161             :     /*
   13162             :      * Invalidate relcache so that others see the new validated constraint.
   13163             :      */
   13164         126 :     CacheInvalidateRelcache(rel);
   13165             : 
   13166             :     /*
   13167             :      * Now update the catalog, while we have the door open.
   13168             :      */
   13169         126 :     copyTuple = heap_copytuple(contuple);
   13170         126 :     copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   13171         126 :     copy_con->convalidated = true;
   13172         126 :     CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
   13173             : 
   13174         126 :     InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
   13175             : 
   13176         126 :     heap_freetuple(copyTuple);
   13177         126 : }
   13178             : 
   13179             : /*
   13180             :  * QueueNNConstraintValidation
   13181             :  *
   13182             :  * Add an entry to the wqueue to validate the given not-null constraint in
   13183             :  * Phase 3 and update the convalidated field in the pg_constraint catalog for
   13184             :  * the specified relation and all its inheriting children.
   13185             :  */
   13186             : static void
   13187         112 : QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
   13188             :                             HeapTuple contuple, bool recurse, bool recursing,
   13189             :                             LOCKMODE lockmode)
   13190             : {
   13191             :     Form_pg_constraint con;
   13192             :     AlteredTableInfo *tab;
   13193             :     HeapTuple   copyTuple;
   13194             :     Form_pg_constraint copy_con;
   13195         112 :     List       *children = NIL;
   13196             :     AttrNumber  attnum;
   13197             :     char       *colname;
   13198             : 
   13199         112 :     con = (Form_pg_constraint) GETSTRUCT(contuple);
   13200             :     Assert(con->contype == CONSTRAINT_NOTNULL);
   13201             : 
   13202         112 :     attnum = extractNotNullColumn(contuple);
   13203             : 
   13204             :     /*
   13205             :      * If we're recursing, we've already done this for parent, so skip it.
   13206             :      * Also, if the constraint is a NO INHERIT constraint, we shouldn't try to
   13207             :      * look for it in the children.
   13208             :      *
   13209             :      * We recurse before validating on the parent, to reduce risk of
   13210             :      * deadlocks.
   13211             :      */
   13212         112 :     if (!recursing && !con->connoinherit)
   13213          76 :         children = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
   13214             : 
   13215         112 :     colname = get_attname(RelationGetRelid(rel), attnum, false);
   13216         378 :     foreach_oid(childoid, children)
   13217             :     {
   13218             :         Relation    childrel;
   13219             :         HeapTuple   contup;
   13220             :         Form_pg_constraint childcon;
   13221             :         char       *conname;
   13222             : 
   13223         154 :         if (childoid == RelationGetRelid(rel))
   13224          76 :             continue;
   13225             : 
   13226             :         /*
   13227             :          * If we are told not to recurse, there had better not be any child
   13228             :          * tables, because we can't mark the constraint on the parent valid
   13229             :          * unless it is valid for all child tables.
   13230             :          */
   13231          78 :         if (!recurse)
   13232           0 :             ereport(ERROR,
   13233             :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   13234             :                     errmsg("constraint must be validated on child tables too"));
   13235             : 
   13236             :         /*
   13237             :          * The column on child might have a different attnum, so search by
   13238             :          * column name.
   13239             :          */
   13240          78 :         contup = findNotNullConstraint(childoid, colname);
   13241          78 :         if (!contup)
   13242           0 :             elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
   13243             :                  colname, get_rel_name(childoid));
   13244          78 :         childcon = (Form_pg_constraint) GETSTRUCT(contup);
   13245          78 :         if (childcon->convalidated)
   13246          42 :             continue;
   13247             : 
   13248             :         /* find_all_inheritors already got lock */
   13249          36 :         childrel = table_open(childoid, NoLock);
   13250          36 :         conname = pstrdup(NameStr(childcon->conname));
   13251             : 
   13252             :         /* XXX improve ATExecValidateConstraint API to avoid double search */
   13253          36 :         ATExecValidateConstraint(wqueue, childrel, conname,
   13254             :                                  false, true, lockmode);
   13255          36 :         table_close(childrel, NoLock);
   13256             :     }
   13257             : 
   13258             :     /* Set attnotnull appropriately without queueing another validation */
   13259         112 :     set_attnotnull(NULL, rel, attnum, true, false);
   13260             : 
   13261         112 :     tab = ATGetQueueEntry(wqueue, rel);
   13262         112 :     tab->verify_new_notnull = true;
   13263             : 
   13264             :     /*
   13265             :      * Invalidate relcache so that others see the new validated constraint.
   13266             :      */
   13267         112 :     CacheInvalidateRelcache(rel);
   13268             : 
   13269             :     /*
   13270             :      * Now update the catalogs, while we have the door open.
   13271             :      */
   13272         112 :     copyTuple = heap_copytuple(contuple);
   13273         112 :     copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   13274         112 :     copy_con->convalidated = true;
   13275         112 :     CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
   13276             : 
   13277         112 :     InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
   13278             : 
   13279         112 :     heap_freetuple(copyTuple);
   13280         112 : }
   13281             : 
   13282             : /*
   13283             :  * transformColumnNameList - transform list of column names
   13284             :  *
   13285             :  * Lookup each name and return its attnum and, optionally, type and collation
   13286             :  * OIDs
   13287             :  *
   13288             :  * Note: the name of this function suggests that it's general-purpose,
   13289             :  * but actually it's only used to look up names appearing in foreign-key
   13290             :  * clauses.  The error messages would need work to use it in other cases,
   13291             :  * and perhaps the validity checks as well.
   13292             :  */
   13293             : static int
   13294        6598 : transformColumnNameList(Oid relId, List *colList,
   13295             :                         int16 *attnums, Oid *atttypids, Oid *attcollids)
   13296             : {
   13297             :     ListCell   *l;
   13298             :     int         attnum;
   13299             : 
   13300        6598 :     attnum = 0;
   13301       12046 :     foreach(l, colList)
   13302             :     {
   13303        5514 :         char       *attname = strVal(lfirst(l));
   13304             :         HeapTuple   atttuple;
   13305             :         Form_pg_attribute attform;
   13306             : 
   13307        5514 :         atttuple = SearchSysCacheAttName(relId, attname);
   13308        5514 :         if (!HeapTupleIsValid(atttuple))
   13309          54 :             ereport(ERROR,
   13310             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
   13311             :                      errmsg("column \"%s\" referenced in foreign key constraint does not exist",
   13312             :                             attname)));
   13313        5460 :         attform = (Form_pg_attribute) GETSTRUCT(atttuple);
   13314        5460 :         if (attform->attnum < 0)
   13315          12 :             ereport(ERROR,
   13316             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   13317             :                      errmsg("system columns cannot be used in foreign keys")));
   13318        5448 :         if (attnum >= INDEX_MAX_KEYS)
   13319           0 :             ereport(ERROR,
   13320             :                     (errcode(ERRCODE_TOO_MANY_COLUMNS),
   13321             :                      errmsg("cannot have more than %d keys in a foreign key",
   13322             :                             INDEX_MAX_KEYS)));
   13323        5448 :         attnums[attnum] = attform->attnum;
   13324        5448 :         if (atttypids != NULL)
   13325        5412 :             atttypids[attnum] = attform->atttypid;
   13326        5448 :         if (attcollids != NULL)
   13327        5412 :             attcollids[attnum] = attform->attcollation;
   13328        5448 :         ReleaseSysCache(atttuple);
   13329        5448 :         attnum++;
   13330             :     }
   13331             : 
   13332        6532 :     return attnum;
   13333             : }
   13334             : 
   13335             : /*
   13336             :  * transformFkeyGetPrimaryKey -
   13337             :  *
   13338             :  *  Look up the names, attnums, types, and collations of the primary key attributes
   13339             :  *  for the pkrel.  Also return the index OID and index opclasses of the
   13340             :  *  index supporting the primary key.  Also return whether the index has
   13341             :  *  WITHOUT OVERLAPS.
   13342             :  *
   13343             :  *  All parameters except pkrel are output parameters.  Also, the function
   13344             :  *  return value is the number of attributes in the primary key.
   13345             :  *
   13346             :  *  Used when the column list in the REFERENCES specification is omitted.
   13347             :  */
   13348             : static int
   13349        1256 : transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
   13350             :                            List **attnamelist,
   13351             :                            int16 *attnums, Oid *atttypids, Oid *attcollids,
   13352             :                            Oid *opclasses, bool *pk_has_without_overlaps)
   13353             : {
   13354             :     List       *indexoidlist;
   13355             :     ListCell   *indexoidscan;
   13356        1256 :     HeapTuple   indexTuple = NULL;
   13357        1256 :     Form_pg_index indexStruct = NULL;
   13358             :     Datum       indclassDatum;
   13359             :     oidvector  *indclass;
   13360             :     int         i;
   13361             : 
   13362             :     /*
   13363             :      * Get the list of index OIDs for the table from the relcache, and look up
   13364             :      * each one in the pg_index syscache until we find one marked primary key
   13365             :      * (hopefully there isn't more than one such).  Insist it's valid, too.
   13366             :      */
   13367        1256 :     *indexOid = InvalidOid;
   13368             : 
   13369        1256 :     indexoidlist = RelationGetIndexList(pkrel);
   13370             : 
   13371        1262 :     foreach(indexoidscan, indexoidlist)
   13372             :     {
   13373        1262 :         Oid         indexoid = lfirst_oid(indexoidscan);
   13374             : 
   13375        1262 :         indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
   13376        1262 :         if (!HeapTupleIsValid(indexTuple))
   13377           0 :             elog(ERROR, "cache lookup failed for index %u", indexoid);
   13378        1262 :         indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
   13379        1262 :         if (indexStruct->indisprimary && indexStruct->indisvalid)
   13380             :         {
   13381             :             /*
   13382             :              * Refuse to use a deferrable primary key.  This is per SQL spec,
   13383             :              * and there would be a lot of interesting semantic problems if we
   13384             :              * tried to allow it.
   13385             :              */
   13386        1256 :             if (!indexStruct->indimmediate)
   13387           0 :                 ereport(ERROR,
   13388             :                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   13389             :                          errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
   13390             :                                 RelationGetRelationName(pkrel))));
   13391             : 
   13392        1256 :             *indexOid = indexoid;
   13393        1256 :             break;
   13394             :         }
   13395           6 :         ReleaseSysCache(indexTuple);
   13396             :     }
   13397             : 
   13398        1256 :     list_free(indexoidlist);
   13399             : 
   13400             :     /*
   13401             :      * Check that we found it
   13402             :      */
   13403        1256 :     if (!OidIsValid(*indexOid))
   13404           0 :         ereport(ERROR,
   13405             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   13406             :                  errmsg("there is no primary key for referenced table \"%s\"",
   13407             :                         RelationGetRelationName(pkrel))));
   13408             : 
   13409             :     /* Must get indclass the hard way */
   13410        1256 :     indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
   13411             :                                            Anum_pg_index_indclass);
   13412        1256 :     indclass = (oidvector *) DatumGetPointer(indclassDatum);
   13413             : 
   13414             :     /*
   13415             :      * Now build the list of PK attributes from the indkey definition (we
   13416             :      * assume a primary key cannot have expressional elements)
   13417             :      */
   13418        1256 :     *attnamelist = NIL;
   13419        2990 :     for (i = 0; i < indexStruct->indnkeyatts; i++)
   13420             :     {
   13421        1734 :         int         pkattno = indexStruct->indkey.values[i];
   13422             : 
   13423        1734 :         attnums[i] = pkattno;
   13424        1734 :         atttypids[i] = attnumTypeId(pkrel, pkattno);
   13425        1734 :         attcollids[i] = attnumCollationId(pkrel, pkattno);
   13426        1734 :         opclasses[i] = indclass->values[i];
   13427        1734 :         *attnamelist = lappend(*attnamelist,
   13428        1734 :                                makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
   13429             :     }
   13430             : 
   13431        1256 :     *pk_has_without_overlaps = indexStruct->indisexclusion;
   13432             : 
   13433        1256 :     ReleaseSysCache(indexTuple);
   13434             : 
   13435        1256 :     return i;
   13436             : }
   13437             : 
   13438             : /*
   13439             :  * transformFkeyCheckAttrs -
   13440             :  *
   13441             :  *  Validate that the 'attnums' columns in the 'pkrel' relation are valid to
   13442             :  *  reference as part of a foreign key constraint.
   13443             :  *
   13444             :  *  Returns the OID of the unique index supporting the constraint and
   13445             :  *  populates the caller-provided 'opclasses' array with the opclasses
   13446             :  *  associated with the index columns.  Also sets whether the index
   13447             :  *  uses WITHOUT OVERLAPS.
   13448             :  *
   13449             :  *  Raises an ERROR on validation failure.
   13450             :  */
   13451             : static Oid
   13452        1282 : transformFkeyCheckAttrs(Relation pkrel,
   13453             :                         int numattrs, int16 *attnums,
   13454             :                         bool with_period, Oid *opclasses,
   13455             :                         bool *pk_has_without_overlaps)
   13456             : {
   13457        1282 :     Oid         indexoid = InvalidOid;
   13458        1282 :     bool        found = false;
   13459        1282 :     bool        found_deferrable = false;
   13460             :     List       *indexoidlist;
   13461             :     ListCell   *indexoidscan;
   13462             :     int         i,
   13463             :                 j;
   13464             : 
   13465             :     /*
   13466             :      * Reject duplicate appearances of columns in the referenced-columns list.
   13467             :      * Such a case is forbidden by the SQL standard, and even if we thought it
   13468             :      * useful to allow it, there would be ambiguity about how to match the
   13469             :      * list to unique indexes (in particular, it'd be unclear which index
   13470             :      * opclass goes with which FK column).
   13471             :      */
   13472        2992 :     for (i = 0; i < numattrs; i++)
   13473             :     {
   13474        2256 :         for (j = i + 1; j < numattrs; j++)
   13475             :         {
   13476         546 :             if (attnums[i] == attnums[j])
   13477          24 :                 ereport(ERROR,
   13478             :                         (errcode(ERRCODE_INVALID_FOREIGN_KEY),
   13479             :                          errmsg("foreign key referenced-columns list must not contain duplicates")));
   13480             :         }
   13481             :     }
   13482             : 
   13483             :     /*
   13484             :      * Get the list of index OIDs for the table from the relcache, and look up
   13485             :      * each one in the pg_index syscache, and match unique indexes to the list
   13486             :      * of attnums we are given.
   13487             :      */
   13488        1258 :     indexoidlist = RelationGetIndexList(pkrel);
   13489             : 
   13490        1438 :     foreach(indexoidscan, indexoidlist)
   13491             :     {
   13492             :         HeapTuple   indexTuple;
   13493             :         Form_pg_index indexStruct;
   13494             : 
   13495        1426 :         indexoid = lfirst_oid(indexoidscan);
   13496        1426 :         indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
   13497        1426 :         if (!HeapTupleIsValid(indexTuple))
   13498           0 :             elog(ERROR, "cache lookup failed for index %u", indexoid);
   13499        1426 :         indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
   13500             : 
   13501             :         /*
   13502             :          * Must have the right number of columns; must be unique (or if
   13503             :          * temporal then exclusion instead) and not a partial index; forget it
   13504             :          * if there are any expressions, too. Invalid indexes are out as well.
   13505             :          */
   13506        2744 :         if (indexStruct->indnkeyatts == numattrs &&
   13507        1318 :             (with_period ? indexStruct->indisexclusion : indexStruct->indisunique) &&
   13508        2608 :             indexStruct->indisvalid &&
   13509        2608 :             heap_attisnull(indexTuple, Anum_pg_index_indpred, NULL) &&
   13510        1304 :             heap_attisnull(indexTuple, Anum_pg_index_indexprs, NULL))
   13511             :         {
   13512             :             Datum       indclassDatum;
   13513             :             oidvector  *indclass;
   13514             : 
   13515             :             /* Must get indclass the hard way */
   13516        1304 :             indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
   13517             :                                                    Anum_pg_index_indclass);
   13518        1304 :             indclass = (oidvector *) DatumGetPointer(indclassDatum);
   13519             : 
   13520             :             /*
   13521             :              * The given attnum list may match the index columns in any order.
   13522             :              * Check for a match, and extract the appropriate opclasses while
   13523             :              * we're at it.
   13524             :              *
   13525             :              * We know that attnums[] is duplicate-free per the test at the
   13526             :              * start of this function, and we checked above that the number of
   13527             :              * index columns agrees, so if we find a match for each attnums[]
   13528             :              * entry then we must have a one-to-one match in some order.
   13529             :              */
   13530        3002 :             for (i = 0; i < numattrs; i++)
   13531             :             {
   13532        1756 :                 found = false;
   13533        2336 :                 for (j = 0; j < numattrs; j++)
   13534             :                 {
   13535        2278 :                     if (attnums[i] == indexStruct->indkey.values[j])
   13536             :                     {
   13537        1698 :                         opclasses[i] = indclass->values[j];
   13538        1698 :                         found = true;
   13539        1698 :                         break;
   13540             :                     }
   13541             :                 }
   13542        1756 :                 if (!found)
   13543          58 :                     break;
   13544             :             }
   13545             :             /* The last attribute in the index must be the PERIOD FK part */
   13546        1304 :             if (found && with_period)
   13547             :             {
   13548         122 :                 int16       periodattnum = attnums[numattrs - 1];
   13549             : 
   13550         122 :                 found = (periodattnum == indexStruct->indkey.values[numattrs - 1]);
   13551             :             }
   13552             : 
   13553             :             /*
   13554             :              * Refuse to use a deferrable unique/primary key.  This is per SQL
   13555             :              * spec, and there would be a lot of interesting semantic problems
   13556             :              * if we tried to allow it.
   13557             :              */
   13558        1304 :             if (found && !indexStruct->indimmediate)
   13559             :             {
   13560             :                 /*
   13561             :                  * Remember that we found an otherwise matching index, so that
   13562             :                  * we can generate a more appropriate error message.
   13563             :                  */
   13564           0 :                 found_deferrable = true;
   13565           0 :                 found = false;
   13566             :             }
   13567             : 
   13568             :             /* We need to know whether the index has WITHOUT OVERLAPS */
   13569        1304 :             if (found)
   13570        1246 :                 *pk_has_without_overlaps = indexStruct->indisexclusion;
   13571             :         }
   13572        1426 :         ReleaseSysCache(indexTuple);
   13573        1426 :         if (found)
   13574        1246 :             break;
   13575             :     }
   13576             : 
   13577        1258 :     if (!found)
   13578             :     {
   13579          12 :         if (found_deferrable)
   13580           0 :             ereport(ERROR,
   13581             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   13582             :                      errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
   13583             :                             RelationGetRelationName(pkrel))));
   13584             :         else
   13585          12 :             ereport(ERROR,
   13586             :                     (errcode(ERRCODE_INVALID_FOREIGN_KEY),
   13587             :                      errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
   13588             :                             RelationGetRelationName(pkrel))));
   13589             :     }
   13590             : 
   13591        1246 :     list_free(indexoidlist);
   13592             : 
   13593        1246 :     return indexoid;
   13594             : }
   13595             : 
   13596             : /*
   13597             :  * findFkeyCast -
   13598             :  *
   13599             :  *  Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
   13600             :  *  Caller has equal regard for binary coercibility and for an exact match.
   13601             : */
   13602             : static CoercionPathType
   13603          12 : findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
   13604             : {
   13605             :     CoercionPathType ret;
   13606             : 
   13607          12 :     if (targetTypeId == sourceTypeId)
   13608             :     {
   13609          12 :         ret = COERCION_PATH_RELABELTYPE;
   13610          12 :         *funcid = InvalidOid;
   13611             :     }
   13612             :     else
   13613             :     {
   13614           0 :         ret = find_coercion_pathway(targetTypeId, sourceTypeId,
   13615             :                                     COERCION_IMPLICIT, funcid);
   13616           0 :         if (ret == COERCION_PATH_NONE)
   13617             :             /* A previously-relied-upon cast is now gone. */
   13618           0 :             elog(ERROR, "could not find cast from %u to %u",
   13619             :                  sourceTypeId, targetTypeId);
   13620             :     }
   13621             : 
   13622          12 :     return ret;
   13623             : }
   13624             : 
   13625             : /*
   13626             :  * Permissions checks on the referenced table for ADD FOREIGN KEY
   13627             :  *
   13628             :  * Note: we have already checked that the user owns the referencing table,
   13629             :  * else we'd have failed much earlier; no additional checks are needed for it.
   13630             :  */
   13631             : static void
   13632        2466 : checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
   13633             : {
   13634        2466 :     Oid         roleid = GetUserId();
   13635             :     AclResult   aclresult;
   13636             :     int         i;
   13637             : 
   13638             :     /* Okay if we have relation-level REFERENCES permission */
   13639        2466 :     aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
   13640             :                                   ACL_REFERENCES);
   13641        2466 :     if (aclresult == ACLCHECK_OK)
   13642        2466 :         return;
   13643             :     /* Else we must have REFERENCES on each column */
   13644           0 :     for (i = 0; i < natts; i++)
   13645             :     {
   13646           0 :         aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
   13647             :                                           roleid, ACL_REFERENCES);
   13648           0 :         if (aclresult != ACLCHECK_OK)
   13649           0 :             aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
   13650           0 :                            RelationGetRelationName(rel));
   13651             :     }
   13652             : }
   13653             : 
   13654             : /*
   13655             :  * Scan the existing rows in a table to verify they meet a proposed FK
   13656             :  * constraint.
   13657             :  *
   13658             :  * Caller must have opened and locked both relations appropriately.
   13659             :  */
   13660             : static void
   13661        1166 : validateForeignKeyConstraint(char *conname,
   13662             :                              Relation rel,
   13663             :                              Relation pkrel,
   13664             :                              Oid pkindOid,
   13665             :                              Oid constraintOid,
   13666             :                              bool hasperiod)
   13667             : {
   13668             :     TupleTableSlot *slot;
   13669             :     TableScanDesc scan;
   13670        1166 :     Trigger     trig = {0};
   13671             :     Snapshot    snapshot;
   13672             :     MemoryContext oldcxt;
   13673             :     MemoryContext perTupCxt;
   13674             : 
   13675        1166 :     ereport(DEBUG1,
   13676             :             (errmsg_internal("validating foreign key constraint \"%s\"", conname)));
   13677             : 
   13678             :     /*
   13679             :      * Build a trigger call structure; we'll need it either way.
   13680             :      */
   13681        1166 :     trig.tgoid = InvalidOid;
   13682        1166 :     trig.tgname = conname;
   13683        1166 :     trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
   13684        1166 :     trig.tgisinternal = true;
   13685        1166 :     trig.tgconstrrelid = RelationGetRelid(pkrel);
   13686        1166 :     trig.tgconstrindid = pkindOid;
   13687        1166 :     trig.tgconstraint = constraintOid;
   13688        1166 :     trig.tgdeferrable = false;
   13689        1166 :     trig.tginitdeferred = false;
   13690             :     /* we needn't fill in remaining fields */
   13691             : 
   13692             :     /*
   13693             :      * See if we can do it with a single LEFT JOIN query.  A false result
   13694             :      * indicates we must proceed with the fire-the-trigger method. We can't do
   13695             :      * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
   13696             :      * left joins.
   13697             :      */
   13698        1166 :     if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
   13699         984 :         return;
   13700             : 
   13701             :     /*
   13702             :      * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
   13703             :      * if that tuple had just been inserted.  If any of those fail, it should
   13704             :      * ereport(ERROR) and that's that.
   13705             :      */
   13706         108 :     snapshot = RegisterSnapshot(GetLatestSnapshot());
   13707         108 :     slot = table_slot_create(rel, NULL);
   13708         108 :     scan = table_beginscan(rel, snapshot, 0, NULL);
   13709             : 
   13710         108 :     perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
   13711             :                                       "validateForeignKeyConstraint",
   13712             :                                       ALLOCSET_SMALL_SIZES);
   13713         108 :     oldcxt = MemoryContextSwitchTo(perTupCxt);
   13714             : 
   13715         192 :     while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
   13716             :     {
   13717         102 :         LOCAL_FCINFO(fcinfo, 0);
   13718         102 :         TriggerData trigdata = {0};
   13719             : 
   13720         102 :         CHECK_FOR_INTERRUPTS();
   13721             : 
   13722             :         /*
   13723             :          * Make a call to the trigger function
   13724             :          *
   13725             :          * No parameters are passed, but we do set a context
   13726             :          */
   13727         510 :         MemSet(fcinfo, 0, SizeForFunctionCallInfo(0));
   13728             : 
   13729             :         /*
   13730             :          * We assume RI_FKey_check_ins won't look at flinfo...
   13731             :          */
   13732         102 :         trigdata.type = T_TriggerData;
   13733         102 :         trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
   13734         102 :         trigdata.tg_relation = rel;
   13735         102 :         trigdata.tg_trigtuple = ExecFetchSlotHeapTuple(slot, false, NULL);
   13736         102 :         trigdata.tg_trigslot = slot;
   13737         102 :         trigdata.tg_trigger = &trig;
   13738             : 
   13739         102 :         fcinfo->context = (Node *) &trigdata;
   13740             : 
   13741         102 :         RI_FKey_check_ins(fcinfo);
   13742             : 
   13743          84 :         MemoryContextReset(perTupCxt);
   13744             :     }
   13745             : 
   13746          90 :     MemoryContextSwitchTo(oldcxt);
   13747          90 :     MemoryContextDelete(perTupCxt);
   13748          90 :     table_endscan(scan);
   13749          90 :     UnregisterSnapshot(snapshot);
   13750          90 :     ExecDropSingleTupleTableSlot(slot);
   13751             : }
   13752             : 
   13753             : /*
   13754             :  * CreateFKCheckTrigger
   13755             :  *      Creates the insert (on_insert=true) or update "check" trigger that
   13756             :  *      implements a given foreign key
   13757             :  *
   13758             :  * Returns the OID of the so created trigger.
   13759             :  */
   13760             : static Oid
   13761        5944 : CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
   13762             :                      Oid constraintOid, Oid indexOid, Oid parentTrigOid,
   13763             :                      bool on_insert)
   13764             : {
   13765             :     ObjectAddress trigAddress;
   13766             :     CreateTrigStmt *fk_trigger;
   13767             : 
   13768             :     /*
   13769             :      * Note: for a self-referential FK (referencing and referenced tables are
   13770             :      * the same), it is important that the ON UPDATE action fires before the
   13771             :      * CHECK action, since both triggers will fire on the same row during an
   13772             :      * UPDATE event; otherwise the CHECK trigger will be checking a non-final
   13773             :      * state of the row.  Triggers fire in name order, so we ensure this by
   13774             :      * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
   13775             :      * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
   13776             :      */
   13777        5944 :     fk_trigger = makeNode(CreateTrigStmt);
   13778        5944 :     fk_trigger->replace = false;
   13779        5944 :     fk_trigger->isconstraint = true;
   13780        5944 :     fk_trigger->trigname = "RI_ConstraintTrigger_c";
   13781        5944 :     fk_trigger->relation = NULL;
   13782             : 
   13783             :     /* Either ON INSERT or ON UPDATE */
   13784        5944 :     if (on_insert)
   13785             :     {
   13786        2972 :         fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
   13787        2972 :         fk_trigger->events = TRIGGER_TYPE_INSERT;
   13788             :     }
   13789             :     else
   13790             :     {
   13791        2972 :         fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
   13792        2972 :         fk_trigger->events = TRIGGER_TYPE_UPDATE;
   13793             :     }
   13794             : 
   13795        5944 :     fk_trigger->args = NIL;
   13796        5944 :     fk_trigger->row = true;
   13797        5944 :     fk_trigger->timing = TRIGGER_TYPE_AFTER;
   13798        5944 :     fk_trigger->columns = NIL;
   13799        5944 :     fk_trigger->whenClause = NULL;
   13800        5944 :     fk_trigger->transitionRels = NIL;
   13801        5944 :     fk_trigger->deferrable = fkconstraint->deferrable;
   13802        5944 :     fk_trigger->initdeferred = fkconstraint->initdeferred;
   13803        5944 :     fk_trigger->constrrel = NULL;
   13804             : 
   13805        5944 :     trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
   13806             :                                 constraintOid, indexOid, InvalidOid,
   13807             :                                 parentTrigOid, NULL, true, false);
   13808             : 
   13809             :     /* Make changes-so-far visible */
   13810        5944 :     CommandCounterIncrement();
   13811             : 
   13812        5944 :     return trigAddress.objectId;
   13813             : }
   13814             : 
   13815             : /*
   13816             :  * createForeignKeyActionTriggers
   13817             :  *      Create the referenced-side "action" triggers that implement a foreign
   13818             :  *      key.
   13819             :  *
   13820             :  * Returns the OIDs of the so created triggers in *deleteTrigOid and
   13821             :  * *updateTrigOid.
   13822             :  */
   13823             : static void
   13824        3402 : createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
   13825             :                                Oid constraintOid, Oid indexOid,
   13826             :                                Oid parentDelTrigger, Oid parentUpdTrigger,
   13827             :                                Oid *deleteTrigOid, Oid *updateTrigOid)
   13828             : {
   13829             :     CreateTrigStmt *fk_trigger;
   13830             :     ObjectAddress trigAddress;
   13831             : 
   13832             :     /*
   13833             :      * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
   13834             :      * DELETE action on the referenced table.
   13835             :      */
   13836        3402 :     fk_trigger = makeNode(CreateTrigStmt);
   13837        3402 :     fk_trigger->replace = false;
   13838        3402 :     fk_trigger->isconstraint = true;
   13839        3402 :     fk_trigger->trigname = "RI_ConstraintTrigger_a";
   13840        3402 :     fk_trigger->relation = NULL;
   13841        3402 :     fk_trigger->args = NIL;
   13842        3402 :     fk_trigger->row = true;
   13843        3402 :     fk_trigger->timing = TRIGGER_TYPE_AFTER;
   13844        3402 :     fk_trigger->events = TRIGGER_TYPE_DELETE;
   13845        3402 :     fk_trigger->columns = NIL;
   13846        3402 :     fk_trigger->whenClause = NULL;
   13847        3402 :     fk_trigger->transitionRels = NIL;
   13848        3402 :     fk_trigger->constrrel = NULL;
   13849             : 
   13850        3402 :     switch (fkconstraint->fk_del_action)
   13851             :     {
   13852        2750 :         case FKCONSTR_ACTION_NOACTION:
   13853        2750 :             fk_trigger->deferrable = fkconstraint->deferrable;
   13854        2750 :             fk_trigger->initdeferred = fkconstraint->initdeferred;
   13855        2750 :             fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
   13856        2750 :             break;
   13857          30 :         case FKCONSTR_ACTION_RESTRICT:
   13858          30 :             fk_trigger->deferrable = false;
   13859          30 :             fk_trigger->initdeferred = false;
   13860          30 :             fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
   13861          30 :             break;
   13862         464 :         case FKCONSTR_ACTION_CASCADE:
   13863         464 :             fk_trigger->deferrable = false;
   13864         464 :             fk_trigger->initdeferred = false;
   13865         464 :             fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
   13866         464 :             break;
   13867          98 :         case FKCONSTR_ACTION_SETNULL:
   13868          98 :             fk_trigger->deferrable = false;
   13869          98 :             fk_trigger->initdeferred = false;
   13870          98 :             fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
   13871          98 :             break;
   13872          60 :         case FKCONSTR_ACTION_SETDEFAULT:
   13873          60 :             fk_trigger->deferrable = false;
   13874          60 :             fk_trigger->initdeferred = false;
   13875          60 :             fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
   13876          60 :             break;
   13877           0 :         default:
   13878           0 :             elog(ERROR, "unrecognized FK action type: %d",
   13879             :                  (int) fkconstraint->fk_del_action);
   13880             :             break;
   13881             :     }
   13882             : 
   13883        3402 :     trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
   13884             :                                 constraintOid, indexOid, InvalidOid,
   13885             :                                 parentDelTrigger, NULL, true, false);
   13886        3402 :     if (deleteTrigOid)
   13887        3402 :         *deleteTrigOid = trigAddress.objectId;
   13888             : 
   13889             :     /* Make changes-so-far visible */
   13890        3402 :     CommandCounterIncrement();
   13891             : 
   13892             :     /*
   13893             :      * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
   13894             :      * UPDATE action on the referenced table.
   13895             :      */
   13896        3402 :     fk_trigger = makeNode(CreateTrigStmt);
   13897        3402 :     fk_trigger->replace = false;
   13898        3402 :     fk_trigger->isconstraint = true;
   13899        3402 :     fk_trigger->trigname = "RI_ConstraintTrigger_a";
   13900        3402 :     fk_trigger->relation = NULL;
   13901        3402 :     fk_trigger->args = NIL;
   13902        3402 :     fk_trigger->row = true;
   13903        3402 :     fk_trigger->timing = TRIGGER_TYPE_AFTER;
   13904        3402 :     fk_trigger->events = TRIGGER_TYPE_UPDATE;
   13905        3402 :     fk_trigger->columns = NIL;
   13906        3402 :     fk_trigger->whenClause = NULL;
   13907        3402 :     fk_trigger->transitionRels = NIL;
   13908        3402 :     fk_trigger->constrrel = NULL;
   13909             : 
   13910        3402 :     switch (fkconstraint->fk_upd_action)
   13911             :     {
   13912        2944 :         case FKCONSTR_ACTION_NOACTION:
   13913        2944 :             fk_trigger->deferrable = fkconstraint->deferrable;
   13914        2944 :             fk_trigger->initdeferred = fkconstraint->initdeferred;
   13915        2944 :             fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
   13916        2944 :             break;
   13917          36 :         case FKCONSTR_ACTION_RESTRICT:
   13918          36 :             fk_trigger->deferrable = false;
   13919          36 :             fk_trigger->initdeferred = false;
   13920          36 :             fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
   13921          36 :             break;
   13922         318 :         case FKCONSTR_ACTION_CASCADE:
   13923         318 :             fk_trigger->deferrable = false;
   13924         318 :             fk_trigger->initdeferred = false;
   13925         318 :             fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
   13926         318 :             break;
   13927          62 :         case FKCONSTR_ACTION_SETNULL:
   13928          62 :             fk_trigger->deferrable = false;
   13929          62 :             fk_trigger->initdeferred = false;
   13930          62 :             fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
   13931          62 :             break;
   13932          42 :         case FKCONSTR_ACTION_SETDEFAULT:
   13933          42 :             fk_trigger->deferrable = false;
   13934          42 :             fk_trigger->initdeferred = false;
   13935          42 :             fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
   13936          42 :             break;
   13937           0 :         default:
   13938           0 :             elog(ERROR, "unrecognized FK action type: %d",
   13939             :                  (int) fkconstraint->fk_upd_action);
   13940             :             break;
   13941             :     }
   13942             : 
   13943        3402 :     trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
   13944             :                                 constraintOid, indexOid, InvalidOid,
   13945             :                                 parentUpdTrigger, NULL, true, false);
   13946        3402 :     if (updateTrigOid)
   13947        3402 :         *updateTrigOid = trigAddress.objectId;
   13948        3402 : }
   13949             : 
   13950             : /*
   13951             :  * createForeignKeyCheckTriggers
   13952             :  *      Create the referencing-side "check" triggers that implement a foreign
   13953             :  *      key.
   13954             :  *
   13955             :  * Returns the OIDs of the so created triggers in *insertTrigOid and
   13956             :  * *updateTrigOid.
   13957             :  */
   13958             : static void
   13959        2972 : createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
   13960             :                               Constraint *fkconstraint, Oid constraintOid,
   13961             :                               Oid indexOid,
   13962             :                               Oid parentInsTrigger, Oid parentUpdTrigger,
   13963             :                               Oid *insertTrigOid, Oid *updateTrigOid)
   13964             : {
   13965        2972 :     *insertTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
   13966             :                                           constraintOid, indexOid,
   13967             :                                           parentInsTrigger, true);
   13968        2972 :     *updateTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
   13969             :                                           constraintOid, indexOid,
   13970             :                                           parentUpdTrigger, false);
   13971        2972 : }
   13972             : 
   13973             : /*
   13974             :  * ALTER TABLE DROP CONSTRAINT
   13975             :  *
   13976             :  * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
   13977             :  */
   13978             : static void
   13979         812 : ATExecDropConstraint(Relation rel, const char *constrName,
   13980             :                      DropBehavior behavior, bool recurse,
   13981             :                      bool missing_ok, LOCKMODE lockmode)
   13982             : {
   13983             :     Relation    conrel;
   13984             :     SysScanDesc scan;
   13985             :     ScanKeyData skey[3];
   13986             :     HeapTuple   tuple;
   13987         812 :     bool        found = false;
   13988             : 
   13989         812 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   13990             : 
   13991             :     /*
   13992             :      * Find and drop the target constraint
   13993             :      */
   13994         812 :     ScanKeyInit(&skey[0],
   13995             :                 Anum_pg_constraint_conrelid,
   13996             :                 BTEqualStrategyNumber, F_OIDEQ,
   13997             :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   13998         812 :     ScanKeyInit(&skey[1],
   13999             :                 Anum_pg_constraint_contypid,
   14000             :                 BTEqualStrategyNumber, F_OIDEQ,
   14001             :                 ObjectIdGetDatum(InvalidOid));
   14002         812 :     ScanKeyInit(&skey[2],
   14003             :                 Anum_pg_constraint_conname,
   14004             :                 BTEqualStrategyNumber, F_NAMEEQ,
   14005             :                 CStringGetDatum(constrName));
   14006         812 :     scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
   14007             :                               true, NULL, 3, skey);
   14008             : 
   14009             :     /* There can be at most one matching row */
   14010         812 :     if (HeapTupleIsValid(tuple = systable_getnext(scan)))
   14011             :     {
   14012         776 :         dropconstraint_internal(rel, tuple, behavior, recurse, false,
   14013             :                                 missing_ok, lockmode);
   14014         590 :         found = true;
   14015             :     }
   14016             : 
   14017         626 :     systable_endscan(scan);
   14018             : 
   14019         626 :     if (!found)
   14020             :     {
   14021          36 :         if (!missing_ok)
   14022          24 :             ereport(ERROR,
   14023             :                     errcode(ERRCODE_UNDEFINED_OBJECT),
   14024             :                     errmsg("constraint \"%s\" of relation \"%s\" does not exist",
   14025             :                            constrName, RelationGetRelationName(rel)));
   14026             :         else
   14027          12 :             ereport(NOTICE,
   14028             :                     errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
   14029             :                            constrName, RelationGetRelationName(rel)));
   14030             :     }
   14031             : 
   14032         602 :     table_close(conrel, RowExclusiveLock);
   14033         602 : }
   14034             : 
   14035             : /*
   14036             :  * Remove a constraint, using its pg_constraint tuple
   14037             :  *
   14038             :  * Implementation for ALTER TABLE DROP CONSTRAINT and ALTER TABLE ALTER COLUMN
   14039             :  * DROP NOT NULL.
   14040             :  *
   14041             :  * Returns the address of the constraint being removed.
   14042             :  */
   14043             : static ObjectAddress
   14044        1206 : dropconstraint_internal(Relation rel, HeapTuple constraintTup, DropBehavior behavior,
   14045             :                         bool recurse, bool recursing, bool missing_ok,
   14046             :                         LOCKMODE lockmode)
   14047             : {
   14048             :     Relation    conrel;
   14049             :     Form_pg_constraint con;
   14050             :     ObjectAddress conobj;
   14051             :     List       *children;
   14052        1206 :     bool        is_no_inherit_constraint = false;
   14053             :     char       *constrName;
   14054        1206 :     char       *colname = NULL;
   14055             : 
   14056             :     /* Guard against stack overflow due to overly deep inheritance tree. */
   14057        1206 :     check_stack_depth();
   14058             : 
   14059             :     /* At top level, permission check was done in ATPrepCmd, else do it */
   14060        1206 :     if (recursing)
   14061         210 :         ATSimplePermissions(AT_DropConstraint, rel,
   14062             :                             ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
   14063             : 
   14064        1200 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
   14065             : 
   14066        1200 :     con = (Form_pg_constraint) GETSTRUCT(constraintTup);
   14067        1200 :     constrName = NameStr(con->conname);
   14068             : 
   14069             :     /* Don't allow drop of inherited constraints */
   14070        1200 :     if (con->coninhcount > 0 && !recursing)
   14071         156 :         ereport(ERROR,
   14072             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14073             :                  errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
   14074             :                         constrName, RelationGetRelationName(rel))));
   14075             : 
   14076             :     /*
   14077             :      * Reset pg_constraint.attnotnull, if this is a not-null constraint.
   14078             :      *
   14079             :      * While doing that, we're in a good position to disallow dropping a not-
   14080             :      * null constraint underneath a primary key, a replica identity index, or
   14081             :      * a generated identity column.
   14082             :      */
   14083        1044 :     if (con->contype == CONSTRAINT_NOTNULL)
   14084             :     {
   14085         314 :         Relation    attrel = table_open(AttributeRelationId, RowExclusiveLock);
   14086         314 :         AttrNumber  attnum = extractNotNullColumn(constraintTup);
   14087             :         Bitmapset  *pkattrs;
   14088             :         Bitmapset  *irattrs;
   14089             :         HeapTuple   atttup;
   14090             :         Form_pg_attribute attForm;
   14091             : 
   14092             :         /* save column name for recursion step */
   14093         314 :         colname = get_attname(RelationGetRelid(rel), attnum, false);
   14094             : 
   14095             :         /*
   14096             :          * Disallow if it's in the primary key.  For partitioned tables we
   14097             :          * cannot rely solely on RelationGetIndexAttrBitmap, because it'll
   14098             :          * return NULL if the primary key is invalid; but we still need to
   14099             :          * protect not-null constraints under such a constraint, so check the
   14100             :          * slow way.
   14101             :          */
   14102         314 :         pkattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_PRIMARY_KEY);
   14103             : 
   14104         314 :         if (pkattrs == NULL &&
   14105         278 :             rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   14106             :         {
   14107          18 :             Oid         pkindex = RelationGetPrimaryKeyIndex(rel, true);
   14108             : 
   14109          18 :             if (OidIsValid(pkindex))
   14110             :             {
   14111           0 :                 Relation    pk = relation_open(pkindex, AccessShareLock);
   14112             : 
   14113           0 :                 pkattrs = NULL;
   14114           0 :                 for (int i = 0; i < pk->rd_index->indnkeyatts; i++)
   14115           0 :                     pkattrs = bms_add_member(pkattrs, pk->rd_index->indkey.values[i]);
   14116             : 
   14117           0 :                 relation_close(pk, AccessShareLock);
   14118             :             }
   14119             :         }
   14120             : 
   14121         350 :         if (pkattrs &&
   14122          36 :             bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, pkattrs))
   14123          24 :             ereport(ERROR,
   14124             :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14125             :                     errmsg("column \"%s\" is in a primary key",
   14126             :                            get_attname(RelationGetRelid(rel), attnum, false)));
   14127             : 
   14128             :         /* Disallow if it's in the replica identity */
   14129         290 :         irattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_IDENTITY_KEY);
   14130         290 :         if (bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, irattrs))
   14131          12 :             ereport(ERROR,
   14132             :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14133             :                     errmsg("column \"%s\" is in index used as replica identity",
   14134             :                            get_attname(RelationGetRelid(rel), attnum, false)));
   14135             : 
   14136             :         /* Disallow if it's a GENERATED AS IDENTITY column */
   14137         278 :         atttup = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
   14138         278 :         if (!HeapTupleIsValid(atttup))
   14139           0 :             elog(ERROR, "cache lookup failed for attribute %d of relation %u",
   14140             :                  attnum, RelationGetRelid(rel));
   14141         278 :         attForm = (Form_pg_attribute) GETSTRUCT(atttup);
   14142         278 :         if (attForm->attidentity != '\0')
   14143           0 :             ereport(ERROR,
   14144             :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   14145             :                     errmsg("column \"%s\" of relation \"%s\" is an identity column",
   14146             :                            get_attname(RelationGetRelid(rel), attnum,
   14147             :                                        false),
   14148             :                            RelationGetRelationName(rel)));
   14149             : 
   14150             :         /* All good -- reset attnotnull if needed */
   14151         278 :         if (attForm->attnotnull)
   14152             :         {
   14153         278 :             attForm->attnotnull = false;
   14154         278 :             CatalogTupleUpdate(attrel, &atttup->t_self, atttup);
   14155             :         }
   14156             : 
   14157         278 :         table_close(attrel, RowExclusiveLock);
   14158             :     }
   14159             : 
   14160        1008 :     is_no_inherit_constraint = con->connoinherit;
   14161             : 
   14162             :     /*
   14163             :      * If it's a foreign-key constraint, we'd better lock the referenced table
   14164             :      * and check that that's not in use, just as we've already done for the
   14165             :      * constrained table (else we might, eg, be dropping a trigger that has
   14166             :      * unfired events).  But we can/must skip that in the self-referential
   14167             :      * case.
   14168             :      */
   14169        1008 :     if (con->contype == CONSTRAINT_FOREIGN &&
   14170         168 :         con->confrelid != RelationGetRelid(rel))
   14171             :     {
   14172             :         Relation    frel;
   14173             : 
   14174             :         /* Must match lock taken by RemoveTriggerById: */
   14175         168 :         frel = table_open(con->confrelid, AccessExclusiveLock);
   14176         168 :         CheckAlterTableIsSafe(frel);
   14177         162 :         table_close(frel, NoLock);
   14178             :     }
   14179             : 
   14180             :     /*
   14181             :      * Perform the actual constraint deletion
   14182             :      */
   14183        1002 :     ObjectAddressSet(conobj, ConstraintRelationId, con->oid);
   14184        1002 :     performDeletion(&conobj, behavior, 0);
   14185             : 
   14186             :     /*
   14187             :      * For partitioned tables, non-CHECK, non-NOT-NULL inherited constraints
   14188             :      * are dropped via the dependency mechanism, so we're done here.
   14189             :      */
   14190         966 :     if (con->contype != CONSTRAINT_CHECK &&
   14191         630 :         con->contype != CONSTRAINT_NOTNULL &&
   14192         352 :         rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   14193             :     {
   14194          78 :         table_close(conrel, RowExclusiveLock);
   14195          78 :         return conobj;
   14196             :     }
   14197             : 
   14198             :     /*
   14199             :      * Propagate to children as appropriate.  Unlike most other ALTER
   14200             :      * routines, we have to do this one level of recursion at a time; we can't
   14201             :      * use find_all_inheritors to do it in one pass.
   14202             :      */
   14203         888 :     if (!is_no_inherit_constraint)
   14204         602 :         children = find_inheritance_children(RelationGetRelid(rel), lockmode);
   14205             :     else
   14206         286 :         children = NIL;
   14207             : 
   14208        2148 :     foreach_oid(childrelid, children)
   14209             :     {
   14210             :         Relation    childrel;
   14211             :         HeapTuple   tuple;
   14212             :         Form_pg_constraint childcon;
   14213             : 
   14214             :         /* find_inheritance_children already got lock */
   14215         384 :         childrel = table_open(childrelid, NoLock);
   14216         384 :         CheckAlterTableIsSafe(childrel);
   14217             : 
   14218             :         /*
   14219             :          * We search for not-null constraints by column name, and others by
   14220             :          * constraint name.
   14221             :          */
   14222         384 :         if (con->contype == CONSTRAINT_NOTNULL)
   14223             :         {
   14224         148 :             tuple = findNotNullConstraint(childrelid, colname);
   14225         148 :             if (!HeapTupleIsValid(tuple))
   14226           0 :                 elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
   14227             :                      colname, RelationGetRelid(childrel));
   14228             :         }
   14229             :         else
   14230             :         {
   14231             :             SysScanDesc scan;
   14232             :             ScanKeyData skey[3];
   14233             : 
   14234         236 :             ScanKeyInit(&skey[0],
   14235             :                         Anum_pg_constraint_conrelid,
   14236             :                         BTEqualStrategyNumber, F_OIDEQ,
   14237             :                         ObjectIdGetDatum(childrelid));
   14238         236 :             ScanKeyInit(&skey[1],
   14239             :                         Anum_pg_constraint_contypid,
   14240             :                         BTEqualStrategyNumber, F_OIDEQ,
   14241             :                         ObjectIdGetDatum(InvalidOid));
   14242         236 :             ScanKeyInit(&skey[2],
   14243             :                         Anum_pg_constraint_conname,
   14244             :                         BTEqualStrategyNumber, F_NAMEEQ,
   14245             :                         CStringGetDatum(constrName));
   14246         236 :             scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
   14247             :                                       true, NULL, 3, skey);
   14248             :             /* There can only be one, so no need to loop */
   14249         236 :             tuple = systable_getnext(scan);
   14250         236 :             if (!HeapTupleIsValid(tuple))
   14251           0 :                 ereport(ERROR,
   14252             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
   14253             :                          errmsg("constraint \"%s\" of relation \"%s\" does not exist",
   14254             :                                 constrName,
   14255             :                                 RelationGetRelationName(childrel))));
   14256         236 :             tuple = heap_copytuple(tuple);
   14257         236 :             systable_endscan(scan);
   14258             :         }
   14259             : 
   14260         384 :         childcon = (Form_pg_constraint) GETSTRUCT(tuple);
   14261             : 
   14262             :         /* Right now only CHECK and not-null constraints can be inherited */
   14263         384 :         if (childcon->contype != CONSTRAINT_CHECK &&
   14264         148 :             childcon->contype != CONSTRAINT_NOTNULL)
   14265           0 :             elog(ERROR, "inherited constraint is not a CHECK or not-null constraint");
   14266             : 
   14267         384 :         if (childcon->coninhcount <= 0) /* shouldn't happen */
   14268           0 :             elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
   14269             :                  childrelid, NameStr(childcon->conname));
   14270             : 
   14271         384 :         if (recurse)
   14272             :         {
   14273             :             /*
   14274             :              * If the child constraint has other definition sources, just
   14275             :              * decrement its inheritance count; if not, recurse to delete it.
   14276             :              */
   14277         282 :             if (childcon->coninhcount == 1 && !childcon->conislocal)
   14278             :             {
   14279             :                 /* Time to delete this child constraint, too */
   14280         210 :                 dropconstraint_internal(childrel, tuple, behavior,
   14281             :                                         recurse, true, missing_ok,
   14282             :                                         lockmode);
   14283             :             }
   14284             :             else
   14285             :             {
   14286             :                 /* Child constraint must survive my deletion */
   14287          72 :                 childcon->coninhcount--;
   14288          72 :                 CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
   14289             : 
   14290             :                 /* Make update visible */
   14291          72 :                 CommandCounterIncrement();
   14292             :             }
   14293             :         }
   14294             :         else
   14295             :         {
   14296             :             /*
   14297             :              * If we were told to drop ONLY in this table (no recursion) and
   14298             :              * there are no further parents for this constraint, we need to
   14299             :              * mark the inheritors' constraints as locally defined rather than
   14300             :              * inherited.
   14301             :              */
   14302         102 :             childcon->coninhcount--;
   14303         102 :             if (childcon->coninhcount == 0)
   14304         102 :                 childcon->conislocal = true;
   14305             : 
   14306         102 :             CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
   14307             : 
   14308             :             /* Make update visible */
   14309         102 :             CommandCounterIncrement();
   14310             :         }
   14311             : 
   14312         378 :         heap_freetuple(tuple);
   14313             : 
   14314         378 :         table_close(childrel, NoLock);
   14315             :     }
   14316             : 
   14317         882 :     table_close(conrel, RowExclusiveLock);
   14318             : 
   14319         882 :     return conobj;
   14320             : }
   14321             : 
   14322             : /*
   14323             :  * ALTER COLUMN TYPE
   14324             :  *
   14325             :  * Unlike other subcommand types, we do parse transformation for ALTER COLUMN
   14326             :  * TYPE during phase 1 --- the AlterTableCmd passed in here is already
   14327             :  * transformed (and must be, because we rely on some transformed fields).
   14328             :  *
   14329             :  * The point of this is that the execution of all ALTER COLUMN TYPEs for a
   14330             :  * table will be done "in parallel" during phase 3, so all the USING
   14331             :  * expressions should be parsed assuming the original column types.  Also,
   14332             :  * this allows a USING expression to refer to a field that will be dropped.
   14333             :  *
   14334             :  * To make this work safely, AT_PASS_DROP then AT_PASS_ALTER_TYPE must be
   14335             :  * the first two execution steps in phase 2; they must not see the effects
   14336             :  * of any other subcommand types, since the USING expressions are parsed
   14337             :  * against the unmodified table's state.
   14338             :  */
   14339             : static void
   14340        1312 : ATPrepAlterColumnType(List **wqueue,
   14341             :                       AlteredTableInfo *tab, Relation rel,
   14342             :                       bool recurse, bool recursing,
   14343             :                       AlterTableCmd *cmd, LOCKMODE lockmode,
   14344             :                       AlterTableUtilityContext *context)
   14345             : {
   14346        1312 :     char       *colName = cmd->name;
   14347        1312 :     ColumnDef  *def = (ColumnDef *) cmd->def;
   14348        1312 :     TypeName   *typeName = def->typeName;
   14349        1312 :     Node       *transform = def->cooked_default;
   14350             :     HeapTuple   tuple;
   14351             :     Form_pg_attribute attTup;
   14352             :     AttrNumber  attnum;
   14353             :     Oid         targettype;
   14354             :     int32       targettypmod;
   14355             :     Oid         targetcollid;
   14356             :     NewColumnValue *newval;
   14357        1312 :     ParseState *pstate = make_parsestate(NULL);
   14358             :     AclResult   aclresult;
   14359             :     bool        is_expr;
   14360             : 
   14361        1312 :     pstate->p_sourcetext = context->queryString;
   14362             : 
   14363        1312 :     if (rel->rd_rel->reloftype && !recursing)
   14364           6 :         ereport(ERROR,
   14365             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   14366             :                  errmsg("cannot alter column type of typed table"),
   14367             :                  parser_errposition(pstate, def->location)));
   14368             : 
   14369             :     /* lookup the attribute so we can check inheritance status */
   14370        1306 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
   14371        1306 :     if (!HeapTupleIsValid(tuple))
   14372           0 :         ereport(ERROR,
   14373             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
   14374             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
   14375             :                         colName, RelationGetRelationName(rel)),
   14376             :                  parser_errposition(pstate, def->location)));
   14377        1306 :     attTup = (Form_pg_attribute) GETSTRUCT(tuple);
   14378        1306 :     attnum = attTup->attnum;
   14379             : 
   14380             :     /* Can't alter a system attribute */
   14381        1306 :     if (attnum <= 0)
   14382           6 :         ereport(ERROR,
   14383             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   14384             :                  errmsg("cannot alter system column \"%s\"", colName),
   14385             :                  parser_errposition(pstate, def->location)));
   14386             : 
   14387             :     /*
   14388             :      * Cannot specify USING when altering type of a generated column, because
   14389             :      * that would violate the generation expression.
   14390             :      */
   14391        1300 :     if (attTup->attgenerated && def->cooked_default)
   14392          12 :         ereport(ERROR,
   14393             :                 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
   14394             :                  errmsg("cannot specify USING when altering type of generated column"),
   14395             :                  errdetail("Column \"%s\" is a generated column.", colName),
   14396             :                  parser_errposition(pstate, def->location)));
   14397             : 
   14398             :     /*
   14399             :      * Don't alter inherited columns.  At outer level, there had better not be
   14400             :      * any inherited definition; when recursing, we assume this was checked at
   14401             :      * the parent level (see below).
   14402             :      */
   14403        1288 :     if (attTup->attinhcount > 0 && !recursing)
   14404           6 :         ereport(ERROR,
   14405             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14406             :                  errmsg("cannot alter inherited column \"%s\"", colName),
   14407             :                  parser_errposition(pstate, def->location)));
   14408             : 
   14409             :     /* Don't alter columns used in the partition key */
   14410        1282 :     if (has_partition_attrs(rel,
   14411             :                             bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
   14412             :                             &is_expr))
   14413          18 :         ereport(ERROR,
   14414             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14415             :                  errmsg("cannot alter column \"%s\" because it is part of the partition key of relation \"%s\"",
   14416             :                         colName, RelationGetRelationName(rel)),
   14417             :                  parser_errposition(pstate, def->location)));
   14418             : 
   14419             :     /* Look up the target type */
   14420        1264 :     typenameTypeIdAndMod(pstate, typeName, &targettype, &targettypmod);
   14421             : 
   14422        1258 :     aclresult = object_aclcheck(TypeRelationId, targettype, GetUserId(), ACL_USAGE);
   14423        1258 :     if (aclresult != ACLCHECK_OK)
   14424          12 :         aclcheck_error_type(aclresult, targettype);
   14425             : 
   14426             :     /* And the collation */
   14427        1246 :     targetcollid = GetColumnDefCollation(pstate, def, targettype);
   14428             : 
   14429             :     /* make sure datatype is legal for a column */
   14430        2480 :     CheckAttributeType(colName, targettype, targetcollid,
   14431        1240 :                        list_make1_oid(rel->rd_rel->reltype),
   14432        1240 :                        (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
   14433             : 
   14434        1228 :     if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
   14435             :     {
   14436             :         /* do nothing */
   14437             :     }
   14438        1192 :     else if (tab->relkind == RELKIND_RELATION ||
   14439         202 :              tab->relkind == RELKIND_PARTITIONED_TABLE)
   14440             :     {
   14441             :         /*
   14442             :          * Set up an expression to transform the old data value to the new
   14443             :          * type. If a USING option was given, use the expression as
   14444             :          * transformed by transformAlterTableStmt, else just take the old
   14445             :          * value and try to coerce it.  We do this first so that type
   14446             :          * incompatibility can be detected before we waste effort, and because
   14447             :          * we need the expression to be parsed against the original table row
   14448             :          * type.
   14449             :          */
   14450        1056 :         if (!transform)
   14451             :         {
   14452         828 :             transform = (Node *) makeVar(1, attnum,
   14453             :                                          attTup->atttypid, attTup->atttypmod,
   14454             :                                          attTup->attcollation,
   14455             :                                          0);
   14456             :         }
   14457             : 
   14458        1056 :         transform = coerce_to_target_type(pstate,
   14459             :                                           transform, exprType(transform),
   14460             :                                           targettype, targettypmod,
   14461             :                                           COERCION_ASSIGNMENT,
   14462             :                                           COERCE_IMPLICIT_CAST,
   14463             :                                           -1);
   14464        1056 :         if (transform == NULL)
   14465             :         {
   14466             :             /* error text depends on whether USING was specified or not */
   14467          24 :             if (def->cooked_default != NULL)
   14468           6 :                 ereport(ERROR,
   14469             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   14470             :                          errmsg("result of USING clause for column \"%s\""
   14471             :                                 " cannot be cast automatically to type %s",
   14472             :                                 colName, format_type_be(targettype)),
   14473             :                          errhint("You might need to add an explicit cast.")));
   14474             :             else
   14475          18 :                 ereport(ERROR,
   14476             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   14477             :                          errmsg("column \"%s\" cannot be cast automatically to type %s",
   14478             :                                 colName, format_type_be(targettype)),
   14479             :                          !attTup->attgenerated ?
   14480             :                 /* translator: USING is SQL, don't translate it */
   14481             :                          errhint("You might need to specify \"USING %s::%s\".",
   14482             :                                  quote_identifier(colName),
   14483             :                                  format_type_with_typemod(targettype,
   14484             :                                                           targettypmod)) : 0));
   14485             :         }
   14486             : 
   14487             :         /* Fix collations after all else */
   14488        1032 :         assign_expr_collations(pstate, transform);
   14489             : 
   14490             :         /* Expand virtual generated columns in the expr. */
   14491        1032 :         transform = expand_generated_columns_in_expr(transform, rel, 1);
   14492             : 
   14493             :         /* Plan the expr now so we can accurately assess the need to rewrite. */
   14494        1032 :         transform = (Node *) expression_planner((Expr *) transform);
   14495             : 
   14496             :         /*
   14497             :          * Add a work queue item to make ATRewriteTable update the column
   14498             :          * contents.
   14499             :          */
   14500        1032 :         newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
   14501        1032 :         newval->attnum = attnum;
   14502        1032 :         newval->expr = (Expr *) transform;
   14503        1032 :         newval->is_generated = false;
   14504             : 
   14505        1032 :         tab->newvals = lappend(tab->newvals, newval);
   14506        1032 :         if (ATColumnChangeRequiresRewrite(transform, attnum))
   14507         836 :             tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
   14508             :     }
   14509         136 :     else if (transform)
   14510          12 :         ereport(ERROR,
   14511             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   14512             :                  errmsg("\"%s\" is not a table",
   14513             :                         RelationGetRelationName(rel))));
   14514             : 
   14515        1192 :     if (!RELKIND_HAS_STORAGE(tab->relkind) || attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
   14516             :     {
   14517             :         /*
   14518             :          * For relations or columns without storage, do this check now.
   14519             :          * Regular tables will check it later when the table is being
   14520             :          * rewritten.
   14521             :          */
   14522         226 :         find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
   14523             :     }
   14524             : 
   14525        1144 :     ReleaseSysCache(tuple);
   14526             : 
   14527             :     /*
   14528             :      * Recurse manually by queueing a new command for each child, if
   14529             :      * necessary. We cannot apply ATSimpleRecursion here because we need to
   14530             :      * remap attribute numbers in the USING expression, if any.
   14531             :      *
   14532             :      * If we are told not to recurse, there had better not be any child
   14533             :      * tables; else the alter would put them out of step.
   14534             :      */
   14535        1144 :     if (recurse)
   14536             :     {
   14537         886 :         Oid         relid = RelationGetRelid(rel);
   14538             :         List       *child_oids,
   14539             :                    *child_numparents;
   14540             :         ListCell   *lo,
   14541             :                    *li;
   14542             : 
   14543         886 :         child_oids = find_all_inheritors(relid, lockmode,
   14544             :                                          &child_numparents);
   14545             : 
   14546             :         /*
   14547             :          * find_all_inheritors does the recursive search of the inheritance
   14548             :          * hierarchy, so all we have to do is process all of the relids in the
   14549             :          * list that it returns.
   14550             :          */
   14551        1980 :         forboth(lo, child_oids, li, child_numparents)
   14552             :         {
   14553        1118 :             Oid         childrelid = lfirst_oid(lo);
   14554        1118 :             int         numparents = lfirst_int(li);
   14555             :             Relation    childrel;
   14556             :             HeapTuple   childtuple;
   14557             :             Form_pg_attribute childattTup;
   14558             : 
   14559        1118 :             if (childrelid == relid)
   14560         886 :                 continue;
   14561             : 
   14562             :             /* find_all_inheritors already got lock */
   14563         232 :             childrel = relation_open(childrelid, NoLock);
   14564         232 :             CheckAlterTableIsSafe(childrel);
   14565             : 
   14566             :             /*
   14567             :              * Verify that the child doesn't have any inherited definitions of
   14568             :              * this column that came from outside this inheritance hierarchy.
   14569             :              * (renameatt makes a similar test, though in a different way
   14570             :              * because of its different recursion mechanism.)
   14571             :              */
   14572         232 :             childtuple = SearchSysCacheAttName(RelationGetRelid(childrel),
   14573             :                                                colName);
   14574         232 :             if (!HeapTupleIsValid(childtuple))
   14575           0 :                 ereport(ERROR,
   14576             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
   14577             :                          errmsg("column \"%s\" of relation \"%s\" does not exist",
   14578             :                                 colName, RelationGetRelationName(childrel))));
   14579         232 :             childattTup = (Form_pg_attribute) GETSTRUCT(childtuple);
   14580             : 
   14581         232 :             if (childattTup->attinhcount > numparents)
   14582           6 :                 ereport(ERROR,
   14583             :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14584             :                          errmsg("cannot alter inherited column \"%s\" of relation \"%s\"",
   14585             :                                 colName, RelationGetRelationName(childrel))));
   14586             : 
   14587         226 :             ReleaseSysCache(childtuple);
   14588             : 
   14589             :             /*
   14590             :              * Remap the attribute numbers.  If no USING expression was
   14591             :              * specified, there is no need for this step.
   14592             :              */
   14593         226 :             if (def->cooked_default)
   14594             :             {
   14595             :                 AttrMap    *attmap;
   14596             :                 bool        found_whole_row;
   14597             : 
   14598             :                 /* create a copy to scribble on */
   14599          78 :                 cmd = copyObject(cmd);
   14600             : 
   14601          78 :                 attmap = build_attrmap_by_name(RelationGetDescr(childrel),
   14602             :                                                RelationGetDescr(rel),
   14603             :                                                false);
   14604         156 :                 ((ColumnDef *) cmd->def)->cooked_default =
   14605          78 :                     map_variable_attnos(def->cooked_default,
   14606             :                                         1, 0,
   14607             :                                         attmap,
   14608             :                                         InvalidOid, &found_whole_row);
   14609          78 :                 if (found_whole_row)
   14610           6 :                     ereport(ERROR,
   14611             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   14612             :                              errmsg("cannot convert whole-row table reference"),
   14613             :                              errdetail("USING expression contains a whole-row table reference.")));
   14614          72 :                 pfree(attmap);
   14615             :             }
   14616         220 :             ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
   14617         208 :             relation_close(childrel, NoLock);
   14618             :         }
   14619             :     }
   14620         308 :     else if (!recursing &&
   14621          50 :              find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
   14622           0 :         ereport(ERROR,
   14623             :                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   14624             :                  errmsg("type of inherited column \"%s\" must be changed in child tables too",
   14625             :                         colName)));
   14626             : 
   14627        1120 :     if (tab->relkind == RELKIND_COMPOSITE_TYPE)
   14628          50 :         ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
   14629        1114 : }
   14630             : 
   14631             : /*
   14632             :  * When the data type of a column is changed, a rewrite might not be required
   14633             :  * if the new type is sufficiently identical to the old one, and the USING
   14634             :  * clause isn't trying to insert some other value.  It's safe to skip the
   14635             :  * rewrite in these cases:
   14636             :  *
   14637             :  * - the old type is binary coercible to the new type
   14638             :  * - the new type is an unconstrained domain over the old type
   14639             :  * - {NEW,OLD} or {OLD,NEW} is {timestamptz,timestamp} and the timezone is UTC
   14640             :  *
   14641             :  * In the case of a constrained domain, we could get by with scanning the
   14642             :  * table and checking the constraint rather than actually rewriting it, but we
   14643             :  * don't currently try to do that.
   14644             :  */
   14645             : static bool
   14646        1032 : ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
   14647             : {
   14648             :     Assert(expr != NULL);
   14649             : 
   14650             :     for (;;)
   14651             :     {
   14652             :         /* only one varno, so no need to check that */
   14653        1150 :         if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
   14654         196 :             return false;
   14655         954 :         else if (IsA(expr, RelabelType))
   14656         106 :             expr = (Node *) ((RelabelType *) expr)->arg;
   14657         848 :         else if (IsA(expr, CoerceToDomain))
   14658             :         {
   14659           0 :             CoerceToDomain *d = (CoerceToDomain *) expr;
   14660             : 
   14661           0 :             if (DomainHasConstraints(d->resulttype))
   14662           0 :                 return true;
   14663           0 :             expr = (Node *) d->arg;
   14664             :         }
   14665         848 :         else if (IsA(expr, FuncExpr))
   14666             :         {
   14667         642 :             FuncExpr   *f = (FuncExpr *) expr;
   14668             : 
   14669         642 :             switch (f->funcid)
   14670             :             {
   14671          18 :                 case F_TIMESTAMPTZ_TIMESTAMP:
   14672             :                 case F_TIMESTAMP_TIMESTAMPTZ:
   14673          18 :                     if (TimestampTimestampTzRequiresRewrite())
   14674           6 :                         return true;
   14675             :                     else
   14676          12 :                         expr = linitial(f->args);
   14677          12 :                     break;
   14678         624 :                 default:
   14679         624 :                     return true;
   14680             :             }
   14681             :         }
   14682             :         else
   14683         206 :             return true;
   14684             :     }
   14685             : }
   14686             : 
   14687             : /*
   14688             :  * ALTER COLUMN .. SET DATA TYPE
   14689             :  *
   14690             :  * Return the address of the modified column.
   14691             :  */
   14692             : static ObjectAddress
   14693        1078 : ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
   14694             :                       AlterTableCmd *cmd, LOCKMODE lockmode)
   14695             : {
   14696        1078 :     char       *colName = cmd->name;
   14697        1078 :     ColumnDef  *def = (ColumnDef *) cmd->def;
   14698        1078 :     TypeName   *typeName = def->typeName;
   14699             :     HeapTuple   heapTup;
   14700             :     Form_pg_attribute attTup,
   14701             :                 attOldTup;
   14702             :     AttrNumber  attnum;
   14703             :     HeapTuple   typeTuple;
   14704             :     Form_pg_type tform;
   14705             :     Oid         targettype;
   14706             :     int32       targettypmod;
   14707             :     Oid         targetcollid;
   14708             :     Node       *defaultexpr;
   14709             :     Relation    attrelation;
   14710             :     Relation    depRel;
   14711             :     ScanKeyData key[3];
   14712             :     SysScanDesc scan;
   14713             :     HeapTuple   depTup;
   14714             :     ObjectAddress address;
   14715             : 
   14716             :     /*
   14717             :      * Clear all the missing values if we're rewriting the table, since this
   14718             :      * renders them pointless.
   14719             :      */
   14720        1078 :     if (tab->rewrite)
   14721             :     {
   14722             :         Relation    newrel;
   14723             : 
   14724         776 :         newrel = table_open(RelationGetRelid(rel), NoLock);
   14725         776 :         RelationClearMissing(newrel);
   14726         776 :         relation_close(newrel, NoLock);
   14727             :         /* make sure we don't conflict with later attribute modifications */
   14728         776 :         CommandCounterIncrement();
   14729             :     }
   14730             : 
   14731        1078 :     attrelation = table_open(AttributeRelationId, RowExclusiveLock);
   14732             : 
   14733             :     /* Look up the target column */
   14734        1078 :     heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
   14735        1078 :     if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
   14736           0 :         ereport(ERROR,
   14737             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
   14738             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
   14739             :                         colName, RelationGetRelationName(rel))));
   14740        1078 :     attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
   14741        1078 :     attnum = attTup->attnum;
   14742        1078 :     attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
   14743             : 
   14744             :     /* Check for multiple ALTER TYPE on same column --- can't cope */
   14745        1078 :     if (attTup->atttypid != attOldTup->atttypid ||
   14746        1078 :         attTup->atttypmod != attOldTup->atttypmod)
   14747           0 :         ereport(ERROR,
   14748             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   14749             :                  errmsg("cannot alter type of column \"%s\" twice",
   14750             :                         colName)));
   14751             : 
   14752             :     /* Look up the target type (should not fail, since prep found it) */
   14753        1078 :     typeTuple = typenameType(NULL, typeName, &targettypmod);
   14754        1078 :     tform = (Form_pg_type) GETSTRUCT(typeTuple);
   14755        1078 :     targettype = tform->oid;
   14756             :     /* And the collation */
   14757        1078 :     targetcollid = GetColumnDefCollation(NULL, def, targettype);
   14758             : 
   14759             :     /*
   14760             :      * If there is a default expression for the column, get it and ensure we
   14761             :      * can coerce it to the new datatype.  (We must do this before changing
   14762             :      * the column type, because build_column_default itself will try to
   14763             :      * coerce, and will not issue the error message we want if it fails.)
   14764             :      *
   14765             :      * We remove any implicit coercion steps at the top level of the old
   14766             :      * default expression; this has been agreed to satisfy the principle of
   14767             :      * least surprise.  (The conversion to the new column type should act like
   14768             :      * it started from what the user sees as the stored expression, and the
   14769             :      * implicit coercions aren't going to be shown.)
   14770             :      */
   14771        1078 :     if (attTup->atthasdef)
   14772             :     {
   14773          92 :         defaultexpr = build_column_default(rel, attnum);
   14774             :         Assert(defaultexpr);
   14775          92 :         defaultexpr = strip_implicit_coercions(defaultexpr);
   14776          92 :         defaultexpr = coerce_to_target_type(NULL,   /* no UNKNOWN params */
   14777             :                                             defaultexpr, exprType(defaultexpr),
   14778             :                                             targettype, targettypmod,
   14779             :                                             COERCION_ASSIGNMENT,
   14780             :                                             COERCE_IMPLICIT_CAST,
   14781             :                                             -1);
   14782          92 :         if (defaultexpr == NULL)
   14783             :         {
   14784           6 :             if (attTup->attgenerated)
   14785           0 :                 ereport(ERROR,
   14786             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   14787             :                          errmsg("generation expression for column \"%s\" cannot be cast automatically to type %s",
   14788             :                                 colName, format_type_be(targettype))));
   14789             :             else
   14790           6 :                 ereport(ERROR,
   14791             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   14792             :                          errmsg("default for column \"%s\" cannot be cast automatically to type %s",
   14793             :                                 colName, format_type_be(targettype))));
   14794             :         }
   14795             :     }
   14796             :     else
   14797         986 :         defaultexpr = NULL;
   14798             : 
   14799             :     /*
   14800             :      * Find everything that depends on the column (constraints, indexes, etc),
   14801             :      * and record enough information to let us recreate the objects.
   14802             :      *
   14803             :      * The actual recreation does not happen here, but only after we have
   14804             :      * performed all the individual ALTER TYPE operations.  We have to save
   14805             :      * the info before executing ALTER TYPE, though, else the deparser will
   14806             :      * get confused.
   14807             :      */
   14808        1072 :     RememberAllDependentForRebuilding(tab, AT_AlterColumnType, rel, attnum, colName);
   14809             : 
   14810             :     /*
   14811             :      * Now scan for dependencies of this column on other things.  The only
   14812             :      * things we should find are the dependency on the column datatype and
   14813             :      * possibly a collation dependency.  Those can be removed.
   14814             :      */
   14815        1036 :     depRel = table_open(DependRelationId, RowExclusiveLock);
   14816             : 
   14817        1036 :     ScanKeyInit(&key[0],
   14818             :                 Anum_pg_depend_classid,
   14819             :                 BTEqualStrategyNumber, F_OIDEQ,
   14820             :                 ObjectIdGetDatum(RelationRelationId));
   14821        1036 :     ScanKeyInit(&key[1],
   14822             :                 Anum_pg_depend_objid,
   14823             :                 BTEqualStrategyNumber, F_OIDEQ,
   14824             :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   14825        1036 :     ScanKeyInit(&key[2],
   14826             :                 Anum_pg_depend_objsubid,
   14827             :                 BTEqualStrategyNumber, F_INT4EQ,
   14828             :                 Int32GetDatum((int32) attnum));
   14829             : 
   14830        1036 :     scan = systable_beginscan(depRel, DependDependerIndexId, true,
   14831             :                               NULL, 3, key);
   14832             : 
   14833        1040 :     while (HeapTupleIsValid(depTup = systable_getnext(scan)))
   14834             :     {
   14835           4 :         Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
   14836             :         ObjectAddress foundObject;
   14837             : 
   14838           4 :         foundObject.classId = foundDep->refclassid;
   14839           4 :         foundObject.objectId = foundDep->refobjid;
   14840           4 :         foundObject.objectSubId = foundDep->refobjsubid;
   14841             : 
   14842           4 :         if (foundDep->deptype != DEPENDENCY_NORMAL)
   14843           0 :             elog(ERROR, "found unexpected dependency type '%c'",
   14844             :                  foundDep->deptype);
   14845           4 :         if (!(foundDep->refclassid == TypeRelationId &&
   14846           4 :               foundDep->refobjid == attTup->atttypid) &&
   14847           0 :             !(foundDep->refclassid == CollationRelationId &&
   14848           0 :               foundDep->refobjid == attTup->attcollation))
   14849           0 :             elog(ERROR, "found unexpected dependency for column: %s",
   14850             :                  getObjectDescription(&foundObject, false));
   14851             : 
   14852           4 :         CatalogTupleDelete(depRel, &depTup->t_self);
   14853             :     }
   14854             : 
   14855        1036 :     systable_endscan(scan);
   14856             : 
   14857        1036 :     table_close(depRel, RowExclusiveLock);
   14858             : 
   14859             :     /*
   14860             :      * Here we go --- change the recorded column type and collation.  (Note
   14861             :      * heapTup is a copy of the syscache entry, so okay to scribble on.) First
   14862             :      * fix up the missing value if any.
   14863             :      */
   14864        1036 :     if (attTup->atthasmissing)
   14865             :     {
   14866             :         Datum       missingval;
   14867             :         bool        missingNull;
   14868             : 
   14869             :         /* if rewrite is true the missing value should already be cleared */
   14870             :         Assert(tab->rewrite == 0);
   14871             : 
   14872             :         /* Get the missing value datum */
   14873           6 :         missingval = heap_getattr(heapTup,
   14874             :                                   Anum_pg_attribute_attmissingval,
   14875             :                                   attrelation->rd_att,
   14876             :                                   &missingNull);
   14877             : 
   14878             :         /* if it's a null array there is nothing to do */
   14879             : 
   14880           6 :         if (!missingNull)
   14881             :         {
   14882             :             /*
   14883             :              * Get the datum out of the array and repack it in a new array
   14884             :              * built with the new type data. We assume that since the table
   14885             :              * doesn't need rewriting, the actual Datum doesn't need to be
   14886             :              * changed, only the array metadata.
   14887             :              */
   14888             : 
   14889           6 :             int         one = 1;
   14890             :             bool        isNull;
   14891           6 :             Datum       valuesAtt[Natts_pg_attribute] = {0};
   14892           6 :             bool        nullsAtt[Natts_pg_attribute] = {0};
   14893           6 :             bool        replacesAtt[Natts_pg_attribute] = {0};
   14894             :             HeapTuple   newTup;
   14895             : 
   14896          12 :             missingval = array_get_element(missingval,
   14897             :                                            1,
   14898             :                                            &one,
   14899             :                                            0,
   14900           6 :                                            attTup->attlen,
   14901           6 :                                            attTup->attbyval,
   14902           6 :                                            attTup->attalign,
   14903             :                                            &isNull);
   14904           6 :             missingval = PointerGetDatum(construct_array(&missingval,
   14905             :                                                          1,
   14906             :                                                          targettype,
   14907           6 :                                                          tform->typlen,
   14908           6 :                                                          tform->typbyval,
   14909           6 :                                                          tform->typalign));
   14910             : 
   14911           6 :             valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
   14912           6 :             replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
   14913           6 :             nullsAtt[Anum_pg_attribute_attmissingval - 1] = false;
   14914             : 
   14915           6 :             newTup = heap_modify_tuple(heapTup, RelationGetDescr(attrelation),
   14916             :                                        valuesAtt, nullsAtt, replacesAtt);
   14917           6 :             heap_freetuple(heapTup);
   14918           6 :             heapTup = newTup;
   14919           6 :             attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
   14920             :         }
   14921             :     }
   14922             : 
   14923        1036 :     attTup->atttypid = targettype;
   14924        1036 :     attTup->atttypmod = targettypmod;
   14925        1036 :     attTup->attcollation = targetcollid;
   14926        1036 :     if (list_length(typeName->arrayBounds) > PG_INT16_MAX)
   14927           0 :         ereport(ERROR,
   14928             :                 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
   14929             :                 errmsg("too many array dimensions"));
   14930        1036 :     attTup->attndims = list_length(typeName->arrayBounds);
   14931        1036 :     attTup->attlen = tform->typlen;
   14932        1036 :     attTup->attbyval = tform->typbyval;
   14933        1036 :     attTup->attalign = tform->typalign;
   14934        1036 :     attTup->attstorage = tform->typstorage;
   14935        1036 :     attTup->attcompression = InvalidCompressionMethod;
   14936             : 
   14937        1036 :     ReleaseSysCache(typeTuple);
   14938             : 
   14939        1036 :     CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
   14940             : 
   14941        1036 :     table_close(attrelation, RowExclusiveLock);
   14942             : 
   14943             :     /* Install dependencies on new datatype and collation */
   14944        1036 :     add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
   14945        1036 :     add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
   14946             : 
   14947             :     /*
   14948             :      * Drop any pg_statistic entry for the column, since it's now wrong type
   14949             :      */
   14950        1036 :     RemoveStatistics(RelationGetRelid(rel), attnum);
   14951             : 
   14952        1036 :     InvokeObjectPostAlterHook(RelationRelationId,
   14953             :                               RelationGetRelid(rel), attnum);
   14954             : 
   14955             :     /*
   14956             :      * Update the default, if present, by brute force --- remove and re-add
   14957             :      * the default.  Probably unsafe to take shortcuts, since the new version
   14958             :      * may well have additional dependencies.  (It's okay to do this now,
   14959             :      * rather than after other ALTER TYPE commands, since the default won't
   14960             :      * depend on other column types.)
   14961             :      */
   14962        1036 :     if (defaultexpr)
   14963             :     {
   14964             :         /*
   14965             :          * If it's a GENERATED default, drop its dependency records, in
   14966             :          * particular its INTERNAL dependency on the column, which would
   14967             :          * otherwise cause dependency.c to refuse to perform the deletion.
   14968             :          */
   14969          86 :         if (attTup->attgenerated)
   14970             :         {
   14971          36 :             Oid         attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
   14972             : 
   14973          36 :             if (!OidIsValid(attrdefoid))
   14974           0 :                 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
   14975             :                      RelationGetRelid(rel), attnum);
   14976          36 :             (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
   14977             :         }
   14978             : 
   14979             :         /*
   14980             :          * Make updates-so-far visible, particularly the new pg_attribute row
   14981             :          * which will be updated again.
   14982             :          */
   14983          86 :         CommandCounterIncrement();
   14984             : 
   14985             :         /*
   14986             :          * We use RESTRICT here for safety, but at present we do not expect
   14987             :          * anything to depend on the default.
   14988             :          */
   14989          86 :         RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
   14990             :                           true);
   14991             : 
   14992          86 :         (void) StoreAttrDefault(rel, attnum, defaultexpr, true);
   14993             :     }
   14994             : 
   14995        1036 :     ObjectAddressSubSet(address, RelationRelationId,
   14996             :                         RelationGetRelid(rel), attnum);
   14997             : 
   14998             :     /* Cleanup */
   14999        1036 :     heap_freetuple(heapTup);
   15000             : 
   15001        1036 :     return address;
   15002             : }
   15003             : 
   15004             : /*
   15005             :  * Subroutine for ATExecAlterColumnType and ATExecSetExpression: Find everything
   15006             :  * that depends on the column (constraints, indexes, etc), and record enough
   15007             :  * information to let us recreate the objects.
   15008             :  */
   15009             : static void
   15010        1168 : RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
   15011             :                                   Relation rel, AttrNumber attnum, const char *colName)
   15012             : {
   15013             :     Relation    depRel;
   15014             :     ScanKeyData key[3];
   15015             :     SysScanDesc scan;
   15016             :     HeapTuple   depTup;
   15017             : 
   15018             :     Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression);
   15019             : 
   15020        1168 :     depRel = table_open(DependRelationId, RowExclusiveLock);
   15021             : 
   15022        1168 :     ScanKeyInit(&key[0],
   15023             :                 Anum_pg_depend_refclassid,
   15024             :                 BTEqualStrategyNumber, F_OIDEQ,
   15025             :                 ObjectIdGetDatum(RelationRelationId));
   15026        1168 :     ScanKeyInit(&key[1],
   15027             :                 Anum_pg_depend_refobjid,
   15028             :                 BTEqualStrategyNumber, F_OIDEQ,
   15029             :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   15030        1168 :     ScanKeyInit(&key[2],
   15031             :                 Anum_pg_depend_refobjsubid,
   15032             :                 BTEqualStrategyNumber, F_INT4EQ,
   15033             :                 Int32GetDatum((int32) attnum));
   15034             : 
   15035        1168 :     scan = systable_beginscan(depRel, DependReferenceIndexId, true,
   15036             :                               NULL, 3, key);
   15037             : 
   15038        2348 :     while (HeapTupleIsValid(depTup = systable_getnext(scan)))
   15039             :     {
   15040        1216 :         Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
   15041             :         ObjectAddress foundObject;
   15042             : 
   15043        1216 :         foundObject.classId = foundDep->classid;
   15044        1216 :         foundObject.objectId = foundDep->objid;
   15045        1216 :         foundObject.objectSubId = foundDep->objsubid;
   15046             : 
   15047        1216 :         switch (foundObject.classId)
   15048             :         {
   15049         286 :             case RelationRelationId:
   15050             :                 {
   15051         286 :                     char        relKind = get_rel_relkind(foundObject.objectId);
   15052             : 
   15053         286 :                     if (relKind == RELKIND_INDEX ||
   15054             :                         relKind == RELKIND_PARTITIONED_INDEX)
   15055             :                     {
   15056             :                         Assert(foundObject.objectSubId == 0);
   15057         248 :                         RememberIndexForRebuilding(foundObject.objectId, tab);
   15058             :                     }
   15059          38 :                     else if (relKind == RELKIND_SEQUENCE)
   15060             :                     {
   15061             :                         /*
   15062             :                          * This must be a SERIAL column's sequence.  We need
   15063             :                          * not do anything to it.
   15064             :                          */
   15065             :                         Assert(foundObject.objectSubId == 0);
   15066             :                     }
   15067             :                     else
   15068             :                     {
   15069             :                         /* Not expecting any other direct dependencies... */
   15070           0 :                         elog(ERROR, "unexpected object depending on column: %s",
   15071             :                              getObjectDescription(&foundObject, false));
   15072             :                     }
   15073         286 :                     break;
   15074             :                 }
   15075             : 
   15076         686 :             case ConstraintRelationId:
   15077             :                 Assert(foundObject.objectSubId == 0);
   15078         686 :                 RememberConstraintForRebuilding(foundObject.objectId, tab);
   15079         686 :                 break;
   15080             : 
   15081           0 :             case ProcedureRelationId:
   15082             : 
   15083             :                 /*
   15084             :                  * A new-style SQL function can depend on a column, if that
   15085             :                  * column is referenced in the parsed function body.  Ideally
   15086             :                  * we'd automatically update the function by deparsing and
   15087             :                  * reparsing it, but that's risky and might well fail anyhow.
   15088             :                  * FIXME someday.
   15089             :                  *
   15090             :                  * This is only a problem for AT_AlterColumnType, not
   15091             :                  * AT_SetExpression.
   15092             :                  */
   15093           0 :                 if (subtype == AT_AlterColumnType)
   15094           0 :                     ereport(ERROR,
   15095             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15096             :                              errmsg("cannot alter type of a column used by a function or procedure"),
   15097             :                              errdetail("%s depends on column \"%s\"",
   15098             :                                        getObjectDescription(&foundObject, false),
   15099             :                                        colName)));
   15100           0 :                 break;
   15101             : 
   15102          12 :             case RewriteRelationId:
   15103             : 
   15104             :                 /*
   15105             :                  * View/rule bodies have pretty much the same issues as
   15106             :                  * function bodies.  FIXME someday.
   15107             :                  */
   15108          12 :                 if (subtype == AT_AlterColumnType)
   15109          12 :                     ereport(ERROR,
   15110             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15111             :                              errmsg("cannot alter type of a column used by a view or rule"),
   15112             :                              errdetail("%s depends on column \"%s\"",
   15113             :                                        getObjectDescription(&foundObject, false),
   15114             :                                        colName)));
   15115           0 :                 break;
   15116             : 
   15117           0 :             case TriggerRelationId:
   15118             : 
   15119             :                 /*
   15120             :                  * A trigger can depend on a column because the column is
   15121             :                  * specified as an update target, or because the column is
   15122             :                  * used in the trigger's WHEN condition.  The first case would
   15123             :                  * not require any extra work, but the second case would
   15124             :                  * require updating the WHEN expression, which has the same
   15125             :                  * issues as above.  Since we can't easily tell which case
   15126             :                  * applies, we punt for both.  FIXME someday.
   15127             :                  */
   15128           0 :                 if (subtype == AT_AlterColumnType)
   15129           0 :                     ereport(ERROR,
   15130             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15131             :                              errmsg("cannot alter type of a column used in a trigger definition"),
   15132             :                              errdetail("%s depends on column \"%s\"",
   15133             :                                        getObjectDescription(&foundObject, false),
   15134             :                                        colName)));
   15135           0 :                 break;
   15136             : 
   15137           0 :             case PolicyRelationId:
   15138             : 
   15139             :                 /*
   15140             :                  * A policy can depend on a column because the column is
   15141             :                  * specified in the policy's USING or WITH CHECK qual
   15142             :                  * expressions.  It might be possible to rewrite and recheck
   15143             :                  * the policy expression, but punt for now.  It's certainly
   15144             :                  * easy enough to remove and recreate the policy; still, FIXME
   15145             :                  * someday.
   15146             :                  */
   15147           0 :                 if (subtype == AT_AlterColumnType)
   15148           0 :                     ereport(ERROR,
   15149             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15150             :                              errmsg("cannot alter type of a column used in a policy definition"),
   15151             :                              errdetail("%s depends on column \"%s\"",
   15152             :                                        getObjectDescription(&foundObject, false),
   15153             :                                        colName)));
   15154           0 :                 break;
   15155             : 
   15156         206 :             case AttrDefaultRelationId:
   15157             :                 {
   15158         206 :                     ObjectAddress col = GetAttrDefaultColumnAddress(foundObject.objectId);
   15159             : 
   15160         206 :                     if (col.objectId == RelationGetRelid(rel) &&
   15161         206 :                         col.objectSubId == attnum)
   15162             :                     {
   15163             :                         /*
   15164             :                          * Ignore the column's own default expression.  The
   15165             :                          * caller deals with it.
   15166             :                          */
   15167             :                     }
   15168             :                     else
   15169             :                     {
   15170             :                         /*
   15171             :                          * This must be a reference from the expression of a
   15172             :                          * generated column elsewhere in the same table.
   15173             :                          * Changing the type/generated expression of a column
   15174             :                          * that is used by a generated column is not allowed
   15175             :                          * by SQL standard, so just punt for now.  It might be
   15176             :                          * doable with some thinking and effort.
   15177             :                          */
   15178          24 :                         if (subtype == AT_AlterColumnType)
   15179          24 :                             ereport(ERROR,
   15180             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15181             :                                      errmsg("cannot alter type of a column used by a generated column"),
   15182             :                                      errdetail("Column \"%s\" is used by generated column \"%s\".",
   15183             :                                                colName,
   15184             :                                                get_attname(col.objectId,
   15185             :                                                            col.objectSubId,
   15186             :                                                            false))));
   15187             :                     }
   15188         182 :                     break;
   15189             :                 }
   15190             : 
   15191          26 :             case StatisticExtRelationId:
   15192             : 
   15193             :                 /*
   15194             :                  * Give the extended-stats machinery a chance to fix anything
   15195             :                  * that this column type change would break.
   15196             :                  */
   15197          26 :                 RememberStatisticsForRebuilding(foundObject.objectId, tab);
   15198          26 :                 break;
   15199             : 
   15200           0 :             case PublicationRelRelationId:
   15201             : 
   15202             :                 /*
   15203             :                  * Column reference in a PUBLICATION ... FOR TABLE ... WHERE
   15204             :                  * clause.  Same issues as above.  FIXME someday.
   15205             :                  */
   15206           0 :                 if (subtype == AT_AlterColumnType)
   15207           0 :                     ereport(ERROR,
   15208             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15209             :                              errmsg("cannot alter type of a column used by a publication WHERE clause"),
   15210             :                              errdetail("%s depends on column \"%s\"",
   15211             :                                        getObjectDescription(&foundObject, false),
   15212             :                                        colName)));
   15213           0 :                 break;
   15214             : 
   15215           0 :             default:
   15216             : 
   15217             :                 /*
   15218             :                  * We don't expect any other sorts of objects to depend on a
   15219             :                  * column.
   15220             :                  */
   15221           0 :                 elog(ERROR, "unexpected object depending on column: %s",
   15222             :                      getObjectDescription(&foundObject, false));
   15223             :                 break;
   15224             :         }
   15225             :     }
   15226             : 
   15227        1132 :     systable_endscan(scan);
   15228        1132 :     table_close(depRel, NoLock);
   15229        1132 : }
   15230             : 
   15231             : /*
   15232             :  * Subroutine for ATExecAlterColumnType: remember that a replica identity
   15233             :  * needs to be reset.
   15234             :  */
   15235             : static void
   15236         456 : RememberReplicaIdentityForRebuilding(Oid indoid, AlteredTableInfo *tab)
   15237             : {
   15238         456 :     if (!get_index_isreplident(indoid))
   15239         438 :         return;
   15240             : 
   15241          18 :     if (tab->replicaIdentityIndex)
   15242           0 :         elog(ERROR, "relation %u has multiple indexes marked as replica identity", tab->relid);
   15243             : 
   15244          18 :     tab->replicaIdentityIndex = get_rel_name(indoid);
   15245             : }
   15246             : 
   15247             : /*
   15248             :  * Subroutine for ATExecAlterColumnType: remember any clustered index.
   15249             :  */
   15250             : static void
   15251         456 : RememberClusterOnForRebuilding(Oid indoid, AlteredTableInfo *tab)
   15252             : {
   15253         456 :     if (!get_index_isclustered(indoid))
   15254         438 :         return;
   15255             : 
   15256          18 :     if (tab->clusterOnIndex)
   15257           0 :         elog(ERROR, "relation %u has multiple clustered indexes", tab->relid);
   15258             : 
   15259          18 :     tab->clusterOnIndex = get_rel_name(indoid);
   15260             : }
   15261             : 
   15262             : /*
   15263             :  * Subroutine for ATExecAlterColumnType: remember that a constraint needs
   15264             :  * to be rebuilt (which we might already know).
   15265             :  */
   15266             : static void
   15267         698 : RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab)
   15268             : {
   15269             :     /*
   15270             :      * This de-duplication check is critical for two independent reasons: we
   15271             :      * mustn't try to recreate the same constraint twice, and if a constraint
   15272             :      * depends on more than one column whose type is to be altered, we must
   15273             :      * capture its definition string before applying any of the column type
   15274             :      * changes.  ruleutils.c will get confused if we ask again later.
   15275             :      */
   15276         698 :     if (!list_member_oid(tab->changedConstraintOids, conoid))
   15277             :     {
   15278             :         /* OK, capture the constraint's existing definition string */
   15279         608 :         char       *defstring = pg_get_constraintdef_command(conoid);
   15280             :         Oid         indoid;
   15281             : 
   15282             :         /*
   15283             :          * It is critical to create not-null constraints ahead of primary key
   15284             :          * indexes; otherwise, the not-null constraint would be created by the
   15285             :          * primary key, and the constraint name would be wrong.
   15286             :          */
   15287         608 :         if (get_constraint_type(conoid) == CONSTRAINT_NOTNULL)
   15288             :         {
   15289         198 :             tab->changedConstraintOids = lcons_oid(conoid,
   15290             :                                                    tab->changedConstraintOids);
   15291         198 :             tab->changedConstraintDefs = lcons(defstring,
   15292             :                                                tab->changedConstraintDefs);
   15293             :         }
   15294             :         else
   15295             :         {
   15296             : 
   15297         410 :             tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
   15298             :                                                      conoid);
   15299         410 :             tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
   15300             :                                                  defstring);
   15301             :         }
   15302             : 
   15303             :         /*
   15304             :          * For the index of a constraint, if any, remember if it is used for
   15305             :          * the table's replica identity or if it is a clustered index, so that
   15306             :          * ATPostAlterTypeCleanup() can queue up commands necessary to restore
   15307             :          * those properties.
   15308             :          */
   15309         608 :         indoid = get_constraint_index(conoid);
   15310         608 :         if (OidIsValid(indoid))
   15311             :         {
   15312         228 :             RememberReplicaIdentityForRebuilding(indoid, tab);
   15313         228 :             RememberClusterOnForRebuilding(indoid, tab);
   15314             :         }
   15315             :     }
   15316         698 : }
   15317             : 
   15318             : /*
   15319             :  * Subroutine for ATExecAlterColumnType: remember that an index needs
   15320             :  * to be rebuilt (which we might already know).
   15321             :  */
   15322             : static void
   15323         248 : RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab)
   15324             : {
   15325             :     /*
   15326             :      * This de-duplication check is critical for two independent reasons: we
   15327             :      * mustn't try to recreate the same index twice, and if an index depends
   15328             :      * on more than one column whose type is to be altered, we must capture
   15329             :      * its definition string before applying any of the column type changes.
   15330             :      * ruleutils.c will get confused if we ask again later.
   15331             :      */
   15332         248 :     if (!list_member_oid(tab->changedIndexOids, indoid))
   15333             :     {
   15334             :         /*
   15335             :          * Before adding it as an index-to-rebuild, we'd better see if it
   15336             :          * belongs to a constraint, and if so rebuild the constraint instead.
   15337             :          * Typically this check fails, because constraint indexes normally
   15338             :          * have only dependencies on their constraint.  But it's possible for
   15339             :          * such an index to also have direct dependencies on table columns,
   15340             :          * for example with a partial exclusion constraint.
   15341             :          */
   15342         240 :         Oid         conoid = get_index_constraint(indoid);
   15343             : 
   15344         240 :         if (OidIsValid(conoid))
   15345             :         {
   15346          12 :             RememberConstraintForRebuilding(conoid, tab);
   15347             :         }
   15348             :         else
   15349             :         {
   15350             :             /* OK, capture the index's existing definition string */
   15351         228 :             char       *defstring = pg_get_indexdef_string(indoid);
   15352             : 
   15353         228 :             tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
   15354             :                                                 indoid);
   15355         228 :             tab->changedIndexDefs = lappend(tab->changedIndexDefs,
   15356             :                                             defstring);
   15357             : 
   15358             :             /*
   15359             :              * Remember if this index is used for the table's replica identity
   15360             :              * or if it is a clustered index, so that ATPostAlterTypeCleanup()
   15361             :              * can queue up commands necessary to restore those properties.
   15362             :              */
   15363         228 :             RememberReplicaIdentityForRebuilding(indoid, tab);
   15364         228 :             RememberClusterOnForRebuilding(indoid, tab);
   15365             :         }
   15366             :     }
   15367         248 : }
   15368             : 
   15369             : /*
   15370             :  * Subroutine for ATExecAlterColumnType: remember that a statistics object
   15371             :  * needs to be rebuilt (which we might already know).
   15372             :  */
   15373             : static void
   15374          26 : RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
   15375             : {
   15376             :     /*
   15377             :      * This de-duplication check is critical for two independent reasons: we
   15378             :      * mustn't try to recreate the same statistics object twice, and if the
   15379             :      * statistics object depends on more than one column whose type is to be
   15380             :      * altered, we must capture its definition string before applying any of
   15381             :      * the type changes. ruleutils.c will get confused if we ask again later.
   15382             :      */
   15383          26 :     if (!list_member_oid(tab->changedStatisticsOids, stxoid))
   15384             :     {
   15385             :         /* OK, capture the statistics object's existing definition string */
   15386          26 :         char       *defstring = pg_get_statisticsobjdef_string(stxoid);
   15387             : 
   15388          26 :         tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
   15389             :                                                  stxoid);
   15390          26 :         tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
   15391             :                                              defstring);
   15392             :     }
   15393          26 : }
   15394             : 
   15395             : /*
   15396             :  * Cleanup after we've finished all the ALTER TYPE or SET EXPRESSION
   15397             :  * operations for a particular relation.  We have to drop and recreate all the
   15398             :  * indexes and constraints that depend on the altered columns.  We do the
   15399             :  * actual dropping here, but re-creation is managed by adding work queue
   15400             :  * entries to do those steps later.
   15401             :  */
   15402             : static void
   15403        1180 : ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
   15404             : {
   15405             :     ObjectAddress obj;
   15406             :     ObjectAddresses *objects;
   15407             :     ListCell   *def_item;
   15408             :     ListCell   *oid_item;
   15409             : 
   15410             :     /*
   15411             :      * Collect all the constraints and indexes to drop so we can process them
   15412             :      * in a single call.  That way we don't have to worry about dependencies
   15413             :      * among them.
   15414             :      */
   15415        1180 :     objects = new_object_addresses();
   15416             : 
   15417             :     /*
   15418             :      * Re-parse the index and constraint definitions, and attach them to the
   15419             :      * appropriate work queue entries.  We do this before dropping because in
   15420             :      * the case of a constraint on another table, we might not yet have
   15421             :      * exclusive lock on the table the constraint is attached to, and we need
   15422             :      * to get that before reparsing/dropping.  (That's possible at least for
   15423             :      * FOREIGN KEY, CHECK, and EXCLUSION constraints; in non-FK cases it
   15424             :      * requires a dependency on the target table's composite type in the other
   15425             :      * table's constraint expressions.)
   15426             :      *
   15427             :      * We can't rely on the output of deparsing to tell us which relation to
   15428             :      * operate on, because concurrent activity might have made the name
   15429             :      * resolve differently.  Instead, we've got to use the OID of the
   15430             :      * constraint or index we're processing to figure out which relation to
   15431             :      * operate on.
   15432             :      */
   15433        1788 :     forboth(oid_item, tab->changedConstraintOids,
   15434             :             def_item, tab->changedConstraintDefs)
   15435             :     {
   15436         608 :         Oid         oldId = lfirst_oid(oid_item);
   15437             :         HeapTuple   tup;
   15438             :         Form_pg_constraint con;
   15439             :         Oid         relid;
   15440             :         Oid         confrelid;
   15441             :         bool        conislocal;
   15442             : 
   15443         608 :         tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
   15444         608 :         if (!HeapTupleIsValid(tup)) /* should not happen */
   15445           0 :             elog(ERROR, "cache lookup failed for constraint %u", oldId);
   15446         608 :         con = (Form_pg_constraint) GETSTRUCT(tup);
   15447         608 :         if (OidIsValid(con->conrelid))
   15448         594 :             relid = con->conrelid;
   15449             :         else
   15450             :         {
   15451             :             /* must be a domain constraint */
   15452          14 :             relid = get_typ_typrelid(getBaseType(con->contypid));
   15453          14 :             if (!OidIsValid(relid))
   15454           0 :                 elog(ERROR, "could not identify relation associated with constraint %u", oldId);
   15455             :         }
   15456         608 :         confrelid = con->confrelid;
   15457         608 :         conislocal = con->conislocal;
   15458         608 :         ReleaseSysCache(tup);
   15459             : 
   15460         608 :         ObjectAddressSet(obj, ConstraintRelationId, oldId);
   15461         608 :         add_exact_object_address(&obj, objects);
   15462             : 
   15463             :         /*
   15464             :          * If the constraint is inherited (only), we don't want to inject a
   15465             :          * new definition here; it'll get recreated when
   15466             :          * ATAddCheckNNConstraint recurses from adding the parent table's
   15467             :          * constraint.  But we had to carry the info this far so that we can
   15468             :          * drop the constraint below.
   15469             :          */
   15470         608 :         if (!conislocal)
   15471          28 :             continue;
   15472             : 
   15473             :         /*
   15474             :          * When rebuilding another table's constraint that references the
   15475             :          * table we're modifying, we might not yet have any lock on the other
   15476             :          * table, so get one now.  We'll need AccessExclusiveLock for the DROP
   15477             :          * CONSTRAINT step, so there's no value in asking for anything weaker.
   15478             :          */
   15479         580 :         if (relid != tab->relid)
   15480          48 :             LockRelationOid(relid, AccessExclusiveLock);
   15481             : 
   15482         580 :         ATPostAlterTypeParse(oldId, relid, confrelid,
   15483         580 :                              (char *) lfirst(def_item),
   15484         580 :                              wqueue, lockmode, tab->rewrite);
   15485             :     }
   15486        1408 :     forboth(oid_item, tab->changedIndexOids,
   15487             :             def_item, tab->changedIndexDefs)
   15488             :     {
   15489         228 :         Oid         oldId = lfirst_oid(oid_item);
   15490             :         Oid         relid;
   15491             : 
   15492         228 :         relid = IndexGetRelation(oldId, false);
   15493             : 
   15494             :         /*
   15495             :          * As above, make sure we have lock on the index's table if it's not
   15496             :          * the same table.
   15497             :          */
   15498         228 :         if (relid != tab->relid)
   15499          12 :             LockRelationOid(relid, AccessExclusiveLock);
   15500             : 
   15501         228 :         ATPostAlterTypeParse(oldId, relid, InvalidOid,
   15502         228 :                              (char *) lfirst(def_item),
   15503         228 :                              wqueue, lockmode, tab->rewrite);
   15504             : 
   15505         228 :         ObjectAddressSet(obj, RelationRelationId, oldId);
   15506         228 :         add_exact_object_address(&obj, objects);
   15507             :     }
   15508             : 
   15509             :     /* add dependencies for new statistics */
   15510        1206 :     forboth(oid_item, tab->changedStatisticsOids,
   15511             :             def_item, tab->changedStatisticsDefs)
   15512             :     {
   15513          26 :         Oid         oldId = lfirst_oid(oid_item);
   15514             :         Oid         relid;
   15515             : 
   15516          26 :         relid = StatisticsGetRelation(oldId, false);
   15517             : 
   15518             :         /*
   15519             :          * As above, make sure we have lock on the statistics object's table
   15520             :          * if it's not the same table.  However, we take
   15521             :          * ShareUpdateExclusiveLock here, aligning with the lock level used in
   15522             :          * CreateStatistics and RemoveStatisticsById.
   15523             :          *
   15524             :          * CAUTION: this should be done after all cases that grab
   15525             :          * AccessExclusiveLock, else we risk causing deadlock due to needing
   15526             :          * to promote our table lock.
   15527             :          */
   15528          26 :         if (relid != tab->relid)
   15529          12 :             LockRelationOid(relid, ShareUpdateExclusiveLock);
   15530             : 
   15531          26 :         ATPostAlterTypeParse(oldId, relid, InvalidOid,
   15532          26 :                              (char *) lfirst(def_item),
   15533          26 :                              wqueue, lockmode, tab->rewrite);
   15534             : 
   15535          26 :         ObjectAddressSet(obj, StatisticExtRelationId, oldId);
   15536          26 :         add_exact_object_address(&obj, objects);
   15537             :     }
   15538             : 
   15539             :     /*
   15540             :      * Queue up command to restore replica identity index marking
   15541             :      */
   15542        1180 :     if (tab->replicaIdentityIndex)
   15543             :     {
   15544          18 :         AlterTableCmd *cmd = makeNode(AlterTableCmd);
   15545          18 :         ReplicaIdentityStmt *subcmd = makeNode(ReplicaIdentityStmt);
   15546             : 
   15547          18 :         subcmd->identity_type = REPLICA_IDENTITY_INDEX;
   15548          18 :         subcmd->name = tab->replicaIdentityIndex;
   15549          18 :         cmd->subtype = AT_ReplicaIdentity;
   15550          18 :         cmd->def = (Node *) subcmd;
   15551             : 
   15552             :         /* do it after indexes and constraints */
   15553          18 :         tab->subcmds[AT_PASS_OLD_CONSTR] =
   15554          18 :             lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
   15555             :     }
   15556             : 
   15557             :     /*
   15558             :      * Queue up command to restore marking of index used for cluster.
   15559             :      */
   15560        1180 :     if (tab->clusterOnIndex)
   15561             :     {
   15562          18 :         AlterTableCmd *cmd = makeNode(AlterTableCmd);
   15563             : 
   15564          18 :         cmd->subtype = AT_ClusterOn;
   15565          18 :         cmd->name = tab->clusterOnIndex;
   15566             : 
   15567             :         /* do it after indexes and constraints */
   15568          18 :         tab->subcmds[AT_PASS_OLD_CONSTR] =
   15569          18 :             lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
   15570             :     }
   15571             : 
   15572             :     /*
   15573             :      * It should be okay to use DROP_RESTRICT here, since nothing else should
   15574             :      * be depending on these objects.
   15575             :      */
   15576        1180 :     performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
   15577             : 
   15578        1180 :     free_object_addresses(objects);
   15579             : 
   15580             :     /*
   15581             :      * The objects will get recreated during subsequent passes over the work
   15582             :      * queue.
   15583             :      */
   15584        1180 : }
   15585             : 
   15586             : /*
   15587             :  * Parse the previously-saved definition string for a constraint, index or
   15588             :  * statistics object against the newly-established column data type(s), and
   15589             :  * queue up the resulting command parsetrees for execution.
   15590             :  *
   15591             :  * This might fail if, for example, you have a WHERE clause that uses an
   15592             :  * operator that's not available for the new column type.
   15593             :  */
   15594             : static void
   15595         834 : ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
   15596             :                      List **wqueue, LOCKMODE lockmode, bool rewrite)
   15597             : {
   15598             :     List       *raw_parsetree_list;
   15599             :     List       *querytree_list;
   15600             :     ListCell   *list_item;
   15601             :     Relation    rel;
   15602             : 
   15603             :     /*
   15604             :      * We expect that we will get only ALTER TABLE and CREATE INDEX
   15605             :      * statements. Hence, there is no need to pass them through
   15606             :      * parse_analyze_*() or the rewriter, but instead we need to pass them
   15607             :      * through parse_utilcmd.c to make them ready for execution.
   15608             :      */
   15609         834 :     raw_parsetree_list = raw_parser(cmd, RAW_PARSE_DEFAULT);
   15610         834 :     querytree_list = NIL;
   15611        1668 :     foreach(list_item, raw_parsetree_list)
   15612             :     {
   15613         834 :         RawStmt    *rs = lfirst_node(RawStmt, list_item);
   15614         834 :         Node       *stmt = rs->stmt;
   15615             : 
   15616         834 :         if (IsA(stmt, IndexStmt))
   15617         228 :             querytree_list = lappend(querytree_list,
   15618         228 :                                      transformIndexStmt(oldRelId,
   15619             :                                                         (IndexStmt *) stmt,
   15620             :                                                         cmd));
   15621         606 :         else if (IsA(stmt, AlterTableStmt))
   15622             :         {
   15623             :             List       *beforeStmts;
   15624             :             List       *afterStmts;
   15625             : 
   15626         566 :             stmt = (Node *) transformAlterTableStmt(oldRelId,
   15627             :                                                     (AlterTableStmt *) stmt,
   15628             :                                                     cmd,
   15629             :                                                     &beforeStmts,
   15630             :                                                     &afterStmts);
   15631         566 :             querytree_list = list_concat(querytree_list, beforeStmts);
   15632         566 :             querytree_list = lappend(querytree_list, stmt);
   15633         566 :             querytree_list = list_concat(querytree_list, afterStmts);
   15634             :         }
   15635          40 :         else if (IsA(stmt, CreateStatsStmt))
   15636          26 :             querytree_list = lappend(querytree_list,
   15637          26 :                                      transformStatsStmt(oldRelId,
   15638             :                                                         (CreateStatsStmt *) stmt,
   15639             :                                                         cmd));
   15640             :         else
   15641          14 :             querytree_list = lappend(querytree_list, stmt);
   15642             :     }
   15643             : 
   15644             :     /* Caller should already have acquired whatever lock we need. */
   15645         834 :     rel = relation_open(oldRelId, NoLock);
   15646             : 
   15647             :     /*
   15648             :      * Attach each generated command to the proper place in the work queue.
   15649             :      * Note this could result in creation of entirely new work-queue entries.
   15650             :      *
   15651             :      * Also note that we have to tweak the command subtypes, because it turns
   15652             :      * out that re-creation of indexes and constraints has to act a bit
   15653             :      * differently from initial creation.
   15654             :      */
   15655        1668 :     foreach(list_item, querytree_list)
   15656             :     {
   15657         834 :         Node       *stm = (Node *) lfirst(list_item);
   15658             :         AlteredTableInfo *tab;
   15659             : 
   15660         834 :         tab = ATGetQueueEntry(wqueue, rel);
   15661             : 
   15662         834 :         if (IsA(stm, IndexStmt))
   15663             :         {
   15664         228 :             IndexStmt  *stmt = (IndexStmt *) stm;
   15665             :             AlterTableCmd *newcmd;
   15666             : 
   15667         228 :             if (!rewrite)
   15668          56 :                 TryReuseIndex(oldId, stmt);
   15669         228 :             stmt->reset_default_tblspc = true;
   15670             :             /* keep the index's comment */
   15671         228 :             stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
   15672             : 
   15673         228 :             newcmd = makeNode(AlterTableCmd);
   15674         228 :             newcmd->subtype = AT_ReAddIndex;
   15675         228 :             newcmd->def = (Node *) stmt;
   15676         228 :             tab->subcmds[AT_PASS_OLD_INDEX] =
   15677         228 :                 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
   15678             :         }
   15679         606 :         else if (IsA(stm, AlterTableStmt))
   15680             :         {
   15681         566 :             AlterTableStmt *stmt = (AlterTableStmt *) stm;
   15682             :             ListCell   *lcmd;
   15683             : 
   15684        1132 :             foreach(lcmd, stmt->cmds)
   15685             :             {
   15686         566 :                 AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
   15687             : 
   15688         566 :                 if (cmd->subtype == AT_AddIndex)
   15689             :                 {
   15690             :                     IndexStmt  *indstmt;
   15691             :                     Oid         indoid;
   15692             : 
   15693         228 :                     indstmt = castNode(IndexStmt, cmd->def);
   15694         228 :                     indoid = get_constraint_index(oldId);
   15695             : 
   15696         228 :                     if (!rewrite)
   15697          48 :                         TryReuseIndex(indoid, indstmt);
   15698             :                     /* keep any comment on the index */
   15699         228 :                     indstmt->idxcomment = GetComment(indoid,
   15700             :                                                      RelationRelationId, 0);
   15701         228 :                     indstmt->reset_default_tblspc = true;
   15702             : 
   15703         228 :                     cmd->subtype = AT_ReAddIndex;
   15704         228 :                     tab->subcmds[AT_PASS_OLD_INDEX] =
   15705         228 :                         lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
   15706             : 
   15707             :                     /* recreate any comment on the constraint */
   15708         228 :                     RebuildConstraintComment(tab,
   15709             :                                              AT_PASS_OLD_INDEX,
   15710             :                                              oldId,
   15711             :                                              rel,
   15712             :                                              NIL,
   15713         228 :                                              indstmt->idxname);
   15714             :                 }
   15715         338 :                 else if (cmd->subtype == AT_AddConstraint)
   15716             :                 {
   15717         338 :                     Constraint *con = castNode(Constraint, cmd->def);
   15718             : 
   15719         338 :                     con->old_pktable_oid = refRelId;
   15720             :                     /* rewriting neither side of a FK */
   15721         338 :                     if (con->contype == CONSTR_FOREIGN &&
   15722          72 :                         !rewrite && tab->rewrite == 0)
   15723           6 :                         TryReuseForeignKey(oldId, con);
   15724         338 :                     con->reset_default_tblspc = true;
   15725         338 :                     cmd->subtype = AT_ReAddConstraint;
   15726         338 :                     tab->subcmds[AT_PASS_OLD_CONSTR] =
   15727         338 :                         lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
   15728             : 
   15729             :                     /*
   15730             :                      * Recreate any comment on the constraint.  If we have
   15731             :                      * recreated a primary key, then transformTableConstraint
   15732             :                      * has added an unnamed not-null constraint here; skip
   15733             :                      * this in that case.
   15734             :                      */
   15735         338 :                     if (con->conname)
   15736         338 :                         RebuildConstraintComment(tab,
   15737             :                                                  AT_PASS_OLD_CONSTR,
   15738             :                                                  oldId,
   15739             :                                                  rel,
   15740             :                                                  NIL,
   15741         338 :                                                  con->conname);
   15742             :                     else
   15743             :                         Assert(con->contype == CONSTR_NOTNULL);
   15744             :                 }
   15745             :                 else
   15746           0 :                     elog(ERROR, "unexpected statement subtype: %d",
   15747             :                          (int) cmd->subtype);
   15748             :             }
   15749             :         }
   15750          40 :         else if (IsA(stm, AlterDomainStmt))
   15751             :         {
   15752          14 :             AlterDomainStmt *stmt = (AlterDomainStmt *) stm;
   15753             : 
   15754          14 :             if (stmt->subtype == AD_AddConstraint)
   15755             :             {
   15756          14 :                 Constraint *con = castNode(Constraint, stmt->def);
   15757          14 :                 AlterTableCmd *cmd = makeNode(AlterTableCmd);
   15758             : 
   15759          14 :                 cmd->subtype = AT_ReAddDomainConstraint;
   15760          14 :                 cmd->def = (Node *) stmt;
   15761          14 :                 tab->subcmds[AT_PASS_OLD_CONSTR] =
   15762          14 :                     lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
   15763             : 
   15764             :                 /* recreate any comment on the constraint */
   15765          14 :                 RebuildConstraintComment(tab,
   15766             :                                          AT_PASS_OLD_CONSTR,
   15767             :                                          oldId,
   15768             :                                          NULL,
   15769             :                                          stmt->typeName,
   15770          14 :                                          con->conname);
   15771             :             }
   15772             :             else
   15773           0 :                 elog(ERROR, "unexpected statement subtype: %d",
   15774             :                      (int) stmt->subtype);
   15775             :         }
   15776          26 :         else if (IsA(stm, CreateStatsStmt))
   15777             :         {
   15778          26 :             CreateStatsStmt *stmt = (CreateStatsStmt *) stm;
   15779             :             AlterTableCmd *newcmd;
   15780             : 
   15781             :             /* keep the statistics object's comment */
   15782          26 :             stmt->stxcomment = GetComment(oldId, StatisticExtRelationId, 0);
   15783             : 
   15784          26 :             newcmd = makeNode(AlterTableCmd);
   15785          26 :             newcmd->subtype = AT_ReAddStatistics;
   15786          26 :             newcmd->def = (Node *) stmt;
   15787          26 :             tab->subcmds[AT_PASS_MISC] =
   15788          26 :                 lappend(tab->subcmds[AT_PASS_MISC], newcmd);
   15789             :         }
   15790             :         else
   15791           0 :             elog(ERROR, "unexpected statement type: %d",
   15792             :                  (int) nodeTag(stm));
   15793             :     }
   15794             : 
   15795         834 :     relation_close(rel, NoLock);
   15796         834 : }
   15797             : 
   15798             : /*
   15799             :  * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
   15800             :  * for a table or domain constraint that is being rebuilt.
   15801             :  *
   15802             :  * objid is the OID of the constraint.
   15803             :  * Pass "rel" for a table constraint, or "domname" (domain's qualified name
   15804             :  * as a string list) for a domain constraint.
   15805             :  * (We could dig that info, as well as the conname, out of the pg_constraint
   15806             :  * entry; but callers already have them so might as well pass them.)
   15807             :  */
   15808             : static void
   15809         580 : RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
   15810             :                          Relation rel, List *domname,
   15811             :                          const char *conname)
   15812             : {
   15813             :     CommentStmt *cmd;
   15814             :     char       *comment_str;
   15815             :     AlterTableCmd *newcmd;
   15816             : 
   15817             :     /* Look for comment for object wanted, and leave if none */
   15818         580 :     comment_str = GetComment(objid, ConstraintRelationId, 0);
   15819         580 :     if (comment_str == NULL)
   15820         490 :         return;
   15821             : 
   15822             :     /* Build CommentStmt node, copying all input data for safety */
   15823          90 :     cmd = makeNode(CommentStmt);
   15824          90 :     if (rel)
   15825             :     {
   15826          78 :         cmd->objtype = OBJECT_TABCONSTRAINT;
   15827          78 :         cmd->object = (Node *)
   15828          78 :             list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
   15829             :                        makeString(pstrdup(RelationGetRelationName(rel))),
   15830             :                        makeString(pstrdup(conname)));
   15831             :     }
   15832             :     else
   15833             :     {
   15834          12 :         cmd->objtype = OBJECT_DOMCONSTRAINT;
   15835          12 :         cmd->object = (Node *)
   15836          12 :             list_make2(makeTypeNameFromNameList(copyObject(domname)),
   15837             :                        makeString(pstrdup(conname)));
   15838             :     }
   15839          90 :     cmd->comment = comment_str;
   15840             : 
   15841             :     /* Append it to list of commands */
   15842          90 :     newcmd = makeNode(AlterTableCmd);
   15843          90 :     newcmd->subtype = AT_ReAddComment;
   15844          90 :     newcmd->def = (Node *) cmd;
   15845          90 :     tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
   15846             : }
   15847             : 
   15848             : /*
   15849             :  * Subroutine for ATPostAlterTypeParse().  Calls out to CheckIndexCompatible()
   15850             :  * for the real analysis, then mutates the IndexStmt based on that verdict.
   15851             :  */
   15852             : static void
   15853         104 : TryReuseIndex(Oid oldId, IndexStmt *stmt)
   15854             : {
   15855         104 :     if (CheckIndexCompatible(oldId,
   15856         104 :                              stmt->accessMethod,
   15857         104 :                              stmt->indexParams,
   15858         104 :                              stmt->excludeOpNames,
   15859         104 :                              stmt->iswithoutoverlaps))
   15860             :     {
   15861         104 :         Relation    irel = index_open(oldId, NoLock);
   15862             : 
   15863             :         /* If it's a partitioned index, there is no storage to share. */
   15864         104 :         if (irel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
   15865             :         {
   15866          74 :             stmt->oldNumber = irel->rd_locator.relNumber;
   15867          74 :             stmt->oldCreateSubid = irel->rd_createSubid;
   15868          74 :             stmt->oldFirstRelfilelocatorSubid = irel->rd_firstRelfilelocatorSubid;
   15869             :         }
   15870         104 :         index_close(irel, NoLock);
   15871             :     }
   15872         104 : }
   15873             : 
   15874             : /*
   15875             :  * Subroutine for ATPostAlterTypeParse().
   15876             :  *
   15877             :  * Stash the old P-F equality operator into the Constraint node, for possible
   15878             :  * use by ATAddForeignKeyConstraint() in determining whether revalidation of
   15879             :  * this constraint can be skipped.
   15880             :  */
   15881             : static void
   15882           6 : TryReuseForeignKey(Oid oldId, Constraint *con)
   15883             : {
   15884             :     HeapTuple   tup;
   15885             :     Datum       adatum;
   15886             :     ArrayType  *arr;
   15887             :     Oid        *rawarr;
   15888             :     int         numkeys;
   15889             :     int         i;
   15890             : 
   15891             :     Assert(con->contype == CONSTR_FOREIGN);
   15892             :     Assert(con->old_conpfeqop == NIL);   /* already prepared this node */
   15893             : 
   15894           6 :     tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
   15895           6 :     if (!HeapTupleIsValid(tup)) /* should not happen */
   15896           0 :         elog(ERROR, "cache lookup failed for constraint %u", oldId);
   15897             : 
   15898           6 :     adatum = SysCacheGetAttrNotNull(CONSTROID, tup,
   15899             :                                     Anum_pg_constraint_conpfeqop);
   15900           6 :     arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
   15901           6 :     numkeys = ARR_DIMS(arr)[0];
   15902             :     /* test follows the one in ri_FetchConstraintInfo() */
   15903           6 :     if (ARR_NDIM(arr) != 1 ||
   15904           6 :         ARR_HASNULL(arr) ||
   15905           6 :         ARR_ELEMTYPE(arr) != OIDOID)
   15906           0 :         elog(ERROR, "conpfeqop is not a 1-D Oid array");
   15907           6 :     rawarr = (Oid *) ARR_DATA_PTR(arr);
   15908             : 
   15909             :     /* stash a List of the operator Oids in our Constraint node */
   15910          12 :     for (i = 0; i < numkeys; i++)
   15911           6 :         con->old_conpfeqop = lappend_oid(con->old_conpfeqop, rawarr[i]);
   15912             : 
   15913           6 :     ReleaseSysCache(tup);
   15914           6 : }
   15915             : 
   15916             : /*
   15917             :  * ALTER COLUMN .. OPTIONS ( ... )
   15918             :  *
   15919             :  * Returns the address of the modified column
   15920             :  */
   15921             : static ObjectAddress
   15922         172 : ATExecAlterColumnGenericOptions(Relation rel,
   15923             :                                 const char *colName,
   15924             :                                 List *options,
   15925             :                                 LOCKMODE lockmode)
   15926             : {
   15927             :     Relation    ftrel;
   15928             :     Relation    attrel;
   15929             :     ForeignServer *server;
   15930             :     ForeignDataWrapper *fdw;
   15931             :     HeapTuple   tuple;
   15932             :     HeapTuple   newtuple;
   15933             :     bool        isnull;
   15934             :     Datum       repl_val[Natts_pg_attribute];
   15935             :     bool        repl_null[Natts_pg_attribute];
   15936             :     bool        repl_repl[Natts_pg_attribute];
   15937             :     Datum       datum;
   15938             :     Form_pg_foreign_table fttableform;
   15939             :     Form_pg_attribute atttableform;
   15940             :     AttrNumber  attnum;
   15941             :     ObjectAddress address;
   15942             : 
   15943         172 :     if (options == NIL)
   15944           0 :         return InvalidObjectAddress;
   15945             : 
   15946             :     /* First, determine FDW validator associated to the foreign table. */
   15947         172 :     ftrel = table_open(ForeignTableRelationId, AccessShareLock);
   15948         172 :     tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(rel->rd_id));
   15949         172 :     if (!HeapTupleIsValid(tuple))
   15950           0 :         ereport(ERROR,
   15951             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   15952             :                  errmsg("foreign table \"%s\" does not exist",
   15953             :                         RelationGetRelationName(rel))));
   15954         172 :     fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
   15955         172 :     server = GetForeignServer(fttableform->ftserver);
   15956         172 :     fdw = GetForeignDataWrapper(server->fdwid);
   15957             : 
   15958         172 :     table_close(ftrel, AccessShareLock);
   15959         172 :     ReleaseSysCache(tuple);
   15960             : 
   15961         172 :     attrel = table_open(AttributeRelationId, RowExclusiveLock);
   15962         172 :     tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
   15963         172 :     if (!HeapTupleIsValid(tuple))
   15964           0 :         ereport(ERROR,
   15965             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
   15966             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
   15967             :                         colName, RelationGetRelationName(rel))));
   15968             : 
   15969             :     /* Prevent them from altering a system attribute */
   15970         172 :     atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
   15971         172 :     attnum = atttableform->attnum;
   15972         172 :     if (attnum <= 0)
   15973           6 :         ereport(ERROR,
   15974             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   15975             :                  errmsg("cannot alter system column \"%s\"", colName)));
   15976             : 
   15977             : 
   15978             :     /* Initialize buffers for new tuple values */
   15979         166 :     memset(repl_val, 0, sizeof(repl_val));
   15980         166 :     memset(repl_null, false, sizeof(repl_null));
   15981         166 :     memset(repl_repl, false, sizeof(repl_repl));
   15982             : 
   15983             :     /* Extract the current options */
   15984         166 :     datum = SysCacheGetAttr(ATTNAME,
   15985             :                             tuple,
   15986             :                             Anum_pg_attribute_attfdwoptions,
   15987             :                             &isnull);
   15988         166 :     if (isnull)
   15989         156 :         datum = PointerGetDatum(NULL);
   15990             : 
   15991             :     /* Transform the options */
   15992         166 :     datum = transformGenericOptions(AttributeRelationId,
   15993             :                                     datum,
   15994             :                                     options,
   15995             :                                     fdw->fdwvalidator);
   15996             : 
   15997         166 :     if (DatumGetPointer(datum) != NULL)
   15998         166 :         repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
   15999             :     else
   16000           0 :         repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
   16001             : 
   16002         166 :     repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
   16003             : 
   16004             :     /* Everything looks good - update the tuple */
   16005             : 
   16006         166 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
   16007             :                                  repl_val, repl_null, repl_repl);
   16008             : 
   16009         166 :     CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
   16010             : 
   16011         166 :     InvokeObjectPostAlterHook(RelationRelationId,
   16012             :                               RelationGetRelid(rel),
   16013             :                               atttableform->attnum);
   16014         166 :     ObjectAddressSubSet(address, RelationRelationId,
   16015             :                         RelationGetRelid(rel), attnum);
   16016             : 
   16017         166 :     ReleaseSysCache(tuple);
   16018             : 
   16019         166 :     table_close(attrel, RowExclusiveLock);
   16020             : 
   16021         166 :     heap_freetuple(newtuple);
   16022             : 
   16023         166 :     return address;
   16024             : }
   16025             : 
   16026             : /*
   16027             :  * ALTER TABLE OWNER
   16028             :  *
   16029             :  * recursing is true if we are recursing from a table to its indexes,
   16030             :  * sequences, or toast table.  We don't allow the ownership of those things to
   16031             :  * be changed separately from the parent table.  Also, we can skip permission
   16032             :  * checks (this is necessary not just an optimization, else we'd fail to
   16033             :  * handle toast tables properly).
   16034             :  *
   16035             :  * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
   16036             :  * free-standing composite type.
   16037             :  */
   16038             : void
   16039        2226 : ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
   16040             : {
   16041             :     Relation    target_rel;
   16042             :     Relation    class_rel;
   16043             :     HeapTuple   tuple;
   16044             :     Form_pg_class tuple_class;
   16045             : 
   16046             :     /*
   16047             :      * Get exclusive lock till end of transaction on the target table. Use
   16048             :      * relation_open so that we can work on indexes and sequences.
   16049             :      */
   16050        2226 :     target_rel = relation_open(relationOid, lockmode);
   16051             : 
   16052             :     /* Get its pg_class tuple, too */
   16053        2226 :     class_rel = table_open(RelationRelationId, RowExclusiveLock);
   16054             : 
   16055        2226 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
   16056        2226 :     if (!HeapTupleIsValid(tuple))
   16057           0 :         elog(ERROR, "cache lookup failed for relation %u", relationOid);
   16058        2226 :     tuple_class = (Form_pg_class) GETSTRUCT(tuple);
   16059             : 
   16060             :     /* Can we change the ownership of this tuple? */
   16061        2226 :     switch (tuple_class->relkind)
   16062             :     {
   16063        1942 :         case RELKIND_RELATION:
   16064             :         case RELKIND_VIEW:
   16065             :         case RELKIND_MATVIEW:
   16066             :         case RELKIND_FOREIGN_TABLE:
   16067             :         case RELKIND_PARTITIONED_TABLE:
   16068             :             /* ok to change owner */
   16069        1942 :             break;
   16070          96 :         case RELKIND_INDEX:
   16071          96 :             if (!recursing)
   16072             :             {
   16073             :                 /*
   16074             :                  * Because ALTER INDEX OWNER used to be allowed, and in fact
   16075             :                  * is generated by old versions of pg_dump, we give a warning
   16076             :                  * and do nothing rather than erroring out.  Also, to avoid
   16077             :                  * unnecessary chatter while restoring those old dumps, say
   16078             :                  * nothing at all if the command would be a no-op anyway.
   16079             :                  */
   16080           0 :                 if (tuple_class->relowner != newOwnerId)
   16081           0 :                     ereport(WARNING,
   16082             :                             (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16083             :                              errmsg("cannot change owner of index \"%s\"",
   16084             :                                     NameStr(tuple_class->relname)),
   16085             :                              errhint("Change the ownership of the index's table instead.")));
   16086             :                 /* quick hack to exit via the no-op path */
   16087           0 :                 newOwnerId = tuple_class->relowner;
   16088             :             }
   16089          96 :             break;
   16090          20 :         case RELKIND_PARTITIONED_INDEX:
   16091          20 :             if (recursing)
   16092          20 :                 break;
   16093           0 :             ereport(ERROR,
   16094             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16095             :                      errmsg("cannot change owner of index \"%s\"",
   16096             :                             NameStr(tuple_class->relname)),
   16097             :                      errhint("Change the ownership of the index's table instead.")));
   16098             :             break;
   16099         118 :         case RELKIND_SEQUENCE:
   16100         118 :             if (!recursing &&
   16101          70 :                 tuple_class->relowner != newOwnerId)
   16102             :             {
   16103             :                 /* if it's an owned sequence, disallow changing it by itself */
   16104             :                 Oid         tableId;
   16105             :                 int32       colId;
   16106             : 
   16107           0 :                 if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
   16108           0 :                     sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
   16109           0 :                     ereport(ERROR,
   16110             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   16111             :                              errmsg("cannot change owner of sequence \"%s\"",
   16112             :                                     NameStr(tuple_class->relname)),
   16113             :                              errdetail("Sequence \"%s\" is linked to table \"%s\".",
   16114             :                                        NameStr(tuple_class->relname),
   16115             :                                        get_rel_name(tableId))));
   16116             :             }
   16117         118 :             break;
   16118           8 :         case RELKIND_COMPOSITE_TYPE:
   16119           8 :             if (recursing)
   16120           8 :                 break;
   16121           0 :             ereport(ERROR,
   16122             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16123             :                      errmsg("\"%s\" is a composite type",
   16124             :                             NameStr(tuple_class->relname)),
   16125             :             /* translator: %s is an SQL ALTER command */
   16126             :                      errhint("Use %s instead.",
   16127             :                              "ALTER TYPE")));
   16128             :             break;
   16129          42 :         case RELKIND_TOASTVALUE:
   16130          42 :             if (recursing)
   16131          42 :                 break;
   16132             :             /* FALL THRU */
   16133             :         default:
   16134           0 :             ereport(ERROR,
   16135             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16136             :                      errmsg("cannot change owner of relation \"%s\"",
   16137             :                             NameStr(tuple_class->relname)),
   16138             :                      errdetail_relkind_not_supported(tuple_class->relkind)));
   16139             :     }
   16140             : 
   16141             :     /*
   16142             :      * If the new owner is the same as the existing owner, consider the
   16143             :      * command to have succeeded.  This is for dump restoration purposes.
   16144             :      */
   16145        2226 :     if (tuple_class->relowner != newOwnerId)
   16146             :     {
   16147             :         Datum       repl_val[Natts_pg_class];
   16148             :         bool        repl_null[Natts_pg_class];
   16149             :         bool        repl_repl[Natts_pg_class];
   16150             :         Acl        *newAcl;
   16151             :         Datum       aclDatum;
   16152             :         bool        isNull;
   16153             :         HeapTuple   newtuple;
   16154             : 
   16155             :         /* skip permission checks when recursing to index or toast table */
   16156         498 :         if (!recursing)
   16157             :         {
   16158             :             /* Superusers can always do it */
   16159         280 :             if (!superuser())
   16160             :             {
   16161          42 :                 Oid         namespaceOid = tuple_class->relnamespace;
   16162             :                 AclResult   aclresult;
   16163             : 
   16164             :                 /* Otherwise, must be owner of the existing object */
   16165          42 :                 if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
   16166           0 :                     aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relationOid)),
   16167           0 :                                    RelationGetRelationName(target_rel));
   16168             : 
   16169             :                 /* Must be able to become new owner */
   16170          42 :                 check_can_set_role(GetUserId(), newOwnerId);
   16171             : 
   16172             :                 /* New owner must have CREATE privilege on namespace */
   16173          30 :                 aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
   16174             :                                             ACL_CREATE);
   16175          30 :                 if (aclresult != ACLCHECK_OK)
   16176           0 :                     aclcheck_error(aclresult, OBJECT_SCHEMA,
   16177           0 :                                    get_namespace_name(namespaceOid));
   16178             :             }
   16179             :         }
   16180             : 
   16181         486 :         memset(repl_null, false, sizeof(repl_null));
   16182         486 :         memset(repl_repl, false, sizeof(repl_repl));
   16183             : 
   16184         486 :         repl_repl[Anum_pg_class_relowner - 1] = true;
   16185         486 :         repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
   16186             : 
   16187             :         /*
   16188             :          * Determine the modified ACL for the new owner.  This is only
   16189             :          * necessary when the ACL is non-null.
   16190             :          */
   16191         486 :         aclDatum = SysCacheGetAttr(RELOID, tuple,
   16192             :                                    Anum_pg_class_relacl,
   16193             :                                    &isNull);
   16194         486 :         if (!isNull)
   16195             :         {
   16196          46 :             newAcl = aclnewowner(DatumGetAclP(aclDatum),
   16197             :                                  tuple_class->relowner, newOwnerId);
   16198          46 :             repl_repl[Anum_pg_class_relacl - 1] = true;
   16199          46 :             repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
   16200             :         }
   16201             : 
   16202         486 :         newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
   16203             : 
   16204         486 :         CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
   16205             : 
   16206         486 :         heap_freetuple(newtuple);
   16207             : 
   16208             :         /*
   16209             :          * We must similarly update any per-column ACLs to reflect the new
   16210             :          * owner; for neatness reasons that's split out as a subroutine.
   16211             :          */
   16212         486 :         change_owner_fix_column_acls(relationOid,
   16213             :                                      tuple_class->relowner,
   16214             :                                      newOwnerId);
   16215             : 
   16216             :         /*
   16217             :          * Update owner dependency reference, if any.  A composite type has
   16218             :          * none, because it's tracked for the pg_type entry instead of here;
   16219             :          * indexes and TOAST tables don't have their own entries either.
   16220             :          */
   16221         486 :         if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
   16222         478 :             tuple_class->relkind != RELKIND_INDEX &&
   16223         382 :             tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
   16224         362 :             tuple_class->relkind != RELKIND_TOASTVALUE)
   16225         320 :             changeDependencyOnOwner(RelationRelationId, relationOid,
   16226             :                                     newOwnerId);
   16227             : 
   16228             :         /*
   16229             :          * Also change the ownership of the table's row type, if it has one
   16230             :          */
   16231         486 :         if (OidIsValid(tuple_class->reltype))
   16232         294 :             AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
   16233             : 
   16234             :         /*
   16235             :          * If we are operating on a table or materialized view, also change
   16236             :          * the ownership of any indexes and sequences that belong to the
   16237             :          * relation, as well as its toast table (if it has one).
   16238             :          */
   16239         486 :         if (tuple_class->relkind == RELKIND_RELATION ||
   16240         262 :             tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
   16241         224 :             tuple_class->relkind == RELKIND_MATVIEW ||
   16242         224 :             tuple_class->relkind == RELKIND_TOASTVALUE)
   16243             :         {
   16244             :             List       *index_oid_list;
   16245             :             ListCell   *i;
   16246             : 
   16247             :             /* Find all the indexes belonging to this relation */
   16248         304 :             index_oid_list = RelationGetIndexList(target_rel);
   16249             : 
   16250             :             /* For each index, recursively change its ownership */
   16251         420 :             foreach(i, index_oid_list)
   16252         116 :                 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
   16253             : 
   16254         304 :             list_free(index_oid_list);
   16255             :         }
   16256             : 
   16257             :         /* If it has a toast table, recurse to change its ownership */
   16258         486 :         if (tuple_class->reltoastrelid != InvalidOid)
   16259          42 :             ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
   16260             :                               true, lockmode);
   16261             : 
   16262             :         /* If it has dependent sequences, recurse to change them too */
   16263         486 :         change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
   16264             :     }
   16265             : 
   16266        2214 :     InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
   16267             : 
   16268        2214 :     ReleaseSysCache(tuple);
   16269        2214 :     table_close(class_rel, RowExclusiveLock);
   16270        2214 :     relation_close(target_rel, NoLock);
   16271        2214 : }
   16272             : 
   16273             : /*
   16274             :  * change_owner_fix_column_acls
   16275             :  *
   16276             :  * Helper function for ATExecChangeOwner.  Scan the columns of the table
   16277             :  * and fix any non-null column ACLs to reflect the new owner.
   16278             :  */
   16279             : static void
   16280         486 : change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
   16281             : {
   16282             :     Relation    attRelation;
   16283             :     SysScanDesc scan;
   16284             :     ScanKeyData key[1];
   16285             :     HeapTuple   attributeTuple;
   16286             : 
   16287         486 :     attRelation = table_open(AttributeRelationId, RowExclusiveLock);
   16288         486 :     ScanKeyInit(&key[0],
   16289             :                 Anum_pg_attribute_attrelid,
   16290             :                 BTEqualStrategyNumber, F_OIDEQ,
   16291             :                 ObjectIdGetDatum(relationOid));
   16292         486 :     scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
   16293             :                               true, NULL, 1, key);
   16294        3372 :     while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
   16295             :     {
   16296        2886 :         Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
   16297             :         Datum       repl_val[Natts_pg_attribute];
   16298             :         bool        repl_null[Natts_pg_attribute];
   16299             :         bool        repl_repl[Natts_pg_attribute];
   16300             :         Acl        *newAcl;
   16301             :         Datum       aclDatum;
   16302             :         bool        isNull;
   16303             :         HeapTuple   newtuple;
   16304             : 
   16305             :         /* Ignore dropped columns */
   16306        2886 :         if (att->attisdropped)
   16307        2884 :             continue;
   16308             : 
   16309        2886 :         aclDatum = heap_getattr(attributeTuple,
   16310             :                                 Anum_pg_attribute_attacl,
   16311             :                                 RelationGetDescr(attRelation),
   16312             :                                 &isNull);
   16313             :         /* Null ACLs do not require changes */
   16314        2886 :         if (isNull)
   16315        2884 :             continue;
   16316             : 
   16317           2 :         memset(repl_null, false, sizeof(repl_null));
   16318           2 :         memset(repl_repl, false, sizeof(repl_repl));
   16319             : 
   16320           2 :         newAcl = aclnewowner(DatumGetAclP(aclDatum),
   16321             :                              oldOwnerId, newOwnerId);
   16322           2 :         repl_repl[Anum_pg_attribute_attacl - 1] = true;
   16323           2 :         repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
   16324             : 
   16325           2 :         newtuple = heap_modify_tuple(attributeTuple,
   16326             :                                      RelationGetDescr(attRelation),
   16327             :                                      repl_val, repl_null, repl_repl);
   16328             : 
   16329           2 :         CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
   16330             : 
   16331           2 :         heap_freetuple(newtuple);
   16332             :     }
   16333         486 :     systable_endscan(scan);
   16334         486 :     table_close(attRelation, RowExclusiveLock);
   16335         486 : }
   16336             : 
   16337             : /*
   16338             :  * change_owner_recurse_to_sequences
   16339             :  *
   16340             :  * Helper function for ATExecChangeOwner.  Examines pg_depend searching
   16341             :  * for sequences that are dependent on serial columns, and changes their
   16342             :  * ownership.
   16343             :  */
   16344             : static void
   16345         486 : change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
   16346             : {
   16347             :     Relation    depRel;
   16348             :     SysScanDesc scan;
   16349             :     ScanKeyData key[2];
   16350             :     HeapTuple   tup;
   16351             : 
   16352             :     /*
   16353             :      * SERIAL sequences are those having an auto dependency on one of the
   16354             :      * table's columns (we don't care *which* column, exactly).
   16355             :      */
   16356         486 :     depRel = table_open(DependRelationId, AccessShareLock);
   16357             : 
   16358         486 :     ScanKeyInit(&key[0],
   16359             :                 Anum_pg_depend_refclassid,
   16360             :                 BTEqualStrategyNumber, F_OIDEQ,
   16361             :                 ObjectIdGetDatum(RelationRelationId));
   16362         486 :     ScanKeyInit(&key[1],
   16363             :                 Anum_pg_depend_refobjid,
   16364             :                 BTEqualStrategyNumber, F_OIDEQ,
   16365             :                 ObjectIdGetDatum(relationOid));
   16366             :     /* we leave refobjsubid unspecified */
   16367             : 
   16368         486 :     scan = systable_beginscan(depRel, DependReferenceIndexId, true,
   16369             :                               NULL, 2, key);
   16370             : 
   16371        1374 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
   16372             :     {
   16373         888 :         Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
   16374             :         Relation    seqRel;
   16375             : 
   16376             :         /* skip dependencies other than auto dependencies on columns */
   16377         888 :         if (depForm->refobjsubid == 0 ||
   16378         352 :             depForm->classid != RelationRelationId ||
   16379         142 :             depForm->objsubid != 0 ||
   16380         142 :             !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
   16381         746 :             continue;
   16382             : 
   16383             :         /* Use relation_open just in case it's an index */
   16384         142 :         seqRel = relation_open(depForm->objid, lockmode);
   16385             : 
   16386             :         /* skip non-sequence relations */
   16387         142 :         if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
   16388             :         {
   16389             :             /* No need to keep the lock */
   16390         116 :             relation_close(seqRel, lockmode);
   16391         116 :             continue;
   16392             :         }
   16393             : 
   16394             :         /* We don't need to close the sequence while we alter it. */
   16395          26 :         ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
   16396             : 
   16397             :         /* Now we can close it.  Keep the lock till end of transaction. */
   16398          26 :         relation_close(seqRel, NoLock);
   16399             :     }
   16400             : 
   16401         486 :     systable_endscan(scan);
   16402             : 
   16403         486 :     relation_close(depRel, AccessShareLock);
   16404         486 : }
   16405             : 
   16406             : /*
   16407             :  * ALTER TABLE CLUSTER ON
   16408             :  *
   16409             :  * The only thing we have to do is to change the indisclustered bits.
   16410             :  *
   16411             :  * Return the address of the new clustering index.
   16412             :  */
   16413             : static ObjectAddress
   16414          64 : ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
   16415             : {
   16416             :     Oid         indexOid;
   16417             :     ObjectAddress address;
   16418             : 
   16419          64 :     indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
   16420             : 
   16421          64 :     if (!OidIsValid(indexOid))
   16422           0 :         ereport(ERROR,
   16423             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   16424             :                  errmsg("index \"%s\" for table \"%s\" does not exist",
   16425             :                         indexName, RelationGetRelationName(rel))));
   16426             : 
   16427             :     /* Check index is valid to cluster on */
   16428          64 :     check_index_is_clusterable(rel, indexOid, lockmode);
   16429             : 
   16430             :     /* And do the work */
   16431          64 :     mark_index_clustered(rel, indexOid, false);
   16432             : 
   16433          58 :     ObjectAddressSet(address,
   16434             :                      RelationRelationId, indexOid);
   16435             : 
   16436          58 :     return address;
   16437             : }
   16438             : 
   16439             : /*
   16440             :  * ALTER TABLE SET WITHOUT CLUSTER
   16441             :  *
   16442             :  * We have to find any indexes on the table that have indisclustered bit
   16443             :  * set and turn it off.
   16444             :  */
   16445             : static void
   16446          18 : ATExecDropCluster(Relation rel, LOCKMODE lockmode)
   16447             : {
   16448          18 :     mark_index_clustered(rel, InvalidOid, false);
   16449          12 : }
   16450             : 
   16451             : /*
   16452             :  * Preparation phase for SET ACCESS METHOD
   16453             :  *
   16454             :  * Check that the access method exists and determine whether a change is
   16455             :  * actually needed.
   16456             :  */
   16457             : static void
   16458         110 : ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname)
   16459             : {
   16460             :     Oid         amoid;
   16461             : 
   16462             :     /*
   16463             :      * Look up the access method name and check that it differs from the
   16464             :      * table's current AM.  If DEFAULT was specified for a partitioned table
   16465             :      * (amname is NULL), set it to InvalidOid to reset the catalogued AM.
   16466             :      */
   16467         110 :     if (amname != NULL)
   16468          74 :         amoid = get_table_am_oid(amname, false);
   16469          36 :     else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   16470          18 :         amoid = InvalidOid;
   16471             :     else
   16472          18 :         amoid = get_table_am_oid(default_table_access_method, false);
   16473             : 
   16474             :     /* if it's a match, phase 3 doesn't need to do anything */
   16475         110 :     if (rel->rd_rel->relam == amoid)
   16476          12 :         return;
   16477             : 
   16478             :     /* Save info for Phase 3 to do the real work */
   16479          98 :     tab->rewrite |= AT_REWRITE_ACCESS_METHOD;
   16480          98 :     tab->newAccessMethod = amoid;
   16481          98 :     tab->chgAccessMethod = true;
   16482             : }
   16483             : 
   16484             : /*
   16485             :  * Special handling of ALTER TABLE SET ACCESS METHOD for relations with no
   16486             :  * storage that have an interest in preserving AM.
   16487             :  *
   16488             :  * Since these have no storage, setting the access method is a catalog only
   16489             :  * operation.
   16490             :  */
   16491             : static void
   16492          44 : ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId)
   16493             : {
   16494             :     Relation    pg_class;
   16495             :     Oid         oldAccessMethodId;
   16496             :     HeapTuple   tuple;
   16497             :     Form_pg_class rd_rel;
   16498          44 :     Oid         reloid = RelationGetRelid(rel);
   16499             : 
   16500             :     /*
   16501             :      * Shouldn't be called on relations having storage; these are processed in
   16502             :      * phase 3.
   16503             :      */
   16504             :     Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
   16505             : 
   16506             :     /* Get a modifiable copy of the relation's pg_class row. */
   16507          44 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
   16508             : 
   16509          44 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
   16510          44 :     if (!HeapTupleIsValid(tuple))
   16511           0 :         elog(ERROR, "cache lookup failed for relation %u", reloid);
   16512          44 :     rd_rel = (Form_pg_class) GETSTRUCT(tuple);
   16513             : 
   16514             :     /* Update the pg_class row. */
   16515          44 :     oldAccessMethodId = rd_rel->relam;
   16516          44 :     rd_rel->relam = newAccessMethodId;
   16517             : 
   16518             :     /* Leave if no update required */
   16519          44 :     if (rd_rel->relam == oldAccessMethodId)
   16520             :     {
   16521           0 :         heap_freetuple(tuple);
   16522           0 :         table_close(pg_class, RowExclusiveLock);
   16523           0 :         return;
   16524             :     }
   16525             : 
   16526          44 :     CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
   16527             : 
   16528             :     /*
   16529             :      * Update the dependency on the new access method.  No dependency is added
   16530             :      * if the new access method is InvalidOid (default case).  Be very careful
   16531             :      * that this has to compare the previous value stored in pg_class with the
   16532             :      * new one.
   16533             :      */
   16534          44 :     if (!OidIsValid(oldAccessMethodId) && OidIsValid(rd_rel->relam))
   16535          20 :     {
   16536             :         ObjectAddress relobj,
   16537             :                     referenced;
   16538             : 
   16539             :         /*
   16540             :          * New access method is defined and there was no dependency
   16541             :          * previously, so record a new one.
   16542             :          */
   16543          20 :         ObjectAddressSet(relobj, RelationRelationId, reloid);
   16544          20 :         ObjectAddressSet(referenced, AccessMethodRelationId, rd_rel->relam);
   16545          20 :         recordDependencyOn(&relobj, &referenced, DEPENDENCY_NORMAL);
   16546             :     }
   16547          24 :     else if (OidIsValid(oldAccessMethodId) &&
   16548          24 :              !OidIsValid(rd_rel->relam))
   16549             :     {
   16550             :         /*
   16551             :          * There was an access method defined, and no new one, so just remove
   16552             :          * the existing dependency.
   16553             :          */
   16554          12 :         deleteDependencyRecordsForClass(RelationRelationId, reloid,
   16555             :                                         AccessMethodRelationId,
   16556             :                                         DEPENDENCY_NORMAL);
   16557             :     }
   16558             :     else
   16559             :     {
   16560             :         Assert(OidIsValid(oldAccessMethodId) &&
   16561             :                OidIsValid(rd_rel->relam));
   16562             : 
   16563             :         /* Both are valid, so update the dependency */
   16564          12 :         changeDependencyFor(RelationRelationId, reloid,
   16565             :                             AccessMethodRelationId,
   16566             :                             oldAccessMethodId, rd_rel->relam);
   16567             :     }
   16568             : 
   16569             :     /* make the relam and dependency changes visible */
   16570          44 :     CommandCounterIncrement();
   16571             : 
   16572          44 :     InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
   16573             : 
   16574          44 :     heap_freetuple(tuple);
   16575          44 :     table_close(pg_class, RowExclusiveLock);
   16576             : }
   16577             : 
   16578             : /*
   16579             :  * ALTER TABLE SET TABLESPACE
   16580             :  */
   16581             : static void
   16582         158 : ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
   16583             : {
   16584             :     Oid         tablespaceId;
   16585             : 
   16586             :     /* Check that the tablespace exists */
   16587         158 :     tablespaceId = get_tablespace_oid(tablespacename, false);
   16588             : 
   16589             :     /* Check permissions except when moving to database's default */
   16590         158 :     if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
   16591             :     {
   16592             :         AclResult   aclresult;
   16593             : 
   16594          66 :         aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(), ACL_CREATE);
   16595          66 :         if (aclresult != ACLCHECK_OK)
   16596           0 :             aclcheck_error(aclresult, OBJECT_TABLESPACE, tablespacename);
   16597             :     }
   16598             : 
   16599             :     /* Save info for Phase 3 to do the real work */
   16600         158 :     if (OidIsValid(tab->newTableSpace))
   16601           0 :         ereport(ERROR,
   16602             :                 (errcode(ERRCODE_SYNTAX_ERROR),
   16603             :                  errmsg("cannot have multiple SET TABLESPACE subcommands")));
   16604             : 
   16605         158 :     tab->newTableSpace = tablespaceId;
   16606         158 : }
   16607             : 
   16608             : /*
   16609             :  * Set, reset, or replace reloptions.
   16610             :  */
   16611             : static void
   16612         960 : ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
   16613             :                     LOCKMODE lockmode)
   16614             : {
   16615             :     Oid         relid;
   16616             :     Relation    pgclass;
   16617             :     HeapTuple   tuple;
   16618             :     HeapTuple   newtuple;
   16619             :     Datum       datum;
   16620             :     Datum       newOptions;
   16621             :     Datum       repl_val[Natts_pg_class];
   16622             :     bool        repl_null[Natts_pg_class];
   16623             :     bool        repl_repl[Natts_pg_class];
   16624         960 :     const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
   16625             : 
   16626         960 :     if (defList == NIL && operation != AT_ReplaceRelOptions)
   16627           0 :         return;                 /* nothing to do */
   16628             : 
   16629         960 :     pgclass = table_open(RelationRelationId, RowExclusiveLock);
   16630             : 
   16631             :     /* Fetch heap tuple */
   16632         960 :     relid = RelationGetRelid(rel);
   16633         960 :     tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relid));
   16634         960 :     if (!HeapTupleIsValid(tuple))
   16635           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   16636             : 
   16637         960 :     if (operation == AT_ReplaceRelOptions)
   16638             :     {
   16639             :         /*
   16640             :          * If we're supposed to replace the reloptions list, we just pretend
   16641             :          * there were none before.
   16642             :          */
   16643         194 :         datum = (Datum) 0;
   16644             :     }
   16645             :     else
   16646             :     {
   16647             :         bool        isnull;
   16648             : 
   16649             :         /* Get the old reloptions */
   16650         766 :         datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
   16651             :                                 &isnull);
   16652         766 :         if (isnull)
   16653         478 :             datum = (Datum) 0;
   16654             :     }
   16655             : 
   16656             :     /* Generate new proposed reloptions (text array) */
   16657         960 :     newOptions = transformRelOptions(datum, defList, NULL, validnsps, false,
   16658             :                                      operation == AT_ResetRelOptions);
   16659             : 
   16660             :     /* Validate */
   16661         954 :     switch (rel->rd_rel->relkind)
   16662             :     {
   16663         536 :         case RELKIND_RELATION:
   16664             :         case RELKIND_MATVIEW:
   16665         536 :             (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
   16666         536 :             break;
   16667           6 :         case RELKIND_PARTITIONED_TABLE:
   16668           6 :             (void) partitioned_table_reloptions(newOptions, true);
   16669           0 :             break;
   16670         296 :         case RELKIND_VIEW:
   16671         296 :             (void) view_reloptions(newOptions, true);
   16672         278 :             break;
   16673         116 :         case RELKIND_INDEX:
   16674             :         case RELKIND_PARTITIONED_INDEX:
   16675         116 :             (void) index_reloptions(rel->rd_indam->amoptions, newOptions, true);
   16676          94 :             break;
   16677           0 :         case RELKIND_TOASTVALUE:
   16678             :             /* fall through to error -- shouldn't ever get here */
   16679             :         default:
   16680           0 :             ereport(ERROR,
   16681             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   16682             :                      errmsg("cannot set options for relation \"%s\"",
   16683             :                             RelationGetRelationName(rel)),
   16684             :                      errdetail_relkind_not_supported(rel->rd_rel->relkind)));
   16685             :             break;
   16686             :     }
   16687             : 
   16688             :     /* Special-case validation of view options */
   16689         908 :     if (rel->rd_rel->relkind == RELKIND_VIEW)
   16690             :     {
   16691         278 :         Query      *view_query = get_view_query(rel);
   16692         278 :         List       *view_options = untransformRelOptions(newOptions);
   16693             :         ListCell   *cell;
   16694         278 :         bool        check_option = false;
   16695             : 
   16696         380 :         foreach(cell, view_options)
   16697             :         {
   16698         102 :             DefElem    *defel = (DefElem *) lfirst(cell);
   16699             : 
   16700         102 :             if (strcmp(defel->defname, "check_option") == 0)
   16701          24 :                 check_option = true;
   16702             :         }
   16703             : 
   16704             :         /*
   16705             :          * If the check option is specified, look to see if the view is
   16706             :          * actually auto-updatable or not.
   16707             :          */
   16708         278 :         if (check_option)
   16709             :         {
   16710             :             const char *view_updatable_error =
   16711          24 :                 view_query_is_auto_updatable(view_query, true);
   16712             : 
   16713          24 :             if (view_updatable_error)
   16714           0 :                 ereport(ERROR,
   16715             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   16716             :                          errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
   16717             :                          errhint("%s", _(view_updatable_error))));
   16718             :         }
   16719             :     }
   16720             : 
   16721             :     /*
   16722             :      * All we need do here is update the pg_class row; the new options will be
   16723             :      * propagated into relcaches during post-commit cache inval.
   16724             :      */
   16725         908 :     memset(repl_val, 0, sizeof(repl_val));
   16726         908 :     memset(repl_null, false, sizeof(repl_null));
   16727         908 :     memset(repl_repl, false, sizeof(repl_repl));
   16728             : 
   16729         908 :     if (newOptions != (Datum) 0)
   16730         614 :         repl_val[Anum_pg_class_reloptions - 1] = newOptions;
   16731             :     else
   16732         294 :         repl_null[Anum_pg_class_reloptions - 1] = true;
   16733             : 
   16734         908 :     repl_repl[Anum_pg_class_reloptions - 1] = true;
   16735             : 
   16736         908 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
   16737             :                                  repl_val, repl_null, repl_repl);
   16738             : 
   16739         908 :     CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
   16740         908 :     UnlockTuple(pgclass, &tuple->t_self, InplaceUpdateTupleLock);
   16741             : 
   16742         908 :     InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
   16743             : 
   16744         908 :     heap_freetuple(newtuple);
   16745             : 
   16746         908 :     ReleaseSysCache(tuple);
   16747             : 
   16748             :     /* repeat the whole exercise for the toast table, if there's one */
   16749         908 :     if (OidIsValid(rel->rd_rel->reltoastrelid))
   16750             :     {
   16751             :         Relation    toastrel;
   16752         268 :         Oid         toastid = rel->rd_rel->reltoastrelid;
   16753             : 
   16754         268 :         toastrel = table_open(toastid, lockmode);
   16755             : 
   16756             :         /* Fetch heap tuple */
   16757         268 :         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
   16758         268 :         if (!HeapTupleIsValid(tuple))
   16759           0 :             elog(ERROR, "cache lookup failed for relation %u", toastid);
   16760             : 
   16761         268 :         if (operation == AT_ReplaceRelOptions)
   16762             :         {
   16763             :             /*
   16764             :              * If we're supposed to replace the reloptions list, we just
   16765             :              * pretend there were none before.
   16766             :              */
   16767           0 :             datum = (Datum) 0;
   16768             :         }
   16769             :         else
   16770             :         {
   16771             :             bool        isnull;
   16772             : 
   16773             :             /* Get the old reloptions */
   16774         268 :             datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
   16775             :                                     &isnull);
   16776         268 :             if (isnull)
   16777         232 :                 datum = (Datum) 0;
   16778             :         }
   16779             : 
   16780         268 :         newOptions = transformRelOptions(datum, defList, "toast", validnsps,
   16781             :                                          false, operation == AT_ResetRelOptions);
   16782             : 
   16783         268 :         (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
   16784             : 
   16785         268 :         memset(repl_val, 0, sizeof(repl_val));
   16786         268 :         memset(repl_null, false, sizeof(repl_null));
   16787         268 :         memset(repl_repl, false, sizeof(repl_repl));
   16788             : 
   16789         268 :         if (newOptions != (Datum) 0)
   16790          42 :             repl_val[Anum_pg_class_reloptions - 1] = newOptions;
   16791             :         else
   16792         226 :             repl_null[Anum_pg_class_reloptions - 1] = true;
   16793             : 
   16794         268 :         repl_repl[Anum_pg_class_reloptions - 1] = true;
   16795             : 
   16796         268 :         newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
   16797             :                                      repl_val, repl_null, repl_repl);
   16798             : 
   16799         268 :         CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
   16800             : 
   16801         268 :         InvokeObjectPostAlterHookArg(RelationRelationId,
   16802             :                                      RelationGetRelid(toastrel), 0,
   16803             :                                      InvalidOid, true);
   16804             : 
   16805         268 :         heap_freetuple(newtuple);
   16806             : 
   16807         268 :         ReleaseSysCache(tuple);
   16808             : 
   16809         268 :         table_close(toastrel, NoLock);
   16810             :     }
   16811             : 
   16812         908 :     table_close(pgclass, RowExclusiveLock);
   16813             : }
   16814             : 
   16815             : /*
   16816             :  * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
   16817             :  * rewriting to be done, so we just want to copy the data as fast as possible.
   16818             :  */
   16819             : static void
   16820         162 : ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
   16821             : {
   16822             :     Relation    rel;
   16823             :     Oid         reltoastrelid;
   16824             :     RelFileNumber newrelfilenumber;
   16825             :     RelFileLocator newrlocator;
   16826         162 :     List       *reltoastidxids = NIL;
   16827             :     ListCell   *lc;
   16828             : 
   16829             :     /*
   16830             :      * Need lock here in case we are recursing to toast table or index
   16831             :      */
   16832         162 :     rel = relation_open(tableOid, lockmode);
   16833             : 
   16834             :     /* Check first if relation can be moved to new tablespace */
   16835         162 :     if (!CheckRelationTableSpaceMove(rel, newTableSpace))
   16836             :     {
   16837           2 :         InvokeObjectPostAlterHook(RelationRelationId,
   16838             :                                   RelationGetRelid(rel), 0);
   16839           2 :         relation_close(rel, NoLock);
   16840           2 :         return;
   16841             :     }
   16842             : 
   16843         160 :     reltoastrelid = rel->rd_rel->reltoastrelid;
   16844             :     /* Fetch the list of indexes on toast relation if necessary */
   16845         160 :     if (OidIsValid(reltoastrelid))
   16846             :     {
   16847          20 :         Relation    toastRel = relation_open(reltoastrelid, lockmode);
   16848             : 
   16849          20 :         reltoastidxids = RelationGetIndexList(toastRel);
   16850          20 :         relation_close(toastRel, lockmode);
   16851             :     }
   16852             : 
   16853             :     /*
   16854             :      * Relfilenumbers are not unique in databases across tablespaces, so we
   16855             :      * need to allocate a new one in the new tablespace.
   16856             :      */
   16857         160 :     newrelfilenumber = GetNewRelFileNumber(newTableSpace, NULL,
   16858         160 :                                            rel->rd_rel->relpersistence);
   16859             : 
   16860             :     /* Open old and new relation */
   16861         160 :     newrlocator = rel->rd_locator;
   16862         160 :     newrlocator.relNumber = newrelfilenumber;
   16863         160 :     newrlocator.spcOid = newTableSpace;
   16864             : 
   16865             :     /* hand off to AM to actually create new rel storage and copy the data */
   16866         160 :     if (rel->rd_rel->relkind == RELKIND_INDEX)
   16867             :     {
   16868          62 :         index_copy_data(rel, newrlocator);
   16869             :     }
   16870             :     else
   16871             :     {
   16872             :         Assert(RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind));
   16873          98 :         table_relation_copy_data(rel, &newrlocator);
   16874             :     }
   16875             : 
   16876             :     /*
   16877             :      * Update the pg_class row.
   16878             :      *
   16879             :      * NB: This wouldn't work if ATExecSetTableSpace() were allowed to be
   16880             :      * executed on pg_class or its indexes (the above copy wouldn't contain
   16881             :      * the updated pg_class entry), but that's forbidden with
   16882             :      * CheckRelationTableSpaceMove().
   16883             :      */
   16884         160 :     SetRelationTableSpace(rel, newTableSpace, newrelfilenumber);
   16885             : 
   16886         160 :     InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
   16887             : 
   16888         160 :     RelationAssumeNewRelfilelocator(rel);
   16889             : 
   16890         160 :     relation_close(rel, NoLock);
   16891             : 
   16892             :     /* Make sure the reltablespace change is visible */
   16893         160 :     CommandCounterIncrement();
   16894             : 
   16895             :     /* Move associated toast relation and/or indexes, too */
   16896         160 :     if (OidIsValid(reltoastrelid))
   16897          20 :         ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
   16898         180 :     foreach(lc, reltoastidxids)
   16899          20 :         ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
   16900             : 
   16901             :     /* Clean up */
   16902         160 :     list_free(reltoastidxids);
   16903             : }
   16904             : 
   16905             : /*
   16906             :  * Special handling of ALTER TABLE SET TABLESPACE for relations with no
   16907             :  * storage that have an interest in preserving tablespace.
   16908             :  *
   16909             :  * Since these have no storage the tablespace can be updated with a simple
   16910             :  * metadata only operation to update the tablespace.
   16911             :  */
   16912             : static void
   16913          36 : ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace)
   16914             : {
   16915             :     /*
   16916             :      * Shouldn't be called on relations having storage; these are processed in
   16917             :      * phase 3.
   16918             :      */
   16919             :     Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
   16920             : 
   16921             :     /* check if relation can be moved to its new tablespace */
   16922          36 :     if (!CheckRelationTableSpaceMove(rel, newTableSpace))
   16923             :     {
   16924           0 :         InvokeObjectPostAlterHook(RelationRelationId,
   16925             :                                   RelationGetRelid(rel),
   16926             :                                   0);
   16927           0 :         return;
   16928             :     }
   16929             : 
   16930             :     /* Update can be done, so change reltablespace */
   16931          30 :     SetRelationTableSpace(rel, newTableSpace, InvalidOid);
   16932             : 
   16933          30 :     InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
   16934             : 
   16935             :     /* Make sure the reltablespace change is visible */
   16936          30 :     CommandCounterIncrement();
   16937             : }
   16938             : 
   16939             : /*
   16940             :  * Alter Table ALL ... SET TABLESPACE
   16941             :  *
   16942             :  * Allows a user to move all objects of some type in a given tablespace in the
   16943             :  * current database to another tablespace.  Objects can be chosen based on the
   16944             :  * owner of the object also, to allow users to move only their objects.
   16945             :  * The user must have CREATE rights on the new tablespace, as usual.   The main
   16946             :  * permissions handling is done by the lower-level table move function.
   16947             :  *
   16948             :  * All to-be-moved objects are locked first. If NOWAIT is specified and the
   16949             :  * lock can't be acquired then we ereport(ERROR).
   16950             :  */
   16951             : Oid
   16952          30 : AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
   16953             : {
   16954          30 :     List       *relations = NIL;
   16955             :     ListCell   *l;
   16956             :     ScanKeyData key[1];
   16957             :     Relation    rel;
   16958             :     TableScanDesc scan;
   16959             :     HeapTuple   tuple;
   16960             :     Oid         orig_tablespaceoid;
   16961             :     Oid         new_tablespaceoid;
   16962          30 :     List       *role_oids = roleSpecsToIds(stmt->roles);
   16963             : 
   16964             :     /* Ensure we were not asked to move something we can't */
   16965          30 :     if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
   16966          12 :         stmt->objtype != OBJECT_MATVIEW)
   16967           0 :         ereport(ERROR,
   16968             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   16969             :                  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
   16970             : 
   16971             :     /* Get the orig and new tablespace OIDs */
   16972          30 :     orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
   16973          30 :     new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
   16974             : 
   16975             :     /* Can't move shared relations in to or out of pg_global */
   16976             :     /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
   16977          30 :     if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
   16978             :         new_tablespaceoid == GLOBALTABLESPACE_OID)
   16979           0 :         ereport(ERROR,
   16980             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   16981             :                  errmsg("cannot move relations in to or out of pg_global tablespace")));
   16982             : 
   16983             :     /*
   16984             :      * Must have CREATE rights on the new tablespace, unless it is the
   16985             :      * database default tablespace (which all users implicitly have CREATE
   16986             :      * rights on).
   16987             :      */
   16988          30 :     if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
   16989             :     {
   16990             :         AclResult   aclresult;
   16991             : 
   16992           0 :         aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
   16993             :                                     ACL_CREATE);
   16994           0 :         if (aclresult != ACLCHECK_OK)
   16995           0 :             aclcheck_error(aclresult, OBJECT_TABLESPACE,
   16996           0 :                            get_tablespace_name(new_tablespaceoid));
   16997             :     }
   16998             : 
   16999             :     /*
   17000             :      * Now that the checks are done, check if we should set either to
   17001             :      * InvalidOid because it is our database's default tablespace.
   17002             :      */
   17003          30 :     if (orig_tablespaceoid == MyDatabaseTableSpace)
   17004           0 :         orig_tablespaceoid = InvalidOid;
   17005             : 
   17006          30 :     if (new_tablespaceoid == MyDatabaseTableSpace)
   17007          30 :         new_tablespaceoid = InvalidOid;
   17008             : 
   17009             :     /* no-op */
   17010          30 :     if (orig_tablespaceoid == new_tablespaceoid)
   17011           0 :         return new_tablespaceoid;
   17012             : 
   17013             :     /*
   17014             :      * Walk the list of objects in the tablespace and move them. This will
   17015             :      * only find objects in our database, of course.
   17016             :      */
   17017          30 :     ScanKeyInit(&key[0],
   17018             :                 Anum_pg_class_reltablespace,
   17019             :                 BTEqualStrategyNumber, F_OIDEQ,
   17020             :                 ObjectIdGetDatum(orig_tablespaceoid));
   17021             : 
   17022          30 :     rel = table_open(RelationRelationId, AccessShareLock);
   17023          30 :     scan = table_beginscan_catalog(rel, 1, key);
   17024         132 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
   17025             :     {
   17026         102 :         Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
   17027         102 :         Oid         relOid = relForm->oid;
   17028             : 
   17029             :         /*
   17030             :          * Do not move objects in pg_catalog as part of this, if an admin
   17031             :          * really wishes to do so, they can issue the individual ALTER
   17032             :          * commands directly.
   17033             :          *
   17034             :          * Also, explicitly avoid any shared tables, temp tables, or TOAST
   17035             :          * (TOAST will be moved with the main table).
   17036             :          */
   17037         102 :         if (IsCatalogNamespace(relForm->relnamespace) ||
   17038         204 :             relForm->relisshared ||
   17039         204 :             isAnyTempNamespace(relForm->relnamespace) ||
   17040         102 :             IsToastNamespace(relForm->relnamespace))
   17041           0 :             continue;
   17042             : 
   17043             :         /* Only move the object type requested */
   17044         102 :         if ((stmt->objtype == OBJECT_TABLE &&
   17045          60 :              relForm->relkind != RELKIND_RELATION &&
   17046          36 :              relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
   17047          66 :             (stmt->objtype == OBJECT_INDEX &&
   17048          36 :              relForm->relkind != RELKIND_INDEX &&
   17049           6 :              relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
   17050          60 :             (stmt->objtype == OBJECT_MATVIEW &&
   17051           6 :              relForm->relkind != RELKIND_MATVIEW))
   17052          42 :             continue;
   17053             : 
   17054             :         /* Check if we are only moving objects owned by certain roles */
   17055          60 :         if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
   17056           0 :             continue;
   17057             : 
   17058             :         /*
   17059             :          * Handle permissions-checking here since we are locking the tables
   17060             :          * and also to avoid doing a bunch of work only to fail part-way. Note
   17061             :          * that permissions will also be checked by AlterTableInternal().
   17062             :          *
   17063             :          * Caller must be considered an owner on the table to move it.
   17064             :          */
   17065          60 :         if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
   17066           0 :             aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relOid)),
   17067           0 :                            NameStr(relForm->relname));
   17068             : 
   17069          60 :         if (stmt->nowait &&
   17070           0 :             !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
   17071           0 :             ereport(ERROR,
   17072             :                     (errcode(ERRCODE_OBJECT_IN_USE),
   17073             :                      errmsg("aborting because lock on relation \"%s.%s\" is not available",
   17074             :                             get_namespace_name(relForm->relnamespace),
   17075             :                             NameStr(relForm->relname))));
   17076             :         else
   17077          60 :             LockRelationOid(relOid, AccessExclusiveLock);
   17078             : 
   17079             :         /* Add to our list of objects to move */
   17080          60 :         relations = lappend_oid(relations, relOid);
   17081             :     }
   17082             : 
   17083          30 :     table_endscan(scan);
   17084          30 :     table_close(rel, AccessShareLock);
   17085             : 
   17086          30 :     if (relations == NIL)
   17087          12 :         ereport(NOTICE,
   17088             :                 (errcode(ERRCODE_NO_DATA_FOUND),
   17089             :                  errmsg("no matching relations in tablespace \"%s\" found",
   17090             :                         orig_tablespaceoid == InvalidOid ? "(database default)" :
   17091             :                         get_tablespace_name(orig_tablespaceoid))));
   17092             : 
   17093             :     /* Everything is locked, loop through and move all of the relations. */
   17094          90 :     foreach(l, relations)
   17095             :     {
   17096          60 :         List       *cmds = NIL;
   17097          60 :         AlterTableCmd *cmd = makeNode(AlterTableCmd);
   17098             : 
   17099          60 :         cmd->subtype = AT_SetTableSpace;
   17100          60 :         cmd->name = stmt->new_tablespacename;
   17101             : 
   17102          60 :         cmds = lappend(cmds, cmd);
   17103             : 
   17104          60 :         EventTriggerAlterTableStart((Node *) stmt);
   17105             :         /* OID is set by AlterTableInternal */
   17106          60 :         AlterTableInternal(lfirst_oid(l), cmds, false);
   17107          60 :         EventTriggerAlterTableEnd();
   17108             :     }
   17109             : 
   17110          30 :     return new_tablespaceoid;
   17111             : }
   17112             : 
   17113             : static void
   17114          62 : index_copy_data(Relation rel, RelFileLocator newrlocator)
   17115             : {
   17116             :     SMgrRelation dstrel;
   17117             : 
   17118             :     /*
   17119             :      * Since we copy the file directly without looking at the shared buffers,
   17120             :      * we'd better first flush out any pages of the source relation that are
   17121             :      * in shared buffers.  We assume no new changes will be made while we are
   17122             :      * holding exclusive lock on the rel.
   17123             :      */
   17124          62 :     FlushRelationBuffers(rel);
   17125             : 
   17126             :     /*
   17127             :      * Create and copy all forks of the relation, and schedule unlinking of
   17128             :      * old physical files.
   17129             :      *
   17130             :      * NOTE: any conflict in relfilenumber value will be caught in
   17131             :      * RelationCreateStorage().
   17132             :      */
   17133          62 :     dstrel = RelationCreateStorage(newrlocator, rel->rd_rel->relpersistence, true);
   17134             : 
   17135             :     /* copy main fork */
   17136          62 :     RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
   17137          62 :                         rel->rd_rel->relpersistence);
   17138             : 
   17139             :     /* copy those extra forks that exist */
   17140          62 :     for (ForkNumber forkNum = MAIN_FORKNUM + 1;
   17141         248 :          forkNum <= MAX_FORKNUM; forkNum++)
   17142             :     {
   17143         186 :         if (smgrexists(RelationGetSmgr(rel), forkNum))
   17144             :         {
   17145           0 :             smgrcreate(dstrel, forkNum, false);
   17146             : 
   17147             :             /*
   17148             :              * WAL log creation if the relation is persistent, or this is the
   17149             :              * init fork of an unlogged relation.
   17150             :              */
   17151           0 :             if (RelationIsPermanent(rel) ||
   17152           0 :                 (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
   17153             :                  forkNum == INIT_FORKNUM))
   17154           0 :                 log_smgrcreate(&newrlocator, forkNum);
   17155           0 :             RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
   17156           0 :                                 rel->rd_rel->relpersistence);
   17157             :         }
   17158             :     }
   17159             : 
   17160             :     /* drop old relation, and close new one */
   17161          62 :     RelationDropStorage(rel);
   17162          62 :     smgrclose(dstrel);
   17163          62 : }
   17164             : 
   17165             : /*
   17166             :  * ALTER TABLE ENABLE/DISABLE TRIGGER
   17167             :  *
   17168             :  * We just pass this off to trigger.c.
   17169             :  */
   17170             : static void
   17171         342 : ATExecEnableDisableTrigger(Relation rel, const char *trigname,
   17172             :                            char fires_when, bool skip_system, bool recurse,
   17173             :                            LOCKMODE lockmode)
   17174             : {
   17175         342 :     EnableDisableTrigger(rel, trigname, InvalidOid,
   17176             :                          fires_when, skip_system, recurse,
   17177             :                          lockmode);
   17178             : 
   17179         342 :     InvokeObjectPostAlterHook(RelationRelationId,
   17180             :                               RelationGetRelid(rel), 0);
   17181         342 : }
   17182             : 
   17183             : /*
   17184             :  * ALTER TABLE ENABLE/DISABLE RULE
   17185             :  *
   17186             :  * We just pass this off to rewriteDefine.c.
   17187             :  */
   17188             : static void
   17189          46 : ATExecEnableDisableRule(Relation rel, const char *rulename,
   17190             :                         char fires_when, LOCKMODE lockmode)
   17191             : {
   17192          46 :     EnableDisableRule(rel, rulename, fires_when);
   17193             : 
   17194          46 :     InvokeObjectPostAlterHook(RelationRelationId,
   17195             :                               RelationGetRelid(rel), 0);
   17196          46 : }
   17197             : 
   17198             : /*
   17199             :  * ALTER TABLE INHERIT
   17200             :  *
   17201             :  * Add a parent to the child's parents. This verifies that all the columns and
   17202             :  * check constraints of the parent appear in the child and that they have the
   17203             :  * same data types and expressions.
   17204             :  */
   17205             : static void
   17206         464 : ATPrepAddInherit(Relation child_rel)
   17207             : {
   17208         464 :     if (child_rel->rd_rel->reloftype)
   17209           6 :         ereport(ERROR,
   17210             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17211             :                  errmsg("cannot change inheritance of typed table")));
   17212             : 
   17213         458 :     if (child_rel->rd_rel->relispartition)
   17214           6 :         ereport(ERROR,
   17215             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17216             :                  errmsg("cannot change inheritance of a partition")));
   17217             : 
   17218         452 :     if (child_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   17219           6 :         ereport(ERROR,
   17220             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17221             :                  errmsg("cannot change inheritance of partitioned table")));
   17222         446 : }
   17223             : 
   17224             : /*
   17225             :  * Return the address of the new parent relation.
   17226             :  */
   17227             : static ObjectAddress
   17228         446 : ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
   17229             : {
   17230             :     Relation    parent_rel;
   17231             :     List       *children;
   17232             :     ObjectAddress address;
   17233             :     const char *trigger_name;
   17234             : 
   17235             :     /*
   17236             :      * A self-exclusive lock is needed here.  See the similar case in
   17237             :      * MergeAttributes() for a full explanation.
   17238             :      */
   17239         446 :     parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
   17240             : 
   17241             :     /*
   17242             :      * Must be owner of both parent and child -- child was checked by
   17243             :      * ATSimplePermissions call in ATPrepCmd
   17244             :      */
   17245         446 :     ATSimplePermissions(AT_AddInherit, parent_rel,
   17246             :                         ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
   17247             : 
   17248             :     /* Permanent rels cannot inherit from temporary ones */
   17249         446 :     if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
   17250           6 :         child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
   17251           0 :         ereport(ERROR,
   17252             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17253             :                  errmsg("cannot inherit from temporary relation \"%s\"",
   17254             :                         RelationGetRelationName(parent_rel))));
   17255             : 
   17256             :     /* If parent rel is temp, it must belong to this session */
   17257         446 :     if (RELATION_IS_OTHER_TEMP(parent_rel))
   17258           0 :         ereport(ERROR,
   17259             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17260             :                  errmsg("cannot inherit from temporary relation of another session")));
   17261             : 
   17262             :     /* Ditto for the child */
   17263         446 :     if (RELATION_IS_OTHER_TEMP(child_rel))
   17264           0 :         ereport(ERROR,
   17265             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17266             :                  errmsg("cannot inherit to temporary relation of another session")));
   17267             : 
   17268             :     /* Prevent partitioned tables from becoming inheritance parents */
   17269         446 :     if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   17270           6 :         ereport(ERROR,
   17271             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17272             :                  errmsg("cannot inherit from partitioned table \"%s\"",
   17273             :                         parent->relname)));
   17274             : 
   17275             :     /* Likewise for partitions */
   17276         440 :     if (parent_rel->rd_rel->relispartition)
   17277           6 :         ereport(ERROR,
   17278             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17279             :                  errmsg("cannot inherit from a partition")));
   17280             : 
   17281             :     /*
   17282             :      * Prevent circularity by seeing if proposed parent inherits from child.
   17283             :      * (In particular, this disallows making a rel inherit from itself.)
   17284             :      *
   17285             :      * This is not completely bulletproof because of race conditions: in
   17286             :      * multi-level inheritance trees, someone else could concurrently be
   17287             :      * making another inheritance link that closes the loop but does not join
   17288             :      * either of the rels we have locked.  Preventing that seems to require
   17289             :      * exclusive locks on the entire inheritance tree, which is a cure worse
   17290             :      * than the disease.  find_all_inheritors() will cope with circularity
   17291             :      * anyway, so don't sweat it too much.
   17292             :      *
   17293             :      * We use weakest lock we can on child's children, namely AccessShareLock.
   17294             :      */
   17295         434 :     children = find_all_inheritors(RelationGetRelid(child_rel),
   17296             :                                    AccessShareLock, NULL);
   17297             : 
   17298         434 :     if (list_member_oid(children, RelationGetRelid(parent_rel)))
   17299          12 :         ereport(ERROR,
   17300             :                 (errcode(ERRCODE_DUPLICATE_TABLE),
   17301             :                  errmsg("circular inheritance not allowed"),
   17302             :                  errdetail("\"%s\" is already a child of \"%s\".",
   17303             :                            parent->relname,
   17304             :                            RelationGetRelationName(child_rel))));
   17305             : 
   17306             :     /*
   17307             :      * If child_rel has row-level triggers with transition tables, we
   17308             :      * currently don't allow it to become an inheritance child.  See also
   17309             :      * prohibitions in ATExecAttachPartition() and CreateTrigger().
   17310             :      */
   17311         422 :     trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
   17312         422 :     if (trigger_name != NULL)
   17313           6 :         ereport(ERROR,
   17314             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   17315             :                  errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
   17316             :                         trigger_name, RelationGetRelationName(child_rel)),
   17317             :                  errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
   17318             : 
   17319             :     /* OK to create inheritance */
   17320         416 :     CreateInheritance(child_rel, parent_rel, false);
   17321             : 
   17322         326 :     ObjectAddressSet(address, RelationRelationId,
   17323             :                      RelationGetRelid(parent_rel));
   17324             : 
   17325             :     /* keep our lock on the parent relation until commit */
   17326         326 :     table_close(parent_rel, NoLock);
   17327             : 
   17328         326 :     return address;
   17329             : }
   17330             : 
   17331             : /*
   17332             :  * CreateInheritance
   17333             :  *      Catalog manipulation portion of creating inheritance between a child
   17334             :  *      table and a parent table.
   17335             :  *
   17336             :  * Common to ATExecAddInherit() and ATExecAttachPartition().
   17337             :  */
   17338             : static void
   17339        2666 : CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
   17340             : {
   17341             :     Relation    catalogRelation;
   17342             :     SysScanDesc scan;
   17343             :     ScanKeyData key;
   17344             :     HeapTuple   inheritsTuple;
   17345             :     int32       inhseqno;
   17346             : 
   17347             :     /* Note: get RowExclusiveLock because we will write pg_inherits below. */
   17348        2666 :     catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
   17349             : 
   17350             :     /*
   17351             :      * Check for duplicates in the list of parents, and determine the highest
   17352             :      * inhseqno already present; we'll use the next one for the new parent.
   17353             :      * Also, if proposed child is a partition, it cannot already be
   17354             :      * inheriting.
   17355             :      *
   17356             :      * Note: we do not reject the case where the child already inherits from
   17357             :      * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
   17358             :      */
   17359        2666 :     ScanKeyInit(&key,
   17360             :                 Anum_pg_inherits_inhrelid,
   17361             :                 BTEqualStrategyNumber, F_OIDEQ,
   17362             :                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
   17363        2666 :     scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
   17364             :                               true, NULL, 1, &key);
   17365             : 
   17366             :     /* inhseqno sequences start at 1 */
   17367        2666 :     inhseqno = 0;
   17368        2736 :     while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
   17369             :     {
   17370          76 :         Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
   17371             : 
   17372          76 :         if (inh->inhparent == RelationGetRelid(parent_rel))
   17373           6 :             ereport(ERROR,
   17374             :                     (errcode(ERRCODE_DUPLICATE_TABLE),
   17375             :                      errmsg("relation \"%s\" would be inherited from more than once",
   17376             :                             RelationGetRelationName(parent_rel))));
   17377             : 
   17378          70 :         if (inh->inhseqno > inhseqno)
   17379          70 :             inhseqno = inh->inhseqno;
   17380             :     }
   17381        2660 :     systable_endscan(scan);
   17382             : 
   17383             :     /* Match up the columns and bump attinhcount as needed */
   17384        2660 :     MergeAttributesIntoExisting(child_rel, parent_rel, ispartition);
   17385             : 
   17386             :     /* Match up the constraints and bump coninhcount as needed */
   17387        2528 :     MergeConstraintsIntoExisting(child_rel, parent_rel);
   17388             : 
   17389             :     /*
   17390             :      * OK, it looks valid.  Make the catalog entries that show inheritance.
   17391             :      */
   17392        2468 :     StoreCatalogInheritance1(RelationGetRelid(child_rel),
   17393             :                              RelationGetRelid(parent_rel),
   17394             :                              inhseqno + 1,
   17395             :                              catalogRelation,
   17396        2468 :                              parent_rel->rd_rel->relkind ==
   17397             :                              RELKIND_PARTITIONED_TABLE);
   17398             : 
   17399             :     /* Now we're done with pg_inherits */
   17400        2468 :     table_close(catalogRelation, RowExclusiveLock);
   17401        2468 : }
   17402             : 
   17403             : /*
   17404             :  * Obtain the source-text form of the constraint expression for a check
   17405             :  * constraint, given its pg_constraint tuple
   17406             :  */
   17407             : static char *
   17408         184 : decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
   17409             : {
   17410             :     Form_pg_constraint con;
   17411             :     bool        isnull;
   17412             :     Datum       attr;
   17413             :     Datum       expr;
   17414             : 
   17415         184 :     con = (Form_pg_constraint) GETSTRUCT(contup);
   17416         184 :     attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
   17417         184 :     if (isnull)
   17418           0 :         elog(ERROR, "null conbin for constraint %u", con->oid);
   17419             : 
   17420         184 :     expr = DirectFunctionCall2(pg_get_expr, attr,
   17421             :                                ObjectIdGetDatum(con->conrelid));
   17422         184 :     return TextDatumGetCString(expr);
   17423             : }
   17424             : 
   17425             : /*
   17426             :  * Determine whether two check constraints are functionally equivalent
   17427             :  *
   17428             :  * The test we apply is to see whether they reverse-compile to the same
   17429             :  * source string.  This insulates us from issues like whether attributes
   17430             :  * have the same physical column numbers in parent and child relations.
   17431             :  *
   17432             :  * Note that we ignore enforceability as there are cases where constraints
   17433             :  * with differing enforceability are allowed.
   17434             :  */
   17435             : static bool
   17436          92 : constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
   17437             : {
   17438          92 :     Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
   17439          92 :     Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
   17440             : 
   17441          92 :     if (acon->condeferrable != bcon->condeferrable ||
   17442          92 :         acon->condeferred != bcon->condeferred ||
   17443          92 :         strcmp(decompile_conbin(a, tupleDesc),
   17444          92 :                decompile_conbin(b, tupleDesc)) != 0)
   17445           6 :         return false;
   17446             :     else
   17447          86 :         return true;
   17448             : }
   17449             : 
   17450             : /*
   17451             :  * Check columns in child table match up with columns in parent, and increment
   17452             :  * their attinhcount.
   17453             :  *
   17454             :  * Called by CreateInheritance
   17455             :  *
   17456             :  * Currently all parent columns must be found in child. Missing columns are an
   17457             :  * error.  One day we might consider creating new columns like CREATE TABLE
   17458             :  * does.  However, that is widely unpopular --- in the common use case of
   17459             :  * partitioned tables it's a foot-gun.
   17460             :  *
   17461             :  * The data type must match exactly. If the parent column is NOT NULL then
   17462             :  * the child must be as well. Defaults are not compared, however.
   17463             :  */
   17464             : static void
   17465        2660 : MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition)
   17466             : {
   17467             :     Relation    attrrel;
   17468             :     TupleDesc   parent_desc;
   17469             : 
   17470        2660 :     attrrel = table_open(AttributeRelationId, RowExclusiveLock);
   17471        2660 :     parent_desc = RelationGetDescr(parent_rel);
   17472             : 
   17473        8486 :     for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++)
   17474             :     {
   17475        5958 :         Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1);
   17476        5958 :         char       *parent_attname = NameStr(parent_att->attname);
   17477             :         HeapTuple   tuple;
   17478             : 
   17479             :         /* Ignore dropped columns in the parent. */
   17480        5958 :         if (parent_att->attisdropped)
   17481         296 :             continue;
   17482             : 
   17483             :         /* Find same column in child (matching on column name). */
   17484        5662 :         tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel), parent_attname);
   17485        5662 :         if (HeapTupleIsValid(tuple))
   17486             :         {
   17487        5650 :             Form_pg_attribute child_att = (Form_pg_attribute) GETSTRUCT(tuple);
   17488             : 
   17489        5650 :             if (parent_att->atttypid != child_att->atttypid ||
   17490        5644 :                 parent_att->atttypmod != child_att->atttypmod)
   17491          12 :                 ereport(ERROR,
   17492             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17493             :                          errmsg("child table \"%s\" has different type for column \"%s\"",
   17494             :                                 RelationGetRelationName(child_rel), parent_attname)));
   17495             : 
   17496        5638 :             if (parent_att->attcollation != child_att->attcollation)
   17497           6 :                 ereport(ERROR,
   17498             :                         (errcode(ERRCODE_COLLATION_MISMATCH),
   17499             :                          errmsg("child table \"%s\" has different collation for column \"%s\"",
   17500             :                                 RelationGetRelationName(child_rel), parent_attname)));
   17501             : 
   17502             :             /*
   17503             :              * If the parent has a not-null constraint that's not NO INHERIT,
   17504             :              * make sure the child has one too.
   17505             :              *
   17506             :              * Other constraints are checked elsewhere.
   17507             :              */
   17508        5632 :             if (parent_att->attnotnull && !child_att->attnotnull)
   17509             :             {
   17510             :                 HeapTuple   contup;
   17511             : 
   17512          48 :                 contup = findNotNullConstraintAttnum(RelationGetRelid(parent_rel),
   17513          48 :                                                      parent_att->attnum);
   17514          48 :                 if (HeapTupleIsValid(contup) &&
   17515          48 :                     !((Form_pg_constraint) GETSTRUCT(contup))->connoinherit)
   17516          30 :                     ereport(ERROR,
   17517             :                             errcode(ERRCODE_DATATYPE_MISMATCH),
   17518             :                             errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
   17519             :                                    parent_attname, RelationGetRelationName(child_rel)));
   17520             :             }
   17521             : 
   17522             :             /*
   17523             :              * Child column must be generated if and only if parent column is.
   17524             :              */
   17525        5602 :             if (parent_att->attgenerated && !child_att->attgenerated)
   17526          36 :                 ereport(ERROR,
   17527             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17528             :                          errmsg("column \"%s\" in child table must be a generated column", parent_attname)));
   17529        5566 :             if (child_att->attgenerated && !parent_att->attgenerated)
   17530          24 :                 ereport(ERROR,
   17531             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17532             :                          errmsg("column \"%s\" in child table must not be a generated column", parent_attname)));
   17533             : 
   17534        5542 :             if (parent_att->attgenerated && child_att->attgenerated && child_att->attgenerated != parent_att->attgenerated)
   17535          12 :                 ereport(ERROR,
   17536             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17537             :                          errmsg("column \"%s\" inherits from generated column of different kind", parent_attname),
   17538             :                          errdetail("Parent column is %s, child column is %s.",
   17539             :                                    parent_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
   17540             :                                    child_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
   17541             : 
   17542             :             /*
   17543             :              * Regular inheritance children are independent enough not to
   17544             :              * inherit identity columns.  But partitions are integral part of
   17545             :              * a partitioned table and inherit identity column.
   17546             :              */
   17547        5530 :             if (ispartition)
   17548        4802 :                 child_att->attidentity = parent_att->attidentity;
   17549             : 
   17550             :             /*
   17551             :              * OK, bump the child column's inheritance count.  (If we fail
   17552             :              * later on, this change will just roll back.)
   17553             :              */
   17554        5530 :             if (pg_add_s16_overflow(child_att->attinhcount, 1,
   17555             :                                     &child_att->attinhcount))
   17556           0 :                 ereport(ERROR,
   17557             :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
   17558             :                         errmsg("too many inheritance parents"));
   17559             : 
   17560             :             /*
   17561             :              * In case of partitions, we must enforce that value of attislocal
   17562             :              * is same in all partitions. (Note: there are only inherited
   17563             :              * attributes in partitions)
   17564             :              */
   17565        5530 :             if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   17566             :             {
   17567             :                 Assert(child_att->attinhcount == 1);
   17568        4802 :                 child_att->attislocal = false;
   17569             :             }
   17570             : 
   17571        5530 :             CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
   17572        5530 :             heap_freetuple(tuple);
   17573             :         }
   17574             :         else
   17575             :         {
   17576          12 :             ereport(ERROR,
   17577             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   17578             :                      errmsg("child table is missing column \"%s\"", parent_attname)));
   17579             :         }
   17580             :     }
   17581             : 
   17582        2528 :     table_close(attrrel, RowExclusiveLock);
   17583        2528 : }
   17584             : 
   17585             : /*
   17586             :  * Check constraints in child table match up with constraints in parent,
   17587             :  * and increment their coninhcount.
   17588             :  *
   17589             :  * Constraints that are marked ONLY in the parent are ignored.
   17590             :  *
   17591             :  * Called by CreateInheritance
   17592             :  *
   17593             :  * Currently all constraints in parent must be present in the child. One day we
   17594             :  * may consider adding new constraints like CREATE TABLE does.
   17595             :  *
   17596             :  * XXX This is O(N^2) which may be an issue with tables with hundreds of
   17597             :  * constraints. As long as tables have more like 10 constraints it shouldn't be
   17598             :  * a problem though. Even 100 constraints ought not be the end of the world.
   17599             :  *
   17600             :  * XXX See MergeWithExistingConstraint too if you change this code.
   17601             :  */
   17602             : static void
   17603        2528 : MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
   17604             : {
   17605             :     Relation    constraintrel;
   17606             :     SysScanDesc parent_scan;
   17607             :     ScanKeyData parent_key;
   17608             :     HeapTuple   parent_tuple;
   17609        2528 :     Oid         parent_relid = RelationGetRelid(parent_rel);
   17610             :     AttrMap    *attmap;
   17611             : 
   17612        2528 :     constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
   17613             : 
   17614             :     /* Outer loop scans through the parent's constraint definitions */
   17615        2528 :     ScanKeyInit(&parent_key,
   17616             :                 Anum_pg_constraint_conrelid,
   17617             :                 BTEqualStrategyNumber, F_OIDEQ,
   17618             :                 ObjectIdGetDatum(parent_relid));
   17619        2528 :     parent_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
   17620             :                                      true, NULL, 1, &parent_key);
   17621             : 
   17622        2528 :     attmap = build_attrmap_by_name(RelationGetDescr(parent_rel),
   17623             :                                    RelationGetDescr(child_rel),
   17624             :                                    true);
   17625             : 
   17626        4478 :     while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
   17627             :     {
   17628        2010 :         Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
   17629             :         SysScanDesc child_scan;
   17630             :         ScanKeyData child_key;
   17631             :         HeapTuple   child_tuple;
   17632             :         AttrNumber  parent_attno;
   17633        2010 :         bool        found = false;
   17634             : 
   17635        2010 :         if (parent_con->contype != CONSTRAINT_CHECK &&
   17636        1874 :             parent_con->contype != CONSTRAINT_NOTNULL)
   17637         994 :             continue;
   17638             : 
   17639             :         /* if the parent's constraint is marked NO INHERIT, it's not inherited */
   17640        1060 :         if (parent_con->connoinherit)
   17641          44 :             continue;
   17642             : 
   17643        1016 :         if (parent_con->contype == CONSTRAINT_NOTNULL)
   17644         900 :             parent_attno = extractNotNullColumn(parent_tuple);
   17645             :         else
   17646         116 :             parent_attno = InvalidAttrNumber;
   17647             : 
   17648             :         /* Search for a child constraint matching this one */
   17649        1016 :         ScanKeyInit(&child_key,
   17650             :                     Anum_pg_constraint_conrelid,
   17651             :                     BTEqualStrategyNumber, F_OIDEQ,
   17652             :                     ObjectIdGetDatum(RelationGetRelid(child_rel)));
   17653        1016 :         child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
   17654             :                                         true, NULL, 1, &child_key);
   17655             : 
   17656        1594 :         while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
   17657             :         {
   17658        1570 :             Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
   17659             :             HeapTuple   child_copy;
   17660             : 
   17661        1570 :             if (child_con->contype != parent_con->contype)
   17662         280 :                 continue;
   17663             : 
   17664             :             /*
   17665             :              * CHECK constraint are matched by constraint name, NOT NULL ones
   17666             :              * by attribute number.
   17667             :              */
   17668        1290 :             if (child_con->contype == CONSTRAINT_CHECK)
   17669             :             {
   17670         152 :                 if (strcmp(NameStr(parent_con->conname),
   17671         122 :                            NameStr(child_con->conname)) != 0)
   17672          30 :                     continue;
   17673             :             }
   17674        1168 :             else if (child_con->contype == CONSTRAINT_NOTNULL)
   17675             :             {
   17676             :                 Form_pg_attribute parent_attr;
   17677             :                 Form_pg_attribute child_attr;
   17678             :                 AttrNumber  child_attno;
   17679             : 
   17680        1168 :                 parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
   17681        1168 :                 child_attno = extractNotNullColumn(child_tuple);
   17682        1168 :                 if (parent_attno != attmap->attnums[child_attno - 1])
   17683         268 :                     continue;
   17684             : 
   17685         900 :                 child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
   17686             :                 /* there shouldn't be constraints on dropped columns */
   17687         900 :                 if (parent_attr->attisdropped || child_attr->attisdropped)
   17688           0 :                     elog(ERROR, "found not-null constraint on dropped columns");
   17689             :             }
   17690             : 
   17691         992 :             if (child_con->contype == CONSTRAINT_CHECK &&
   17692          92 :                 !constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
   17693           6 :                 ereport(ERROR,
   17694             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   17695             :                          errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
   17696             :                                 RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
   17697             : 
   17698             :             /*
   17699             :              * If the child constraint is "no inherit" then cannot merge
   17700             :              */
   17701         986 :             if (child_con->connoinherit)
   17702          12 :                 ereport(ERROR,
   17703             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   17704             :                          errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
   17705             :                                 NameStr(child_con->conname), RelationGetRelationName(child_rel))));
   17706             : 
   17707             :             /*
   17708             :              * If the child constraint is "not valid" then cannot merge with a
   17709             :              * valid parent constraint
   17710             :              */
   17711         974 :             if (parent_con->convalidated && child_con->conenforced &&
   17712         920 :                 !child_con->convalidated)
   17713          12 :                 ereport(ERROR,
   17714             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   17715             :                          errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
   17716             :                                 NameStr(child_con->conname), RelationGetRelationName(child_rel))));
   17717             : 
   17718             :             /*
   17719             :              * A NOT ENFORCED child constraint cannot be merged with an
   17720             :              * ENFORCED parent constraint. However, the reverse is allowed,
   17721             :              * where the child constraint is ENFORCED.
   17722             :              */
   17723         962 :             if (parent_con->conenforced && !child_con->conenforced)
   17724           6 :                 ereport(ERROR,
   17725             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   17726             :                          errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
   17727             :                                 NameStr(child_con->conname), RelationGetRelationName(child_rel))));
   17728             : 
   17729             :             /*
   17730             :              * OK, bump the child constraint's inheritance count.  (If we fail
   17731             :              * later on, this change will just roll back.)
   17732             :              */
   17733         956 :             child_copy = heap_copytuple(child_tuple);
   17734         956 :             child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
   17735             : 
   17736         956 :             if (pg_add_s16_overflow(child_con->coninhcount, 1,
   17737             :                                     &child_con->coninhcount))
   17738           0 :                 ereport(ERROR,
   17739             :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
   17740             :                         errmsg("too many inheritance parents"));
   17741             : 
   17742             :             /*
   17743             :              * In case of partitions, an inherited constraint must be
   17744             :              * inherited only once since it cannot have multiple parents and
   17745             :              * it is never considered local.
   17746             :              */
   17747         956 :             if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   17748             :             {
   17749             :                 Assert(child_con->coninhcount == 1);
   17750         808 :                 child_con->conislocal = false;
   17751             :             }
   17752             : 
   17753         956 :             CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
   17754         956 :             heap_freetuple(child_copy);
   17755             : 
   17756         956 :             found = true;
   17757         956 :             break;
   17758             :         }
   17759             : 
   17760         980 :         systable_endscan(child_scan);
   17761             : 
   17762         980 :         if (!found)
   17763             :         {
   17764          24 :             if (parent_con->contype == CONSTRAINT_NOTNULL)
   17765           0 :                 ereport(ERROR,
   17766             :                         errcode(ERRCODE_DATATYPE_MISMATCH),
   17767             :                         errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
   17768             :                                get_attname(parent_relid,
   17769             :                                            extractNotNullColumn(parent_tuple),
   17770             :                                            false),
   17771             :                                RelationGetRelationName(child_rel)));
   17772             : 
   17773          24 :             ereport(ERROR,
   17774             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   17775             :                      errmsg("child table is missing constraint \"%s\"",
   17776             :                             NameStr(parent_con->conname))));
   17777             :         }
   17778             :     }
   17779             : 
   17780        2468 :     systable_endscan(parent_scan);
   17781        2468 :     table_close(constraintrel, RowExclusiveLock);
   17782        2468 : }
   17783             : 
   17784             : /*
   17785             :  * ALTER TABLE NO INHERIT
   17786             :  *
   17787             :  * Return value is the address of the relation that is no longer parent.
   17788             :  */
   17789             : static ObjectAddress
   17790          94 : ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
   17791             : {
   17792             :     ObjectAddress address;
   17793             :     Relation    parent_rel;
   17794             : 
   17795          94 :     if (rel->rd_rel->relispartition)
   17796           0 :         ereport(ERROR,
   17797             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   17798             :                  errmsg("cannot change inheritance of a partition")));
   17799             : 
   17800             :     /*
   17801             :      * AccessShareLock on the parent is probably enough, seeing that DROP
   17802             :      * TABLE doesn't lock parent tables at all.  We need some lock since we'll
   17803             :      * be inspecting the parent's schema.
   17804             :      */
   17805          94 :     parent_rel = table_openrv(parent, AccessShareLock);
   17806             : 
   17807             :     /*
   17808             :      * We don't bother to check ownership of the parent table --- ownership of
   17809             :      * the child is presumed enough rights.
   17810             :      */
   17811             : 
   17812             :     /* Off to RemoveInheritance() where most of the work happens */
   17813          94 :     RemoveInheritance(rel, parent_rel, false);
   17814             : 
   17815          88 :     ObjectAddressSet(address, RelationRelationId,
   17816             :                      RelationGetRelid(parent_rel));
   17817             : 
   17818             :     /* keep our lock on the parent relation until commit */
   17819          88 :     table_close(parent_rel, NoLock);
   17820             : 
   17821          88 :     return address;
   17822             : }
   17823             : 
   17824             : /*
   17825             :  * MarkInheritDetached
   17826             :  *
   17827             :  * Set inhdetachpending for a partition, for ATExecDetachPartition
   17828             :  * in concurrent mode.  While at it, verify that no other partition is
   17829             :  * already pending detach.
   17830             :  */
   17831             : static void
   17832         146 : MarkInheritDetached(Relation child_rel, Relation parent_rel)
   17833             : {
   17834             :     Relation    catalogRelation;
   17835             :     SysScanDesc scan;
   17836             :     ScanKeyData key;
   17837             :     HeapTuple   inheritsTuple;
   17838         146 :     bool        found = false;
   17839             : 
   17840             :     Assert(parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
   17841             : 
   17842             :     /*
   17843             :      * Find pg_inherits entries by inhparent.  (We need to scan them all in
   17844             :      * order to verify that no other partition is pending detach.)
   17845             :      */
   17846         146 :     catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
   17847         146 :     ScanKeyInit(&key,
   17848             :                 Anum_pg_inherits_inhparent,
   17849             :                 BTEqualStrategyNumber, F_OIDEQ,
   17850             :                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
   17851         146 :     scan = systable_beginscan(catalogRelation, InheritsParentIndexId,
   17852             :                               true, NULL, 1, &key);
   17853             : 
   17854         576 :     while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
   17855             :     {
   17856             :         Form_pg_inherits inhForm;
   17857             : 
   17858         286 :         inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
   17859         286 :         if (inhForm->inhdetachpending)
   17860           2 :             ereport(ERROR,
   17861             :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   17862             :                     errmsg("partition \"%s\" already pending detach in partitioned table \"%s.%s\"",
   17863             :                            get_rel_name(inhForm->inhrelid),
   17864             :                            get_namespace_name(parent_rel->rd_rel->relnamespace),
   17865             :                            RelationGetRelationName(parent_rel)),
   17866             :                     errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
   17867             : 
   17868         284 :         if (inhForm->inhrelid == RelationGetRelid(child_rel))
   17869             :         {
   17870             :             HeapTuple   newtup;
   17871             : 
   17872         144 :             newtup = heap_copytuple(inheritsTuple);
   17873         144 :             ((Form_pg_inherits) GETSTRUCT(newtup))->inhdetachpending = true;
   17874             : 
   17875         144 :             CatalogTupleUpdate(catalogRelation,
   17876         144 :                                &inheritsTuple->t_self,
   17877             :                                newtup);
   17878         144 :             found = true;
   17879         144 :             heap_freetuple(newtup);
   17880             :             /* keep looking, to ensure we catch others pending detach */
   17881             :         }
   17882             :     }
   17883             : 
   17884             :     /* Done */
   17885         144 :     systable_endscan(scan);
   17886         144 :     table_close(catalogRelation, RowExclusiveLock);
   17887             : 
   17888         144 :     if (!found)
   17889           0 :         ereport(ERROR,
   17890             :                 (errcode(ERRCODE_UNDEFINED_TABLE),
   17891             :                  errmsg("relation \"%s\" is not a partition of relation \"%s\"",
   17892             :                         RelationGetRelationName(child_rel),
   17893             :                         RelationGetRelationName(parent_rel))));
   17894         144 : }
   17895             : 
   17896             : /*
   17897             :  * RemoveInheritance
   17898             :  *
   17899             :  * Drop a parent from the child's parents. This just adjusts the attinhcount
   17900             :  * and attislocal of the columns and removes the pg_inherit and pg_depend
   17901             :  * entries.  expect_detached is passed down to DeleteInheritsTuple, q.v..
   17902             :  *
   17903             :  * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
   17904             :  * up attislocal stays true, which means if a child is ever removed from a
   17905             :  * parent then its columns will never be automatically dropped which may
   17906             :  * surprise. But at least we'll never surprise by dropping columns someone
   17907             :  * isn't expecting to be dropped which would actually mean data loss.
   17908             :  *
   17909             :  * coninhcount and conislocal for inherited constraints are adjusted in
   17910             :  * exactly the same way.
   17911             :  *
   17912             :  * Common to ATExecDropInherit() and ATExecDetachPartition().
   17913             :  */
   17914             : static void
   17915         606 : RemoveInheritance(Relation child_rel, Relation parent_rel, bool expect_detached)
   17916             : {
   17917             :     Relation    catalogRelation;
   17918             :     SysScanDesc scan;
   17919             :     ScanKeyData key[3];
   17920             :     HeapTuple   attributeTuple,
   17921             :                 constraintTuple;
   17922             :     AttrMap    *attmap;
   17923             :     List       *connames;
   17924             :     List       *nncolumns;
   17925             :     bool        found;
   17926             :     bool        is_partitioning;
   17927             : 
   17928         606 :     is_partitioning = (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
   17929             : 
   17930         606 :     found = DeleteInheritsTuple(RelationGetRelid(child_rel),
   17931             :                                 RelationGetRelid(parent_rel),
   17932             :                                 expect_detached,
   17933         606 :                                 RelationGetRelationName(child_rel));
   17934         606 :     if (!found)
   17935             :     {
   17936          24 :         if (is_partitioning)
   17937          18 :             ereport(ERROR,
   17938             :                     (errcode(ERRCODE_UNDEFINED_TABLE),
   17939             :                      errmsg("relation \"%s\" is not a partition of relation \"%s\"",
   17940             :                             RelationGetRelationName(child_rel),
   17941             :                             RelationGetRelationName(parent_rel))));
   17942             :         else
   17943           6 :             ereport(ERROR,
   17944             :                     (errcode(ERRCODE_UNDEFINED_TABLE),
   17945             :                      errmsg("relation \"%s\" is not a parent of relation \"%s\"",
   17946             :                             RelationGetRelationName(parent_rel),
   17947             :                             RelationGetRelationName(child_rel))));
   17948             :     }
   17949             : 
   17950             :     /*
   17951             :      * Search through child columns looking for ones matching parent rel
   17952             :      */
   17953         582 :     catalogRelation = table_open(AttributeRelationId, RowExclusiveLock);
   17954         582 :     ScanKeyInit(&key[0],
   17955             :                 Anum_pg_attribute_attrelid,
   17956             :                 BTEqualStrategyNumber, F_OIDEQ,
   17957             :                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
   17958         582 :     scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
   17959             :                               true, NULL, 1, key);
   17960        5198 :     while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
   17961             :     {
   17962        4616 :         Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
   17963             : 
   17964             :         /* Ignore if dropped or not inherited */
   17965        4616 :         if (att->attisdropped)
   17966           6 :             continue;
   17967        4610 :         if (att->attinhcount <= 0)
   17968        3522 :             continue;
   17969             : 
   17970        1088 :         if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
   17971        1088 :                                         NameStr(att->attname)))
   17972             :         {
   17973             :             /* Decrement inhcount and possibly set islocal to true */
   17974        1034 :             HeapTuple   copyTuple = heap_copytuple(attributeTuple);
   17975        1034 :             Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
   17976             : 
   17977        1034 :             copy_att->attinhcount--;
   17978        1034 :             if (copy_att->attinhcount == 0)
   17979        1004 :                 copy_att->attislocal = true;
   17980             : 
   17981        1034 :             CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
   17982        1034 :             heap_freetuple(copyTuple);
   17983             :         }
   17984             :     }
   17985         582 :     systable_endscan(scan);
   17986         582 :     table_close(catalogRelation, RowExclusiveLock);
   17987             : 
   17988             :     /*
   17989             :      * Likewise, find inherited check and not-null constraints and disinherit
   17990             :      * them. To do this, we first need a list of the names of the parent's
   17991             :      * check constraints.  (We cheat a bit by only checking for name matches,
   17992             :      * assuming that the expressions will match.)
   17993             :      *
   17994             :      * For NOT NULL columns, we store column numbers to match, mapping them in
   17995             :      * to the child rel's attribute numbers.
   17996             :      */
   17997         582 :     attmap = build_attrmap_by_name(RelationGetDescr(child_rel),
   17998             :                                    RelationGetDescr(parent_rel),
   17999             :                                    false);
   18000             : 
   18001         582 :     catalogRelation = table_open(ConstraintRelationId, RowExclusiveLock);
   18002         582 :     ScanKeyInit(&key[0],
   18003             :                 Anum_pg_constraint_conrelid,
   18004             :                 BTEqualStrategyNumber, F_OIDEQ,
   18005             :                 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
   18006         582 :     scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
   18007             :                               true, NULL, 1, key);
   18008             : 
   18009         582 :     connames = NIL;
   18010         582 :     nncolumns = NIL;
   18011             : 
   18012        1236 :     while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
   18013             :     {
   18014         654 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
   18015             : 
   18016         654 :         if (con->connoinherit)
   18017         110 :             continue;
   18018             : 
   18019         544 :         if (con->contype == CONSTRAINT_CHECK)
   18020          12 :             connames = lappend(connames, pstrdup(NameStr(con->conname)));
   18021         544 :         if (con->contype == CONSTRAINT_NOTNULL)
   18022             :         {
   18023         208 :             AttrNumber  parent_attno = extractNotNullColumn(constraintTuple);
   18024             : 
   18025         208 :             nncolumns = lappend_int(nncolumns, attmap->attnums[parent_attno - 1]);
   18026             :         }
   18027             :     }
   18028             : 
   18029         582 :     systable_endscan(scan);
   18030             : 
   18031             :     /* Now scan the child's constraints to find matches */
   18032         582 :     ScanKeyInit(&key[0],
   18033             :                 Anum_pg_constraint_conrelid,
   18034             :                 BTEqualStrategyNumber, F_OIDEQ,
   18035             :                 ObjectIdGetDatum(RelationGetRelid(child_rel)));
   18036         582 :     scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
   18037             :                               true, NULL, 1, key);
   18038             : 
   18039        1232 :     while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
   18040             :     {
   18041         650 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
   18042         650 :         bool        match = false;
   18043             : 
   18044             :         /*
   18045             :          * Match CHECK constraints by name, not-null constraints by column
   18046             :          * number, and ignore all others.
   18047             :          */
   18048         650 :         if (con->contype == CONSTRAINT_CHECK)
   18049             :         {
   18050         142 :             foreach_ptr(char, chkname, connames)
   18051             :             {
   18052          18 :                 if (con->contype == CONSTRAINT_CHECK &&
   18053          18 :                     strcmp(NameStr(con->conname), chkname) == 0)
   18054             :                 {
   18055          12 :                     match = true;
   18056          12 :                     connames = foreach_delete_current(connames, chkname);
   18057          12 :                     break;
   18058             :                 }
   18059             :             }
   18060             :         }
   18061         582 :         else if (con->contype == CONSTRAINT_NOTNULL)
   18062             :         {
   18063         268 :             AttrNumber  child_attno = extractNotNullColumn(constraintTuple);
   18064             : 
   18065         542 :             foreach_int(prevattno, nncolumns)
   18066             :             {
   18067         214 :                 if (prevattno == child_attno)
   18068             :                 {
   18069         208 :                     match = true;
   18070         208 :                     nncolumns = foreach_delete_current(nncolumns, prevattno);
   18071         208 :                     break;
   18072             :                 }
   18073             :             }
   18074             :         }
   18075             :         else
   18076         314 :             continue;
   18077             : 
   18078         336 :         if (match)
   18079             :         {
   18080             :             /* Decrement inhcount and possibly set islocal to true */
   18081         220 :             HeapTuple   copyTuple = heap_copytuple(constraintTuple);
   18082         220 :             Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
   18083             : 
   18084         220 :             if (copy_con->coninhcount <= 0) /* shouldn't happen */
   18085           0 :                 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
   18086             :                      RelationGetRelid(child_rel), NameStr(copy_con->conname));
   18087             : 
   18088         220 :             copy_con->coninhcount--;
   18089         220 :             if (copy_con->coninhcount == 0)
   18090         202 :                 copy_con->conislocal = true;
   18091             : 
   18092         220 :             CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
   18093         220 :             heap_freetuple(copyTuple);
   18094             :         }
   18095             :     }
   18096             : 
   18097             :     /* We should have matched all constraints */
   18098         582 :     if (connames != NIL || nncolumns != NIL)
   18099           0 :         elog(ERROR, "%d unmatched constraints while removing inheritance from \"%s\" to \"%s\"",
   18100             :              list_length(connames) + list_length(nncolumns),
   18101             :              RelationGetRelationName(child_rel), RelationGetRelationName(parent_rel));
   18102             : 
   18103         582 :     systable_endscan(scan);
   18104         582 :     table_close(catalogRelation, RowExclusiveLock);
   18105             : 
   18106         582 :     drop_parent_dependency(RelationGetRelid(child_rel),
   18107             :                            RelationRelationId,
   18108             :                            RelationGetRelid(parent_rel),
   18109             :                            child_dependency_type(is_partitioning));
   18110             : 
   18111             :     /*
   18112             :      * Post alter hook of this inherits. Since object_access_hook doesn't take
   18113             :      * multiple object identifiers, we relay oid of parent relation using
   18114             :      * auxiliary_id argument.
   18115             :      */
   18116         582 :     InvokeObjectPostAlterHookArg(InheritsRelationId,
   18117             :                                  RelationGetRelid(child_rel), 0,
   18118             :                                  RelationGetRelid(parent_rel), false);
   18119         582 : }
   18120             : 
   18121             : /*
   18122             :  * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
   18123             :  * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
   18124             :  * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
   18125             :  * be TypeRelationId).  There's no convenient way to do this, so go trawling
   18126             :  * through pg_depend.
   18127             :  */
   18128             : static void
   18129         594 : drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
   18130             :                        DependencyType deptype)
   18131             : {
   18132             :     Relation    catalogRelation;
   18133             :     SysScanDesc scan;
   18134             :     ScanKeyData key[3];
   18135             :     HeapTuple   depTuple;
   18136             : 
   18137         594 :     catalogRelation = table_open(DependRelationId, RowExclusiveLock);
   18138             : 
   18139         594 :     ScanKeyInit(&key[0],
   18140             :                 Anum_pg_depend_classid,
   18141             :                 BTEqualStrategyNumber, F_OIDEQ,
   18142             :                 ObjectIdGetDatum(RelationRelationId));
   18143         594 :     ScanKeyInit(&key[1],
   18144             :                 Anum_pg_depend_objid,
   18145             :                 BTEqualStrategyNumber, F_OIDEQ,
   18146             :                 ObjectIdGetDatum(relid));
   18147         594 :     ScanKeyInit(&key[2],
   18148             :                 Anum_pg_depend_objsubid,
   18149             :                 BTEqualStrategyNumber, F_INT4EQ,
   18150             :                 Int32GetDatum(0));
   18151             : 
   18152         594 :     scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
   18153             :                               NULL, 3, key);
   18154             : 
   18155        1846 :     while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
   18156             :     {
   18157        1252 :         Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
   18158             : 
   18159        1252 :         if (dep->refclassid == refclassid &&
   18160         636 :             dep->refobjid == refobjid &&
   18161         594 :             dep->refobjsubid == 0 &&
   18162         594 :             dep->deptype == deptype)
   18163         594 :             CatalogTupleDelete(catalogRelation, &depTuple->t_self);
   18164             :     }
   18165             : 
   18166         594 :     systable_endscan(scan);
   18167         594 :     table_close(catalogRelation, RowExclusiveLock);
   18168         594 : }
   18169             : 
   18170             : /*
   18171             :  * ALTER TABLE OF
   18172             :  *
   18173             :  * Attach a table to a composite type, as though it had been created with CREATE
   18174             :  * TABLE OF.  All attname, atttypid, atttypmod and attcollation must match.  The
   18175             :  * subject table must not have inheritance parents.  These restrictions ensure
   18176             :  * that you cannot create a configuration impossible with CREATE TABLE OF alone.
   18177             :  *
   18178             :  * The address of the type is returned.
   18179             :  */
   18180             : static ObjectAddress
   18181          66 : ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
   18182             : {
   18183          66 :     Oid         relid = RelationGetRelid(rel);
   18184             :     Type        typetuple;
   18185             :     Form_pg_type typeform;
   18186             :     Oid         typeid;
   18187             :     Relation    inheritsRelation,
   18188             :                 relationRelation;
   18189             :     SysScanDesc scan;
   18190             :     ScanKeyData key;
   18191             :     AttrNumber  table_attno,
   18192             :                 type_attno;
   18193             :     TupleDesc   typeTupleDesc,
   18194             :                 tableTupleDesc;
   18195             :     ObjectAddress tableobj,
   18196             :                 typeobj;
   18197             :     HeapTuple   classtuple;
   18198             : 
   18199             :     /* Validate the type. */
   18200          66 :     typetuple = typenameType(NULL, ofTypename, NULL);
   18201          66 :     check_of_type(typetuple);
   18202          66 :     typeform = (Form_pg_type) GETSTRUCT(typetuple);
   18203          66 :     typeid = typeform->oid;
   18204             : 
   18205             :     /* Fail if the table has any inheritance parents. */
   18206          66 :     inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
   18207          66 :     ScanKeyInit(&key,
   18208             :                 Anum_pg_inherits_inhrelid,
   18209             :                 BTEqualStrategyNumber, F_OIDEQ,
   18210             :                 ObjectIdGetDatum(relid));
   18211          66 :     scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
   18212             :                               true, NULL, 1, &key);
   18213          66 :     if (HeapTupleIsValid(systable_getnext(scan)))
   18214           6 :         ereport(ERROR,
   18215             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18216             :                  errmsg("typed tables cannot inherit")));
   18217          60 :     systable_endscan(scan);
   18218          60 :     table_close(inheritsRelation, AccessShareLock);
   18219             : 
   18220             :     /*
   18221             :      * Check the tuple descriptors for compatibility.  Unlike inheritance, we
   18222             :      * require that the order also match.  However, attnotnull need not match.
   18223             :      */
   18224          60 :     typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
   18225          60 :     tableTupleDesc = RelationGetDescr(rel);
   18226          60 :     table_attno = 1;
   18227         190 :     for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
   18228             :     {
   18229             :         Form_pg_attribute type_attr,
   18230             :                     table_attr;
   18231             :         const char *type_attname,
   18232             :                    *table_attname;
   18233             : 
   18234             :         /* Get the next non-dropped type attribute. */
   18235         154 :         type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
   18236         154 :         if (type_attr->attisdropped)
   18237          44 :             continue;
   18238         110 :         type_attname = NameStr(type_attr->attname);
   18239             : 
   18240             :         /* Get the next non-dropped table attribute. */
   18241             :         do
   18242             :         {
   18243         122 :             if (table_attno > tableTupleDesc->natts)
   18244           6 :                 ereport(ERROR,
   18245             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   18246             :                          errmsg("table is missing column \"%s\"",
   18247             :                                 type_attname)));
   18248         116 :             table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
   18249         116 :             table_attno++;
   18250         116 :         } while (table_attr->attisdropped);
   18251         104 :         table_attname = NameStr(table_attr->attname);
   18252             : 
   18253             :         /* Compare name. */
   18254         104 :         if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
   18255           6 :             ereport(ERROR,
   18256             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   18257             :                      errmsg("table has column \"%s\" where type requires \"%s\"",
   18258             :                             table_attname, type_attname)));
   18259             : 
   18260             :         /* Compare type. */
   18261          98 :         if (table_attr->atttypid != type_attr->atttypid ||
   18262          92 :             table_attr->atttypmod != type_attr->atttypmod ||
   18263          86 :             table_attr->attcollation != type_attr->attcollation)
   18264          12 :             ereport(ERROR,
   18265             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   18266             :                      errmsg("table \"%s\" has different type for column \"%s\"",
   18267             :                             RelationGetRelationName(rel), type_attname)));
   18268             :     }
   18269          36 :     ReleaseTupleDesc(typeTupleDesc);
   18270             : 
   18271             :     /* Any remaining columns at the end of the table had better be dropped. */
   18272          36 :     for (; table_attno <= tableTupleDesc->natts; table_attno++)
   18273             :     {
   18274           6 :         Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
   18275             :                                                      table_attno - 1);
   18276             : 
   18277           6 :         if (!table_attr->attisdropped)
   18278           6 :             ereport(ERROR,
   18279             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   18280             :                      errmsg("table has extra column \"%s\"",
   18281             :                             NameStr(table_attr->attname))));
   18282             :     }
   18283             : 
   18284             :     /* If the table was already typed, drop the existing dependency. */
   18285          30 :     if (rel->rd_rel->reloftype)
   18286           6 :         drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
   18287             :                                DEPENDENCY_NORMAL);
   18288             : 
   18289             :     /* Record a dependency on the new type. */
   18290          30 :     tableobj.classId = RelationRelationId;
   18291          30 :     tableobj.objectId = relid;
   18292          30 :     tableobj.objectSubId = 0;
   18293          30 :     typeobj.classId = TypeRelationId;
   18294          30 :     typeobj.objectId = typeid;
   18295          30 :     typeobj.objectSubId = 0;
   18296          30 :     recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
   18297             : 
   18298             :     /* Update pg_class.reloftype */
   18299          30 :     relationRelation = table_open(RelationRelationId, RowExclusiveLock);
   18300          30 :     classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
   18301          30 :     if (!HeapTupleIsValid(classtuple))
   18302           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   18303          30 :     ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
   18304          30 :     CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
   18305             : 
   18306          30 :     InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
   18307             : 
   18308          30 :     heap_freetuple(classtuple);
   18309          30 :     table_close(relationRelation, RowExclusiveLock);
   18310             : 
   18311          30 :     ReleaseSysCache(typetuple);
   18312             : 
   18313          30 :     return typeobj;
   18314             : }
   18315             : 
   18316             : /*
   18317             :  * ALTER TABLE NOT OF
   18318             :  *
   18319             :  * Detach a typed table from its originating type.  Just clear reloftype and
   18320             :  * remove the dependency.
   18321             :  */
   18322             : static void
   18323           6 : ATExecDropOf(Relation rel, LOCKMODE lockmode)
   18324             : {
   18325           6 :     Oid         relid = RelationGetRelid(rel);
   18326             :     Relation    relationRelation;
   18327             :     HeapTuple   tuple;
   18328             : 
   18329           6 :     if (!OidIsValid(rel->rd_rel->reloftype))
   18330           0 :         ereport(ERROR,
   18331             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18332             :                  errmsg("\"%s\" is not a typed table",
   18333             :                         RelationGetRelationName(rel))));
   18334             : 
   18335             :     /*
   18336             :      * We don't bother to check ownership of the type --- ownership of the
   18337             :      * table is presumed enough rights.  No lock required on the type, either.
   18338             :      */
   18339             : 
   18340           6 :     drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
   18341             :                            DEPENDENCY_NORMAL);
   18342             : 
   18343             :     /* Clear pg_class.reloftype */
   18344           6 :     relationRelation = table_open(RelationRelationId, RowExclusiveLock);
   18345           6 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
   18346           6 :     if (!HeapTupleIsValid(tuple))
   18347           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   18348           6 :     ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
   18349           6 :     CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
   18350             : 
   18351           6 :     InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
   18352             : 
   18353           6 :     heap_freetuple(tuple);
   18354           6 :     table_close(relationRelation, RowExclusiveLock);
   18355           6 : }
   18356             : 
   18357             : /*
   18358             :  * relation_mark_replica_identity: Update a table's replica identity
   18359             :  *
   18360             :  * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
   18361             :  * index. Otherwise, it must be InvalidOid.
   18362             :  *
   18363             :  * Caller had better hold an exclusive lock on the relation, as the results
   18364             :  * of running two of these concurrently wouldn't be pretty.
   18365             :  */
   18366             : static void
   18367         464 : relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
   18368             :                                bool is_internal)
   18369             : {
   18370             :     Relation    pg_index;
   18371             :     Relation    pg_class;
   18372             :     HeapTuple   pg_class_tuple;
   18373             :     HeapTuple   pg_index_tuple;
   18374             :     Form_pg_class pg_class_form;
   18375             :     Form_pg_index pg_index_form;
   18376             :     ListCell   *index;
   18377             : 
   18378             :     /*
   18379             :      * Check whether relreplident has changed, and update it if so.
   18380             :      */
   18381         464 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
   18382         464 :     pg_class_tuple = SearchSysCacheCopy1(RELOID,
   18383             :                                          ObjectIdGetDatum(RelationGetRelid(rel)));
   18384         464 :     if (!HeapTupleIsValid(pg_class_tuple))
   18385           0 :         elog(ERROR, "cache lookup failed for relation \"%s\"",
   18386             :              RelationGetRelationName(rel));
   18387         464 :     pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
   18388         464 :     if (pg_class_form->relreplident != ri_type)
   18389             :     {
   18390         414 :         pg_class_form->relreplident = ri_type;
   18391         414 :         CatalogTupleUpdate(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
   18392             :     }
   18393         464 :     table_close(pg_class, RowExclusiveLock);
   18394         464 :     heap_freetuple(pg_class_tuple);
   18395             : 
   18396             :     /*
   18397             :      * Update the per-index indisreplident flags correctly.
   18398             :      */
   18399         464 :     pg_index = table_open(IndexRelationId, RowExclusiveLock);
   18400        1188 :     foreach(index, RelationGetIndexList(rel))
   18401             :     {
   18402         724 :         Oid         thisIndexOid = lfirst_oid(index);
   18403         724 :         bool        dirty = false;
   18404             : 
   18405         724 :         pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
   18406             :                                              ObjectIdGetDatum(thisIndexOid));
   18407         724 :         if (!HeapTupleIsValid(pg_index_tuple))
   18408           0 :             elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
   18409         724 :         pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
   18410             : 
   18411         724 :         if (thisIndexOid == indexOid)
   18412             :         {
   18413             :             /* Set the bit if not already set. */
   18414         240 :             if (!pg_index_form->indisreplident)
   18415             :             {
   18416         222 :                 dirty = true;
   18417         222 :                 pg_index_form->indisreplident = true;
   18418             :             }
   18419             :         }
   18420             :         else
   18421             :         {
   18422             :             /* Unset the bit if set. */
   18423         484 :             if (pg_index_form->indisreplident)
   18424             :             {
   18425          52 :                 dirty = true;
   18426          52 :                 pg_index_form->indisreplident = false;
   18427             :             }
   18428             :         }
   18429             : 
   18430         724 :         if (dirty)
   18431             :         {
   18432         274 :             CatalogTupleUpdate(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
   18433         274 :             InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
   18434             :                                          InvalidOid, is_internal);
   18435             : 
   18436             :             /*
   18437             :              * Invalidate the relcache for the table, so that after we commit
   18438             :              * all sessions will refresh the table's replica identity index
   18439             :              * before attempting any UPDATE or DELETE on the table.  (If we
   18440             :              * changed the table's pg_class row above, then a relcache inval
   18441             :              * is already queued due to that; but we might not have.)
   18442             :              */
   18443         274 :             CacheInvalidateRelcache(rel);
   18444             :         }
   18445         724 :         heap_freetuple(pg_index_tuple);
   18446             :     }
   18447             : 
   18448         464 :     table_close(pg_index, RowExclusiveLock);
   18449         464 : }
   18450             : 
   18451             : /*
   18452             :  * ALTER TABLE <name> REPLICA IDENTITY ...
   18453             :  */
   18454             : static void
   18455         512 : ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
   18456             : {
   18457             :     Oid         indexOid;
   18458             :     Relation    indexRel;
   18459             :     int         key;
   18460             : 
   18461         512 :     if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
   18462             :     {
   18463           6 :         relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
   18464           6 :         return;
   18465             :     }
   18466         506 :     else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
   18467             :     {
   18468         170 :         relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
   18469         170 :         return;
   18470             :     }
   18471         336 :     else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
   18472             :     {
   18473          48 :         relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
   18474          48 :         return;
   18475             :     }
   18476         288 :     else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
   18477             :     {
   18478             :          /* fallthrough */ ;
   18479             :     }
   18480             :     else
   18481           0 :         elog(ERROR, "unexpected identity type %u", stmt->identity_type);
   18482             : 
   18483             :     /* Check that the index exists */
   18484         288 :     indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
   18485         288 :     if (!OidIsValid(indexOid))
   18486           0 :         ereport(ERROR,
   18487             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   18488             :                  errmsg("index \"%s\" for table \"%s\" does not exist",
   18489             :                         stmt->name, RelationGetRelationName(rel))));
   18490             : 
   18491         288 :     indexRel = index_open(indexOid, ShareLock);
   18492             : 
   18493             :     /* Check that the index is on the relation we're altering. */
   18494         288 :     if (indexRel->rd_index == NULL ||
   18495         288 :         indexRel->rd_index->indrelid != RelationGetRelid(rel))
   18496           6 :         ereport(ERROR,
   18497             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18498             :                  errmsg("\"%s\" is not an index for table \"%s\"",
   18499             :                         RelationGetRelationName(indexRel),
   18500             :                         RelationGetRelationName(rel))));
   18501             : 
   18502             :     /*
   18503             :      * The AM must support uniqueness, and the index must in fact be unique.
   18504             :      * If we have a WITHOUT OVERLAPS constraint (identified by uniqueness +
   18505             :      * exclusion), we can use that too.
   18506             :      */
   18507         282 :     if ((!indexRel->rd_indam->amcanunique ||
   18508         262 :          !indexRel->rd_index->indisunique) &&
   18509          26 :         !(indexRel->rd_index->indisunique && indexRel->rd_index->indisexclusion))
   18510          12 :         ereport(ERROR,
   18511             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18512             :                  errmsg("cannot use non-unique index \"%s\" as replica identity",
   18513             :                         RelationGetRelationName(indexRel))));
   18514             :     /* Deferred indexes are not guaranteed to be always unique. */
   18515         270 :     if (!indexRel->rd_index->indimmediate)
   18516          12 :         ereport(ERROR,
   18517             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   18518             :                  errmsg("cannot use non-immediate index \"%s\" as replica identity",
   18519             :                         RelationGetRelationName(indexRel))));
   18520             :     /* Expression indexes aren't supported. */
   18521         258 :     if (RelationGetIndexExpressions(indexRel) != NIL)
   18522           6 :         ereport(ERROR,
   18523             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   18524             :                  errmsg("cannot use expression index \"%s\" as replica identity",
   18525             :                         RelationGetRelationName(indexRel))));
   18526             :     /* Predicate indexes aren't supported. */
   18527         252 :     if (RelationGetIndexPredicate(indexRel) != NIL)
   18528           6 :         ereport(ERROR,
   18529             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   18530             :                  errmsg("cannot use partial index \"%s\" as replica identity",
   18531             :                         RelationGetRelationName(indexRel))));
   18532             : 
   18533             :     /* Check index for nullable columns. */
   18534         552 :     for (key = 0; key < IndexRelationGetNumberOfKeyAttributes(indexRel); key++)
   18535             :     {
   18536         312 :         int16       attno = indexRel->rd_index->indkey.values[key];
   18537             :         Form_pg_attribute attr;
   18538             : 
   18539             :         /*
   18540             :          * Reject any other system columns.  (Going forward, we'll disallow
   18541             :          * indexes containing such columns in the first place, but they might
   18542             :          * exist in older branches.)
   18543             :          */
   18544         312 :         if (attno <= 0)
   18545           0 :             ereport(ERROR,
   18546             :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
   18547             :                      errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
   18548             :                             RelationGetRelationName(indexRel), attno)));
   18549             : 
   18550         312 :         attr = TupleDescAttr(rel->rd_att, attno - 1);
   18551         312 :         if (!attr->attnotnull)
   18552           6 :             ereport(ERROR,
   18553             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   18554             :                      errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
   18555             :                             RelationGetRelationName(indexRel),
   18556             :                             NameStr(attr->attname))));
   18557             :     }
   18558             : 
   18559             :     /* This index is suitable for use as a replica identity. Mark it. */
   18560         240 :     relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
   18561             : 
   18562         240 :     index_close(indexRel, NoLock);
   18563             : }
   18564             : 
   18565             : /*
   18566             :  * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
   18567             :  */
   18568             : static void
   18569         348 : ATExecSetRowSecurity(Relation rel, bool rls)
   18570             : {
   18571             :     Relation    pg_class;
   18572             :     Oid         relid;
   18573             :     HeapTuple   tuple;
   18574             : 
   18575         348 :     relid = RelationGetRelid(rel);
   18576             : 
   18577             :     /* Pull the record for this relation and update it */
   18578         348 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
   18579             : 
   18580         348 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
   18581             : 
   18582         348 :     if (!HeapTupleIsValid(tuple))
   18583           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   18584             : 
   18585         348 :     ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = rls;
   18586         348 :     CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
   18587             : 
   18588         348 :     InvokeObjectPostAlterHook(RelationRelationId,
   18589             :                               RelationGetRelid(rel), 0);
   18590             : 
   18591         348 :     table_close(pg_class, RowExclusiveLock);
   18592         348 :     heap_freetuple(tuple);
   18593         348 : }
   18594             : 
   18595             : /*
   18596             :  * ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
   18597             :  */
   18598             : static void
   18599         132 : ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
   18600             : {
   18601             :     Relation    pg_class;
   18602             :     Oid         relid;
   18603             :     HeapTuple   tuple;
   18604             : 
   18605         132 :     relid = RelationGetRelid(rel);
   18606             : 
   18607         132 :     pg_class = table_open(RelationRelationId, RowExclusiveLock);
   18608             : 
   18609         132 :     tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
   18610             : 
   18611         132 :     if (!HeapTupleIsValid(tuple))
   18612           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
   18613             : 
   18614         132 :     ((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
   18615         132 :     CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
   18616             : 
   18617         132 :     InvokeObjectPostAlterHook(RelationRelationId,
   18618             :                               RelationGetRelid(rel), 0);
   18619             : 
   18620         132 :     table_close(pg_class, RowExclusiveLock);
   18621         132 :     heap_freetuple(tuple);
   18622         132 : }
   18623             : 
   18624             : /*
   18625             :  * ALTER FOREIGN TABLE <name> OPTIONS (...)
   18626             :  */
   18627             : static void
   18628          58 : ATExecGenericOptions(Relation rel, List *options)
   18629             : {
   18630             :     Relation    ftrel;
   18631             :     ForeignServer *server;
   18632             :     ForeignDataWrapper *fdw;
   18633             :     HeapTuple   tuple;
   18634             :     bool        isnull;
   18635             :     Datum       repl_val[Natts_pg_foreign_table];
   18636             :     bool        repl_null[Natts_pg_foreign_table];
   18637             :     bool        repl_repl[Natts_pg_foreign_table];
   18638             :     Datum       datum;
   18639             :     Form_pg_foreign_table tableform;
   18640             : 
   18641          58 :     if (options == NIL)
   18642           0 :         return;
   18643             : 
   18644          58 :     ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
   18645             : 
   18646          58 :     tuple = SearchSysCacheCopy1(FOREIGNTABLEREL,
   18647             :                                 ObjectIdGetDatum(rel->rd_id));
   18648          58 :     if (!HeapTupleIsValid(tuple))
   18649           0 :         ereport(ERROR,
   18650             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   18651             :                  errmsg("foreign table \"%s\" does not exist",
   18652             :                         RelationGetRelationName(rel))));
   18653          58 :     tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
   18654          58 :     server = GetForeignServer(tableform->ftserver);
   18655          58 :     fdw = GetForeignDataWrapper(server->fdwid);
   18656             : 
   18657          58 :     memset(repl_val, 0, sizeof(repl_val));
   18658          58 :     memset(repl_null, false, sizeof(repl_null));
   18659          58 :     memset(repl_repl, false, sizeof(repl_repl));
   18660             : 
   18661             :     /* Extract the current options */
   18662          58 :     datum = SysCacheGetAttr(FOREIGNTABLEREL,
   18663             :                             tuple,
   18664             :                             Anum_pg_foreign_table_ftoptions,
   18665             :                             &isnull);
   18666          58 :     if (isnull)
   18667           4 :         datum = PointerGetDatum(NULL);
   18668             : 
   18669             :     /* Transform the options */
   18670          58 :     datum = transformGenericOptions(ForeignTableRelationId,
   18671             :                                     datum,
   18672             :                                     options,
   18673             :                                     fdw->fdwvalidator);
   18674             : 
   18675          56 :     if (DatumGetPointer(datum) != NULL)
   18676          56 :         repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
   18677             :     else
   18678           0 :         repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
   18679             : 
   18680          56 :     repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
   18681             : 
   18682             :     /* Everything looks good - update the tuple */
   18683             : 
   18684          56 :     tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
   18685             :                               repl_val, repl_null, repl_repl);
   18686             : 
   18687          56 :     CatalogTupleUpdate(ftrel, &tuple->t_self, tuple);
   18688             : 
   18689             :     /*
   18690             :      * Invalidate relcache so that all sessions will refresh any cached plans
   18691             :      * that might depend on the old options.
   18692             :      */
   18693          56 :     CacheInvalidateRelcache(rel);
   18694             : 
   18695          56 :     InvokeObjectPostAlterHook(ForeignTableRelationId,
   18696             :                               RelationGetRelid(rel), 0);
   18697             : 
   18698          56 :     table_close(ftrel, RowExclusiveLock);
   18699             : 
   18700          56 :     heap_freetuple(tuple);
   18701             : }
   18702             : 
   18703             : /*
   18704             :  * ALTER TABLE ALTER COLUMN SET COMPRESSION
   18705             :  *
   18706             :  * Return value is the address of the modified column
   18707             :  */
   18708             : static ObjectAddress
   18709          78 : ATExecSetCompression(Relation rel,
   18710             :                      const char *column,
   18711             :                      Node *newValue,
   18712             :                      LOCKMODE lockmode)
   18713             : {
   18714             :     Relation    attrel;
   18715             :     HeapTuple   tuple;
   18716             :     Form_pg_attribute atttableform;
   18717             :     AttrNumber  attnum;
   18718             :     char       *compression;
   18719             :     char        cmethod;
   18720             :     ObjectAddress address;
   18721             : 
   18722          78 :     compression = strVal(newValue);
   18723             : 
   18724          78 :     attrel = table_open(AttributeRelationId, RowExclusiveLock);
   18725             : 
   18726             :     /* copy the cache entry so we can scribble on it below */
   18727          78 :     tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), column);
   18728          78 :     if (!HeapTupleIsValid(tuple))
   18729           0 :         ereport(ERROR,
   18730             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
   18731             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
   18732             :                         column, RelationGetRelationName(rel))));
   18733             : 
   18734             :     /* prevent them from altering a system attribute */
   18735          78 :     atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
   18736          78 :     attnum = atttableform->attnum;
   18737          78 :     if (attnum <= 0)
   18738           0 :         ereport(ERROR,
   18739             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   18740             :                  errmsg("cannot alter system column \"%s\"", column)));
   18741             : 
   18742             :     /*
   18743             :      * Check that column type is compressible, then get the attribute
   18744             :      * compression method code
   18745             :      */
   18746          78 :     cmethod = GetAttributeCompression(atttableform->atttypid, compression);
   18747             : 
   18748             :     /* update pg_attribute entry */
   18749          72 :     atttableform->attcompression = cmethod;
   18750          72 :     CatalogTupleUpdate(attrel, &tuple->t_self, tuple);
   18751             : 
   18752          72 :     InvokeObjectPostAlterHook(RelationRelationId,
   18753             :                               RelationGetRelid(rel),
   18754             :                               attnum);
   18755             : 
   18756             :     /*
   18757             :      * Apply the change to indexes as well (only for simple index columns,
   18758             :      * matching behavior of index.c ConstructTupleDescriptor()).
   18759             :      */
   18760          72 :     SetIndexStorageProperties(rel, attrel, attnum,
   18761             :                               false, 0,
   18762             :                               true, cmethod,
   18763             :                               lockmode);
   18764             : 
   18765          72 :     heap_freetuple(tuple);
   18766             : 
   18767          72 :     table_close(attrel, RowExclusiveLock);
   18768             : 
   18769             :     /* make changes visible */
   18770          72 :     CommandCounterIncrement();
   18771             : 
   18772          72 :     ObjectAddressSubSet(address, RelationRelationId,
   18773             :                         RelationGetRelid(rel), attnum);
   18774          72 :     return address;
   18775             : }
   18776             : 
   18777             : 
   18778             : /*
   18779             :  * Preparation phase for SET LOGGED/UNLOGGED
   18780             :  *
   18781             :  * This verifies that we're not trying to change a temp table.  Also,
   18782             :  * existing foreign key constraints are checked to avoid ending up with
   18783             :  * permanent tables referencing unlogged tables.
   18784             :  */
   18785             : static void
   18786         100 : ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel, bool toLogged)
   18787             : {
   18788             :     Relation    pg_constraint;
   18789             :     HeapTuple   tuple;
   18790             :     SysScanDesc scan;
   18791             :     ScanKeyData skey[1];
   18792             : 
   18793             :     /*
   18794             :      * Disallow changing status for a temp table.  Also verify whether we can
   18795             :      * get away with doing nothing; in such cases we don't need to run the
   18796             :      * checks below, either.
   18797             :      */
   18798         100 :     switch (rel->rd_rel->relpersistence)
   18799             :     {
   18800           0 :         case RELPERSISTENCE_TEMP:
   18801           0 :             ereport(ERROR,
   18802             :                     (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   18803             :                      errmsg("cannot change logged status of table \"%s\" because it is temporary",
   18804             :                             RelationGetRelationName(rel)),
   18805             :                      errtable(rel)));
   18806             :             break;
   18807          56 :         case RELPERSISTENCE_PERMANENT:
   18808          56 :             if (toLogged)
   18809             :                 /* nothing to do */
   18810          12 :                 return;
   18811          50 :             break;
   18812          44 :         case RELPERSISTENCE_UNLOGGED:
   18813          44 :             if (!toLogged)
   18814             :                 /* nothing to do */
   18815           6 :                 return;
   18816          38 :             break;
   18817             :     }
   18818             : 
   18819             :     /*
   18820             :      * Check that the table is not part of any publication when changing to
   18821             :      * UNLOGGED, as UNLOGGED tables can't be published.
   18822             :      */
   18823         138 :     if (!toLogged &&
   18824          50 :         GetRelationPublications(RelationGetRelid(rel)) != NIL)
   18825           0 :         ereport(ERROR,
   18826             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   18827             :                  errmsg("cannot change table \"%s\" to unlogged because it is part of a publication",
   18828             :                         RelationGetRelationName(rel)),
   18829             :                  errdetail("Unlogged relations cannot be replicated.")));
   18830             : 
   18831             :     /*
   18832             :      * Check existing foreign key constraints to preserve the invariant that
   18833             :      * permanent tables cannot reference unlogged ones.  Self-referencing
   18834             :      * foreign keys can safely be ignored.
   18835             :      */
   18836          88 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
   18837             : 
   18838             :     /*
   18839             :      * Scan conrelid if changing to permanent, else confrelid.  This also
   18840             :      * determines whether a useful index exists.
   18841             :      */
   18842          88 :     ScanKeyInit(&skey[0],
   18843             :                 toLogged ? Anum_pg_constraint_conrelid :
   18844             :                 Anum_pg_constraint_confrelid,
   18845             :                 BTEqualStrategyNumber, F_OIDEQ,
   18846             :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   18847          88 :     scan = systable_beginscan(pg_constraint,
   18848             :                               toLogged ? ConstraintRelidTypidNameIndexId : InvalidOid,
   18849             :                               true, NULL, 1, skey);
   18850             : 
   18851         142 :     while (HeapTupleIsValid(tuple = systable_getnext(scan)))
   18852             :     {
   18853          66 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
   18854             : 
   18855          66 :         if (con->contype == CONSTRAINT_FOREIGN)
   18856             :         {
   18857             :             Oid         foreignrelid;
   18858             :             Relation    foreignrel;
   18859             : 
   18860             :             /* the opposite end of what we used as scankey */
   18861          30 :             foreignrelid = toLogged ? con->confrelid : con->conrelid;
   18862             : 
   18863             :             /* ignore if self-referencing */
   18864          30 :             if (RelationGetRelid(rel) == foreignrelid)
   18865          12 :                 continue;
   18866             : 
   18867          18 :             foreignrel = relation_open(foreignrelid, AccessShareLock);
   18868             : 
   18869          18 :             if (toLogged)
   18870             :             {
   18871           6 :                 if (!RelationIsPermanent(foreignrel))
   18872           6 :                     ereport(ERROR,
   18873             :                             (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   18874             :                              errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
   18875             :                                     RelationGetRelationName(rel),
   18876             :                                     RelationGetRelationName(foreignrel)),
   18877             :                              errtableconstraint(rel, NameStr(con->conname))));
   18878             :             }
   18879             :             else
   18880             :             {
   18881          12 :                 if (RelationIsPermanent(foreignrel))
   18882           6 :                     ereport(ERROR,
   18883             :                             (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   18884             :                              errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
   18885             :                                     RelationGetRelationName(rel),
   18886             :                                     RelationGetRelationName(foreignrel)),
   18887             :                              errtableconstraint(rel, NameStr(con->conname))));
   18888             :             }
   18889             : 
   18890           6 :             relation_close(foreignrel, AccessShareLock);
   18891             :         }
   18892             :     }
   18893             : 
   18894          76 :     systable_endscan(scan);
   18895             : 
   18896          76 :     table_close(pg_constraint, AccessShareLock);
   18897             : 
   18898             :     /* force rewrite if necessary; see comment in ATRewriteTables */
   18899          76 :     tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
   18900          76 :     if (toLogged)
   18901          32 :         tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
   18902             :     else
   18903          44 :         tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
   18904          76 :     tab->chgPersistence = true;
   18905             : }
   18906             : 
   18907             : /*
   18908             :  * Execute ALTER TABLE SET SCHEMA
   18909             :  */
   18910             : ObjectAddress
   18911         104 : AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
   18912             : {
   18913             :     Relation    rel;
   18914             :     Oid         relid;
   18915             :     Oid         oldNspOid;
   18916             :     Oid         nspOid;
   18917             :     RangeVar   *newrv;
   18918             :     ObjectAddresses *objsMoved;
   18919             :     ObjectAddress myself;
   18920             : 
   18921         104 :     relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
   18922         104 :                                      stmt->missing_ok ? RVR_MISSING_OK : 0,
   18923             :                                      RangeVarCallbackForAlterRelation,
   18924             :                                      stmt);
   18925             : 
   18926         102 :     if (!OidIsValid(relid))
   18927             :     {
   18928          12 :         ereport(NOTICE,
   18929             :                 (errmsg("relation \"%s\" does not exist, skipping",
   18930             :                         stmt->relation->relname)));
   18931          12 :         return InvalidObjectAddress;
   18932             :     }
   18933             : 
   18934          90 :     rel = relation_open(relid, NoLock);
   18935             : 
   18936          90 :     oldNspOid = RelationGetNamespace(rel);
   18937             : 
   18938             :     /* If it's an owned sequence, disallow moving it by itself. */
   18939          90 :     if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
   18940             :     {
   18941             :         Oid         tableId;
   18942             :         int32       colId;
   18943             : 
   18944          10 :         if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
   18945           2 :             sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
   18946           6 :             ereport(ERROR,
   18947             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   18948             :                      errmsg("cannot move an owned sequence into another schema"),
   18949             :                      errdetail("Sequence \"%s\" is linked to table \"%s\".",
   18950             :                                RelationGetRelationName(rel),
   18951             :                                get_rel_name(tableId))));
   18952             :     }
   18953             : 
   18954             :     /* Get and lock schema OID and check its permissions. */
   18955          84 :     newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
   18956          84 :     nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
   18957             : 
   18958             :     /* common checks on switching namespaces */
   18959          84 :     CheckSetNamespace(oldNspOid, nspOid);
   18960             : 
   18961          84 :     objsMoved = new_object_addresses();
   18962          84 :     AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
   18963          84 :     free_object_addresses(objsMoved);
   18964             : 
   18965          84 :     ObjectAddressSet(myself, RelationRelationId, relid);
   18966             : 
   18967          84 :     if (oldschema)
   18968          84 :         *oldschema = oldNspOid;
   18969             : 
   18970             :     /* close rel, but keep lock until commit */
   18971          84 :     relation_close(rel, NoLock);
   18972             : 
   18973          84 :     return myself;
   18974             : }
   18975             : 
   18976             : /*
   18977             :  * The guts of relocating a table or materialized view to another namespace:
   18978             :  * besides moving the relation itself, its dependent objects are relocated to
   18979             :  * the new schema.
   18980             :  */
   18981             : void
   18982          86 : AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
   18983             :                             ObjectAddresses *objsMoved)
   18984             : {
   18985             :     Relation    classRel;
   18986             : 
   18987             :     Assert(objsMoved != NULL);
   18988             : 
   18989             :     /* OK, modify the pg_class row and pg_depend entry */
   18990          86 :     classRel = table_open(RelationRelationId, RowExclusiveLock);
   18991             : 
   18992          86 :     AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
   18993             :                                    nspOid, true, objsMoved);
   18994             : 
   18995             :     /* Fix the table's row type too, if it has one */
   18996          86 :     if (OidIsValid(rel->rd_rel->reltype))
   18997          84 :         AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
   18998             :                                    false,   /* isImplicitArray */
   18999             :                                    false,   /* ignoreDependent */
   19000             :                                    false,   /* errorOnTableType */
   19001             :                                    objsMoved);
   19002             : 
   19003             :     /* Fix other dependent stuff */
   19004          86 :     AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
   19005          86 :     AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
   19006             :                        objsMoved, AccessExclusiveLock);
   19007          86 :     AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
   19008             :                               false, objsMoved);
   19009             : 
   19010          86 :     table_close(classRel, RowExclusiveLock);
   19011          86 : }
   19012             : 
   19013             : /*
   19014             :  * The guts of relocating a relation to another namespace: fix the pg_class
   19015             :  * entry, and the pg_depend entry if any.  Caller must already have
   19016             :  * opened and write-locked pg_class.
   19017             :  */
   19018             : void
   19019         188 : AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
   19020             :                                Oid oldNspOid, Oid newNspOid,
   19021             :                                bool hasDependEntry,
   19022             :                                ObjectAddresses *objsMoved)
   19023             : {
   19024             :     HeapTuple   classTup;
   19025             :     Form_pg_class classForm;
   19026             :     ObjectAddress thisobj;
   19027         188 :     bool        already_done = false;
   19028             : 
   19029             :     /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
   19030         188 :     classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
   19031         188 :     if (!HeapTupleIsValid(classTup))
   19032           0 :         elog(ERROR, "cache lookup failed for relation %u", relOid);
   19033         188 :     classForm = (Form_pg_class) GETSTRUCT(classTup);
   19034             : 
   19035             :     Assert(classForm->relnamespace == oldNspOid);
   19036             : 
   19037         188 :     thisobj.classId = RelationRelationId;
   19038         188 :     thisobj.objectId = relOid;
   19039         188 :     thisobj.objectSubId = 0;
   19040             : 
   19041             :     /*
   19042             :      * If the object has already been moved, don't move it again.  If it's
   19043             :      * already in the right place, don't move it, but still fire the object
   19044             :      * access hook.
   19045             :      */
   19046         188 :     already_done = object_address_present(&thisobj, objsMoved);
   19047         188 :     if (!already_done && oldNspOid != newNspOid)
   19048         146 :     {
   19049         146 :         ItemPointerData otid = classTup->t_self;
   19050             : 
   19051             :         /* check for duplicate name (more friendly than unique-index failure) */
   19052         146 :         if (get_relname_relid(NameStr(classForm->relname),
   19053             :                               newNspOid) != InvalidOid)
   19054           0 :             ereport(ERROR,
   19055             :                     (errcode(ERRCODE_DUPLICATE_TABLE),
   19056             :                      errmsg("relation \"%s\" already exists in schema \"%s\"",
   19057             :                             NameStr(classForm->relname),
   19058             :                             get_namespace_name(newNspOid))));
   19059             : 
   19060             :         /* classTup is a copy, so OK to scribble on */
   19061         146 :         classForm->relnamespace = newNspOid;
   19062             : 
   19063         146 :         CatalogTupleUpdate(classRel, &otid, classTup);
   19064         146 :         UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
   19065             : 
   19066             : 
   19067             :         /* Update dependency on schema if caller said so */
   19068         250 :         if (hasDependEntry &&
   19069         104 :             changeDependencyFor(RelationRelationId,
   19070             :                                 relOid,
   19071             :                                 NamespaceRelationId,
   19072             :                                 oldNspOid,
   19073             :                                 newNspOid) != 1)
   19074           0 :             elog(ERROR, "could not change schema dependency for relation \"%s\"",
   19075             :                  NameStr(classForm->relname));
   19076             :     }
   19077             :     else
   19078          42 :         UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
   19079         188 :     if (!already_done)
   19080             :     {
   19081         188 :         add_exact_object_address(&thisobj, objsMoved);
   19082             : 
   19083         188 :         InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
   19084             :     }
   19085             : 
   19086         188 :     heap_freetuple(classTup);
   19087         188 : }
   19088             : 
   19089             : /*
   19090             :  * Move all indexes for the specified relation to another namespace.
   19091             :  *
   19092             :  * Note: we assume adequate permission checking was done by the caller,
   19093             :  * and that the caller has a suitable lock on the owning relation.
   19094             :  */
   19095             : static void
   19096          86 : AlterIndexNamespaces(Relation classRel, Relation rel,
   19097             :                      Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
   19098             : {
   19099             :     List       *indexList;
   19100             :     ListCell   *l;
   19101             : 
   19102          86 :     indexList = RelationGetIndexList(rel);
   19103             : 
   19104         132 :     foreach(l, indexList)
   19105             :     {
   19106          46 :         Oid         indexOid = lfirst_oid(l);
   19107             :         ObjectAddress thisobj;
   19108             : 
   19109          46 :         thisobj.classId = RelationRelationId;
   19110          46 :         thisobj.objectId = indexOid;
   19111          46 :         thisobj.objectSubId = 0;
   19112             : 
   19113             :         /*
   19114             :          * Note: currently, the index will not have its own dependency on the
   19115             :          * namespace, so we don't need to do changeDependencyFor(). There's no
   19116             :          * row type in pg_type, either.
   19117             :          *
   19118             :          * XXX this objsMoved test may be pointless -- surely we have a single
   19119             :          * dependency link from a relation to each index?
   19120             :          */
   19121          46 :         if (!object_address_present(&thisobj, objsMoved))
   19122             :         {
   19123          46 :             AlterRelationNamespaceInternal(classRel, indexOid,
   19124             :                                            oldNspOid, newNspOid,
   19125             :                                            false, objsMoved);
   19126          46 :             add_exact_object_address(&thisobj, objsMoved);
   19127             :         }
   19128             :     }
   19129             : 
   19130          86 :     list_free(indexList);
   19131          86 : }
   19132             : 
   19133             : /*
   19134             :  * Move all identity and SERIAL-column sequences of the specified relation to another
   19135             :  * namespace.
   19136             :  *
   19137             :  * Note: we assume adequate permission checking was done by the caller,
   19138             :  * and that the caller has a suitable lock on the owning relation.
   19139             :  */
   19140             : static void
   19141          86 : AlterSeqNamespaces(Relation classRel, Relation rel,
   19142             :                    Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
   19143             :                    LOCKMODE lockmode)
   19144             : {
   19145             :     Relation    depRel;
   19146             :     SysScanDesc scan;
   19147             :     ScanKeyData key[2];
   19148             :     HeapTuple   tup;
   19149             : 
   19150             :     /*
   19151             :      * SERIAL sequences are those having an auto dependency on one of the
   19152             :      * table's columns (we don't care *which* column, exactly).
   19153             :      */
   19154          86 :     depRel = table_open(DependRelationId, AccessShareLock);
   19155             : 
   19156          86 :     ScanKeyInit(&key[0],
   19157             :                 Anum_pg_depend_refclassid,
   19158             :                 BTEqualStrategyNumber, F_OIDEQ,
   19159             :                 ObjectIdGetDatum(RelationRelationId));
   19160          86 :     ScanKeyInit(&key[1],
   19161             :                 Anum_pg_depend_refobjid,
   19162             :                 BTEqualStrategyNumber, F_OIDEQ,
   19163             :                 ObjectIdGetDatum(RelationGetRelid(rel)));
   19164             :     /* we leave refobjsubid unspecified */
   19165             : 
   19166          86 :     scan = systable_beginscan(depRel, DependReferenceIndexId, true,
   19167             :                               NULL, 2, key);
   19168             : 
   19169         616 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
   19170             :     {
   19171         530 :         Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
   19172             :         Relation    seqRel;
   19173             : 
   19174             :         /* skip dependencies other than auto dependencies on columns */
   19175         530 :         if (depForm->refobjsubid == 0 ||
   19176         382 :             depForm->classid != RelationRelationId ||
   19177          42 :             depForm->objsubid != 0 ||
   19178          42 :             !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
   19179         488 :             continue;
   19180             : 
   19181             :         /* Use relation_open just in case it's an index */
   19182          42 :         seqRel = relation_open(depForm->objid, lockmode);
   19183             : 
   19184             :         /* skip non-sequence relations */
   19185          42 :         if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
   19186             :         {
   19187             :             /* No need to keep the lock */
   19188           0 :             relation_close(seqRel, lockmode);
   19189           0 :             continue;
   19190             :         }
   19191             : 
   19192             :         /* Fix the pg_class and pg_depend entries */
   19193          42 :         AlterRelationNamespaceInternal(classRel, depForm->objid,
   19194             :                                        oldNspOid, newNspOid,
   19195             :                                        true, objsMoved);
   19196             : 
   19197             :         /*
   19198             :          * Sequences used to have entries in pg_type, but no longer do.  If we
   19199             :          * ever re-instate that, we'll need to move the pg_type entry to the
   19200             :          * new namespace, too (using AlterTypeNamespaceInternal).
   19201             :          */
   19202             :         Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
   19203             : 
   19204             :         /* Now we can close it.  Keep the lock till end of transaction. */
   19205          42 :         relation_close(seqRel, NoLock);
   19206             :     }
   19207             : 
   19208          86 :     systable_endscan(scan);
   19209             : 
   19210          86 :     relation_close(depRel, AccessShareLock);
   19211          86 : }
   19212             : 
   19213             : 
   19214             : /*
   19215             :  * This code supports
   19216             :  *  CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
   19217             :  *
   19218             :  * Because we only support this for TEMP tables, it's sufficient to remember
   19219             :  * the state in a backend-local data structure.
   19220             :  */
   19221             : 
   19222             : /*
   19223             :  * Register a newly-created relation's ON COMMIT action.
   19224             :  */
   19225             : void
   19226         176 : register_on_commit_action(Oid relid, OnCommitAction action)
   19227             : {
   19228             :     OnCommitItem *oc;
   19229             :     MemoryContext oldcxt;
   19230             : 
   19231             :     /*
   19232             :      * We needn't bother registering the relation unless there is an ON COMMIT
   19233             :      * action we need to take.
   19234             :      */
   19235         176 :     if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
   19236          24 :         return;
   19237             : 
   19238         152 :     oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
   19239             : 
   19240         152 :     oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
   19241         152 :     oc->relid = relid;
   19242         152 :     oc->oncommit = action;
   19243         152 :     oc->creating_subid = GetCurrentSubTransactionId();
   19244         152 :     oc->deleting_subid = InvalidSubTransactionId;
   19245             : 
   19246             :     /*
   19247             :      * We use lcons() here so that ON COMMIT actions are processed in reverse
   19248             :      * order of registration.  That might not be essential but it seems
   19249             :      * reasonable.
   19250             :      */
   19251         152 :     on_commits = lcons(oc, on_commits);
   19252             : 
   19253         152 :     MemoryContextSwitchTo(oldcxt);
   19254             : }
   19255             : 
   19256             : /*
   19257             :  * Unregister any ON COMMIT action when a relation is deleted.
   19258             :  *
   19259             :  * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
   19260             :  */
   19261             : void
   19262       48930 : remove_on_commit_action(Oid relid)
   19263             : {
   19264             :     ListCell   *l;
   19265             : 
   19266       49076 :     foreach(l, on_commits)
   19267             :     {
   19268         286 :         OnCommitItem *oc = (OnCommitItem *) lfirst(l);
   19269             : 
   19270         286 :         if (oc->relid == relid)
   19271             :         {
   19272         140 :             oc->deleting_subid = GetCurrentSubTransactionId();
   19273         140 :             break;
   19274             :         }
   19275             :     }
   19276       48930 : }
   19277             : 
   19278             : /*
   19279             :  * Perform ON COMMIT actions.
   19280             :  *
   19281             :  * This is invoked just before actually committing, since it's possible
   19282             :  * to encounter errors.
   19283             :  */
   19284             : void
   19285     1105960 : PreCommit_on_commit_actions(void)
   19286             : {
   19287             :     ListCell   *l;
   19288     1105960 :     List       *oids_to_truncate = NIL;
   19289     1105960 :     List       *oids_to_drop = NIL;
   19290             : 
   19291     1106782 :     foreach(l, on_commits)
   19292             :     {
   19293         822 :         OnCommitItem *oc = (OnCommitItem *) lfirst(l);
   19294             : 
   19295             :         /* Ignore entry if already dropped in this xact */
   19296         822 :         if (oc->deleting_subid != InvalidSubTransactionId)
   19297          74 :             continue;
   19298             : 
   19299         748 :         switch (oc->oncommit)
   19300             :         {
   19301           0 :             case ONCOMMIT_NOOP:
   19302             :             case ONCOMMIT_PRESERVE_ROWS:
   19303             :                 /* Do nothing (there shouldn't be such entries, actually) */
   19304           0 :                 break;
   19305         694 :             case ONCOMMIT_DELETE_ROWS:
   19306             : 
   19307             :                 /*
   19308             :                  * If this transaction hasn't accessed any temporary
   19309             :                  * relations, we can skip truncating ON COMMIT DELETE ROWS
   19310             :                  * tables, as they must still be empty.
   19311             :                  */
   19312         694 :                 if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
   19313         448 :                     oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
   19314         694 :                 break;
   19315          54 :             case ONCOMMIT_DROP:
   19316          54 :                 oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
   19317          54 :                 break;
   19318             :         }
   19319             :     }
   19320             : 
   19321             :     /*
   19322             :      * Truncate relations before dropping so that all dependencies between
   19323             :      * relations are removed after they are worked on.  Doing it like this
   19324             :      * might be a waste as it is possible that a relation being truncated will
   19325             :      * be dropped anyway due to its parent being dropped, but this makes the
   19326             :      * code more robust because of not having to re-check that the relation
   19327             :      * exists at truncation time.
   19328             :      */
   19329     1105960 :     if (oids_to_truncate != NIL)
   19330         382 :         heap_truncate(oids_to_truncate);
   19331             : 
   19332     1105954 :     if (oids_to_drop != NIL)
   19333             :     {
   19334          48 :         ObjectAddresses *targetObjects = new_object_addresses();
   19335             : 
   19336         102 :         foreach(l, oids_to_drop)
   19337             :         {
   19338             :             ObjectAddress object;
   19339             : 
   19340          54 :             object.classId = RelationRelationId;
   19341          54 :             object.objectId = lfirst_oid(l);
   19342          54 :             object.objectSubId = 0;
   19343             : 
   19344             :             Assert(!object_address_present(&object, targetObjects));
   19345             : 
   19346          54 :             add_exact_object_address(&object, targetObjects);
   19347             :         }
   19348             : 
   19349             :         /*
   19350             :          * Object deletion might involve toast table access (to clean up
   19351             :          * toasted catalog entries), so ensure we have a valid snapshot.
   19352             :          */
   19353          48 :         PushActiveSnapshot(GetTransactionSnapshot());
   19354             : 
   19355             :         /*
   19356             :          * Since this is an automatic drop, rather than one directly initiated
   19357             :          * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
   19358             :          */
   19359          48 :         performMultipleDeletions(targetObjects, DROP_CASCADE,
   19360             :                                  PERFORM_DELETION_INTERNAL | PERFORM_DELETION_QUIETLY);
   19361             : 
   19362          48 :         PopActiveSnapshot();
   19363             : 
   19364             : #ifdef USE_ASSERT_CHECKING
   19365             : 
   19366             :         /*
   19367             :          * Note that table deletion will call remove_on_commit_action, so the
   19368             :          * entry should get marked as deleted.
   19369             :          */
   19370             :         foreach(l, on_commits)
   19371             :         {
   19372             :             OnCommitItem *oc = (OnCommitItem *) lfirst(l);
   19373             : 
   19374             :             if (oc->oncommit != ONCOMMIT_DROP)
   19375             :                 continue;
   19376             : 
   19377             :             Assert(oc->deleting_subid != InvalidSubTransactionId);
   19378             :         }
   19379             : #endif
   19380             :     }
   19381     1105954 : }
   19382             : 
   19383             : /*
   19384             :  * Post-commit or post-abort cleanup for ON COMMIT management.
   19385             :  *
   19386             :  * All we do here is remove no-longer-needed OnCommitItem entries.
   19387             :  *
   19388             :  * During commit, remove entries that were deleted during this transaction;
   19389             :  * during abort, remove those created during this transaction.
   19390             :  */
   19391             : void
   19392     1155650 : AtEOXact_on_commit_actions(bool isCommit)
   19393             : {
   19394             :     ListCell   *cur_item;
   19395             : 
   19396     1156502 :     foreach(cur_item, on_commits)
   19397             :     {
   19398         852 :         OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
   19399             : 
   19400         954 :         if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
   19401         102 :             oc->creating_subid != InvalidSubTransactionId)
   19402             :         {
   19403             :             /* cur_item must be removed */
   19404         152 :             on_commits = foreach_delete_current(on_commits, cur_item);
   19405         152 :             pfree(oc);
   19406             :         }
   19407             :         else
   19408             :         {
   19409             :             /* cur_item must be preserved */
   19410         700 :             oc->creating_subid = InvalidSubTransactionId;
   19411         700 :             oc->deleting_subid = InvalidSubTransactionId;
   19412             :         }
   19413             :     }
   19414     1155650 : }
   19415             : 
   19416             : /*
   19417             :  * Post-subcommit or post-subabort cleanup for ON COMMIT management.
   19418             :  *
   19419             :  * During subabort, we can immediately remove entries created during this
   19420             :  * subtransaction.  During subcommit, just relabel entries marked during
   19421             :  * this subtransaction as being the parent's responsibility.
   19422             :  */
   19423             : void
   19424       20100 : AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
   19425             :                               SubTransactionId parentSubid)
   19426             : {
   19427             :     ListCell   *cur_item;
   19428             : 
   19429       20100 :     foreach(cur_item, on_commits)
   19430             :     {
   19431           0 :         OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
   19432             : 
   19433           0 :         if (!isCommit && oc->creating_subid == mySubid)
   19434             :         {
   19435             :             /* cur_item must be removed */
   19436           0 :             on_commits = foreach_delete_current(on_commits, cur_item);
   19437           0 :             pfree(oc);
   19438             :         }
   19439             :         else
   19440             :         {
   19441             :             /* cur_item must be preserved */
   19442           0 :             if (oc->creating_subid == mySubid)
   19443           0 :                 oc->creating_subid = parentSubid;
   19444           0 :             if (oc->deleting_subid == mySubid)
   19445           0 :                 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
   19446             :         }
   19447             :     }
   19448       20100 : }
   19449             : 
   19450             : /*
   19451             :  * This is intended as a callback for RangeVarGetRelidExtended().  It allows
   19452             :  * the relation to be locked only if (1) it's a plain or partitioned table,
   19453             :  * materialized view, or TOAST table and (2) the current user is the owner (or
   19454             :  * the superuser) or has been granted MAINTAIN.  This meets the
   19455             :  * permission-checking needs of CLUSTER, REINDEX TABLE, and REFRESH
   19456             :  * MATERIALIZED VIEW; we expose it here so that it can be used by all.
   19457             :  */
   19458             : void
   19459        1012 : RangeVarCallbackMaintainsTable(const RangeVar *relation,
   19460             :                                Oid relId, Oid oldRelId, void *arg)
   19461             : {
   19462             :     char        relkind;
   19463             :     AclResult   aclresult;
   19464             : 
   19465             :     /* Nothing to do if the relation was not found. */
   19466        1012 :     if (!OidIsValid(relId))
   19467           6 :         return;
   19468             : 
   19469             :     /*
   19470             :      * If the relation does exist, check whether it's an index.  But note that
   19471             :      * the relation might have been dropped between the time we did the name
   19472             :      * lookup and now.  In that case, there's nothing to do.
   19473             :      */
   19474        1006 :     relkind = get_rel_relkind(relId);
   19475        1006 :     if (!relkind)
   19476           0 :         return;
   19477        1006 :     if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
   19478         138 :         relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
   19479          28 :         ereport(ERROR,
   19480             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19481             :                  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
   19482             : 
   19483             :     /* Check permissions */
   19484         978 :     aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
   19485         978 :     if (aclresult != ACLCHECK_OK)
   19486          30 :         aclcheck_error(aclresult,
   19487          30 :                        get_relkind_objtype(get_rel_relkind(relId)),
   19488          30 :                        relation->relname);
   19489             : }
   19490             : 
   19491             : /*
   19492             :  * Callback to RangeVarGetRelidExtended() for TRUNCATE processing.
   19493             :  */
   19494             : static void
   19495        2166 : RangeVarCallbackForTruncate(const RangeVar *relation,
   19496             :                             Oid relId, Oid oldRelId, void *arg)
   19497             : {
   19498             :     HeapTuple   tuple;
   19499             : 
   19500             :     /* Nothing to do if the relation was not found. */
   19501        2166 :     if (!OidIsValid(relId))
   19502           0 :         return;
   19503             : 
   19504        2166 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
   19505        2166 :     if (!HeapTupleIsValid(tuple))   /* should not happen */
   19506           0 :         elog(ERROR, "cache lookup failed for relation %u", relId);
   19507             : 
   19508        2166 :     truncate_check_rel(relId, (Form_pg_class) GETSTRUCT(tuple));
   19509        2160 :     truncate_check_perms(relId, (Form_pg_class) GETSTRUCT(tuple));
   19510             : 
   19511        2128 :     ReleaseSysCache(tuple);
   19512             : }
   19513             : 
   19514             : /*
   19515             :  * Callback for RangeVarGetRelidExtended().  Checks that the current user is
   19516             :  * the owner of the relation, or superuser.
   19517             :  */
   19518             : void
   19519       15958 : RangeVarCallbackOwnsRelation(const RangeVar *relation,
   19520             :                              Oid relId, Oid oldRelId, void *arg)
   19521             : {
   19522             :     HeapTuple   tuple;
   19523             : 
   19524             :     /* Nothing to do if the relation was not found. */
   19525       15958 :     if (!OidIsValid(relId))
   19526           8 :         return;
   19527             : 
   19528       15950 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
   19529       15950 :     if (!HeapTupleIsValid(tuple))   /* should not happen */
   19530           0 :         elog(ERROR, "cache lookup failed for relation %u", relId);
   19531             : 
   19532       15950 :     if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
   19533           6 :         aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relId)),
   19534           6 :                        relation->relname);
   19535             : 
   19536       31768 :     if (!allowSystemTableMods &&
   19537       15824 :         IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
   19538           2 :         ereport(ERROR,
   19539             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
   19540             :                  errmsg("permission denied: \"%s\" is a system catalog",
   19541             :                         relation->relname)));
   19542             : 
   19543       15942 :     ReleaseSysCache(tuple);
   19544             : }
   19545             : 
   19546             : /*
   19547             :  * Common RangeVarGetRelid callback for rename, set schema, and alter table
   19548             :  * processing.
   19549             :  */
   19550             : static void
   19551       33706 : RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
   19552             :                                  void *arg)
   19553             : {
   19554       33706 :     Node       *stmt = (Node *) arg;
   19555             :     ObjectType  reltype;
   19556             :     HeapTuple   tuple;
   19557             :     Form_pg_class classform;
   19558             :     AclResult   aclresult;
   19559             :     char        relkind;
   19560             : 
   19561       33706 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
   19562       33706 :     if (!HeapTupleIsValid(tuple))
   19563         216 :         return;                 /* concurrently dropped */
   19564       33490 :     classform = (Form_pg_class) GETSTRUCT(tuple);
   19565       33490 :     relkind = classform->relkind;
   19566             : 
   19567             :     /* Must own relation. */
   19568       33490 :     if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
   19569          60 :         aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
   19570             : 
   19571             :     /* No system table modifications unless explicitly allowed. */
   19572       33430 :     if (!allowSystemTableMods && IsSystemClass(relid, classform))
   19573          30 :         ereport(ERROR,
   19574             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
   19575             :                  errmsg("permission denied: \"%s\" is a system catalog",
   19576             :                         rv->relname)));
   19577             : 
   19578             :     /*
   19579             :      * Extract the specified relation type from the statement parse tree.
   19580             :      *
   19581             :      * Also, for ALTER .. RENAME, check permissions: the user must (still)
   19582             :      * have CREATE rights on the containing namespace.
   19583             :      */
   19584       33400 :     if (IsA(stmt, RenameStmt))
   19585             :     {
   19586         490 :         aclresult = object_aclcheck(NamespaceRelationId, classform->relnamespace,
   19587             :                                     GetUserId(), ACL_CREATE);
   19588         490 :         if (aclresult != ACLCHECK_OK)
   19589           0 :             aclcheck_error(aclresult, OBJECT_SCHEMA,
   19590           0 :                            get_namespace_name(classform->relnamespace));
   19591         490 :         reltype = ((RenameStmt *) stmt)->renameType;
   19592             :     }
   19593       32910 :     else if (IsA(stmt, AlterObjectSchemaStmt))
   19594          90 :         reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
   19595             : 
   19596       32820 :     else if (IsA(stmt, AlterTableStmt))
   19597       32820 :         reltype = ((AlterTableStmt *) stmt)->objtype;
   19598             :     else
   19599             :     {
   19600           0 :         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
   19601             :         reltype = OBJECT_TABLE; /* placate compiler */
   19602             :     }
   19603             : 
   19604             :     /*
   19605             :      * For compatibility with prior releases, we allow ALTER TABLE to be used
   19606             :      * with most other types of relations (but not composite types). We allow
   19607             :      * similar flexibility for ALTER INDEX in the case of RENAME, but not
   19608             :      * otherwise.  Otherwise, the user must select the correct form of the
   19609             :      * command for the relation at issue.
   19610             :      */
   19611       33400 :     if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
   19612           0 :         ereport(ERROR,
   19613             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19614             :                  errmsg("\"%s\" is not a sequence", rv->relname)));
   19615             : 
   19616       33400 :     if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
   19617           0 :         ereport(ERROR,
   19618             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19619             :                  errmsg("\"%s\" is not a view", rv->relname)));
   19620             : 
   19621       33400 :     if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
   19622           0 :         ereport(ERROR,
   19623             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19624             :                  errmsg("\"%s\" is not a materialized view", rv->relname)));
   19625             : 
   19626       33400 :     if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
   19627           0 :         ereport(ERROR,
   19628             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19629             :                  errmsg("\"%s\" is not a foreign table", rv->relname)));
   19630             : 
   19631       33400 :     if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
   19632           0 :         ereport(ERROR,
   19633             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19634             :                  errmsg("\"%s\" is not a composite type", rv->relname)));
   19635             : 
   19636       33400 :     if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX &&
   19637             :         relkind != RELKIND_PARTITIONED_INDEX
   19638          36 :         && !IsA(stmt, RenameStmt))
   19639           6 :         ereport(ERROR,
   19640             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19641             :                  errmsg("\"%s\" is not an index", rv->relname)));
   19642             : 
   19643             :     /*
   19644             :      * Don't allow ALTER TABLE on composite types. We want people to use ALTER
   19645             :      * TYPE for that.
   19646             :      */
   19647       33394 :     if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
   19648           0 :         ereport(ERROR,
   19649             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19650             :                  errmsg("\"%s\" is a composite type", rv->relname),
   19651             :         /* translator: %s is an SQL ALTER command */
   19652             :                  errhint("Use %s instead.",
   19653             :                          "ALTER TYPE")));
   19654             : 
   19655             :     /*
   19656             :      * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
   19657             :      * to a different schema, such as indexes and TOAST tables.
   19658             :      */
   19659       33394 :     if (IsA(stmt, AlterObjectSchemaStmt))
   19660             :     {
   19661          90 :         if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX)
   19662           0 :             ereport(ERROR,
   19663             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19664             :                      errmsg("cannot change schema of index \"%s\"",
   19665             :                             rv->relname),
   19666             :                      errhint("Change the schema of the table instead.")));
   19667          90 :         else if (relkind == RELKIND_COMPOSITE_TYPE)
   19668           0 :             ereport(ERROR,
   19669             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19670             :                      errmsg("cannot change schema of composite type \"%s\"",
   19671             :                             rv->relname),
   19672             :             /* translator: %s is an SQL ALTER command */
   19673             :                      errhint("Use %s instead.",
   19674             :                              "ALTER TYPE")));
   19675          90 :         else if (relkind == RELKIND_TOASTVALUE)
   19676           0 :             ereport(ERROR,
   19677             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   19678             :                      errmsg("cannot change schema of TOAST table \"%s\"",
   19679             :                             rv->relname),
   19680             :                      errhint("Change the schema of the table instead.")));
   19681             :     }
   19682             : 
   19683       33394 :     ReleaseSysCache(tuple);
   19684             : }
   19685             : 
   19686             : /*
   19687             :  * Transform any expressions present in the partition key
   19688             :  *
   19689             :  * Returns a transformed PartitionSpec.
   19690             :  */
   19691             : static PartitionSpec *
   19692        5064 : transformPartitionSpec(Relation rel, PartitionSpec *partspec)
   19693             : {
   19694             :     PartitionSpec *newspec;
   19695             :     ParseState *pstate;
   19696             :     ParseNamespaceItem *nsitem;
   19697             :     ListCell   *l;
   19698             : 
   19699        5064 :     newspec = makeNode(PartitionSpec);
   19700             : 
   19701        5064 :     newspec->strategy = partspec->strategy;
   19702        5064 :     newspec->partParams = NIL;
   19703        5064 :     newspec->location = partspec->location;
   19704             : 
   19705             :     /* Check valid number of columns for strategy */
   19706        7592 :     if (partspec->strategy == PARTITION_STRATEGY_LIST &&
   19707        2528 :         list_length(partspec->partParams) != 1)
   19708           6 :         ereport(ERROR,
   19709             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   19710             :                  errmsg("cannot use \"list\" partition strategy with more than one column")));
   19711             : 
   19712             :     /*
   19713             :      * Create a dummy ParseState and insert the target relation as its sole
   19714             :      * rangetable entry.  We need a ParseState for transformExpr.
   19715             :      */
   19716        5058 :     pstate = make_parsestate(NULL);
   19717        5058 :     nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
   19718             :                                            NULL, false, true);
   19719        5058 :     addNSItemToQuery(pstate, nsitem, true, true, true);
   19720             : 
   19721             :     /* take care of any partition expressions */
   19722       10542 :     foreach(l, partspec->partParams)
   19723             :     {
   19724        5508 :         PartitionElem *pelem = lfirst_node(PartitionElem, l);
   19725             : 
   19726        5508 :         if (pelem->expr)
   19727             :         {
   19728             :             /* Copy, to avoid scribbling on the input */
   19729         304 :             pelem = copyObject(pelem);
   19730             : 
   19731             :             /* Now do parse transformation of the expression */
   19732         304 :             pelem->expr = transformExpr(pstate, pelem->expr,
   19733             :                                         EXPR_KIND_PARTITION_EXPRESSION);
   19734             : 
   19735             :             /* we have to fix its collations too */
   19736         280 :             assign_expr_collations(pstate, pelem->expr);
   19737             :         }
   19738             : 
   19739        5484 :         newspec->partParams = lappend(newspec->partParams, pelem);
   19740             :     }
   19741             : 
   19742        5034 :     return newspec;
   19743             : }
   19744             : 
   19745             : /*
   19746             :  * Compute per-partition-column information from a list of PartitionElems.
   19747             :  * Expressions in the PartitionElems must be parse-analyzed already.
   19748             :  */
   19749             : static void
   19750        5034 : ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
   19751             :                       List **partexprs, Oid *partopclass, Oid *partcollation,
   19752             :                       PartitionStrategy strategy)
   19753             : {
   19754             :     int         attn;
   19755             :     ListCell   *lc;
   19756             :     Oid         am_oid;
   19757             : 
   19758        5034 :     attn = 0;
   19759       10422 :     foreach(lc, partParams)
   19760             :     {
   19761        5484 :         PartitionElem *pelem = lfirst_node(PartitionElem, lc);
   19762             :         Oid         atttype;
   19763             :         Oid         attcollation;
   19764             : 
   19765        5484 :         if (pelem->name != NULL)
   19766             :         {
   19767             :             /* Simple attribute reference */
   19768             :             HeapTuple   atttuple;
   19769             :             Form_pg_attribute attform;
   19770             : 
   19771        5204 :             atttuple = SearchSysCacheAttName(RelationGetRelid(rel),
   19772        5204 :                                              pelem->name);
   19773        5204 :             if (!HeapTupleIsValid(atttuple))
   19774          12 :                 ereport(ERROR,
   19775             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
   19776             :                          errmsg("column \"%s\" named in partition key does not exist",
   19777             :                                 pelem->name),
   19778             :                          parser_errposition(pstate, pelem->location)));
   19779        5192 :             attform = (Form_pg_attribute) GETSTRUCT(atttuple);
   19780             : 
   19781        5192 :             if (attform->attnum <= 0)
   19782           6 :                 ereport(ERROR,
   19783             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   19784             :                          errmsg("cannot use system column \"%s\" in partition key",
   19785             :                                 pelem->name),
   19786             :                          parser_errposition(pstate, pelem->location)));
   19787             : 
   19788             :             /*
   19789             :              * Stored generated columns cannot work: They are computed after
   19790             :              * BEFORE triggers, but partition routing is done before all
   19791             :              * triggers.  Maybe virtual generated columns could be made to
   19792             :              * work, but then they would need to be handled as an expression
   19793             :              * below.
   19794             :              */
   19795        5186 :             if (attform->attgenerated)
   19796          12 :                 ereport(ERROR,
   19797             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   19798             :                          errmsg("cannot use generated column in partition key"),
   19799             :                          errdetail("Column \"%s\" is a generated column.",
   19800             :                                    pelem->name),
   19801             :                          parser_errposition(pstate, pelem->location)));
   19802             : 
   19803        5174 :             partattrs[attn] = attform->attnum;
   19804        5174 :             atttype = attform->atttypid;
   19805        5174 :             attcollation = attform->attcollation;
   19806        5174 :             ReleaseSysCache(atttuple);
   19807             :         }
   19808             :         else
   19809             :         {
   19810             :             /* Expression */
   19811         280 :             Node       *expr = pelem->expr;
   19812             :             char        partattname[16];
   19813             : 
   19814             :             Assert(expr != NULL);
   19815         280 :             atttype = exprType(expr);
   19816         280 :             attcollation = exprCollation(expr);
   19817             : 
   19818             :             /*
   19819             :              * The expression must be of a storable type (e.g., not RECORD).
   19820             :              * The test is the same as for whether a table column is of a safe
   19821             :              * type (which is why we needn't check for the non-expression
   19822             :              * case).
   19823             :              */
   19824         280 :             snprintf(partattname, sizeof(partattname), "%d", attn + 1);
   19825         280 :             CheckAttributeType(partattname,
   19826             :                                atttype, attcollation,
   19827             :                                NIL, CHKATYPE_IS_PARTKEY);
   19828             : 
   19829             :             /*
   19830             :              * Strip any top-level COLLATE clause.  This ensures that we treat
   19831             :              * "x COLLATE y" and "(x COLLATE y)" alike.
   19832             :              */
   19833         268 :             while (IsA(expr, CollateExpr))
   19834           0 :                 expr = (Node *) ((CollateExpr *) expr)->arg;
   19835             : 
   19836         268 :             if (IsA(expr, Var) &&
   19837          12 :                 ((Var *) expr)->varattno > 0)
   19838             :             {
   19839             :                 /*
   19840             :                  * User wrote "(column)" or "(column COLLATE something)".
   19841             :                  * Treat it like simple attribute anyway.
   19842             :                  */
   19843           6 :                 partattrs[attn] = ((Var *) expr)->varattno;
   19844             :             }
   19845             :             else
   19846             :             {
   19847         262 :                 Bitmapset  *expr_attrs = NULL;
   19848             :                 int         i;
   19849             : 
   19850         262 :                 partattrs[attn] = 0;    /* marks the column as expression */
   19851         262 :                 *partexprs = lappend(*partexprs, expr);
   19852             : 
   19853             :                 /*
   19854             :                  * transformPartitionSpec() should have already rejected
   19855             :                  * subqueries, aggregates, window functions, and SRFs, based
   19856             :                  * on the EXPR_KIND_ for partition expressions.
   19857             :                  */
   19858             : 
   19859             :                 /*
   19860             :                  * Cannot allow system column references, since that would
   19861             :                  * make partition routing impossible: their values won't be
   19862             :                  * known yet when we need to do that.
   19863             :                  */
   19864         262 :                 pull_varattnos(expr, 1, &expr_attrs);
   19865        2096 :                 for (i = FirstLowInvalidHeapAttributeNumber; i < 0; i++)
   19866             :                 {
   19867        1834 :                     if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber,
   19868             :                                       expr_attrs))
   19869           0 :                         ereport(ERROR,
   19870             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   19871             :                                  errmsg("partition key expressions cannot contain system column references")));
   19872             :                 }
   19873             : 
   19874             :                 /*
   19875             :                  * Stored generated columns cannot work: They are computed
   19876             :                  * after BEFORE triggers, but partition routing is done before
   19877             :                  * all triggers.  Virtual generated columns could probably
   19878             :                  * work, but it would require more work elsewhere (for example
   19879             :                  * SET EXPRESSION would need to check whether the column is
   19880             :                  * used in partition keys).  Seems safer to prohibit for now.
   19881             :                  */
   19882         262 :                 i = -1;
   19883         570 :                 while ((i = bms_next_member(expr_attrs, i)) >= 0)
   19884             :                 {
   19885         320 :                     AttrNumber  attno = i + FirstLowInvalidHeapAttributeNumber;
   19886             : 
   19887         320 :                     if (attno > 0 &&
   19888         314 :                         TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated)
   19889          12 :                         ereport(ERROR,
   19890             :                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   19891             :                                  errmsg("cannot use generated column in partition key"),
   19892             :                                  errdetail("Column \"%s\" is a generated column.",
   19893             :                                            get_attname(RelationGetRelid(rel), attno, false)),
   19894             :                                  parser_errposition(pstate, pelem->location)));
   19895             :                 }
   19896             : 
   19897             :                 /*
   19898             :                  * Preprocess the expression before checking for mutability.
   19899             :                  * This is essential for the reasons described in
   19900             :                  * contain_mutable_functions_after_planning.  However, we call
   19901             :                  * expression_planner for ourselves rather than using that
   19902             :                  * function, because if constant-folding reduces the
   19903             :                  * expression to a constant, we'd like to know that so we can
   19904             :                  * complain below.
   19905             :                  *
   19906             :                  * Like contain_mutable_functions_after_planning, assume that
   19907             :                  * expression_planner won't scribble on its input, so this
   19908             :                  * won't affect the partexprs entry we saved above.
   19909             :                  */
   19910         250 :                 expr = (Node *) expression_planner((Expr *) expr);
   19911             : 
   19912             :                 /*
   19913             :                  * Partition expressions cannot contain mutable functions,
   19914             :                  * because a given row must always map to the same partition
   19915             :                  * as long as there is no change in the partition boundary
   19916             :                  * structure.
   19917             :                  */
   19918         250 :                 if (contain_mutable_functions(expr))
   19919           6 :                     ereport(ERROR,
   19920             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   19921             :                              errmsg("functions in partition key expression must be marked IMMUTABLE")));
   19922             : 
   19923             :                 /*
   19924             :                  * While it is not exactly *wrong* for a partition expression
   19925             :                  * to be a constant, it seems better to reject such keys.
   19926             :                  */
   19927         244 :                 if (IsA(expr, Const))
   19928          12 :                     ereport(ERROR,
   19929             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   19930             :                              errmsg("cannot use constant expression as partition key")));
   19931             :             }
   19932             :         }
   19933             : 
   19934             :         /*
   19935             :          * Apply collation override if any
   19936             :          */
   19937        5412 :         if (pelem->collation)
   19938          54 :             attcollation = get_collation_oid(pelem->collation, false);
   19939             : 
   19940             :         /*
   19941             :          * Check we have a collation iff it's a collatable type.  The only
   19942             :          * expected failures here are (1) COLLATE applied to a noncollatable
   19943             :          * type, or (2) partition expression had an unresolved collation. But
   19944             :          * we might as well code this to be a complete consistency check.
   19945             :          */
   19946        5412 :         if (type_is_collatable(atttype))
   19947             :         {
   19948         606 :             if (!OidIsValid(attcollation))
   19949           0 :                 ereport(ERROR,
   19950             :                         (errcode(ERRCODE_INDETERMINATE_COLLATION),
   19951             :                          errmsg("could not determine which collation to use for partition expression"),
   19952             :                          errhint("Use the COLLATE clause to set the collation explicitly.")));
   19953             :         }
   19954             :         else
   19955             :         {
   19956        4806 :             if (OidIsValid(attcollation))
   19957           0 :                 ereport(ERROR,
   19958             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
   19959             :                          errmsg("collations are not supported by type %s",
   19960             :                                 format_type_be(atttype))));
   19961             :         }
   19962             : 
   19963        5412 :         partcollation[attn] = attcollation;
   19964             : 
   19965             :         /*
   19966             :          * Identify the appropriate operator class.  For list and range
   19967             :          * partitioning, we use a btree operator class; hash partitioning uses
   19968             :          * a hash operator class.
   19969             :          */
   19970        5412 :         if (strategy == PARTITION_STRATEGY_HASH)
   19971         320 :             am_oid = HASH_AM_OID;
   19972             :         else
   19973        5092 :             am_oid = BTREE_AM_OID;
   19974             : 
   19975        5412 :         if (!pelem->opclass)
   19976             :         {
   19977        5274 :             partopclass[attn] = GetDefaultOpClass(atttype, am_oid);
   19978             : 
   19979        5274 :             if (!OidIsValid(partopclass[attn]))
   19980             :             {
   19981          12 :                 if (strategy == PARTITION_STRATEGY_HASH)
   19982           0 :                     ereport(ERROR,
   19983             :                             (errcode(ERRCODE_UNDEFINED_OBJECT),
   19984             :                              errmsg("data type %s has no default operator class for access method \"%s\"",
   19985             :                                     format_type_be(atttype), "hash"),
   19986             :                              errhint("You must specify a hash operator class or define a default hash operator class for the data type.")));
   19987             :                 else
   19988          12 :                     ereport(ERROR,
   19989             :                             (errcode(ERRCODE_UNDEFINED_OBJECT),
   19990             :                              errmsg("data type %s has no default operator class for access method \"%s\"",
   19991             :                                     format_type_be(atttype), "btree"),
   19992             :                              errhint("You must specify a btree operator class or define a default btree operator class for the data type.")));
   19993             :             }
   19994             :         }
   19995             :         else
   19996         138 :             partopclass[attn] = ResolveOpClass(pelem->opclass,
   19997             :                                                atttype,
   19998             :                                                am_oid == HASH_AM_OID ? "hash" : "btree",
   19999             :                                                am_oid);
   20000             : 
   20001        5388 :         attn++;
   20002             :     }
   20003        4938 : }
   20004             : 
   20005             : /*
   20006             :  * PartConstraintImpliedByRelConstraint
   20007             :  *      Do scanrel's existing constraints imply the partition constraint?
   20008             :  *
   20009             :  * "Existing constraints" include its check constraints and column-level
   20010             :  * not-null constraints.  partConstraint describes the partition constraint,
   20011             :  * in implicit-AND form.
   20012             :  */
   20013             : bool
   20014        3066 : PartConstraintImpliedByRelConstraint(Relation scanrel,
   20015             :                                      List *partConstraint)
   20016             : {
   20017        3066 :     List       *existConstraint = NIL;
   20018        3066 :     TupleConstr *constr = RelationGetDescr(scanrel)->constr;
   20019             :     int         i;
   20020             : 
   20021        3066 :     if (constr && constr->has_not_null)
   20022             :     {
   20023         790 :         int         natts = scanrel->rd_att->natts;
   20024             : 
   20025        2614 :         for (i = 1; i <= natts; i++)
   20026             :         {
   20027        1824 :             CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
   20028             : 
   20029             :             /* invalid not-null constraint must be ignored here */
   20030        1824 :             if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
   20031             :             {
   20032        1086 :                 Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
   20033        1086 :                 NullTest   *ntest = makeNode(NullTest);
   20034             : 
   20035        1086 :                 ntest->arg = (Expr *) makeVar(1,
   20036             :                                               i,
   20037             :                                               wholeatt->atttypid,
   20038             :                                               wholeatt->atttypmod,
   20039             :                                               wholeatt->attcollation,
   20040             :                                               0);
   20041        1086 :                 ntest->nulltesttype = IS_NOT_NULL;
   20042             : 
   20043             :                 /*
   20044             :                  * argisrow=false is correct even for a composite column,
   20045             :                  * because attnotnull does not represent a SQL-spec IS NOT
   20046             :                  * NULL test in such a case, just IS DISTINCT FROM NULL.
   20047             :                  */
   20048        1086 :                 ntest->argisrow = false;
   20049        1086 :                 ntest->location = -1;
   20050        1086 :                 existConstraint = lappend(existConstraint, ntest);
   20051             :             }
   20052             :         }
   20053             :     }
   20054             : 
   20055        3066 :     return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
   20056             : }
   20057             : 
   20058             : /*
   20059             :  * ConstraintImpliedByRelConstraint
   20060             :  *      Do scanrel's existing constraints imply the given constraint?
   20061             :  *
   20062             :  * testConstraint is the constraint to validate. provenConstraint is a
   20063             :  * caller-provided list of conditions which this function may assume
   20064             :  * to be true. Both provenConstraint and testConstraint must be in
   20065             :  * implicit-AND form, must only contain immutable clauses, and must
   20066             :  * contain only Vars with varno = 1.
   20067             :  */
   20068             : bool
   20069        4310 : ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
   20070             : {
   20071        4310 :     List       *existConstraint = list_copy(provenConstraint);
   20072        4310 :     TupleConstr *constr = RelationGetDescr(scanrel)->constr;
   20073             :     int         num_check,
   20074             :                 i;
   20075             : 
   20076        4310 :     num_check = (constr != NULL) ? constr->num_check : 0;
   20077        4818 :     for (i = 0; i < num_check; i++)
   20078             :     {
   20079             :         Node       *cexpr;
   20080             : 
   20081             :         /*
   20082             :          * If this constraint hasn't been fully validated yet, we must ignore
   20083             :          * it here.
   20084             :          */
   20085         508 :         if (!constr->check[i].ccvalid)
   20086           6 :             continue;
   20087             : 
   20088             :         /*
   20089             :          * NOT ENFORCED constraints are always marked as invalid, which should
   20090             :          * have been ignored.
   20091             :          */
   20092             :         Assert(constr->check[i].ccenforced);
   20093             : 
   20094         502 :         cexpr = stringToNode(constr->check[i].ccbin);
   20095             : 
   20096             :         /*
   20097             :          * Run each expression through const-simplification and
   20098             :          * canonicalization.  It is necessary, because we will be comparing it
   20099             :          * to similarly-processed partition constraint expressions, and may
   20100             :          * fail to detect valid matches without this.
   20101             :          */
   20102         502 :         cexpr = eval_const_expressions(NULL, cexpr);
   20103         502 :         cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
   20104             : 
   20105         502 :         existConstraint = list_concat(existConstraint,
   20106         502 :                                       make_ands_implicit((Expr *) cexpr));
   20107             :     }
   20108             : 
   20109             :     /*
   20110             :      * Try to make the proof.  Since we are comparing CHECK constraints, we
   20111             :      * need to use weak implication, i.e., we assume existConstraint is
   20112             :      * not-false and try to prove the same for testConstraint.
   20113             :      *
   20114             :      * Note that predicate_implied_by assumes its first argument is known
   20115             :      * immutable.  That should always be true for both NOT NULL and partition
   20116             :      * constraints, so we don't test it here.
   20117             :      */
   20118        4310 :     return predicate_implied_by(testConstraint, existConstraint, true);
   20119             : }
   20120             : 
   20121             : /*
   20122             :  * QueuePartitionConstraintValidation
   20123             :  *
   20124             :  * Add an entry to wqueue to have the given partition constraint validated by
   20125             :  * Phase 3, for the given relation, and all its children.
   20126             :  *
   20127             :  * We first verify whether the given constraint is implied by pre-existing
   20128             :  * relation constraints; if it is, there's no need to scan the table to
   20129             :  * validate, so don't queue in that case.
   20130             :  */
   20131             : static void
   20132        2576 : QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
   20133             :                                    List *partConstraint,
   20134             :                                    bool validate_default)
   20135             : {
   20136             :     /*
   20137             :      * Based on the table's existing constraints, determine whether or not we
   20138             :      * may skip scanning the table.
   20139             :      */
   20140        2576 :     if (PartConstraintImpliedByRelConstraint(scanrel, partConstraint))
   20141             :     {
   20142          88 :         if (!validate_default)
   20143          66 :             ereport(DEBUG1,
   20144             :                     (errmsg_internal("partition constraint for table \"%s\" is implied by existing constraints",
   20145             :                                      RelationGetRelationName(scanrel))));
   20146             :         else
   20147          22 :             ereport(DEBUG1,
   20148             :                     (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
   20149             :                                      RelationGetRelationName(scanrel))));
   20150          88 :         return;
   20151             :     }
   20152             : 
   20153             :     /*
   20154             :      * Constraints proved insufficient. For plain relations, queue a
   20155             :      * validation item now; for partitioned tables, recurse to process each
   20156             :      * partition.
   20157             :      */
   20158        2488 :     if (scanrel->rd_rel->relkind == RELKIND_RELATION)
   20159             :     {
   20160             :         AlteredTableInfo *tab;
   20161             : 
   20162             :         /* Grab a work queue entry. */
   20163        2070 :         tab = ATGetQueueEntry(wqueue, scanrel);
   20164             :         Assert(tab->partition_constraint == NULL);
   20165        2070 :         tab->partition_constraint = (Expr *) linitial(partConstraint);
   20166        2070 :         tab->validate_default = validate_default;
   20167             :     }
   20168         418 :     else if (scanrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   20169             :     {
   20170         366 :         PartitionDesc partdesc = RelationGetPartitionDesc(scanrel, true);
   20171             :         int         i;
   20172             : 
   20173         756 :         for (i = 0; i < partdesc->nparts; i++)
   20174             :         {
   20175             :             Relation    part_rel;
   20176             :             List       *thisPartConstraint;
   20177             : 
   20178             :             /*
   20179             :              * This is the minimum lock we need to prevent deadlocks.
   20180             :              */
   20181         390 :             part_rel = table_open(partdesc->oids[i], AccessExclusiveLock);
   20182             : 
   20183             :             /*
   20184             :              * Adjust the constraint for scanrel so that it matches this
   20185             :              * partition's attribute numbers.
   20186             :              */
   20187             :             thisPartConstraint =
   20188         390 :                 map_partition_varattnos(partConstraint, 1,
   20189             :                                         part_rel, scanrel);
   20190             : 
   20191         390 :             QueuePartitionConstraintValidation(wqueue, part_rel,
   20192             :                                                thisPartConstraint,
   20193             :                                                validate_default);
   20194         390 :             table_close(part_rel, NoLock);  /* keep lock till commit */
   20195             :         }
   20196             :     }
   20197             : }
   20198             : 
   20199             : /*
   20200             :  * ALTER TABLE <name> ATTACH PARTITION <partition-name> FOR VALUES
   20201             :  *
   20202             :  * Return the address of the newly attached partition.
   20203             :  */
   20204             : static ObjectAddress
   20205        2406 : ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
   20206             :                       AlterTableUtilityContext *context)
   20207             : {
   20208             :     Relation    attachrel,
   20209             :                 catalog;
   20210             :     List       *attachrel_children;
   20211             :     List       *partConstraint;
   20212             :     SysScanDesc scan;
   20213             :     ScanKeyData skey;
   20214             :     AttrNumber  attno;
   20215             :     int         natts;
   20216             :     TupleDesc   tupleDesc;
   20217             :     ObjectAddress address;
   20218             :     const char *trigger_name;
   20219             :     Oid         defaultPartOid;
   20220             :     List       *partBoundConstraint;
   20221        2406 :     ParseState *pstate = make_parsestate(NULL);
   20222             : 
   20223        2406 :     pstate->p_sourcetext = context->queryString;
   20224             : 
   20225             :     /*
   20226             :      * We must lock the default partition if one exists, because attaching a
   20227             :      * new partition will change its partition constraint.
   20228             :      */
   20229             :     defaultPartOid =
   20230        2406 :         get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
   20231        2406 :     if (OidIsValid(defaultPartOid))
   20232         182 :         LockRelationOid(defaultPartOid, AccessExclusiveLock);
   20233             : 
   20234        2406 :     attachrel = table_openrv(cmd->name, AccessExclusiveLock);
   20235             : 
   20236             :     /*
   20237             :      * XXX I think it'd be a good idea to grab locks on all tables referenced
   20238             :      * by FKs at this point also.
   20239             :      */
   20240             : 
   20241             :     /*
   20242             :      * Must be owner of both parent and source table -- parent was checked by
   20243             :      * ATSimplePermissions call in ATPrepCmd
   20244             :      */
   20245        2400 :     ATSimplePermissions(AT_AttachPartition, attachrel,
   20246             :                         ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
   20247             : 
   20248             :     /* A partition can only have one parent */
   20249        2394 :     if (attachrel->rd_rel->relispartition)
   20250           6 :         ereport(ERROR,
   20251             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20252             :                  errmsg("\"%s\" is already a partition",
   20253             :                         RelationGetRelationName(attachrel))));
   20254             : 
   20255        2388 :     if (OidIsValid(attachrel->rd_rel->reloftype))
   20256           6 :         ereport(ERROR,
   20257             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20258             :                  errmsg("cannot attach a typed table as partition")));
   20259             : 
   20260             :     /*
   20261             :      * Table being attached should not already be part of inheritance; either
   20262             :      * as a child table...
   20263             :      */
   20264        2382 :     catalog = table_open(InheritsRelationId, AccessShareLock);
   20265        2382 :     ScanKeyInit(&skey,
   20266             :                 Anum_pg_inherits_inhrelid,
   20267             :                 BTEqualStrategyNumber, F_OIDEQ,
   20268             :                 ObjectIdGetDatum(RelationGetRelid(attachrel)));
   20269        2382 :     scan = systable_beginscan(catalog, InheritsRelidSeqnoIndexId, true,
   20270             :                               NULL, 1, &skey);
   20271        2382 :     if (HeapTupleIsValid(systable_getnext(scan)))
   20272           6 :         ereport(ERROR,
   20273             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20274             :                  errmsg("cannot attach inheritance child as partition")));
   20275        2376 :     systable_endscan(scan);
   20276             : 
   20277             :     /* ...or as a parent table (except the case when it is partitioned) */
   20278        2376 :     ScanKeyInit(&skey,
   20279             :                 Anum_pg_inherits_inhparent,
   20280             :                 BTEqualStrategyNumber, F_OIDEQ,
   20281             :                 ObjectIdGetDatum(RelationGetRelid(attachrel)));
   20282        2376 :     scan = systable_beginscan(catalog, InheritsParentIndexId, true, NULL,
   20283             :                               1, &skey);
   20284        2376 :     if (HeapTupleIsValid(systable_getnext(scan)) &&
   20285         262 :         attachrel->rd_rel->relkind == RELKIND_RELATION)
   20286           6 :         ereport(ERROR,
   20287             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20288             :                  errmsg("cannot attach inheritance parent as partition")));
   20289        2370 :     systable_endscan(scan);
   20290        2370 :     table_close(catalog, AccessShareLock);
   20291             : 
   20292             :     /*
   20293             :      * Prevent circularity by seeing if rel is a partition of attachrel. (In
   20294             :      * particular, this disallows making a rel a partition of itself.)
   20295             :      *
   20296             :      * We do that by checking if rel is a member of the list of attachrel's
   20297             :      * partitions provided the latter is partitioned at all.  We want to avoid
   20298             :      * having to construct this list again, so we request the strongest lock
   20299             :      * on all partitions.  We need the strongest lock, because we may decide
   20300             :      * to scan them if we find out that the table being attached (or its leaf
   20301             :      * partitions) may contain rows that violate the partition constraint. If
   20302             :      * the table has a constraint that would prevent such rows, which by
   20303             :      * definition is present in all the partitions, we need not scan the
   20304             :      * table, nor its partitions.  But we cannot risk a deadlock by taking a
   20305             :      * weaker lock now and the stronger one only when needed.
   20306             :      */
   20307        2370 :     attachrel_children = find_all_inheritors(RelationGetRelid(attachrel),
   20308             :                                              AccessExclusiveLock, NULL);
   20309        2370 :     if (list_member_oid(attachrel_children, RelationGetRelid(rel)))
   20310          12 :         ereport(ERROR,
   20311             :                 (errcode(ERRCODE_DUPLICATE_TABLE),
   20312             :                  errmsg("circular inheritance not allowed"),
   20313             :                  errdetail("\"%s\" is already a child of \"%s\".",
   20314             :                            RelationGetRelationName(rel),
   20315             :                            RelationGetRelationName(attachrel))));
   20316             : 
   20317             :     /* If the parent is permanent, so must be all of its partitions. */
   20318        2358 :     if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
   20319        2316 :         attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
   20320           6 :         ereport(ERROR,
   20321             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20322             :                  errmsg("cannot attach a temporary relation as partition of permanent relation \"%s\"",
   20323             :                         RelationGetRelationName(rel))));
   20324             : 
   20325             :     /* Temp parent cannot have a partition that is itself not a temp */
   20326        2352 :     if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
   20327          42 :         attachrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
   20328          18 :         ereport(ERROR,
   20329             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20330             :                  errmsg("cannot attach a permanent relation as partition of temporary relation \"%s\"",
   20331             :                         RelationGetRelationName(rel))));
   20332             : 
   20333             :     /* If the parent is temp, it must belong to this session */
   20334        2334 :     if (RELATION_IS_OTHER_TEMP(rel))
   20335           0 :         ereport(ERROR,
   20336             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20337             :                  errmsg("cannot attach as partition of temporary relation of another session")));
   20338             : 
   20339             :     /* Ditto for the partition */
   20340        2334 :     if (RELATION_IS_OTHER_TEMP(attachrel))
   20341           0 :         ereport(ERROR,
   20342             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20343             :                  errmsg("cannot attach temporary relation of another session as partition")));
   20344             : 
   20345             :     /*
   20346             :      * Check if attachrel has any identity columns or any columns that aren't
   20347             :      * in the parent.
   20348             :      */
   20349        2334 :     tupleDesc = RelationGetDescr(attachrel);
   20350        2334 :     natts = tupleDesc->natts;
   20351        7962 :     for (attno = 1; attno <= natts; attno++)
   20352             :     {
   20353        5670 :         Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
   20354        5670 :         char       *attributeName = NameStr(attribute->attname);
   20355             : 
   20356             :         /* Ignore dropped */
   20357        5670 :         if (attribute->attisdropped)
   20358         580 :             continue;
   20359             : 
   20360        5090 :         if (attribute->attidentity)
   20361          24 :             ereport(ERROR,
   20362             :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   20363             :                     errmsg("table \"%s\" being attached contains an identity column \"%s\"",
   20364             :                            RelationGetRelationName(attachrel), attributeName),
   20365             :                     errdetail("The new partition may not contain an identity column."));
   20366             : 
   20367             :         /* Try to find the column in parent (matching on column name) */
   20368        5066 :         if (!SearchSysCacheExists2(ATTNAME,
   20369             :                                    ObjectIdGetDatum(RelationGetRelid(rel)),
   20370             :                                    CStringGetDatum(attributeName)))
   20371          18 :             ereport(ERROR,
   20372             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
   20373             :                      errmsg("table \"%s\" contains column \"%s\" not found in parent \"%s\"",
   20374             :                             RelationGetRelationName(attachrel), attributeName,
   20375             :                             RelationGetRelationName(rel)),
   20376             :                      errdetail("The new partition may contain only the columns present in parent.")));
   20377             :     }
   20378             : 
   20379             :     /*
   20380             :      * If child_rel has row-level triggers with transition tables, we
   20381             :      * currently don't allow it to become a partition.  See also prohibitions
   20382             :      * in ATExecAddInherit() and CreateTrigger().
   20383             :      */
   20384        2292 :     trigger_name = FindTriggerIncompatibleWithInheritance(attachrel->trigdesc);
   20385        2292 :     if (trigger_name != NULL)
   20386           6 :         ereport(ERROR,
   20387             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   20388             :                  errmsg("trigger \"%s\" prevents table \"%s\" from becoming a partition",
   20389             :                         trigger_name, RelationGetRelationName(attachrel)),
   20390             :                  errdetail("ROW triggers with transition tables are not supported on partitions.")));
   20391             : 
   20392             :     /*
   20393             :      * Check that the new partition's bound is valid and does not overlap any
   20394             :      * of existing partitions of the parent - note that it does not return on
   20395             :      * error.
   20396             :      */
   20397        2286 :     check_new_partition_bound(RelationGetRelationName(attachrel), rel,
   20398             :                               cmd->bound, pstate);
   20399             : 
   20400             :     /* OK to create inheritance.  Rest of the checks performed there */
   20401        2250 :     CreateInheritance(attachrel, rel, true);
   20402             : 
   20403             :     /* Update the pg_class entry. */
   20404        2142 :     StorePartitionBound(attachrel, rel, cmd->bound);
   20405             : 
   20406             :     /* Ensure there exists a correct set of indexes in the partition. */
   20407        2142 :     AttachPartitionEnsureIndexes(wqueue, rel, attachrel);
   20408             : 
   20409             :     /* and triggers */
   20410        2112 :     CloneRowTriggersToPartition(rel, attachrel);
   20411             : 
   20412             :     /*
   20413             :      * Clone foreign key constraints.  Callee is responsible for setting up
   20414             :      * for phase 3 constraint verification.
   20415             :      */
   20416        2106 :     CloneForeignKeyConstraints(wqueue, rel, attachrel);
   20417             : 
   20418             :     /*
   20419             :      * Generate partition constraint from the partition bound specification.
   20420             :      * If the parent itself is a partition, make sure to include its
   20421             :      * constraint as well.
   20422             :      */
   20423        2088 :     partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
   20424             : 
   20425             :     /*
   20426             :      * Use list_concat_copy() to avoid modifying partBoundConstraint in place,
   20427             :      * since it's needed later to construct the constraint expression for
   20428             :      * validating against the default partition, if any.
   20429             :      */
   20430        2088 :     partConstraint = list_concat_copy(partBoundConstraint,
   20431        2088 :                                       RelationGetPartitionQual(rel));
   20432             : 
   20433             :     /* Skip validation if there are no constraints to validate. */
   20434        2088 :     if (partConstraint)
   20435             :     {
   20436             :         /*
   20437             :          * Run the partition quals through const-simplification similar to
   20438             :          * check constraints.  We skip canonicalize_qual, though, because
   20439             :          * partition quals should be in canonical form already.
   20440             :          */
   20441             :         partConstraint =
   20442        2040 :             (List *) eval_const_expressions(NULL,
   20443             :                                             (Node *) partConstraint);
   20444             : 
   20445             :         /* XXX this sure looks wrong */
   20446        2040 :         partConstraint = list_make1(make_ands_explicit(partConstraint));
   20447             : 
   20448             :         /*
   20449             :          * Adjust the generated constraint to match this partition's attribute
   20450             :          * numbers.
   20451             :          */
   20452        2040 :         partConstraint = map_partition_varattnos(partConstraint, 1, attachrel,
   20453             :                                                  rel);
   20454             : 
   20455             :         /* Validate partition constraints against the table being attached. */
   20456        2040 :         QueuePartitionConstraintValidation(wqueue, attachrel, partConstraint,
   20457             :                                            false);
   20458             :     }
   20459             : 
   20460             :     /*
   20461             :      * If we're attaching a partition other than the default partition and a
   20462             :      * default one exists, then that partition's partition constraint changes,
   20463             :      * so add an entry to the work queue to validate it, too.  (We must not do
   20464             :      * this when the partition being attached is the default one; we already
   20465             :      * did it above!)
   20466             :      */
   20467        2088 :     if (OidIsValid(defaultPartOid))
   20468             :     {
   20469             :         Relation    defaultrel;
   20470             :         List       *defPartConstraint;
   20471             : 
   20472             :         Assert(!cmd->bound->is_default);
   20473             : 
   20474             :         /* we already hold a lock on the default partition */
   20475         146 :         defaultrel = table_open(defaultPartOid, NoLock);
   20476             :         defPartConstraint =
   20477         146 :             get_proposed_default_constraint(partBoundConstraint);
   20478             : 
   20479             :         /*
   20480             :          * Map the Vars in the constraint expression from rel's attnos to
   20481             :          * defaultrel's.
   20482             :          */
   20483             :         defPartConstraint =
   20484         146 :             map_partition_varattnos(defPartConstraint,
   20485             :                                     1, defaultrel, rel);
   20486         146 :         QueuePartitionConstraintValidation(wqueue, defaultrel,
   20487             :                                            defPartConstraint, true);
   20488             : 
   20489             :         /* keep our lock until commit. */
   20490         146 :         table_close(defaultrel, NoLock);
   20491             :     }
   20492             : 
   20493        2088 :     ObjectAddressSet(address, RelationRelationId, RelationGetRelid(attachrel));
   20494             : 
   20495             :     /*
   20496             :      * If the partition we just attached is partitioned itself, invalidate
   20497             :      * relcache for all descendent partitions too to ensure that their
   20498             :      * rd_partcheck expression trees are rebuilt; partitions already locked at
   20499             :      * the beginning of this function.
   20500             :      */
   20501        2088 :     if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   20502             :     {
   20503             :         ListCell   *l;
   20504             : 
   20505        1032 :         foreach(l, attachrel_children)
   20506             :         {
   20507         690 :             CacheInvalidateRelcacheByRelid(lfirst_oid(l));
   20508             :         }
   20509             :     }
   20510             : 
   20511             :     /* keep our lock until commit */
   20512        2088 :     table_close(attachrel, NoLock);
   20513             : 
   20514        2088 :     return address;
   20515             : }
   20516             : 
   20517             : /*
   20518             :  * AttachPartitionEnsureIndexes
   20519             :  *      subroutine for ATExecAttachPartition to create/match indexes
   20520             :  *
   20521             :  * Enforce the indexing rule for partitioned tables during ALTER TABLE / ATTACH
   20522             :  * PARTITION: every partition must have an index attached to each index on the
   20523             :  * partitioned table.
   20524             :  */
   20525             : static void
   20526        2142 : AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
   20527             : {
   20528             :     List       *idxes;
   20529             :     List       *attachRelIdxs;
   20530             :     Relation   *attachrelIdxRels;
   20531             :     IndexInfo **attachInfos;
   20532             :     ListCell   *cell;
   20533             :     MemoryContext cxt;
   20534             :     MemoryContext oldcxt;
   20535             : 
   20536        2142 :     cxt = AllocSetContextCreate(CurrentMemoryContext,
   20537             :                                 "AttachPartitionEnsureIndexes",
   20538             :                                 ALLOCSET_DEFAULT_SIZES);
   20539        2142 :     oldcxt = MemoryContextSwitchTo(cxt);
   20540             : 
   20541        2142 :     idxes = RelationGetIndexList(rel);
   20542        2142 :     attachRelIdxs = RelationGetIndexList(attachrel);
   20543        2142 :     attachrelIdxRels = palloc(sizeof(Relation) * list_length(attachRelIdxs));
   20544        2142 :     attachInfos = palloc(sizeof(IndexInfo *) * list_length(attachRelIdxs));
   20545             : 
   20546             :     /* Build arrays of all existing indexes and their IndexInfos */
   20547        4666 :     foreach_oid(cldIdxId, attachRelIdxs)
   20548             :     {
   20549         382 :         int         i = foreach_current_index(cldIdxId);
   20550             : 
   20551         382 :         attachrelIdxRels[i] = index_open(cldIdxId, AccessShareLock);
   20552         382 :         attachInfos[i] = BuildIndexInfo(attachrelIdxRels[i]);
   20553             :     }
   20554             : 
   20555             :     /*
   20556             :      * If we're attaching a foreign table, we must fail if any of the indexes
   20557             :      * is a constraint index; otherwise, there's nothing to do here.  Do this
   20558             :      * before starting work, to avoid wasting the effort of building a few
   20559             :      * non-unique indexes before coming across a unique one.
   20560             :      */
   20561        2142 :     if (attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
   20562             :     {
   20563          88 :         foreach(cell, idxes)
   20564             :         {
   20565          36 :             Oid         idx = lfirst_oid(cell);
   20566          36 :             Relation    idxRel = index_open(idx, AccessShareLock);
   20567             : 
   20568          36 :             if (idxRel->rd_index->indisunique ||
   20569          24 :                 idxRel->rd_index->indisprimary)
   20570          12 :                 ereport(ERROR,
   20571             :                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
   20572             :                          errmsg("cannot attach foreign table \"%s\" as partition of partitioned table \"%s\"",
   20573             :                                 RelationGetRelationName(attachrel),
   20574             :                                 RelationGetRelationName(rel)),
   20575             :                          errdetail("Partitioned table \"%s\" contains unique indexes.",
   20576             :                                    RelationGetRelationName(rel))));
   20577          24 :             index_close(idxRel, AccessShareLock);
   20578             :         }
   20579             : 
   20580          52 :         goto out;
   20581             :     }
   20582             : 
   20583             :     /*
   20584             :      * For each index on the partitioned table, find a matching one in the
   20585             :      * partition-to-be; if one is not found, create one.
   20586             :      */
   20587        2510 :     foreach(cell, idxes)
   20588             :     {
   20589         450 :         Oid         idx = lfirst_oid(cell);
   20590         450 :         Relation    idxRel = index_open(idx, AccessShareLock);
   20591             :         IndexInfo  *info;
   20592             :         AttrMap    *attmap;
   20593         450 :         bool        found = false;
   20594             :         Oid         constraintOid;
   20595             : 
   20596             :         /*
   20597             :          * Ignore indexes in the partitioned table other than partitioned
   20598             :          * indexes.
   20599             :          */
   20600         450 :         if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
   20601             :         {
   20602           0 :             index_close(idxRel, AccessShareLock);
   20603           0 :             continue;
   20604             :         }
   20605             : 
   20606             :         /* construct an indexinfo to compare existing indexes against */
   20607         450 :         info = BuildIndexInfo(idxRel);
   20608         450 :         attmap = build_attrmap_by_name(RelationGetDescr(attachrel),
   20609             :                                        RelationGetDescr(rel),
   20610             :                                        false);
   20611         450 :         constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(rel), idx);
   20612             : 
   20613             :         /*
   20614             :          * Scan the list of existing indexes in the partition-to-be, and mark
   20615             :          * the first matching, valid, unattached one we find, if any, as
   20616             :          * partition of the parent index.  If we find one, we're done.
   20617             :          */
   20618         510 :         for (int i = 0; i < list_length(attachRelIdxs); i++)
   20619             :         {
   20620         274 :             Oid         cldIdxId = RelationGetRelid(attachrelIdxRels[i]);
   20621         274 :             Oid         cldConstrOid = InvalidOid;
   20622             : 
   20623             :             /* does this index have a parent?  if so, can't use it */
   20624         274 :             if (attachrelIdxRels[i]->rd_rel->relispartition)
   20625          12 :                 continue;
   20626             : 
   20627             :             /* If this index is invalid, can't use it */
   20628         262 :             if (!attachrelIdxRels[i]->rd_index->indisvalid)
   20629           6 :                 continue;
   20630             : 
   20631         256 :             if (CompareIndexInfo(attachInfos[i], info,
   20632         256 :                                  attachrelIdxRels[i]->rd_indcollation,
   20633         256 :                                  idxRel->rd_indcollation,
   20634         256 :                                  attachrelIdxRels[i]->rd_opfamily,
   20635         256 :                                  idxRel->rd_opfamily,
   20636             :                                  attmap))
   20637             :             {
   20638             :                 /*
   20639             :                  * If this index is being created in the parent because of a
   20640             :                  * constraint, then the child needs to have a constraint also,
   20641             :                  * so look for one.  If there is no such constraint, this
   20642             :                  * index is no good, so keep looking.
   20643             :                  */
   20644         220 :                 if (OidIsValid(constraintOid))
   20645             :                 {
   20646             :                     cldConstrOid =
   20647         122 :                         get_relation_idx_constraint_oid(RelationGetRelid(attachrel),
   20648             :                                                         cldIdxId);
   20649             :                     /* no dice */
   20650         122 :                     if (!OidIsValid(cldConstrOid))
   20651           6 :                         continue;
   20652             : 
   20653             :                     /* Ensure they're both the same type of constraint */
   20654         232 :                     if (get_constraint_type(constraintOid) !=
   20655         116 :                         get_constraint_type(cldConstrOid))
   20656           0 :                         continue;
   20657             :                 }
   20658             : 
   20659             :                 /* bingo. */
   20660         214 :                 IndexSetParentIndex(attachrelIdxRels[i], idx);
   20661         214 :                 if (OidIsValid(constraintOid))
   20662         116 :                     ConstraintSetParentConstraint(cldConstrOid, constraintOid,
   20663             :                                                   RelationGetRelid(attachrel));
   20664         214 :                 found = true;
   20665             : 
   20666         214 :                 CommandCounterIncrement();
   20667         214 :                 break;
   20668             :             }
   20669             :         }
   20670             : 
   20671             :         /*
   20672             :          * If no suitable index was found in the partition-to-be, create one
   20673             :          * now.  Note that if this is a PK, not-null constraints must already
   20674             :          * exist.
   20675             :          */
   20676         450 :         if (!found)
   20677             :         {
   20678             :             IndexStmt  *stmt;
   20679             :             Oid         conOid;
   20680             : 
   20681         236 :             stmt = generateClonedIndexStmt(NULL,
   20682             :                                            idxRel, attmap,
   20683             :                                            &conOid);
   20684         236 :             DefineIndex(RelationGetRelid(attachrel), stmt, InvalidOid,
   20685             :                         RelationGetRelid(idxRel),
   20686             :                         conOid,
   20687             :                         -1,
   20688             :                         true, false, false, false, false);
   20689             :         }
   20690             : 
   20691         432 :         index_close(idxRel, AccessShareLock);
   20692             :     }
   20693             : 
   20694        2112 : out:
   20695             :     /* Clean up. */
   20696        2482 :     for (int i = 0; i < list_length(attachRelIdxs); i++)
   20697         370 :         index_close(attachrelIdxRels[i], AccessShareLock);
   20698        2112 :     MemoryContextSwitchTo(oldcxt);
   20699        2112 :     MemoryContextDelete(cxt);
   20700        2112 : }
   20701             : 
   20702             : /*
   20703             :  * CloneRowTriggersToPartition
   20704             :  *      subroutine for ATExecAttachPartition/DefineRelation to create row
   20705             :  *      triggers on partitions
   20706             :  */
   20707             : static void
   20708        2556 : CloneRowTriggersToPartition(Relation parent, Relation partition)
   20709             : {
   20710             :     Relation    pg_trigger;
   20711             :     ScanKeyData key;
   20712             :     SysScanDesc scan;
   20713             :     HeapTuple   tuple;
   20714             :     MemoryContext perTupCxt;
   20715             : 
   20716        2556 :     ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
   20717             :                 F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
   20718        2556 :     pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
   20719        2556 :     scan = systable_beginscan(pg_trigger, TriggerRelidNameIndexId,
   20720             :                               true, NULL, 1, &key);
   20721             : 
   20722        2556 :     perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
   20723             :                                       "clone trig", ALLOCSET_SMALL_SIZES);
   20724             : 
   20725        4418 :     while (HeapTupleIsValid(tuple = systable_getnext(scan)))
   20726             :     {
   20727        1868 :         Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
   20728             :         CreateTrigStmt *trigStmt;
   20729        1868 :         Node       *qual = NULL;
   20730             :         Datum       value;
   20731             :         bool        isnull;
   20732        1868 :         List       *cols = NIL;
   20733        1868 :         List       *trigargs = NIL;
   20734             :         MemoryContext oldcxt;
   20735             : 
   20736             :         /*
   20737             :          * Ignore statement-level triggers; those are not cloned.
   20738             :          */
   20739        1868 :         if (!TRIGGER_FOR_ROW(trigForm->tgtype))
   20740        1712 :             continue;
   20741             : 
   20742             :         /*
   20743             :          * Don't clone internal triggers, because the constraint cloning code
   20744             :          * will.
   20745             :          */
   20746        1850 :         if (trigForm->tgisinternal)
   20747        1694 :             continue;
   20748             : 
   20749             :         /*
   20750             :          * Complain if we find an unexpected trigger type.
   20751             :          */
   20752         156 :         if (!TRIGGER_FOR_BEFORE(trigForm->tgtype) &&
   20753         138 :             !TRIGGER_FOR_AFTER(trigForm->tgtype))
   20754           0 :             elog(ERROR, "unexpected trigger \"%s\" found",
   20755             :                  NameStr(trigForm->tgname));
   20756             : 
   20757             :         /* Use short-lived context for CREATE TRIGGER */
   20758         156 :         oldcxt = MemoryContextSwitchTo(perTupCxt);
   20759             : 
   20760             :         /*
   20761             :          * If there is a WHEN clause, generate a 'cooked' version of it that's
   20762             :          * appropriate for the partition.
   20763             :          */
   20764         156 :         value = heap_getattr(tuple, Anum_pg_trigger_tgqual,
   20765             :                              RelationGetDescr(pg_trigger), &isnull);
   20766         156 :         if (!isnull)
   20767             :         {
   20768           6 :             qual = stringToNode(TextDatumGetCString(value));
   20769           6 :             qual = (Node *) map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
   20770             :                                                     partition, parent);
   20771           6 :             qual = (Node *) map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
   20772             :                                                     partition, parent);
   20773             :         }
   20774             : 
   20775             :         /*
   20776             :          * If there is a column list, transform it to a list of column names.
   20777             :          * Note we don't need to map this list in any way ...
   20778             :          */
   20779         156 :         if (trigForm->tgattr.dim1 > 0)
   20780             :         {
   20781             :             int         i;
   20782             : 
   20783          12 :             for (i = 0; i < trigForm->tgattr.dim1; i++)
   20784             :             {
   20785             :                 Form_pg_attribute col;
   20786             : 
   20787           6 :                 col = TupleDescAttr(parent->rd_att,
   20788           6 :                                     trigForm->tgattr.values[i] - 1);
   20789           6 :                 cols = lappend(cols,
   20790           6 :                                makeString(pstrdup(NameStr(col->attname))));
   20791             :             }
   20792             :         }
   20793             : 
   20794             :         /* Reconstruct trigger arguments list. */
   20795         156 :         if (trigForm->tgnargs > 0)
   20796             :         {
   20797             :             char       *p;
   20798             : 
   20799          12 :             value = heap_getattr(tuple, Anum_pg_trigger_tgargs,
   20800             :                                  RelationGetDescr(pg_trigger), &isnull);
   20801          12 :             if (isnull)
   20802           0 :                 elog(ERROR, "tgargs is null for trigger \"%s\" in partition \"%s\"",
   20803             :                      NameStr(trigForm->tgname), RelationGetRelationName(partition));
   20804             : 
   20805          12 :             p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
   20806             : 
   20807          36 :             for (int i = 0; i < trigForm->tgnargs; i++)
   20808             :             {
   20809          24 :                 trigargs = lappend(trigargs, makeString(pstrdup(p)));
   20810          24 :                 p += strlen(p) + 1;
   20811             :             }
   20812             :         }
   20813             : 
   20814         156 :         trigStmt = makeNode(CreateTrigStmt);
   20815         156 :         trigStmt->replace = false;
   20816         156 :         trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
   20817         156 :         trigStmt->trigname = NameStr(trigForm->tgname);
   20818         156 :         trigStmt->relation = NULL;
   20819         156 :         trigStmt->funcname = NULL;   /* passed separately */
   20820         156 :         trigStmt->args = trigargs;
   20821         156 :         trigStmt->row = true;
   20822         156 :         trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
   20823         156 :         trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
   20824         156 :         trigStmt->columns = cols;
   20825         156 :         trigStmt->whenClause = NULL; /* passed separately */
   20826         156 :         trigStmt->transitionRels = NIL; /* not supported at present */
   20827         156 :         trigStmt->deferrable = trigForm->tgdeferrable;
   20828         156 :         trigStmt->initdeferred = trigForm->tginitdeferred;
   20829         156 :         trigStmt->constrrel = NULL; /* passed separately */
   20830             : 
   20831         156 :         CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
   20832             :                               trigForm->tgconstrrelid, InvalidOid, InvalidOid,
   20833             :                               trigForm->tgfoid, trigForm->oid, qual,
   20834         156 :                               false, true, trigForm->tgenabled);
   20835             : 
   20836         150 :         MemoryContextSwitchTo(oldcxt);
   20837         150 :         MemoryContextReset(perTupCxt);
   20838             :     }
   20839             : 
   20840        2550 :     MemoryContextDelete(perTupCxt);
   20841             : 
   20842        2550 :     systable_endscan(scan);
   20843        2550 :     table_close(pg_trigger, RowExclusiveLock);
   20844        2550 : }
   20845             : 
   20846             : /*
   20847             :  * ALTER TABLE DETACH PARTITION
   20848             :  *
   20849             :  * Return the address of the relation that is no longer a partition of rel.
   20850             :  *
   20851             :  * If concurrent mode is requested, we run in two transactions.  A side-
   20852             :  * effect is that this command cannot run in a multi-part ALTER TABLE.
   20853             :  * Currently, that's enforced by the grammar.
   20854             :  *
   20855             :  * The strategy for concurrency is to first modify the partition's
   20856             :  * pg_inherit catalog row to make it visible to everyone that the
   20857             :  * partition is detached, lock the partition against writes, and commit
   20858             :  * the transaction; anyone who requests the partition descriptor from
   20859             :  * that point onwards has to ignore such a partition.  In a second
   20860             :  * transaction, we wait until all transactions that could have seen the
   20861             :  * partition as attached are gone, then we remove the rest of partition
   20862             :  * metadata (pg_inherits and pg_class.relpartbounds).
   20863             :  */
   20864             : static ObjectAddress
   20865         578 : ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
   20866             :                       RangeVar *name, bool concurrent)
   20867             : {
   20868             :     Relation    partRel;
   20869             :     ObjectAddress address;
   20870             :     Oid         defaultPartOid;
   20871             : 
   20872             :     /*
   20873             :      * We must lock the default partition, because detaching this partition
   20874             :      * will change its partition constraint.
   20875             :      */
   20876             :     defaultPartOid =
   20877         578 :         get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
   20878         578 :     if (OidIsValid(defaultPartOid))
   20879             :     {
   20880             :         /*
   20881             :          * Concurrent detaching when a default partition exists is not
   20882             :          * supported. The main problem is that the default partition
   20883             :          * constraint would change.  And there's a definitional problem: what
   20884             :          * should happen to the tuples that are being inserted that belong to
   20885             :          * the partition being detached?  Putting them on the partition being
   20886             :          * detached would be wrong, since they'd become "lost" after the
   20887             :          * detaching completes but we cannot put them in the default partition
   20888             :          * either until we alter its partition constraint.
   20889             :          *
   20890             :          * I think we could solve this problem if we effected the constraint
   20891             :          * change before committing the first transaction.  But the lock would
   20892             :          * have to remain AEL and it would cause concurrent query planning to
   20893             :          * be blocked, so changing it that way would be even worse.
   20894             :          */
   20895         106 :         if (concurrent)
   20896          12 :             ereport(ERROR,
   20897             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   20898             :                      errmsg("cannot detach partitions concurrently when a default partition exists")));
   20899          94 :         LockRelationOid(defaultPartOid, AccessExclusiveLock);
   20900             :     }
   20901             : 
   20902             :     /*
   20903             :      * In concurrent mode, the partition is locked with share-update-exclusive
   20904             :      * in the first transaction.  This allows concurrent transactions to be
   20905             :      * doing DML to the partition.
   20906             :      */
   20907         566 :     partRel = table_openrv(name, concurrent ? ShareUpdateExclusiveLock :
   20908             :                            AccessExclusiveLock);
   20909             : 
   20910             :     /*
   20911             :      * Check inheritance conditions and either delete the pg_inherits row (in
   20912             :      * non-concurrent mode) or just set the inhdetachpending flag.
   20913             :      */
   20914         554 :     if (!concurrent)
   20915         408 :         RemoveInheritance(partRel, rel, false);
   20916             :     else
   20917         146 :         MarkInheritDetached(partRel, rel);
   20918             : 
   20919             :     /*
   20920             :      * Ensure that foreign keys still hold after this detach.  This keeps
   20921             :      * locks on the referencing tables, which prevents concurrent transactions
   20922             :      * from adding rows that we wouldn't see.  For this to work in concurrent
   20923             :      * mode, it is critical that the partition appears as no longer attached
   20924             :      * for the RI queries as soon as the first transaction commits.
   20925             :      */
   20926         534 :     ATDetachCheckNoForeignKeyRefs(partRel);
   20927             : 
   20928             :     /*
   20929             :      * Concurrent mode has to work harder; first we add a new constraint to
   20930             :      * the partition that matches the partition constraint.  Then we close our
   20931             :      * existing transaction, and in a new one wait for all processes to catch
   20932             :      * up on the catalog updates we've done so far; at that point we can
   20933             :      * complete the operation.
   20934             :      */
   20935         500 :     if (concurrent)
   20936             :     {
   20937             :         Oid         partrelid,
   20938             :                     parentrelid;
   20939             :         LOCKTAG     tag;
   20940             :         char       *parentrelname;
   20941             :         char       *partrelname;
   20942             : 
   20943             :         /*
   20944             :          * We're almost done now; the only traces that remain are the
   20945             :          * pg_inherits tuple and the partition's relpartbounds.  Before we can
   20946             :          * remove those, we need to wait until all transactions that know that
   20947             :          * this is a partition are gone.
   20948             :          */
   20949             : 
   20950             :         /*
   20951             :          * Remember relation OIDs to re-acquire them later; and relation names
   20952             :          * too, for error messages if something is dropped in between.
   20953             :          */
   20954         140 :         partrelid = RelationGetRelid(partRel);
   20955         140 :         parentrelid = RelationGetRelid(rel);
   20956         140 :         parentrelname = MemoryContextStrdup(PortalContext,
   20957         140 :                                             RelationGetRelationName(rel));
   20958         140 :         partrelname = MemoryContextStrdup(PortalContext,
   20959         140 :                                           RelationGetRelationName(partRel));
   20960             : 
   20961             :         /* Invalidate relcache entries for the parent -- must be before close */
   20962         140 :         CacheInvalidateRelcache(rel);
   20963             : 
   20964         140 :         table_close(partRel, NoLock);
   20965         140 :         table_close(rel, NoLock);
   20966         140 :         tab->rel = NULL;
   20967             : 
   20968             :         /* Make updated catalog entry visible */
   20969         140 :         PopActiveSnapshot();
   20970         140 :         CommitTransactionCommand();
   20971             : 
   20972         140 :         StartTransactionCommand();
   20973             : 
   20974             :         /*
   20975             :          * Now wait.  This ensures that all queries that were planned
   20976             :          * including the partition are finished before we remove the rest of
   20977             :          * catalog entries.  We don't need or indeed want to acquire this
   20978             :          * lock, though -- that would block later queries.
   20979             :          *
   20980             :          * We don't need to concern ourselves with waiting for a lock on the
   20981             :          * partition itself, since we will acquire AccessExclusiveLock below.
   20982             :          */
   20983         140 :         SET_LOCKTAG_RELATION(tag, MyDatabaseId, parentrelid);
   20984         140 :         WaitForLockersMultiple(list_make1(&tag), AccessExclusiveLock, false);
   20985             : 
   20986             :         /*
   20987             :          * Now acquire locks in both relations again.  Note they may have been
   20988             :          * removed in the meantime, so care is required.
   20989             :          */
   20990          90 :         rel = try_relation_open(parentrelid, ShareUpdateExclusiveLock);
   20991          90 :         partRel = try_relation_open(partrelid, AccessExclusiveLock);
   20992             : 
   20993             :         /* If the relations aren't there, something bad happened; bail out */
   20994          90 :         if (rel == NULL)
   20995             :         {
   20996           0 :             if (partRel != NULL)    /* shouldn't happen */
   20997           0 :                 elog(WARNING, "dangling partition \"%s\" remains, can't fix",
   20998             :                      partrelname);
   20999           0 :             ereport(ERROR,
   21000             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21001             :                      errmsg("partitioned table \"%s\" was removed concurrently",
   21002             :                             parentrelname)));
   21003             :         }
   21004          90 :         if (partRel == NULL)
   21005           0 :             ereport(ERROR,
   21006             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21007             :                      errmsg("partition \"%s\" was removed concurrently", partrelname)));
   21008             : 
   21009          90 :         tab->rel = rel;
   21010             :     }
   21011             : 
   21012             :     /*
   21013             :      * Detaching the partition might involve TOAST table access, so ensure we
   21014             :      * have a valid snapshot.
   21015             :      */
   21016         450 :     PushActiveSnapshot(GetTransactionSnapshot());
   21017             : 
   21018             :     /* Do the final part of detaching */
   21019         450 :     DetachPartitionFinalize(rel, partRel, concurrent, defaultPartOid);
   21020             : 
   21021         448 :     PopActiveSnapshot();
   21022             : 
   21023         448 :     ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
   21024             : 
   21025             :     /* keep our lock until commit */
   21026         448 :     table_close(partRel, NoLock);
   21027             : 
   21028         448 :     return address;
   21029             : }
   21030             : 
   21031             : /*
   21032             :  * Second part of ALTER TABLE .. DETACH.
   21033             :  *
   21034             :  * This is separate so that it can be run independently when the second
   21035             :  * transaction of the concurrent algorithm fails (crash or abort).
   21036             :  */
   21037             : static void
   21038         464 : DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
   21039             :                         Oid defaultPartOid)
   21040             : {
   21041             :     Relation    classRel;
   21042             :     List       *fks;
   21043             :     ListCell   *cell;
   21044             :     List       *indexes;
   21045             :     Datum       new_val[Natts_pg_class];
   21046             :     bool        new_null[Natts_pg_class],
   21047             :                 new_repl[Natts_pg_class];
   21048             :     HeapTuple   tuple,
   21049             :                 newtuple;
   21050         464 :     Relation    trigrel = NULL;
   21051         464 :     List       *fkoids = NIL;
   21052             : 
   21053         464 :     if (concurrent)
   21054             :     {
   21055             :         /*
   21056             :          * We can remove the pg_inherits row now. (In the non-concurrent case,
   21057             :          * this was already done).
   21058             :          */
   21059         104 :         RemoveInheritance(partRel, rel, true);
   21060             :     }
   21061             : 
   21062             :     /* Drop any triggers that were cloned on creation/attach. */
   21063         464 :     DropClonedTriggersFromPartition(RelationGetRelid(partRel));
   21064             : 
   21065             :     /*
   21066             :      * Detach any foreign keys that are inherited.  This includes creating
   21067             :      * additional action triggers.
   21068             :      */
   21069         464 :     fks = copyObject(RelationGetFKeyList(partRel));
   21070         464 :     if (fks != NIL)
   21071          84 :         trigrel = table_open(TriggerRelationId, RowExclusiveLock);
   21072             : 
   21073             :     /*
   21074             :      * It's possible that the partition being detached has a foreign key that
   21075             :      * references a partitioned table.  When that happens, there are multiple
   21076             :      * pg_constraint rows for the partition: one points to the partitioned
   21077             :      * table itself, while the others point to each of its partitions.  Only
   21078             :      * the topmost one is to be considered here; the child constraints must be
   21079             :      * left alone, because conceptually those aren't coming from our parent
   21080             :      * partitioned table, but from this partition itself.
   21081             :      *
   21082             :      * We implement this by collecting all the constraint OIDs in a first scan
   21083             :      * of the FK array, and skipping in the loop below those constraints whose
   21084             :      * parents are listed here.
   21085             :      */
   21086        1096 :     foreach_node(ForeignKeyCacheInfo, fk, fks)
   21087         168 :         fkoids = lappend_oid(fkoids, fk->conoid);
   21088             : 
   21089         632 :     foreach(cell, fks)
   21090             :     {
   21091         168 :         ForeignKeyCacheInfo *fk = lfirst(cell);
   21092             :         HeapTuple   contup;
   21093             :         Form_pg_constraint conform;
   21094             : 
   21095         168 :         contup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
   21096         168 :         if (!HeapTupleIsValid(contup))
   21097           0 :             elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
   21098         168 :         conform = (Form_pg_constraint) GETSTRUCT(contup);
   21099             : 
   21100             :         /*
   21101             :          * Consider only inherited foreign keys, and only if their parents
   21102             :          * aren't in the list.
   21103             :          */
   21104         168 :         if (conform->contype != CONSTRAINT_FOREIGN ||
   21105         312 :             !OidIsValid(conform->conparentid) ||
   21106         144 :             list_member_oid(fkoids, conform->conparentid))
   21107             :         {
   21108          66 :             ReleaseSysCache(contup);
   21109          66 :             continue;
   21110             :         }
   21111             : 
   21112             :         /*
   21113             :          * The constraint on this table must be marked no longer a child of
   21114             :          * the parent's constraint, as do its check triggers.
   21115             :          */
   21116         102 :         ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
   21117             : 
   21118             :         /*
   21119             :          * Also, look up the partition's "check" triggers corresponding to the
   21120             :          * ENFORCED constraint being detached and detach them from the parent
   21121             :          * triggers. NOT ENFORCED constraints do not have these triggers;
   21122             :          * therefore, this step is not needed.
   21123             :          */
   21124         102 :         if (fk->conenforced)
   21125             :         {
   21126             :             Oid         insertTriggerOid,
   21127             :                         updateTriggerOid;
   21128             : 
   21129         102 :             GetForeignKeyCheckTriggers(trigrel,
   21130             :                                        fk->conoid, fk->confrelid, fk->conrelid,
   21131             :                                        &insertTriggerOid, &updateTriggerOid);
   21132             :             Assert(OidIsValid(insertTriggerOid));
   21133         102 :             TriggerSetParentTrigger(trigrel, insertTriggerOid, InvalidOid,
   21134             :                                     RelationGetRelid(partRel));
   21135             :             Assert(OidIsValid(updateTriggerOid));
   21136         102 :             TriggerSetParentTrigger(trigrel, updateTriggerOid, InvalidOid,
   21137             :                                     RelationGetRelid(partRel));
   21138             :         }
   21139             : 
   21140             :         /*
   21141             :          * Lastly, create the action triggers on the referenced table, using
   21142             :          * addFkRecurseReferenced, which requires some elaborate setup (so put
   21143             :          * it in a separate block).  While at it, if the table is partitioned,
   21144             :          * that function will recurse to create the pg_constraint rows and
   21145             :          * action triggers for each partition.
   21146             :          *
   21147             :          * Note there's no need to do addFkConstraint() here, because the
   21148             :          * pg_constraint row already exists.
   21149             :          */
   21150             :         {
   21151             :             Constraint *fkconstraint;
   21152             :             int         numfks;
   21153             :             AttrNumber  conkey[INDEX_MAX_KEYS];
   21154             :             AttrNumber  confkey[INDEX_MAX_KEYS];
   21155             :             Oid         conpfeqop[INDEX_MAX_KEYS];
   21156             :             Oid         conppeqop[INDEX_MAX_KEYS];
   21157             :             Oid         conffeqop[INDEX_MAX_KEYS];
   21158             :             int         numfkdelsetcols;
   21159             :             AttrNumber  confdelsetcols[INDEX_MAX_KEYS];
   21160             :             Relation    refdRel;
   21161             : 
   21162         102 :             DeconstructFkConstraintRow(contup,
   21163             :                                        &numfks,
   21164             :                                        conkey,
   21165             :                                        confkey,
   21166             :                                        conpfeqop,
   21167             :                                        conppeqop,
   21168             :                                        conffeqop,
   21169             :                                        &numfkdelsetcols,
   21170             :                                        confdelsetcols);
   21171             : 
   21172             :             /* Create a synthetic node we'll use throughout */
   21173         102 :             fkconstraint = makeNode(Constraint);
   21174         102 :             fkconstraint->contype = CONSTRAINT_FOREIGN;
   21175         102 :             fkconstraint->conname = pstrdup(NameStr(conform->conname));
   21176         102 :             fkconstraint->deferrable = conform->condeferrable;
   21177         102 :             fkconstraint->initdeferred = conform->condeferred;
   21178         102 :             fkconstraint->is_enforced = conform->conenforced;
   21179         102 :             fkconstraint->skip_validation = true;
   21180         102 :             fkconstraint->initially_valid = conform->convalidated;
   21181             :             /* a few irrelevant fields omitted here */
   21182         102 :             fkconstraint->pktable = NULL;
   21183         102 :             fkconstraint->fk_attrs = NIL;
   21184         102 :             fkconstraint->pk_attrs = NIL;
   21185         102 :             fkconstraint->fk_matchtype = conform->confmatchtype;
   21186         102 :             fkconstraint->fk_upd_action = conform->confupdtype;
   21187         102 :             fkconstraint->fk_del_action = conform->confdeltype;
   21188         102 :             fkconstraint->fk_del_set_cols = NIL;
   21189         102 :             fkconstraint->old_conpfeqop = NIL;
   21190         102 :             fkconstraint->old_pktable_oid = InvalidOid;
   21191         102 :             fkconstraint->location = -1;
   21192             : 
   21193             :             /* set up colnames, used to generate the constraint name */
   21194         252 :             for (int i = 0; i < numfks; i++)
   21195             :             {
   21196             :                 Form_pg_attribute att;
   21197             : 
   21198         150 :                 att = TupleDescAttr(RelationGetDescr(partRel),
   21199         150 :                                     conkey[i] - 1);
   21200             : 
   21201         150 :                 fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
   21202         150 :                                                  makeString(NameStr(att->attname)));
   21203             :             }
   21204             : 
   21205         102 :             refdRel = table_open(fk->confrelid, ShareRowExclusiveLock);
   21206             : 
   21207         102 :             addFkRecurseReferenced(fkconstraint, partRel,
   21208             :                                    refdRel,
   21209             :                                    conform->conindid,
   21210             :                                    fk->conoid,
   21211             :                                    numfks,
   21212             :                                    confkey,
   21213             :                                    conkey,
   21214             :                                    conpfeqop,
   21215             :                                    conppeqop,
   21216             :                                    conffeqop,
   21217             :                                    numfkdelsetcols,
   21218             :                                    confdelsetcols,
   21219             :                                    true,
   21220             :                                    InvalidOid, InvalidOid,
   21221         102 :                                    conform->conperiod);
   21222         102 :             table_close(refdRel, NoLock);   /* keep lock till end of xact */
   21223             :         }
   21224             : 
   21225         102 :         ReleaseSysCache(contup);
   21226             :     }
   21227         464 :     list_free_deep(fks);
   21228         464 :     if (trigrel)
   21229          84 :         table_close(trigrel, RowExclusiveLock);
   21230             : 
   21231             :     /*
   21232             :      * Any sub-constraints that are in the referenced-side of a larger
   21233             :      * constraint have to be removed.  This partition is no longer part of the
   21234             :      * key space of the constraint.
   21235             :      */
   21236         524 :     foreach(cell, GetParentedForeignKeyRefs(partRel))
   21237             :     {
   21238          62 :         Oid         constrOid = lfirst_oid(cell);
   21239             :         ObjectAddress constraint;
   21240             : 
   21241          62 :         ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
   21242          62 :         deleteDependencyRecordsForClass(ConstraintRelationId,
   21243             :                                         constrOid,
   21244             :                                         ConstraintRelationId,
   21245             :                                         DEPENDENCY_INTERNAL);
   21246          62 :         CommandCounterIncrement();
   21247             : 
   21248          62 :         ObjectAddressSet(constraint, ConstraintRelationId, constrOid);
   21249          62 :         performDeletion(&constraint, DROP_RESTRICT, 0);
   21250             :     }
   21251             : 
   21252             :     /* Now we can detach indexes */
   21253         462 :     indexes = RelationGetIndexList(partRel);
   21254         656 :     foreach(cell, indexes)
   21255             :     {
   21256         194 :         Oid         idxid = lfirst_oid(cell);
   21257             :         Oid         parentidx;
   21258             :         Relation    idx;
   21259             :         Oid         constrOid;
   21260             :         Oid         parentConstrOid;
   21261             : 
   21262         194 :         if (!has_superclass(idxid))
   21263          12 :             continue;
   21264             : 
   21265         182 :         parentidx = get_partition_parent(idxid, false);
   21266             :         Assert((IndexGetRelation(parentidx, false) == RelationGetRelid(rel)));
   21267             : 
   21268         182 :         idx = index_open(idxid, AccessExclusiveLock);
   21269         182 :         IndexSetParentIndex(idx, InvalidOid);
   21270             : 
   21271             :         /*
   21272             :          * If there's a constraint associated with the index, detach it too.
   21273             :          * Careful: it is possible for a constraint index in a partition to be
   21274             :          * the child of a non-constraint index, so verify whether the parent
   21275             :          * index does actually have a constraint.
   21276             :          */
   21277         182 :         constrOid = get_relation_idx_constraint_oid(RelationGetRelid(partRel),
   21278             :                                                     idxid);
   21279         182 :         parentConstrOid = get_relation_idx_constraint_oid(RelationGetRelid(rel),
   21280             :                                                           parentidx);
   21281         182 :         if (OidIsValid(parentConstrOid) && OidIsValid(constrOid))
   21282          84 :             ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
   21283             : 
   21284         182 :         index_close(idx, NoLock);
   21285             :     }
   21286             : 
   21287             :     /* Update pg_class tuple */
   21288         462 :     classRel = table_open(RelationRelationId, RowExclusiveLock);
   21289         462 :     tuple = SearchSysCacheCopy1(RELOID,
   21290             :                                 ObjectIdGetDatum(RelationGetRelid(partRel)));
   21291         462 :     if (!HeapTupleIsValid(tuple))
   21292           0 :         elog(ERROR, "cache lookup failed for relation %u",
   21293             :              RelationGetRelid(partRel));
   21294             :     Assert(((Form_pg_class) GETSTRUCT(tuple))->relispartition);
   21295             : 
   21296             :     /* Clear relpartbound and reset relispartition */
   21297         462 :     memset(new_val, 0, sizeof(new_val));
   21298         462 :     memset(new_null, false, sizeof(new_null));
   21299         462 :     memset(new_repl, false, sizeof(new_repl));
   21300         462 :     new_val[Anum_pg_class_relpartbound - 1] = (Datum) 0;
   21301         462 :     new_null[Anum_pg_class_relpartbound - 1] = true;
   21302         462 :     new_repl[Anum_pg_class_relpartbound - 1] = true;
   21303         462 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
   21304             :                                  new_val, new_null, new_repl);
   21305             : 
   21306         462 :     ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = false;
   21307         462 :     CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
   21308         462 :     heap_freetuple(newtuple);
   21309         462 :     table_close(classRel, RowExclusiveLock);
   21310             : 
   21311             :     /*
   21312             :      * Drop identity property from all identity columns of partition.
   21313             :      */
   21314        1318 :     for (int attno = 0; attno < RelationGetNumberOfAttributes(partRel); attno++)
   21315             :     {
   21316         856 :         Form_pg_attribute attr = TupleDescAttr(partRel->rd_att, attno);
   21317             : 
   21318         856 :         if (!attr->attisdropped && attr->attidentity)
   21319           6 :             ATExecDropIdentity(partRel, NameStr(attr->attname), false,
   21320             :                                AccessExclusiveLock, true, true);
   21321             :     }
   21322             : 
   21323         462 :     if (OidIsValid(defaultPartOid))
   21324             :     {
   21325             :         /*
   21326             :          * If the relation being detached is the default partition itself,
   21327             :          * remove it from the parent's pg_partitioned_table entry.
   21328             :          *
   21329             :          * If not, we must invalidate default partition's relcache entry, as
   21330             :          * in StorePartitionBound: its partition constraint depends on every
   21331             :          * other partition's partition constraint.
   21332             :          */
   21333          46 :         if (RelationGetRelid(partRel) == defaultPartOid)
   21334           2 :             update_default_partition_oid(RelationGetRelid(rel), InvalidOid);
   21335             :         else
   21336          44 :             CacheInvalidateRelcacheByRelid(defaultPartOid);
   21337             :     }
   21338             : 
   21339             :     /*
   21340             :      * Invalidate the parent's relcache so that the partition is no longer
   21341             :      * included in its partition descriptor.
   21342             :      */
   21343         462 :     CacheInvalidateRelcache(rel);
   21344             : 
   21345             :     /*
   21346             :      * If the partition we just detached is partitioned itself, invalidate
   21347             :      * relcache for all descendent partitions too to ensure that their
   21348             :      * rd_partcheck expression trees are rebuilt; must lock partitions before
   21349             :      * doing so, using the same lockmode as what partRel has been locked with
   21350             :      * by the caller.
   21351             :      */
   21352         462 :     if (partRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   21353             :     {
   21354             :         List       *children;
   21355             : 
   21356          62 :         children = find_all_inheritors(RelationGetRelid(partRel),
   21357             :                                        AccessExclusiveLock, NULL);
   21358         204 :         foreach(cell, children)
   21359             :         {
   21360         142 :             CacheInvalidateRelcacheByRelid(lfirst_oid(cell));
   21361             :         }
   21362             :     }
   21363         462 : }
   21364             : 
   21365             : /*
   21366             :  * ALTER TABLE ... DETACH PARTITION ... FINALIZE
   21367             :  *
   21368             :  * To use when a DETACH PARTITION command previously did not run to
   21369             :  * completion; this completes the detaching process.
   21370             :  */
   21371             : static ObjectAddress
   21372          14 : ATExecDetachPartitionFinalize(Relation rel, RangeVar *name)
   21373             : {
   21374             :     Relation    partRel;
   21375             :     ObjectAddress address;
   21376          14 :     Snapshot    snap = GetActiveSnapshot();
   21377             : 
   21378          14 :     partRel = table_openrv(name, AccessExclusiveLock);
   21379             : 
   21380             :     /*
   21381             :      * Wait until existing snapshots are gone.  This is important if the
   21382             :      * second transaction of DETACH PARTITION CONCURRENTLY is canceled: the
   21383             :      * user could immediately run DETACH FINALIZE without actually waiting for
   21384             :      * existing transactions.  We must not complete the detach action until
   21385             :      * all such queries are complete (otherwise we would present them with an
   21386             :      * inconsistent view of catalogs).
   21387             :      */
   21388          14 :     WaitForOlderSnapshots(snap->xmin, false);
   21389             : 
   21390          14 :     DetachPartitionFinalize(rel, partRel, true, InvalidOid);
   21391             : 
   21392          14 :     ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
   21393             : 
   21394          14 :     table_close(partRel, NoLock);
   21395             : 
   21396          14 :     return address;
   21397             : }
   21398             : 
   21399             : /*
   21400             :  * DropClonedTriggersFromPartition
   21401             :  *      subroutine for ATExecDetachPartition to remove any triggers that were
   21402             :  *      cloned to the partition when it was created-as-partition or attached.
   21403             :  *      This undoes what CloneRowTriggersToPartition did.
   21404             :  */
   21405             : static void
   21406         464 : DropClonedTriggersFromPartition(Oid partitionId)
   21407             : {
   21408             :     ScanKeyData skey;
   21409             :     SysScanDesc scan;
   21410             :     HeapTuple   trigtup;
   21411             :     Relation    tgrel;
   21412             :     ObjectAddresses *objects;
   21413             : 
   21414         464 :     objects = new_object_addresses();
   21415             : 
   21416             :     /*
   21417             :      * Scan pg_trigger to search for all triggers on this rel.
   21418             :      */
   21419         464 :     ScanKeyInit(&skey, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
   21420             :                 F_OIDEQ, ObjectIdGetDatum(partitionId));
   21421         464 :     tgrel = table_open(TriggerRelationId, RowExclusiveLock);
   21422         464 :     scan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
   21423             :                               true, NULL, 1, &skey);
   21424         876 :     while (HeapTupleIsValid(trigtup = systable_getnext(scan)))
   21425             :     {
   21426         412 :         Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(trigtup);
   21427             :         ObjectAddress trig;
   21428             : 
   21429             :         /* Ignore triggers that weren't cloned */
   21430         412 :         if (!OidIsValid(pg_trigger->tgparentid))
   21431         394 :             continue;
   21432             : 
   21433             :         /*
   21434             :          * Ignore internal triggers that are implementation objects of foreign
   21435             :          * keys, because these will be detached when the foreign keys
   21436             :          * themselves are.
   21437             :          */
   21438         346 :         if (OidIsValid(pg_trigger->tgconstrrelid))
   21439         328 :             continue;
   21440             : 
   21441             :         /*
   21442             :          * This is ugly, but necessary: remove the dependency markings on the
   21443             :          * trigger so that it can be removed.
   21444             :          */
   21445          18 :         deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
   21446             :                                         TriggerRelationId,
   21447             :                                         DEPENDENCY_PARTITION_PRI);
   21448          18 :         deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
   21449             :                                         RelationRelationId,
   21450             :                                         DEPENDENCY_PARTITION_SEC);
   21451             : 
   21452             :         /* remember this trigger to remove it below */
   21453          18 :         ObjectAddressSet(trig, TriggerRelationId, pg_trigger->oid);
   21454          18 :         add_exact_object_address(&trig, objects);
   21455             :     }
   21456             : 
   21457             :     /* make the dependency removal visible to the deletion below */
   21458         464 :     CommandCounterIncrement();
   21459         464 :     performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
   21460             : 
   21461             :     /* done */
   21462         464 :     free_object_addresses(objects);
   21463         464 :     systable_endscan(scan);
   21464         464 :     table_close(tgrel, RowExclusiveLock);
   21465         464 : }
   21466             : 
   21467             : /*
   21468             :  * Before acquiring lock on an index, acquire the same lock on the owning
   21469             :  * table.
   21470             :  */
   21471             : struct AttachIndexCallbackState
   21472             : {
   21473             :     Oid         partitionOid;
   21474             :     Oid         parentTblOid;
   21475             :     bool        lockedParentTbl;
   21476             : };
   21477             : 
   21478             : static void
   21479         392 : RangeVarCallbackForAttachIndex(const RangeVar *rv, Oid relOid, Oid oldRelOid,
   21480             :                                void *arg)
   21481             : {
   21482             :     struct AttachIndexCallbackState *state;
   21483             :     Form_pg_class classform;
   21484             :     HeapTuple   tuple;
   21485             : 
   21486         392 :     state = (struct AttachIndexCallbackState *) arg;
   21487             : 
   21488         392 :     if (!state->lockedParentTbl)
   21489             :     {
   21490         380 :         LockRelationOid(state->parentTblOid, AccessShareLock);
   21491         380 :         state->lockedParentTbl = true;
   21492             :     }
   21493             : 
   21494             :     /*
   21495             :      * If we previously locked some other heap, and the name we're looking up
   21496             :      * no longer refers to an index on that relation, release the now-useless
   21497             :      * lock.  XXX maybe we should do *after* we verify whether the index does
   21498             :      * not actually belong to the same relation ...
   21499             :      */
   21500         392 :     if (relOid != oldRelOid && OidIsValid(state->partitionOid))
   21501             :     {
   21502           0 :         UnlockRelationOid(state->partitionOid, AccessShareLock);
   21503           0 :         state->partitionOid = InvalidOid;
   21504             :     }
   21505             : 
   21506             :     /* Didn't find a relation, so no need for locking or permission checks. */
   21507         392 :     if (!OidIsValid(relOid))
   21508           6 :         return;
   21509             : 
   21510         386 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
   21511         386 :     if (!HeapTupleIsValid(tuple))
   21512           0 :         return;                 /* concurrently dropped, so nothing to do */
   21513         386 :     classform = (Form_pg_class) GETSTRUCT(tuple);
   21514         386 :     if (classform->relkind != RELKIND_PARTITIONED_INDEX &&
   21515         294 :         classform->relkind != RELKIND_INDEX)
   21516           6 :         ereport(ERROR,
   21517             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   21518             :                  errmsg("\"%s\" is not an index", rv->relname)));
   21519         380 :     ReleaseSysCache(tuple);
   21520             : 
   21521             :     /*
   21522             :      * Since we need only examine the heap's tupledesc, an access share lock
   21523             :      * on it (preventing any DDL) is sufficient.
   21524             :      */
   21525         380 :     state->partitionOid = IndexGetRelation(relOid, false);
   21526         380 :     LockRelationOid(state->partitionOid, AccessShareLock);
   21527             : }
   21528             : 
   21529             : /*
   21530             :  * ALTER INDEX i1 ATTACH PARTITION i2
   21531             :  */
   21532             : static ObjectAddress
   21533         380 : ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx, RangeVar *name)
   21534             : {
   21535             :     Relation    partIdx;
   21536             :     Relation    partTbl;
   21537             :     Relation    parentTbl;
   21538             :     ObjectAddress address;
   21539             :     Oid         partIdxId;
   21540             :     Oid         currParent;
   21541             :     struct AttachIndexCallbackState state;
   21542             : 
   21543             :     /*
   21544             :      * We need to obtain lock on the index 'name' to modify it, but we also
   21545             :      * need to read its owning table's tuple descriptor -- so we need to lock
   21546             :      * both.  To avoid deadlocks, obtain lock on the table before doing so on
   21547             :      * the index.  Furthermore, we need to examine the parent table of the
   21548             :      * partition, so lock that one too.
   21549             :      */
   21550         380 :     state.partitionOid = InvalidOid;
   21551         380 :     state.parentTblOid = parentIdx->rd_index->indrelid;
   21552         380 :     state.lockedParentTbl = false;
   21553             :     partIdxId =
   21554         380 :         RangeVarGetRelidExtended(name, AccessExclusiveLock, 0,
   21555             :                                  RangeVarCallbackForAttachIndex,
   21556             :                                  &state);
   21557             :     /* Not there? */
   21558         368 :     if (!OidIsValid(partIdxId))
   21559           0 :         ereport(ERROR,
   21560             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
   21561             :                  errmsg("index \"%s\" does not exist", name->relname)));
   21562             : 
   21563             :     /* no deadlock risk: RangeVarGetRelidExtended already acquired the lock */
   21564         368 :     partIdx = relation_open(partIdxId, AccessExclusiveLock);
   21565             : 
   21566             :     /* we already hold locks on both tables, so this is safe: */
   21567         368 :     parentTbl = relation_open(parentIdx->rd_index->indrelid, AccessShareLock);
   21568         368 :     partTbl = relation_open(partIdx->rd_index->indrelid, NoLock);
   21569             : 
   21570         368 :     ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partIdx));
   21571             : 
   21572             :     /* Silently do nothing if already in the right state */
   21573         736 :     currParent = partIdx->rd_rel->relispartition ?
   21574         368 :         get_partition_parent(partIdxId, false) : InvalidOid;
   21575         368 :     if (currParent != RelationGetRelid(parentIdx))
   21576             :     {
   21577             :         IndexInfo  *childInfo;
   21578             :         IndexInfo  *parentInfo;
   21579             :         AttrMap    *attmap;
   21580             :         bool        found;
   21581             :         int         i;
   21582             :         PartitionDesc partDesc;
   21583             :         Oid         constraintOid,
   21584         344 :                     cldConstrId = InvalidOid;
   21585             : 
   21586             :         /*
   21587             :          * If this partition already has an index attached, refuse the
   21588             :          * operation.
   21589             :          */
   21590         344 :         refuseDupeIndexAttach(parentIdx, partIdx, partTbl);
   21591             : 
   21592         338 :         if (OidIsValid(currParent))
   21593           0 :             ereport(ERROR,
   21594             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21595             :                      errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   21596             :                             RelationGetRelationName(partIdx),
   21597             :                             RelationGetRelationName(parentIdx)),
   21598             :                      errdetail("Index \"%s\" is already attached to another index.",
   21599             :                                RelationGetRelationName(partIdx))));
   21600             : 
   21601             :         /* Make sure it indexes a partition of the other index's table */
   21602         338 :         partDesc = RelationGetPartitionDesc(parentTbl, true);
   21603         338 :         found = false;
   21604         528 :         for (i = 0; i < partDesc->nparts; i++)
   21605             :         {
   21606         522 :             if (partDesc->oids[i] == state.partitionOid)
   21607             :             {
   21608         332 :                 found = true;
   21609         332 :                 break;
   21610             :             }
   21611             :         }
   21612         338 :         if (!found)
   21613           6 :             ereport(ERROR,
   21614             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21615             :                      errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   21616             :                             RelationGetRelationName(partIdx),
   21617             :                             RelationGetRelationName(parentIdx)),
   21618             :                      errdetail("Index \"%s\" is not an index on any partition of table \"%s\".",
   21619             :                                RelationGetRelationName(partIdx),
   21620             :                                RelationGetRelationName(parentTbl))));
   21621             : 
   21622             :         /* Ensure the indexes are compatible */
   21623         332 :         childInfo = BuildIndexInfo(partIdx);
   21624         332 :         parentInfo = BuildIndexInfo(parentIdx);
   21625         332 :         attmap = build_attrmap_by_name(RelationGetDescr(partTbl),
   21626             :                                        RelationGetDescr(parentTbl),
   21627             :                                        false);
   21628         332 :         if (!CompareIndexInfo(childInfo, parentInfo,
   21629         332 :                               partIdx->rd_indcollation,
   21630         332 :                               parentIdx->rd_indcollation,
   21631         332 :                               partIdx->rd_opfamily,
   21632         332 :                               parentIdx->rd_opfamily,
   21633             :                               attmap))
   21634          42 :             ereport(ERROR,
   21635             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   21636             :                      errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   21637             :                             RelationGetRelationName(partIdx),
   21638             :                             RelationGetRelationName(parentIdx)),
   21639             :                      errdetail("The index definitions do not match.")));
   21640             : 
   21641             :         /*
   21642             :          * If there is a constraint in the parent, make sure there is one in
   21643             :          * the child too.
   21644             :          */
   21645         290 :         constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(parentTbl),
   21646             :                                                         RelationGetRelid(parentIdx));
   21647             : 
   21648         290 :         if (OidIsValid(constraintOid))
   21649             :         {
   21650         110 :             cldConstrId = get_relation_idx_constraint_oid(RelationGetRelid(partTbl),
   21651             :                                                           partIdxId);
   21652         110 :             if (!OidIsValid(cldConstrId))
   21653           6 :                 ereport(ERROR,
   21654             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
   21655             :                          errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   21656             :                                 RelationGetRelationName(partIdx),
   21657             :                                 RelationGetRelationName(parentIdx)),
   21658             :                          errdetail("The index \"%s\" belongs to a constraint in table \"%s\" but no constraint exists for index \"%s\".",
   21659             :                                    RelationGetRelationName(parentIdx),
   21660             :                                    RelationGetRelationName(parentTbl),
   21661             :                                    RelationGetRelationName(partIdx))));
   21662             :         }
   21663             : 
   21664             :         /*
   21665             :          * If it's a primary key, make sure the columns in the partition are
   21666             :          * NOT NULL.
   21667             :          */
   21668         284 :         if (parentIdx->rd_index->indisprimary)
   21669          92 :             verifyPartitionIndexNotNull(childInfo, partTbl);
   21670             : 
   21671             :         /* All good -- do it */
   21672         284 :         IndexSetParentIndex(partIdx, RelationGetRelid(parentIdx));
   21673         284 :         if (OidIsValid(constraintOid))
   21674         104 :             ConstraintSetParentConstraint(cldConstrId, constraintOid,
   21675             :                                           RelationGetRelid(partTbl));
   21676             : 
   21677         284 :         free_attrmap(attmap);
   21678             : 
   21679         284 :         validatePartitionedIndex(parentIdx, parentTbl);
   21680             :     }
   21681             : 
   21682         308 :     relation_close(parentTbl, AccessShareLock);
   21683             :     /* keep these locks till commit */
   21684         308 :     relation_close(partTbl, NoLock);
   21685         308 :     relation_close(partIdx, NoLock);
   21686             : 
   21687         308 :     return address;
   21688             : }
   21689             : 
   21690             : /*
   21691             :  * Verify whether the given partition already contains an index attached
   21692             :  * to the given partitioned index.  If so, raise an error.
   21693             :  */
   21694             : static void
   21695         344 : refuseDupeIndexAttach(Relation parentIdx, Relation partIdx, Relation partitionTbl)
   21696             : {
   21697             :     Oid         existingIdx;
   21698             : 
   21699         344 :     existingIdx = index_get_partition(partitionTbl,
   21700             :                                       RelationGetRelid(parentIdx));
   21701         344 :     if (OidIsValid(existingIdx))
   21702           6 :         ereport(ERROR,
   21703             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
   21704             :                  errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
   21705             :                         RelationGetRelationName(partIdx),
   21706             :                         RelationGetRelationName(parentIdx)),
   21707             :                  errdetail("Another index \"%s\" is already attached for partition \"%s\".",
   21708             :                            get_rel_name(existingIdx),
   21709             :                            RelationGetRelationName(partitionTbl))));
   21710         338 : }
   21711             : 
   21712             : /*
   21713             :  * Verify whether the set of attached partition indexes to a parent index on
   21714             :  * a partitioned table is complete.  If it is, mark the parent index valid.
   21715             :  *
   21716             :  * This should be called each time a partition index is attached.
   21717             :  */
   21718             : static void
   21719         326 : validatePartitionedIndex(Relation partedIdx, Relation partedTbl)
   21720             : {
   21721             :     Relation    inheritsRel;
   21722             :     SysScanDesc scan;
   21723             :     ScanKeyData key;
   21724         326 :     int         tuples = 0;
   21725             :     HeapTuple   inhTup;
   21726         326 :     bool        updated = false;
   21727             : 
   21728             :     Assert(partedIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
   21729             : 
   21730             :     /*
   21731             :      * Scan pg_inherits for this parent index.  Count each valid index we find
   21732             :      * (verifying the pg_index entry for each), and if we reach the total
   21733             :      * amount we expect, we can mark this parent index as valid.
   21734             :      */
   21735         326 :     inheritsRel = table_open(InheritsRelationId, AccessShareLock);
   21736         326 :     ScanKeyInit(&key, Anum_pg_inherits_inhparent,
   21737             :                 BTEqualStrategyNumber, F_OIDEQ,
   21738             :                 ObjectIdGetDatum(RelationGetRelid(partedIdx)));
   21739         326 :     scan = systable_beginscan(inheritsRel, InheritsParentIndexId, true,
   21740             :                               NULL, 1, &key);
   21741         844 :     while ((inhTup = systable_getnext(scan)) != NULL)
   21742             :     {
   21743         518 :         Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(inhTup);
   21744             :         HeapTuple   indTup;
   21745             :         Form_pg_index indexForm;
   21746             : 
   21747         518 :         indTup = SearchSysCache1(INDEXRELID,
   21748             :                                  ObjectIdGetDatum(inhForm->inhrelid));
   21749         518 :         if (!HeapTupleIsValid(indTup))
   21750           0 :             elog(ERROR, "cache lookup failed for index %u", inhForm->inhrelid);
   21751         518 :         indexForm = (Form_pg_index) GETSTRUCT(indTup);
   21752         518 :         if (indexForm->indisvalid)
   21753         460 :             tuples += 1;
   21754         518 :         ReleaseSysCache(indTup);
   21755             :     }
   21756             : 
   21757             :     /* Done with pg_inherits */
   21758         326 :     systable_endscan(scan);
   21759         326 :     table_close(inheritsRel, AccessShareLock);
   21760             : 
   21761             :     /*
   21762             :      * If we found as many inherited indexes as the partitioned table has
   21763             :      * partitions, we're good; update pg_index to set indisvalid.
   21764             :      */
   21765         326 :     if (tuples == RelationGetPartitionDesc(partedTbl, true)->nparts)
   21766             :     {
   21767             :         Relation    idxRel;
   21768             :         HeapTuple   indTup;
   21769             :         Form_pg_index indexForm;
   21770             : 
   21771         164 :         idxRel = table_open(IndexRelationId, RowExclusiveLock);
   21772         164 :         indTup = SearchSysCacheCopy1(INDEXRELID,
   21773             :                                      ObjectIdGetDatum(RelationGetRelid(partedIdx)));
   21774         164 :         if (!HeapTupleIsValid(indTup))
   21775           0 :             elog(ERROR, "cache lookup failed for index %u",
   21776             :                  RelationGetRelid(partedIdx));
   21777         164 :         indexForm = (Form_pg_index) GETSTRUCT(indTup);
   21778             : 
   21779         164 :         indexForm->indisvalid = true;
   21780         164 :         updated = true;
   21781             : 
   21782         164 :         CatalogTupleUpdate(idxRel, &indTup->t_self, indTup);
   21783             : 
   21784         164 :         table_close(idxRel, RowExclusiveLock);
   21785         164 :         heap_freetuple(indTup);
   21786             :     }
   21787             : 
   21788             :     /*
   21789             :      * If this index is in turn a partition of a larger index, validating it
   21790             :      * might cause the parent to become valid also.  Try that.
   21791             :      */
   21792         326 :     if (updated && partedIdx->rd_rel->relispartition)
   21793             :     {
   21794             :         Oid         parentIdxId,
   21795             :                     parentTblId;
   21796             :         Relation    parentIdx,
   21797             :                     parentTbl;
   21798             : 
   21799             :         /* make sure we see the validation we just did */
   21800          42 :         CommandCounterIncrement();
   21801             : 
   21802          42 :         parentIdxId = get_partition_parent(RelationGetRelid(partedIdx), false);
   21803          42 :         parentTblId = get_partition_parent(RelationGetRelid(partedTbl), false);
   21804          42 :         parentIdx = relation_open(parentIdxId, AccessExclusiveLock);
   21805          42 :         parentTbl = relation_open(parentTblId, AccessExclusiveLock);
   21806             :         Assert(!parentIdx->rd_index->indisvalid);
   21807             : 
   21808          42 :         validatePartitionedIndex(parentIdx, parentTbl);
   21809             : 
   21810          42 :         relation_close(parentIdx, AccessExclusiveLock);
   21811          42 :         relation_close(parentTbl, AccessExclusiveLock);
   21812             :     }
   21813         326 : }
   21814             : 
   21815             : /*
   21816             :  * When attaching an index as a partition of a partitioned index which is a
   21817             :  * primary key, verify that all the columns in the partition are marked NOT
   21818             :  * NULL.
   21819             :  */
   21820             : static void
   21821          92 : verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition)
   21822             : {
   21823         186 :     for (int i = 0; i < iinfo->ii_NumIndexKeyAttrs; i++)
   21824             :     {
   21825          94 :         Form_pg_attribute att = TupleDescAttr(RelationGetDescr(partition),
   21826          94 :                                               iinfo->ii_IndexAttrNumbers[i] - 1);
   21827             : 
   21828          94 :         if (!att->attnotnull)
   21829           0 :             ereport(ERROR,
   21830             :                     errcode(ERRCODE_INVALID_TABLE_DEFINITION),
   21831             :                     errmsg("invalid primary key definition"),
   21832             :                     errdetail("Column \"%s\" of relation \"%s\" is not marked NOT NULL.",
   21833             :                               NameStr(att->attname),
   21834             :                               RelationGetRelationName(partition)));
   21835             :     }
   21836          92 : }
   21837             : 
   21838             : /*
   21839             :  * Return an OID list of constraints that reference the given relation
   21840             :  * that are marked as having a parent constraints.
   21841             :  */
   21842             : static List *
   21843         998 : GetParentedForeignKeyRefs(Relation partition)
   21844             : {
   21845             :     Relation    pg_constraint;
   21846             :     HeapTuple   tuple;
   21847             :     SysScanDesc scan;
   21848             :     ScanKeyData key[2];
   21849         998 :     List       *constraints = NIL;
   21850             : 
   21851             :     /*
   21852             :      * If no indexes, or no columns are referenceable by FKs, we can avoid the
   21853             :      * scan.
   21854             :      */
   21855        1426 :     if (RelationGetIndexList(partition) == NIL ||
   21856         428 :         bms_is_empty(RelationGetIndexAttrBitmap(partition,
   21857             :                                                 INDEX_ATTR_BITMAP_KEY)))
   21858         726 :         return NIL;
   21859             : 
   21860             :     /* Search for constraints referencing this table */
   21861         272 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
   21862         272 :     ScanKeyInit(&key[0],
   21863             :                 Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
   21864             :                 F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(partition)));
   21865         272 :     ScanKeyInit(&key[1],
   21866             :                 Anum_pg_constraint_contype, BTEqualStrategyNumber,
   21867             :                 F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
   21868             : 
   21869             :     /* XXX This is a seqscan, as we don't have a usable index */
   21870         272 :     scan = systable_beginscan(pg_constraint, InvalidOid, true, NULL, 2, key);
   21871         444 :     while ((tuple = systable_getnext(scan)) != NULL)
   21872             :     {
   21873         172 :         Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   21874             : 
   21875             :         /*
   21876             :          * We only need to process constraints that are part of larger ones.
   21877             :          */
   21878         172 :         if (!OidIsValid(constrForm->conparentid))
   21879           0 :             continue;
   21880             : 
   21881         172 :         constraints = lappend_oid(constraints, constrForm->oid);
   21882             :     }
   21883             : 
   21884         272 :     systable_endscan(scan);
   21885         272 :     table_close(pg_constraint, AccessShareLock);
   21886             : 
   21887         272 :     return constraints;
   21888             : }
   21889             : 
   21890             : /*
   21891             :  * During DETACH PARTITION, verify that any foreign keys pointing to the
   21892             :  * partitioned table would not become invalid.  An error is raised if any
   21893             :  * referenced values exist.
   21894             :  */
   21895             : static void
   21896         534 : ATDetachCheckNoForeignKeyRefs(Relation partition)
   21897             : {
   21898             :     List       *constraints;
   21899             :     ListCell   *cell;
   21900             : 
   21901         534 :     constraints = GetParentedForeignKeyRefs(partition);
   21902             : 
   21903         610 :     foreach(cell, constraints)
   21904             :     {
   21905         110 :         Oid         constrOid = lfirst_oid(cell);
   21906             :         HeapTuple   tuple;
   21907             :         Form_pg_constraint constrForm;
   21908             :         Relation    rel;
   21909         110 :         Trigger     trig = {0};
   21910             : 
   21911         110 :         tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
   21912         110 :         if (!HeapTupleIsValid(tuple))
   21913           0 :             elog(ERROR, "cache lookup failed for constraint %u", constrOid);
   21914         110 :         constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
   21915             : 
   21916             :         Assert(OidIsValid(constrForm->conparentid));
   21917             :         Assert(constrForm->confrelid == RelationGetRelid(partition));
   21918             : 
   21919             :         /* prevent data changes into the referencing table until commit */
   21920         110 :         rel = table_open(constrForm->conrelid, ShareLock);
   21921             : 
   21922         110 :         trig.tgoid = InvalidOid;
   21923         110 :         trig.tgname = NameStr(constrForm->conname);
   21924         110 :         trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
   21925         110 :         trig.tgisinternal = true;
   21926         110 :         trig.tgconstrrelid = RelationGetRelid(partition);
   21927         110 :         trig.tgconstrindid = constrForm->conindid;
   21928         110 :         trig.tgconstraint = constrForm->oid;
   21929         110 :         trig.tgdeferrable = false;
   21930         110 :         trig.tginitdeferred = false;
   21931             :         /* we needn't fill in remaining fields */
   21932             : 
   21933         110 :         RI_PartitionRemove_Check(&trig, rel, partition);
   21934             : 
   21935          76 :         ReleaseSysCache(tuple);
   21936             : 
   21937          76 :         table_close(rel, NoLock);
   21938             :     }
   21939         500 : }
   21940             : 
   21941             : /*
   21942             :  * resolve column compression specification to compression method.
   21943             :  */
   21944             : static char
   21945      259372 : GetAttributeCompression(Oid atttypid, const char *compression)
   21946             : {
   21947             :     char        cmethod;
   21948             : 
   21949      259372 :     if (compression == NULL || strcmp(compression, "default") == 0)
   21950      259188 :         return InvalidCompressionMethod;
   21951             : 
   21952             :     /*
   21953             :      * To specify a nondefault method, the column data type must be toastable.
   21954             :      * Note this says nothing about whether the column's attstorage setting
   21955             :      * permits compression; we intentionally allow attstorage and
   21956             :      * attcompression to be independent.  But with a non-toastable type,
   21957             :      * attstorage could not be set to a value that would permit compression.
   21958             :      *
   21959             :      * We don't actually need to enforce this, since nothing bad would happen
   21960             :      * if attcompression were non-default; it would never be consulted.  But
   21961             :      * it seems more user-friendly to complain about a certainly-useless
   21962             :      * attempt to set the property.
   21963             :      */
   21964         184 :     if (!TypeIsToastable(atttypid))
   21965           6 :         ereport(ERROR,
   21966             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   21967             :                  errmsg("column data type %s does not support compression",
   21968             :                         format_type_be(atttypid))));
   21969             : 
   21970         178 :     cmethod = CompressionNameToMethod(compression);
   21971         178 :     if (!CompressionMethodIsValid(cmethod))
   21972          12 :         ereport(ERROR,
   21973             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   21974             :                  errmsg("invalid compression method \"%s\"", compression)));
   21975             : 
   21976         166 :     return cmethod;
   21977             : }
   21978             : 
   21979             : /*
   21980             :  * resolve column storage specification
   21981             :  */
   21982             : static char
   21983         274 : GetAttributeStorage(Oid atttypid, const char *storagemode)
   21984             : {
   21985         274 :     char        cstorage = 0;
   21986             : 
   21987         274 :     if (pg_strcasecmp(storagemode, "plain") == 0)
   21988          56 :         cstorage = TYPSTORAGE_PLAIN;
   21989         218 :     else if (pg_strcasecmp(storagemode, "external") == 0)
   21990         176 :         cstorage = TYPSTORAGE_EXTERNAL;
   21991          42 :     else if (pg_strcasecmp(storagemode, "extended") == 0)
   21992          16 :         cstorage = TYPSTORAGE_EXTENDED;
   21993          26 :     else if (pg_strcasecmp(storagemode, "main") == 0)
   21994          20 :         cstorage = TYPSTORAGE_MAIN;
   21995           6 :     else if (pg_strcasecmp(storagemode, "default") == 0)
   21996           6 :         cstorage = get_typstorage(atttypid);
   21997             :     else
   21998           0 :         ereport(ERROR,
   21999             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   22000             :                  errmsg("invalid storage type \"%s\"",
   22001             :                         storagemode)));
   22002             : 
   22003             :     /*
   22004             :      * safety check: do not allow toasted storage modes unless column datatype
   22005             :      * is TOAST-aware.
   22006             :      */
   22007         274 :     if (!(cstorage == TYPSTORAGE_PLAIN || TypeIsToastable(atttypid)))
   22008           6 :         ereport(ERROR,
   22009             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
   22010             :                  errmsg("column data type %s can only have storage PLAIN",
   22011             :                         format_type_be(atttypid))));
   22012             : 
   22013         268 :     return cstorage;
   22014             : }
 |